Proof of Concept “Remote Process Address Space Manipulation on Android” (ptrace)

Hi,

your phone must be rooted else you don’t have the permission todo such “evil” things.

Why write your own and don’t use the apps out there?

I only found 1 App that is able todo this. (GameCIH) It is a pretty nice app, has more features than mine has, because i just wrote a PoC. Someone else can pick up my work say thanks to me give me a little credit and implement all the features. Should be easy with my code. There are big problems with GameCIH i explain them now.

Problems of GameCIH

  • For most people a blackbox (I don’t give blackboxes root rights)
  • Ads sucks like hell
  • “Not supported in Lite Version” => wtf you can’t buy a non Lite Version in the marketplace. So there is memory you can’t reach.

GameCIH Not supported in Lite Version

This happens if the memory you want to manipulate is not accessable through pread on “/proc/<pid>/mem”. I have to say a nice restriction for a lite version. You can test it but mostly you want to modify memory in this region. My app has a restriction too. I don’t search the whole memory it is easy patchable in the source. I made it for performance issues. The code is far from perfect just use it as PoC like i titled it ;). Maybe only god knows i bring a clean version with more features than GameCIH… My time is short…

Now the nerdy part

I try to show only the source i need to. The whole source is compilable as attachment ;).

I introduced a Class that make executing code as root possible (NDK crafted executeables) and a root shell code. The whole thing is based on this: http://www.kdsbest.com/?p=192

The java side is basic Android GUI development i don’t discuss this here. RTFM ;).

The C Code…

Let’s start with the main function. We support 2 Modes. Search in and Poke to Memory. I know the code is not performance tuned and you will see i match the memory in the GUI which is highly inefficient, but i really didn’t give a fuck. This is just to show you guys the “Behind the Scene” of apps like GameCIH.

Basicly it works like this:

Attach to Process… Process now is a child Process of our Process… Suspend Child Process… Do Shit (Search or Poke)… Resume Child Process… Free Child Process so it is without our parent Process

int main(int argc, char **argv) {
if (argc == 4) {
int pid = atoi(argv[1]);
int number = atoi(argv[2]);
if (strcmp(argv[3], "all") == 0) {
ptrace(PTRACE_ATTACH, pid, NULL, NULL);
wait(NULL);
searchAll(pid, number);
ptrace(PTRACE_CONT, pid, NULL, NULL);
ptrace(PTRACE_DETACH, pid, NULL, NULL);
} else {
ptrace(PTRACE_ATTACH, pid, NULL, NULL);
wait(NULL);

long add;
sscanf(argv[3], "0x%x", &add);
ptrace(PTRACE_POKEDATA, pid, add, number);
printf("Poke at 0x%x (%d): %d", add, add, number);
ptrace(PTRACE_CONT, pid, NULL, NULL);
ptrace(PTRACE_DETACH, pid, NULL, NULL);
}
}
}

The Poke should be clear and easy for everyone to understand. The search with PTRACE_PEEKDATA is highly inefficient cause it just gives you 4 bytes of the memory and you have to traverse it. You do alot function calls and loops which makes this slow as hell. Android will think your app is crashed if you do this. But we are lucky there is a “/proc/<pid>/mem” file which is basicly the remote memory. Higher Regions are not readable through this (i didn’t manage it), so we fallback to the PTRACE_PEEKDATA version. You don’t need to fear we got access to the whole memory “/proc/<pid>/maps” offers.

“/proc/<pid>/maps” shows you which memory regions are allocated

“/proc/<pid>/mem” is the remote memory

So we got 2 remote memory read methods:

The fast one but can fail:

ssize_t readregion(void *buf, pid_t pid, long start, long end, size_t max) {
ssize_t len;
char mem[32];
int fdMEM;
snprintf(mem, sizeof(mem), "/proc/%d/mem", pid);

if ((fdMEM = open(mem, O_RDONLY)) == -1) {
return -1;
}

if (end - start < max)
max = end - start;
len = pread(fdMEM, buf, max, start);

close(fdMEM);

return len;
}

The slow one but never fails:

ssize_t readregionpeek(long*buf, pid_t pid, long start, long end, size_t max) {
if (end - start < max)
max = end - start;
int i, imax;
imax = max / 4;
for (i = 0; i < imax; i++) {
buf[i] = ptrace(PTRACE_PEEKDATA, pid, start + (i * 4), NULL);
}
return max;
}

Got a question?

http://www.twitter.com/KDSBest

Download here

Download here

Android Root in your Application

A rooted phone is always a security hole, but you can do some impressive applications with it. The “rootshell” i show in this example isn’t that “scary”. You can use this class if you want, but give credit ;). You can execute shell commands as root via this class (the phone must be rooted!). The code is pretty straight forward.

package com.android.kdsbest;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

public class RootShell {
public String execute(String command) {
String[] str = new String[1];
str[0] = command;
return execute(str);
}

public String execute(String[] commands) {
return execute(commands, true);
}
public String execute(String[] commands, boolean errorStream) {
DataOutputStream dos = null;
DataInputStream dis = null;
DataInputStream des = null;
Process process = null;

try {
process = Runtime.getRuntime().exec(&quot;su -c sh&quot;);
} catch (IOException io) {
}
dos = new DataOutputStream(process.getOutputStream());
dis = new DataInputStream(process.getInputStream());
if(errorStream)
des = new DataInputStream(process.getErrorStream());
try {
String result = &quot;&quot;;
for (String single : commands) {
dos.writeBytes(single + &quot;\n&quot;);
dos.flush();
}
dos.writeBytes(&quot;exit\n&quot;);
dos.flush();
process.waitFor();
while(dis.available() &gt; 0)
result += dis.readLine() + &quot;\n&quot;;
if(errorStream)
{
while(des.available() &gt; 0)
result += des.readLine() + &quot;\n&quot;;
}
dis.close();
dos.close();
if(errorStream)
des.close();
return result;
} catch (Exception e) {
return e.getMessage();
}
}
}

Limitations

Basicly this can execute every shell command as root, but your application still has no root rights. So you can’t write to files or something like this as root or complex applications that goes beyond normal shell commands (or are way to complex to make them as shellscript).

NDK C/C++ > Java

Normaly you use the NDK to create a shared object and interface it in java. With a wrapper code or something like this. If you modify the example make script (Android.mk) to this. You will build an executable.

Android.mk

LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)

LOCAL_MODULE    := NDK_Function
LOCAL_SRC_FILES := NDK_Function.c

include $(BUILD_EXECUTABLE)

NDK_Function.c


#include &lt;stdio.h&gt;
int main(int argc, char **argv)
{
printf(&quot;TEST Hack by KDSBest\n&quot;);
}

Just build it like you would do with the shared object.

Merge everything and give our NDK_Function executeable file root rights.

Now you have to copy the NDK_Function (executeable file) to the assets of your java application. Here comes the “tricky” part. The java application copies the NDK_Function file to a temp directory. Then it uses the root shell to chmod and execute this file as root. Now you can write C code that is executed as root.

An example activity that does the trick

package com.android.kdsbest;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ScrollView;
import android.widget.TextView;

public class MemoryManipulatorActivity extends Activity {

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView tv = new TextView(this);
ScrollView sv = new ScrollView(this);
String debug = &quot;&quot;;
RootShell shell = new RootShell();
try {
BufferedInputStream is = new BufferedInputStream(getAssets().open(
&quot;NDK_Function&quot;));
int ib = -1;
debug += &quot;Start File\n&quot;;
File file = new File(&quot;/data/data/com.android.kdsbest/NDK_Function&quot;);
debug += &quot;Creating File...\n&quot;;
if(file.createNewFile())
{
debug += &quot;File created!\n&quot;;
}
else
{
debug += &quot;File existed!\n&quot;;
}
BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(file));

debug += &quot;Write executable file...\n&quot;;
while ((ib = is.read()) != -1) {
os.write(ib);
}
is.close();
os.close();
} catch (Exception e) {
debug += &quot;ERROR: &quot; + e.getMessage() + &quot;\n&quot;;

}

debug += &quot;Building Shellscript...\n&quot;;
String[] commands = new String[2];
commands[0] = &quot;chmod 777 /data/data/com.android.kdsbest/NDK_Function&quot;;
commands[1] = &quot;/data/data/com.android.kdsbest/NDK_Function&quot;;
debug += &quot;Execute our file as root...\n&quot;;
tv.setText(shell.execute(commands, false));
sv.addView(tv);
setContentView(sv);
}
}


Problems

Guys i often see Apps that need your phone rooted. This is an security issue. Let’s take for example GameCIH (i write an open source version at the moment). This thing uses a technique similar to the one i explained. Java code can be reversed easy but the C code is a blackbox (IDA can create assembler for you). Why does it need sockets? Maybe it is calling home idk. Don’t trust anyone blind. I will make an open source solution for you.
Stay tuned

KDSBest

Learning Hacking (Where do i start?)

Alot of people ask “How do i learn hacking?”, “Where do i start?”, “How do i become a hacker”… and so on. I answered the question a million times. Now we all can just give them this link to my blog. ^^ First of all i want to thank MadHaTTrr. He talked to me about this topic in IRC and we discussed it abit. This is my opinion about everything. Others might think about it in a different way. Eat it or just throw it away.

What is hacking?

Hacking is a hobby. There are many ways of hacking. Some break security systems, some reverse code and some write homebrew things. In my opinion everything has todo with hacking. If you want to become a “hacker”. You have to get some knowledge in computer science and love to play around with it. That’s basicly everything a hacker needs ;).

What do i have to learn?

This really depends on what you want to achieve. For example “I want to learn to break into systems with tools out there and i don’t want to know a programming language”. For me you are no hacker then but then you just need to learn metasploit and co. 😉
There are some main topics in my opinion that are important.

  • Using a computer (Linux, configuration and so on)
  • Networking (Protocols and how does everything work)
  • Software (Developing and Reversing)
  • Hardware (How does your cpu work and so on. Not my best topic but i got some knowledge here)

Using a computer

Most people, who read my blog, have this knowledge. If you don’t i give you the advise to install Linux and play around with it. Configure some apache servers or something like that. Just play around till you feel comfortable with it. Compile some programms and so on. If you are able to compile your linux kernel and use it (maybe with an optimized configuration for your pc). This topic should be done for you. You don’t need to know how to compile a kernel. Just feeling comfortable with linux should proof you know how to use your computer ;).

The other topics can be learned parallel. There is no need to focus on one topic.

Networking

In my opinion everyone needs to know how to setup a network. Learn how to calculate the subnet mask and co. This should be easy just read something about it. Google helps alot here ;).
Learn how everything works. Examples are ARP Protocol, TCP/IP Protocol and how WLAN works. With this knowledge you can have alot of fun. You should be able to MitM attack a router and pc with this. With this setup sniffing should be possible. This is enough knowledge here in my opinion but depending on your needs you can lern more. Google topics or interesting tools

  • pcap (for devs, if you want or know software development, this is interesting for you)
  • arpspoof (dsniff package)
  • fragrouter (-B1 was it if i remember right to do forwarding so the network doesn’t break if you hook in there)
  • dsniff tools etc.

All tools you need here are on the net and knowing a network can be quite funny on a LAN Party. Guys never really never ever login private pages on a lan party or something like this. Public networks are public for a network hacker ;).

Software

This is my favorite. I work as software engineer and i love this topic. For Reversing this blog has a tutorial series, which starts here. Before lerning reversing you have to learn software development. I recommend every so called “hacker” to have at least a basic C knowledge. People always ask what language do i have to learn. The question is obsolete. If you know C, which is a functional language, very well and want to learn functional programming in VB. The only thing that differs is the syntax. I read very often there are so many differnces and just a hand of people know assembler. This is just plain bullshit. I know more than a hand of people that reverse code (which will be assembler). 😉 Other rumor i hear often from wannabe hackers. Are that you use absolute adresses while developing assembler and the compiler creates relative adresses. That’s why nearly noone knows assembler. That means knowing assembler needs basic addition and subtraction. Yeah a assembler developer can’t do that -.-. I recommend to learn this languages in this order:

  • C (functional programming)
  • C++ (Object oriented programming)
  • Assembler (Low level programming)

If you don’t want to learn reversing C/C++ should be enough for you to know.

Starting with C
What do i develope? First of all buy a book (there a millions out there) and read it. Don’t copy paste the examples. After the book you know basic software development. Congratulations! If you don’t know what todo now. I will help you. I started developing software when i was pretty young. Around 11-12 years old. I developed software todo my math homework. For example a calculator which knows the Gaussian elimination. Developing software, which helps you at your work or day is always a good starting point. If you don’t have such examples start with a basic game. TicTacToe or something more complex chess. If you get bored of such things try to write AI for it. You can always ask me on twitter here. I developed this and this, any idea what i can develope next? I always got ideas :D. My father, who is software engineer too, gave me a todo. I will never forget it took me ages to make this work (without looking an algorithm at the internet). I developed it myself.
A calculator which gets a formula like this:
12+32*2-(12+32)*2/(12+(113-13)*3)…
and gives the result back. With all common rules/precedence. Multiply and division has a higher precedence than addition/subtraction. And of course brackets serves first ;).
If you got it right extend your example with not and compare. If this works you can say you know how to develope software.
Before or after this you can learn C++ with the propose to learn OOP. Again a book and read/learn. Most people buy direct a C/C++ book which is fair enough.

Assembler
The masterpiece ^^, i know noone who really developes software with it. Except he is forced to. Knowing this language gives you the following advantages:

  • Basic knowledge for reversing
  • Code optimizing
  • Everyone, who knows assembler. Can imagine what the CPU does.

Hardware

Buzz words here are for example: “von neumann architecture”. You should know how a cpu works and how to read/write a circuit by a binary table or formula. This is the basic, which i know. If you want to go deeper in this topic. Microcontroller and/or FPGAs should be your topic. Learning this topic can be exspensive. Reversing a hardware curcuit like the gameboy or something older should be a good start. With a voltage and continuity tester you can check what is connected to each other. No matter how many layers the board has. Drawing a circuit diagramm of a gameboy or thing of your choice should be a nice start. Even if it doesn’t explain much. Doing it can be quite fun (hardware is really not my main topic ^^). If you want to learn more here. I give you the advice to buy a dev board and play around with it. I recommend you to learn the Software part next or better before this topic. Going deep into hardware engineering needs software.

Conclusion

There is no way to give you a numbered list what todo/learn to be a hacker. Hacker just means that you know computer science and want to do experiments with this knowledge. If i had to start from the beginning i would do it this way.

  1. Install Linux and play around with it (with a book about my distro)
  2. Setup my network in linux so i got internet 😀
  3. Learn C/C++ with a book and all it’s examples
  4. Develope the code todos i gave you and while i am frustrated in failing ^^. Learn how to use the networking tools i gave you.
  5. Go to a lan party or hotspot and play around with the networking tools (don’t do bad things, if you sniff a password be happy, you made it. Don’t use it for bad things! You want to be a hacker not a cracker)
  6. Play around with some hardware and develope software

Now some years should be gone and you should have the knowledge to go alone from here on.

I hope this helps some people to make the right decisions. How to start.

Reverse Engineering Win32 Part 6 “DLL Injection Method 2 (The Hook!)”

Hi guys,

we inject a DLL via a hook. The code is pretty simple and self explained. Our DLL need a exported function to set the hook to. Mine looks something like this.

extern "C" DLLINJECTIONTEST_API LRESULT CALLBACK DLLInjectionTestFunction(int nCode, WPARAM wParam, LPARAM lParam)
{
 MessageBoxA(NULL, "TEST", "TEST", MB_OK);

 return CallNextHookEx(0, nCode, wParam, lParam);
};

My DLL function name got mangled but i load it in IDA and just read the real name. 😉 I couldn’t get the .def file work propaly.

My function that sets the hook looks like this:

int SetHook(char* dllName, char* funcName, DWORD threadId)
{
 HMODULE hDll;
 FARPROC dllFunction;
 hDll = LoadLibraryA(dllName);
 dllFunction = GetProcAddress(hDll, funcName);
 printf("DLL %d Func %d\n", hDll, dllFunction);
 hHook = SetWindowsHookEx(WH_KEYBOARD, (HOOKPROC) dllFunction, hDll, threadId);

 if(hHook==NULL)
 {
 return GetLastError();
 }

 return 0;
}

And a call looks like this:

if(SetHook("C:\\DLLInjectionTest.dll", "_DLLInjectionTestFunction@12", (DWORD) pi.dwThreadId) != 0)
 {
 printf("Error Hook! %d", GetLastError());
 return 0;
 }

We use the dwThreadId instead of the hThreadId. I don’t know why but now windows wants the Id and not the handle. Rest is pretty much the same as in DLL Injection Method 1. Execute a exe and get ThreadId (There are other ways todo that, for example if you want to hook into a running process and so on). The hook calles the DLL Main Attach and Detach function and if a keystroke is pressed our MessageBox is printed (you could create a hotkey for something 😉 ).

The Code should be pretty much self explained. A good comment in Method 1 showed another way. Now you got 3 ways to inject DLLs.

Download here

Stay tuned,

KDSBest

Basic Windows Shellcode Development Part 1

Hi,

Why Shellcode?

Shellcode is the Opcode presentation of Assembler code. It is important because if you managed to get the EIP to point to your shellcode it gets executed. If you are not a perfect assembler developer, i will show you some tricks. I use shellcode in Exploits and Code Injection. My reversing tutorial has in the Part 5 a little shellcode, which loads a library.

My way of developing shellcode

I didn’t found this method! I don’t know, who developed it. I read about it around 6-8 years ago. Sorry i can’t give credit, but i still want to show you this method. First of all i develop the shellcode i want as C function. The C function has this basic structure:

// Shellcode Development 1.cpp : Definiert den Einstiegspunkt für die Konsolenanwendung.
//

#include &quot;stdafx.h&quot;

__declspec(naked) void shellcode()
{
 __asm
 {
 pushad;
 pushfd
 };

 __asm
 {
 popfd;
 popad;
 ret
 };
}

int _tmain(int argc, _TCHAR* argv[])
{

 shellcode();

 return 0;
}

The code is straight forward… The main function executes the shellcode. Shellcode is a __declspec(naked) function, this means it has no stack or something like that. We have full control about the code. The assembler structure around this is my basic setup. Saving all register and flags, at the end restoring them and jump back to the real code.

Simple MessageBox Code

Now we try to make the shellcode be able to show a MessageBox.

// Shellcode Development 1.cpp : Definiert den Einstiegspunkt für die Konsolenanwendung.
//

#include &quot;stdafx.h&quot;
#include &lt;Windows.h&gt;

__declspec(naked) void shellcode()
{
 __asm
 {
 pushad;
 pushfd
 };

 MessageBoxA(NULL, &quot;KDSBest's Shellcode&quot;, &quot;KDSBest's Shellcode&quot;, MB_OK);

 __asm
 {
 popfd;
 popad;
 ret
 };
}

int _tmain(int argc, _TCHAR* argv[])
{

 shellcode();

 return 0;
}

Getting the Shellcode

We set a breakpoint in our Shellcode and start the VC++ Debugger ;).

Next we right click (open the context menu) and click “Gehe zu Disassembly” (I don’t know if that is right i got the german IDE) should be something like “Goto Disassembly” or “Show Disassembly”. If you don’t find it leave a comment or twitter message ;). This picture might help you:

Now you should see this and make sure enabled to show “Codebytes” they call it in german. I highlighted it with my mouse:

The bytecodes you see are your shellcode. In my picture you see this:

00211396 68 3C 57 21 00       push        offset string &quot;KDSBest's Shellcode&quot; (21573Ch)
0021139B 68 3C 57 21 00       push        offset string &quot;KDSBest's Shellcode&quot; (21573Ch)

This won’t work in your remote process (injected or exploited). You don’t know what’s behind this adress. You have to change the adress or calculate it in the code above.

Part2 will handle this topic.

Roadmap (Parts)

  1. Introducing the Method (you just read it, i wanted to get Part 2 in Part 1. But i lack of time sorry.)
  2. Extending the Method to make it possible to inject strings and create the right adresses
  3. Removing 0x00 commands to create a shellcode which matches a string

Stay tuned,

KDSBest

Reverse Engineering Win32 Part 5 “DLL Injection Method 1 (In my opinion the Best)”

Hi guys,

i have to thank everyone, who wanted this topic. The Game i am reversing 😀 is vulnerable to DLL injection. I can inject code in it ^^ with this method.

DLL Injection “What is it?”

You force the other application to load your dll (DLL Attach Event of your dll will get executed). There are some methods, which make this possible. The most clean one in my opinion is this one.

How does it work?

We inject a small shellcode in the Application:

unsigned char sc[] = {
 // Push ret
 0x68, retChar[0], retChar[1], retChar[2], retChar[3],
 // Push all flags
 0x9C,
 // Push all register
 0x60,
 // Push 0x66666666 (later we convert it to the string of "C:\DLLInjectionTest.dll")
 0x68, strChar[0], strChar[1], strChar[2], strChar[3],
 // Mov eax, 0x66666666 (later we convert it to LoadLibrary adress)
 0xB8, apiChar[0], apiChar[1], apiChar[2], apiChar[3],
 // Call eax
 0xFF, 0xD0,
 // Pop all register
 0x61,
 // Pop all flags
 0x9D,
 // Ret
 0xC3
 };

The shellcode just call LoadLibraryA with the dll you want it to use ^^.

If we inject the Shellcode, which gets executed. Why not let the Shellcode does our dirty work? Why do we need a DLL todo this?

There are several reasons:

  1. You can write C Code in your DLL, so you can faster write complex code injections. An AES Decrypter in Shellcode is sick, but writing a DLL in C Code is possible and alot easier.
  2. The Game i reverse has a “security” feature. It creates it’s own Process as a ChildProcess. You can’t access the child Process remote (You can but it is hard, parent process is just for monitoring and so on). But if you load your dll in the Parent Process, it will be loaded in the child process aswell. So you got a workaround this “security” feature. (I guess they hooked LoadLibrary and every library loaded, they load in the child process too. They made the mistake ;).

How does the Code works?

We create the Process (so we have full access to it and get the ProcessID and ThreadID for free):

// Create Process SUSPENDED
 PROCESS_INFORMATION pi;
 STARTUPINFOA Startup;
 ZeroMemory(&Startup, sizeof(Startup));
 ZeroMemory(&pi, sizeof(pi));
 CreateProcessA("C:\\Windows\\notepad.exe", NULL, NULL, NULL, NULL, CREATE_SUSPENDED, NULL, NULL, &Startup, &pi);

Next we run the Thread so it can initialise all it’s dlls and so on (IMPORTANT: You don’t need todo this. If the game or whatever you want to manipulate has well security try without this!):

ResumeThread(pi.hThread);
 Sleep(1000);
 SuspendThread(pi.hThread);

Next we allocate Memory for our DLL Name (On the remote process, i love this function):

remote_dllStringPtr = VirtualAllocEx(pi.hProcess, NULL, strlen(dllPath)+1, MEM_COMMIT, PAGE_READWRITE);

After this we get the current EIP (This is possible because the process is suspended).

 printf("Get EIP\n");
 ctx.ContextFlags = CONTEXT_CONTROL;
 GetThreadContext(pi.hThread, &ctx);
 printf("EIP: %X\n", ctx.Eip);</pre>

Now we allocate memory for our shellcode and fill our allocated memory:

printf("Allocating Remote Memory For Shellcode\n");
 remote_shellcodePtr = VirtualAllocEx(pi.hProcess, NULL, shellcodeLen, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
 printf("Shellcode Adress: %X\n", remote_shellcodePtr);

printf("Write DLL Path To Remote Process\n");
 WriteProcessMemory(pi.hProcess, remote_dllStringPtr, dllPath, strlen(dllPath)+1, NULL);

 printf("Write Shellcode To Remote Process\n");
 WriteProcessMemory(pi.hProcess, remote_shellcodePtr, shellcode, shellcodeLen, NULL);

At the end we set the EIP of the remote process to our shellcode:

printf("Set EIP\n");
 ctx.Eip = (DWORD)remote_shellcodePtr;
 ctx.ContextFlags = CONTEXT_CONTROL;
 SetThreadContext(pi.hThread, &ctx);

 printf("Run The Shellcode\n");
 ResumeThread(pi.hThread);

Code

// DLL Injection Method1.cpp : Definiert den Einstiegspunkt für die Konsolenanwendung.
//

#include "stdafx.h"
#include <Windows.h>

void createShellcode(int ret, int str, unsigned char** shellcode, int* shellcodeSize)
{
 unsigned char* retChar = (unsigned char*) &ret;
 unsigned char* strChar = (unsigned char*) &str;
 int api = (int) GetProcAddress(LoadLibraryA("kernel32.dll"), "LoadLibraryA");
 unsigned char* apiChar = (unsigned char*) &api;
 unsigned char sc[] = {
 // Push ret
 0x68, retChar[0], retChar[1], retChar[2], retChar[3],
 // Push all flags
 0x9C,
 // Push all register
 0x60,
 // Push 0x66666666 (later we convert it to the string of "C:\DLLInjectionTest.dll")
 0x68, strChar[0], strChar[1], strChar[2], strChar[3],
 // Mov eax, 0x66666666 (later we convert it to LoadLibrary adress)
 0xB8, apiChar[0], apiChar[1], apiChar[2], apiChar[3],
 // Call eax
 0xFF, 0xD0,
 // Pop all register
 0x61,
 // Pop all flags
 0x9D,
 // Ret
 0xC3
 };

 *shellcodeSize = 22;
 *shellcode = (unsigned char*) malloc(22);
 memcpy(*shellcode, sc, 22);
}

int _tmain(int argc, char* argv[])
{
 // Path to the DLL, which you want to inject
 char dllPath[] = "C:\\DLLInjectionTest.dll";

 unsigned char* shellcode;
 int shellcodeLen;

 LPVOID remote_dllStringPtr;
 LPVOID remote_shellcodePtr;

 CONTEXT ctx;

 // Create Process SUSPENDED
 PROCESS_INFORMATION pi;
 STARTUPINFOA Startup;
 ZeroMemory(&Startup, sizeof(Startup));
 ZeroMemory(&pi, sizeof(pi));
 CreateProcessA("C:\\Windows\\notepad.exe", NULL, NULL, NULL, NULL, CREATE_SUSPENDED, NULL, NULL, &Startup, &pi);

 ResumeThread(pi.hThread);
 Sleep(1000);
 SuspendThread(pi.hThread);

 printf("Allocating Remote Memory For DLL Path\n");
 remote_dllStringPtr = VirtualAllocEx(pi.hProcess, NULL, strlen(dllPath)+1, MEM_COMMIT, PAGE_READWRITE);
 printf("DLL Adress: %X\n", remote_dllStringPtr);

 printf("Get EIP\n");
 ctx.ContextFlags = CONTEXT_CONTROL;
 GetThreadContext(pi.hThread, &ctx);
 printf("EIP: %X\n", ctx.Eip);

 printf("Build Shellcode\n");
 createShellcode(ctx.Eip, (int) remote_dllStringPtr, &shellcode, &shellcodeLen);

 printf ("Created Shellcode: \n");
 for(int i=0; i<shellcodeLen; i++)
 printf ("%X ", shellcode[i]);
 printf("\n");

 printf("Allocating Remote Memory For Shellcode\n");
 remote_shellcodePtr = VirtualAllocEx(pi.hProcess, NULL, shellcodeLen, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
 printf("Shellcode Adress: %X\n", remote_shellcodePtr);

 printf("Write DLL Path To Remote Process\n");
 WriteProcessMemory(pi.hProcess, remote_dllStringPtr, dllPath, strlen(dllPath)+1, NULL);

 printf("Write Shellcode To Remote Process\n");
 WriteProcessMemory(pi.hProcess, remote_shellcodePtr, shellcode, shellcodeLen, NULL);

 printf("Set EIP\n");
 ctx.Eip = (DWORD)remote_shellcodePtr;
 ctx.ContextFlags = CONTEXT_CONTROL;
 SetThreadContext(pi.hThread, &ctx);

 printf("Run The Shellcode\n");
 ResumeThread(pi.hThread);

 printf("Wait Till Code Was Executed\n");
 Sleep(8000);

 printf("Free Remote Resources\n");
 VirtualFreeEx(pi.hProcess, remote_dllStringPtr, strlen(dllPath)+1, MEM_DECOMMIT);
 VirtualFreeEx(pi.hProcess, remote_shellcodePtr, shellcodeLen, MEM_DECOMMIT);

 return 0;
}

Download here

There are other ways todo this, but this method can be attached to a process and can create a process. It is one of the strongest DLL Injections.
Next DLL Injection Method i will show you is with SetWindowHookEx (Preventing the SetWindowHookEx should be nearly impossible without beeing on driver Level, but i don’t like it you will see why 😉 ).

Reverse Engineering Win32 Part 4 “Common Calling Conventions”

Hi guys,

there are 3 common calling conventions in my opinion.

fastcall

int __fastcall fastcall(int a, int b)
{
 return a+b;
}

Assembler View

int __fastcall fastcall(int a, int b)
{
00E81370  push        ebp
00E81371  mov         ebp,esp
00E81373  sub         esp,0D8h
00E81379  push        ebx
00E8137A  push        esi
00E8137B  push        edi
00E8137C  push        ecx
00E8137D  lea         edi,[ebp-0D8h]
00E81383  mov         ecx,36h
00E81388  mov         eax,0CCCCCCCCh
00E8138D  rep stos    dword ptr es:[edi]
00E8138F  pop         ecx
00E81390  mov         dword ptr [ebp-14h],edx
00E81393  mov         dword ptr [ebp-8],ecx
 return a+b;
00E81396  mov         eax,dword ptr [a]
00E81399  add         eax,dword ptr [b]
}
00E8139C  pop         edi
00E8139D  pop         esi
00E8139E  pop         ebx
00E8139F  mov         esp,ebp
00E813A1  pop         ebp
00E813A2  ret

The first two arguments (left to right) are placed into two registers (ECX, EDX). All others are pushed to the stack (right to left).

If you want to get the adress of an register stored variable, it copies it to another location.

fastcall(1, 2);
00E8187E  mov         edx,2
00E81883  mov         ecx,1
00E81888  call        fastcall (0E81154h)

cdecl (default convention)

int __cdecl c_decl(int a, int b)
 {
 return a+b;
 }

Assembler View

int __cdecl c_decl(int a, int b)
{
00E813B0  push        ebp
00E813B1  mov         ebp,esp
00E813B3  sub         esp,0C0h
00E813B9  push        ebx
00E813BA  push        esi
00E813BB  push        edi
00E813BC  lea         edi,[ebp-0C0h]
00E813C2  mov         ecx,30h
00E813C7  mov         eax,0CCCCCCCCh
00E813CC  rep stos    dword ptr es:[edi]
 return a+b;
00E813CE  mov         eax,dword ptr [a]
00E813D1  add         eax,dword ptr [b]
}
00E813D4  pop         edi
00E813D5  pop         esi
00E813D6  pop         ebx
00E813D7  mov         esp,ebp
00E813D9  pop         ebp
00E813DA  ret

All arguments get pushed to the stack (right to left). The code that calls the function cleans the stack. This makes it possible to have functions with infinite arguments.

 c_decl(1, 2);
00E8188D  push        2
00E8188F  push        1
00E81891  call        c_decl (0E8100Ah)
00E81896  add         esp,8  

stdcall (default WinAPI convention)

int __stdcall stdcall(int a, int b)
 {
 return a+b;
 }

Assembler View

int __stdcall stdcall(int a, int b)
{
00E813F0  push        ebp
00E813F1  mov         ebp,esp
00E813F3  sub         esp,0C0h
00E813F9  push        ebx
00E813FA  push        esi
00E813FB  push        edi
00E813FC  lea         edi,[ebp-0C0h]
00E81402  mov         ecx,30h
00E81407  mov         eax,0CCCCCCCCh
00E8140C  rep stos    dword ptr es:[edi]
 return a+b;
00E8140E  mov         eax,dword ptr [a]
00E81411  add         eax,dword ptr [b]
}
00E81414  pop         edi
00E81415  pop         esi
00E81416  pop         ebx
00E81417  mov         esp,ebp
00E81419  pop         ebp
00E8141A  ret         8

All arguments get pushed to the stack (right to left). The function itself cleans the stack. This makes it impossible to have functions with infinite arguments, but the call size is smaller.

 stdcall(1, 2);
00E81899  push        2
00E8189B  push        1
00E8189D  call        stdcall (0E810A0h)

Conclusion
This should just show you how to identify the calls. A little knowledge 😀

Stay tuned

KDSBest

I hope i have enough time next time to create a complexer tutorial part ^^

Reverse Engineering Win32 Part 3 “Anti-Attach for Debugger”

Hi guys,

the most importan thing in reversing code is to know you enemy. I will show you an Anti-Debugger Method. This code will make it hard for you to attach a Debugger. I guy called Dwar found it in a game, which i currently reverse for fun. I hate cheating and it is not my intension to create a cheat. This file has just a heavy anti Debugger and is fun to learn from it.

We override the function DbgUiRemoteBreakin. This function handles the Debugger attaching. If a debugger attaches to a process, a new thread is created with DbgUIRemoteBreakin as entry point (In the process, which you want to debug). The full working attach goes like this. DbgUiDebugActiveProcess gets called this calls DbgUiIssueRemoteBreakin and this creates a thread that start at DbgUiRemoteBreakin. The thread is created by this function RtlCreateUserThread. DbgUiRemoteBreakin calls DbgBreakPoint (int3 and ret), which paused the main thread. And the debugger is attached. Btw all functions mentioned are in ntdll.dll.

HackIt 2 Code

// Reversing HackIt 2 (Anti-Attach Debugger).cpp : Definiert den Einstiegspunkt für die Konsolenanwendung.
//

#include "stdafx.h"
#include <Windows.h>

int _tmain(int argc, _TCHAR* argv[])
{
 FARPROC func;
 SIZE_T idontcare;
 char dllname[] = "ntdll.dll";
 func = GetProcAddress(LoadLibraryA(dllname), "DbgUiRemoteBreakin");

// I override just 4 bytes you can override more to make it look like real code, for the showcase this is enough
byte code[] = { 0xC2, 0x0C, 0x00, 0xF8 };

 WriteProcessMemory(GetCurrentProcess(), func, &code, 4, &idontcare);
 printf("Try to attach a Debugger");
 while(true)
 {
 Sleep(1000);
 }
 return 0;
}

Download here

To fix this is quite simple. Write a Loader which writes the real Code back to the Process and then you can attach a Debugger again.
If you want to attach the Debugger you have to attach it to the Loader, because both are console applications. They share the same ParentProcess.
The Loader code.

// Reversing HackIt 2 (Anti-Attach Debugger).cpp : Definiert den Einstiegspunkt für die Konsolenanwendung.
//

#include "stdafx.h"
#include <Windows.h>

int _tmain(int argc, _TCHAR* argv[])
{
 // Create the Process with the exe file of the Hack It
 char game[]="Reversing HackIt 2 (Anti-Attach Debugger).exe";
 STARTUPINFOA Startup;
 PROCESS_INFORMATION pi;
 FARPROC func;
 SIZE_T idontcare;
 char dllname[] = "ntdll.dll";

 ZeroMemory(&Startup, sizeof(Startup));
 ZeroMemory(&pi, sizeof(pi));
 Startup.cb = sizeof(Startup);
 if(CreateProcessA(game, NULL, NULL, NULL, NULL, CREATE_SUSPENDED, NULL, NULL, &Startup, &pi))

 func = GetProcAddress(LoadLibraryA(dllname), "DbgUiRemoteBreakin");
 byte code[] = { 0x6A, 0x08, 0x68, 0x30 };

 WriteProcessMemory(pi.hThread, func, &code, 4, &idontcare);
 printf("Try to attach a Debugger");
 while(true)
 {
 Sleep(1000);
 }
 return 0;
}

Download here

Greeting

Kevin

Windows 7 ASLR Fuck Off with Example Code ;)

This is an Loader which does this Hack: OllyDBG Hack explained here: http://www.kdsbest.com/?p=117

I wanted to cover it in my “normal” Tutorial Series”… This is way to complicated for the start of reversing took me 5 hours to make this work. Windows 7 uses an Anti-Hack Mechanism called address space layout randomization (ASLR). To Workaround this i need to inject alot assembler code and so on. This is my work.

// Reversing HackIt 1 Loader by KDSBest.cpp : Definiert den Einstiegspunkt für die Konsolenanwendung.
//

#include "stdafx.h"
#include <Windows.h>

PROCESS_INFORMATION pi;
DWORD byteswritten;

DWORD memwrite(FARPROC add, byte buf)
{
 if (WriteProcessMemory(pi.hProcess, add, &buf, 1, &byteswritten)==0)
 printf("[%X] -> %X ... NOT OK!!!\n", add, buf);
 else
 printf("[%X] -> %X ... OK!!!\n", add, buf);
 return byteswritten;
}

void doit()
{
 // Create the Process with the exe file of the Hack It
 char game[]="Reversing HackIt 1 by KDSBest.exe";
 STARTUPINFOA Startup;
 ZeroMemory(&Startup, sizeof(Startup));
 ZeroMemory(&pi, sizeof(pi));
 Startup.cb = sizeof(Startup);
 printf("Create...\n");
 if(CreateProcessA(game, NULL, NULL, NULL, NULL, CREATE_SUSPENDED, NULL, NULL, &Startup, &pi))

 printf("Created...\n");
 printf("Write...\n");

 // Just run the thread for a short time so dlls are initialized
 ResumeThread(pi.hThread);
 Sleep(10);

 // Stop the Thread
 SuspendThread(pi.hThread);

 // override junk code of kernel32.heapsetinformation
 // call 77AA85C1 -> kernel32.WriteProcessMemory
 memwrite((FARPROC) 0x77A9C43A, 0xE8);
 memwrite((FARPROC) 0x77A9C43B, 0x82);
 memwrite((FARPROC) 0x77A9C43C, 0xC1);
 memwrite((FARPROC) 0x77A9C43D, 0x00);
 memwrite((FARPROC) 0x77A9C43E, 0x00);
 // nop
 memwrite((FARPROC) 0x77A9C43F, 0x90);

 // override complete remote kernel32.WriteProcessMemory
 // push eax
 memwrite((FARPROC) 0x77AA85C1, 0x50);
 // add esp, 8
 memwrite((FARPROC) 0x77AA85C2, 0x83);
 memwrite((FARPROC) 0x77AA85C3, 0xC4);
 memwrite((FARPROC) 0x77AA85C4, 0x08);
 // pop eax
 memwrite((FARPROC) 0x77AA85C5, 0x58);
 // push eax
 memwrite((FARPROC) 0x77AA85C6, 0x50);
 // sub esp, 8
 memwrite((FARPROC) 0x77AA85C7, 0x83);
 memwrite((FARPROC) 0x77AA85C8, 0xEC);
 memwrite((FARPROC) 0x77AA85C9, 0x08);
 // push ebx
 memwrite((FARPROC) 0x77AA85CA, 0x53);
 // mov ebx, 7FFDED90
 memwrite((FARPROC) 0x77AA85CB, 0xBB);
 memwrite((FARPROC) 0x77AA85CC, 0x90);
 memwrite((FARPROC) 0x77AA85CD, 0xED);
 memwrite((FARPROC) 0x77AA85CE, 0xFD);
 memwrite((FARPROC) 0x77AA85CF, 0x7F);
 // mov [ebx], eax
 memwrite((FARPROC) 0x77AA85D0, 0x89);
 memwrite((FARPROC) 0x77AA85D1, 0x03);
 // pop ebx
 memwrite((FARPROC) 0x77AA85D2, 0x5B);
 // pop eax
 memwrite((FARPROC) 0x77AA85D3, 0x58);
 // retn
 memwrite((FARPROC) 0x77AA85D4, 0xC3);

 int ASLR = 0;
 // Start the Thread
 ResumeThread(pi.hThread);

 // As Long as ASLR adress is 0
 while (ASLR == 0)
 {
 // Read Memory
 ReadProcessMemory(pi.hProcess, (FARPROC) 0x7FFDED90, &ASLR, 4, &byteswritten);
//        printf("Read %X [%X]\n", ASLR, byteswritten);
 // If we don't have access something went wrong kill it and retry completly new
 if (byteswritten == 0)
 {
 TerminateProcess(pi.hProcess, 1);
 doit();
 return ;
 }
 }

 // ASLR Adress could be read stop the thread as fast as you can
 SuspendThread(pi.hThread);

 // Calculate position of the "mov eax, 1"
 ASLR -= 0x4E2;
 printf("Real Address of mov eax, 1 is %X\n", ASLR);
 printf("The Byte 1 is %X\n", ASLR+1);
 // Change it to "mov eax, 0"
 memwrite((FARPROC) (ASLR+1), 0x00);

 // Get the messagebox
 ResumeThread(pi.hThread);
}

int _tmain(int argc, _TCHAR* argv[])
{
 doit();

 return 0;
}

Bevore the MessageBox function is called. The programm is initialised with a Kernel 32 function called HeapSetInformation. Every kernel32 dll call has junk code in windows 7. Thanks MS for that enough space todo some dirty shit ;). I use the junk code to jump to a modified WriteProcessMemory function (I wrote a new function). The new function does calulate with the return adress of the HeapSetInformation call the ASLR position of the “mov eax, 1” (to get a pass this should be “mov eax, 0”).

If you got windows 7 you can test it else you can try also and report me if it worked or not.
If you got questions feel free to ask me via twitter or comment here 😉

You can’t execute the loader out of VS 2010 Express. The Debugger is not fast enough i guess. Start the Exe by hand. If Failure MessageBoxes will pop up press the ok button on them. Till you got the Pass. That are timing problems i am too tired to mess with this now.

Download here

Download here

Stay tuned

KDSBest

Reverse Engineering Win32 Part 2 “The Basic with IDA and OllyDBG”

Hi,

Running the Programm will show this:

First of all you nearly always do is let the Disassembler do his job. I used IDA. We see a MessageBox so we look which function might create the MessageBox. For this we use the Import Table of the Exe File. IDA will show this to us like this:

So we found the API, which creates the MessageBox. It is called “MessageBoxA”. Now we let IDA show us the Calls to MessageBoxA. To get this i double click the MessageBoxA and get this:

Do a right click and select the marked option to get all References to this call:

Then you should see this:

Now we know in the IDA function sub_411380 is the MessageBoxA call.
A closer look to the function will reveal this:

The important part:

//Set EAX register to true
.text:004113CA mov eax, 1

//Check if eax is true
.text:004113CF test eax, eax
//The jump will never happen
.text:004113D1 jz short loc_4113DB

//Setting the Failure Text
.text:004113D3 lea eax, [ebp+var_10]
.text:004113D6 mov [ebp+lpCaption], eax
//Jump to MessageBox Call
.text:004113D9 jmp short loc_4113E1
.text:004113DB ; —————————————————————————
.text:004113DB
// Setting the Pass Text
.text:004113DB loc_4113DB: ; CODE XREF: sub_411380+51j
.text:004113DB lea eax, [ebp+var_20]
.text:004113DE mov [ebp+lpCaption], eax
.text:004113E1
// MessageBox Call

.text:004113E1 loc_4113E1: ; CODE XREF: sub_411380+59j
.text:004113E1 mov esi, esp
.text:004113E3 push 0 ; uType
.text:004113E5 mov eax, [ebp+lpCaption]
.text:004113E8 push eax ; lpCaption
.text:004113E9 mov ecx, [ebp+lpCaption]
.text:004113EC push ecx ; lpText
.text:004113ED push 0 ; hWnd
.text:004113EF call ds:MessageBoxA

We have several attack Vectors.

Possible Attack 1

.text:004113CA mov eax, 1

should be

.text:004113CA mov eax, 0

Possible Attack 2

.text:004113D1 jz short loc_4113DB

should be

.text:004113D1 jmp short loc_4113DB

Possible Attack 3

.text:004113D9 jmp short loc_4113E1

get filled with NOPs.

Attacking 1 with OllyDBG

Load the File in OllyDBG and create a breakpoint at MessageBoxA (User32.DLL).

Next Run the Code… It should break in the MessageBoxA Function. Now do ALT+F9 “Execute till user code”… Click the MessageBox else you will never reach the user code ^^. You should see this now:

The code you just saw is the same one you saw on IDA which i showed you the possible attacks.
Create a Breakpoint at “mov eax, 1“.
Restart everything and let it run till the Breakpoint ^^. Now you are here:

Double click the “mov eax, 1” line and modify it to “mov eax, 0“:

Now run it -> breaks at your messagebox breakpoint -> run and tadaa

Download here

Next we create a Loader for what we did with OllyDBG