mytestpy

pid raw_input Enter the PID of the process to attach to debugger.attach int pid printf_address print Address of printf 0x 08x printf_address debugger.bp_set printf_address debugger.run So to test this, fire up printf_loop.py in a command-line console. Take note of the python.exe PID using Windows Task Manager. Now run your my_test.py script, and enter the PID. You should see output shown in Listing 3-3. Enter the PID of the process to attach to 4048 Address of printf 0x77c4186a Setting...

Buffer Overflows

Buffer overflows are the most common type of software vulnerability. All kinds of innocuous memory-management functions, string-manipulation routines, and even intrinsic functionality are part of the programming language itself and cause software to fail because of buffer overflows. In short, a buffer overflow occurs when a quantity of data is stored in a region of memory that is too small to hold it. A metaphor to explain this concept would be to think of a buffer as a bucket that can hold a...

Info 1

Debuggers are the apple of the hacker's eye. Debuggers enable you to perform runtime tracing of a process, or dynamic analysis. The ability to perform dynamic analysis is absolutely essential when it comes to exploit development, fuzzer assistance, and malware inspection. It is crucial that you understand what debuggers are and what makes them tick. Debuggers provide a whole host of features and functionality that are useful when assessing software for defects. Most come with the ability to...

DriverlibThe Static Analysis Tool for Drivers

Driverlib is a Python library designed to automate some of the tedious reverse engineering tasks required to discover key pieces of information from a driver. Typically in order to determine which device names and IOCTL codes a driver supports, we would have to load it into IDA Pro or Immunity Debugger and manually track down the information by walking 5 To download Wireshark go to http www.wireshark.org . through the disassembly. We will take a look at some of the driverlib code to understand...

Remote Thread Creation

There are some primary differences between DLL injection and code injection however, they are both achieved in the same manner remote thread creation. The Win32 API comes preloaded with a function to do just that, CreateRemoteThreadO,1 which is exported from kernel32.dll. It has the following prototype HANDLE WINAPI CreateRemoteThread HANDLE hProcess, LPSECURITY_ATTRIBUTES lpThreadAttributes, SIZE_T dwStackSize, LPTHREAD_START_ROUTINE lpStartAddress, LPVOID lpParameter, DWORD dwCreationFlags,...

Code Injection

Let's move on to something slightly more insidious. Code injection enables us to insert raw shellcode into a running process and have it immediately executed in memory without leaving a trace on disk. This is also what allows attackers to migrate their shell connection from one process to another, post-exploitation. We are going to take a simple piece of shellcode that simply terminates a process based on its PID. This will enable you to move into a remote process and kill the process you were...

IDAPyEmu

Our first example will be to load an example binary into IDA Pro and use PyEmu to emulate a simple function call. The binary is a simple C application called addnum.exe that is available with the rest of the source for this book at http www.nostarch.com ghpython.htm. This binary simply takes two numbers as command-line parameters and adds them together before outputting the result. Let's take a quick peek at the source before looking at the disassembly. include lt stdlib.h gt include lt stdio.h...

Finding the IOCTL Dispatch Routine

Any driver that implements an IOCTL interface must have an IOCTL dispatch routine that handles the processing of the various IOCTL requests. When a driver loads, the first function that gets called is the DriverEntry routine. A skeleton DriverEntry routine for a driver that implements an IOCTL dispatch is shown in Listing 10-3 NTSTATUS DriverEntry IN PDRIVER_OBJECT DriverObject, IN PUNICODE_STRING RegistryPath UNICODE_STRING uDeviceName UNICODE_STRING uDeviceSymlink PDEVICE_OBJECT gDeviceObject...

firefoxhookpy

Let's set a global pattern that we can make the hook This is our entry hook callback function the argument we are interested in is args l def ssl_sniff dbg, args Now we read out the memory pointed to by the second argument it is stored as an ASCII string, so we'll loop on a read until we reach a NULL byte buffer byte dbg.read_process_memory args l offset, 1 if byte x00 buffer byte offset 1 continue else print Pre-Encrypted s buffer Quick and dirty process enumeration to find firefox.exe for...

mydebuggerpy

if Let's obtain the thread and context information self.h_thread self.context print Event Code d Thread ID d debug_event.dwDebugEventCode, debug_event.dwThreadId If the event code is an exception, we want to if debug_event.dwDebugEventCode EXCEPTION_DEBUG_EVENT self.exception_address if exception EXCEPTION_ACCESS_VIOLATION print Access Violation Detected. If a breakpoint is detected, we call an internal elif exception EXCEPTION_BREAKPOINT continue_status self.exception_handler_breakpoint print...

Sulley

Named after the big, fuzzy, blue monster in the movie Monsters, Inc., Sulley is a potent Python-based fuzzing framework developed by Pedram Amini and Aaron Portnoy of TippingPoint. Sulley is more than just a fuzzer it comes packed with packet-capturing capabilities, extensive crash reporting, and VMWare automation. It also is able to restart the target application after a crash has occurred so that the fuzzing session can carry on hunting for bugs. In short, Sulley is badass. For data...

Def Exception Handler Single Step Self

if self.exception EXCEPTION_ACCESS_VIOLATION print Access Violation Detected. elif self.exception EXCEPTION_BREAKPOINT continue_status self.exception_handler_breakpoint elif self.exception EXCEPTION_GUARD_PAGE print Guard Page Access Detected. elif self.exception EXCEPTION_SINGLE_STEP def determine if this single step event occurred in reaction to a hardware breakpoint and grab the hit breakpoint. according to the Intel docs, we should be able to check for the BS flag in Dr6. but it appears...

mytestpy 1

pid raw_input Enter the PID of the process to attach to debugger.attach int pid printf print Address of printf 0x 08x printf debugger.run This harness simply sets a breakpoint on the printf call whenever it gets executed. The length of the breakpoint is only a single byte. You will notice that in this harness we imported the my_debugger_defines.py file this is so we can access the HW_EXECUTE constant, which provides a little code clarity. When you run the script you should see output similar to...

Coding the Backdoor

Let's start by building our execution redirection code, which very simply starts up an application of our choosing. The reason it's called execution redirection is because we will name our backdoor calc.exe and move the original calc.exe to a different location. When the user attempts to use the calculator, she will be inadvertently running our backdoor, which in turn will start the proper calculator and thus not alert the user that anything is amiss. Note that we are including the...

Security Data Visualization

Graphical Techniques for Network Analysis Security data visualization tools offer graphical windows into the world of computer security data, revealing fascinating and useful insights into networking, cryptography, and file structures. After learning how to graph and display data correctly, readers will be able to understand complex data sets at a glance. Readers also learn what network attacks look like and how to assess their network for vulnerabilities with visualization software like...

PyEmu Overview

PyEmu is split into three main systems PyCPU, PyMemory, and PyEmu. For the most part you will be interacting only with the parent PyEmu class, which then interacts with the PyCPU and PyMemory classes in order to perform all of the low-level emulation tasks. When you are asking PyEmu to execute instructions, it calls down into PyCPU to perform the actual execution. PyCPU then calls back to PyEmu to request the necessary memory from PyMemory to fulfill the execution task. When the instruction is...

Compiling with pyexe

A handy Python library called py2exe2 allows you to compile a Python script into a full-fledged Windows executable. You must use py2exe on a Windows machine, so keep this in mind as we proceed through the following steps. 2 For the py2exe download, go to Once you run the py2exe installer, you are ready to use it inside a build script. In order to compile our backdoor, we create a simple setup script that defines how we want the executable to be built. Open a new file, name it setup.py, and...

Info

SETTING UP YOUR DEVELOPMENT ENVIRONMENT Before you can experience the art of gray hat Python programming, you must work through the least exciting portion of this book, setting up your development environment. It is essential that you have a solid development environment, which allows you to spend time absorbing the interesting information in this book rather than stumbling around trying to get your code to execute. This chapter quickly covers the installation of Python 2.5, configuring your...

Integer Overflows

Integer overflows are an interesting class of bugs that involve exploiting the way a compiler sizes signed integers and how the processor handles arithmetic operations on these integers. A signed integer is one that can hold a value from -32767 to 32767 and is 2 bytes in length. An integer overflow occurs when an attempt is made to store a value beyond this range in a signed integer. Since the value is too large to be stored in a 32-bit signed integer, the processor drops the high-order bits in...

Info Yyr

Now that we have covered the basics, it's time to implement what you've learned into a real working debugger. When Microsoft developed Windows, it added an amazing array of debugging functions to assist developers and quality assurance professionals. We will heavily utilize these functions to create our own pure Python debugger. An important thing to note here is that we are essentially performing an in-depth study of Pedram Amini's PyDbg, as it is the cleanest Windows Python debugger...

Defeating AntiDebugging Routines in Malware

Current malware variants are becoming more and more devious in their methods of infection, propagation, and their ability to defend themselves from analysis. Aside from common code-obfuscation techniques, such as using packers or encryption techniques, malware will commonly employ anti-debugging routines in an attempt to prevent a malware analyst from using a debugger to understand its behavior. Using Immunity Debugger and some Python, we are able to create some simple scripts to help bypass...

Sulley Sessions

Sulley sessions are the mechanism that ties together requests and takes care of the network packet capture, process debugging, crash reporting, and virtual machine control. To begin, let's define a sessions file and dissect the various parts. Crack open a new Python file, name it ftp_session.py, and enter the following code. from requests import ftp this is our ftp.py file def receive_ftp_banner sock sock.recv 1024 sess 0 target.netmon 26001 target.procmon 26002 target.procmon_options proc_name...

Idapython Scripting Ida Pro

IDA Pro1 has long been the disassembler of choice for reverse engineers and continues to be the most powerful static analysis tool available. Produced by Hex-Rays SA2 of Brussels, Belgium, led by its legendary chief architect Ilfak Guilfanov, IDA Pro sports a myriad of analysis capabilities. It can analyze binaries for most architectures, runs on a variety of platforms, and has a built-in debugger. Along with its core capabilities, IDA Pro has IDC, which is its own scripting language, and an...

Handlers

Handlers provide a very flexible and powerful callback mechanism to enable the reverser to observe, modify, or change certain points of execution. Eight primary handlers are exposed from PyEmu register handlers, library handlers, exception handlers, instruction handlers, opcode handlers, memory handlers, high-level memory handlers, and the program counter handler. Let's quickly cover each, and then we'll be on our way to some real use cases. Register handlers are used to watch for changes in a...

Executable Packers

Executable packers or compressors have been around for quite some time. Originally they were used to reduce the size of an executable so that it could fit on a 1.44MB floppy disk, but they have since grown to be a major part of code obfuscation for malware authors. A typical packer will compress the code and data segments of the target binary and replace the entry point with a decompressor. When the binary is executed, the decompressor runs, which decompresses the original binary into memory,...

UPX Packer

UPX is a free, open source executable packer that works on Linux, Windows, and a host of other executable types. It offers varying levels of compression and a myriad of additional options for changing the target executable during the packing process. We are going to apply only basic compression to our target executable, but feel free to explore the options that UPX supports. To start, download the UPX executable from http upx.sourceforge.net. Once the file is downloaded, extract the Zip file to...

Process Snapshots

PyDbg comes stocked with a very cool feature called process snapshotting. Using process snapshotting you are able to freeze a process, obtain all of its memory, and resume the process. At any later point you can revert the process to the point where the snapshot was taken. This can be quite handy when reverse engineering a binary or analyzing a crash. Our first step is to get an accurate picture of what the target process was up to at a precise moment. In order for the picture to be accurate,...

findinstructionpy

search_code .join args search_bytes imm.Assemble search_code search_results imm.Search search_bytes 3 An in-depth explanation of DEP can be found at http support.microsoft.com kb 875352 EN-US . Retrieve the memory page where this hit exists and make sure it's executable code_page imm.getMemoryPagebyAddress hit 0 access code_page.getAccess human True if execute in access.lower imm.log Found s ox 08x search_code, hit , address hit return Finished searching for instructions, check the Log window....

mydebuggerpy Pbs

self.first_breakpoint True self.hardware_breakpoints def bp_set_hw self, address, length, condition Check for a valid length value if length not in i, 2, 4 if condition not in HW_ACCESS, HW_EXECUTE, HW_WRITE return False if not available 0 elif not available 1 elif not available 2 elif not We want to set the debug register in every thread for thread_id in self.enumerate_threads context Enable the appropriate flag in the DR7 register to set the breakpoint context.Dr7 1 lt lt available 2 Save the...

Fuzzing Windows Drivers

Attacking Windows drivers is becoming commonplace for bug hunters and exploit developers alike. Although there have been some remote attacks on drivers in the past few years, it is far more common to use a local attack against a driver to obtain escalated privileges on the compromised machine. In the previous chapter, we used Sulley to find a stack overflow in WarFTPD. What we didn't know was that the WarFTPD daemon was running as a limited user, essentially the user that had started the...

Exploit Development

Finding a vulnerability in a software system is only the beginning of a long and arduous journey on your way to getting a reliable exploit working. Immunity Debugger has many design features in place to make this journey a little easier on the exploit developer. We will develop some PyCommands to speed up the process of getting a working exploit, including a way to find specific instructions for getting EIP into our shellcode and to determine what bad characters we need to filter out when...

accessviolationhandlerpy

Utility libraries included with PyDbg import utils This is our access violation handler def check_accessv dbg We skip first-chance exceptions if dbg.dbg.u.Exception.dwFirstChance crash_bin utils.crash_binning.crash_binning pid raw_input Enter the Process ID dbg.run Now run the buffer_overflow.py file and take note of its PID it will pause until you are ready to let it run. Execute the access_violation_handler.py file, and enter the PID of the test harness. Once you have the debugger attached,...

findantideppy

buf immutils.int2str32_swapped addr return ord buf 0 , ord buf l , ord buf 2 , ord buf 3 DESC Find address to bypass software DEP mod return Error Ntdll.dll not found ret imm.searchCommands MOV AL,l nRET if not ret return Error Sorry, the first addy cannot be found addylist.append 0x 08x s a 0 , a 2 ret imm.comboBox Please, choose the First Address sets AL to 1 , addylist imm.Log First Address 0x 08x firstaddy, address firstaddy ret imm.searchCommandsOnModule mod.getBase , CMP AL,0xl n PUSH 0x2...

Function Emulation

The first step when creating a new PyEmu script is to make sure you have the path to PyEmu set correctly. Open a new Python script, name it addnum_function_call.py, and enter the following code. import sys sys.path.append C PyEmu Now that we have the path set up correctly, we can begin scripting out the PyEmu function-calling code. First we have to map the code and data sections of the binary we are reversing so that the emulator has some real code to execute. Because we are using IDAPython, we...

Pyemu The Scriptable Emulator

PyEmu was released at BlackHat 20071 by Cody Pierce, one of the talented members of the TippingPoint DVLabs team. PyEmu is a pure Python IA32 emulator that allows a developer to use Python to drive CPU emulation tasks. Using an emulator can be very beneficial for reverse engineering malware, when you don't necessarily want the real malware code to execute. And it can be useful for a whole host of other reverse engineering tasks as well. PyEmu has three methods to enable emulation IDAPyEmu,...

Slaying WarFTPD with Sulley

Now that you have a basic understanding of how to create a protocol description using Sulley primitives, let's apply it to a real target, WarFTPD 1.65, which has a known stack overflow when passing in overly long values for the USER or PASS commands. Both of those commands are used to authenticate an FTP user to the server so that the user can perform file transfer operations on the host the server daemon is running on. Download WarFTPD from ftp ftp.jgaa. Then run the installer. It will unzip...

PyHooks

Immunity Debugger ships with 13 different flavors of hooks, each of which you can implement as either a standalone script or inside a PyCommand at runtime. The following hook types can be used When a breakpoint is encountered, these types of hooks can be called. Both hook types behave the same way, except that when a BpHook is encountered it actually stops debuggee execution, whereas the LogBpHook continues execution after the hook is hit. Any exception that occurs in the process will trigger...

Dll And Code Injection

At times when you are reversing or attacking a target, it is useful for you to be able to load code into a remote process and have it execute within that process's context. Whether you're stealing password hashes or gaining remote desktop control of a target system, DLL and code injection have powerful applications. We will create some simple utilities in Python that will enable you to harness both techniques so that you can easily implement them at will. These techniques should be part of...

IDAPython Installation

To install IDAPython you first need to download the binary package use the following link Once you have the zip file downloaded, unzip it to a directory of your choosing. Inside the decompressed folder you will see a plugins directory, and contained within it is a file named python.plw. You need to copy python .plw into IDA Pro's plugins directory on a default installation it would be located in C Program FilesMDA plugins. From the decompressed IDAPython folder copy the python directory into...

Function Code Coverage

When performing dynamic analysis on a target binary, it can be quite useful to understand what code gets executed while you are using the target executable. Whether this means testing code coverage on a networked application after you send it a packet or using a document viewer after you've opened a document, code coverage is a useful metric to understand how an executable operates. We'll use IDAPython to iterate through all of the functions in a target binary and set breakpoints on the head of...

Debugger Hooks

One very cool feature that IDAPython supports is the ability to define a debugger hook within IDA and set up event handlers for the various debugging events that may occur. Although IDA is not commonly used for debugging tasks, there are times when it is easier to simply fire up the native IDA debugger than switch to another tool. We will use one of these debugger hooks later on when creating a simple code coverage tool. To set up a debugger hook, you first define a base debugger hook class and...

Format String Attacks

Format string attacks involve an attacker passing input that gets treated as the format specifier in certain string-manipulation routines, such as the C function printf. Let's first examine the prototype of the printf function int printf const char format, The first parameter is the fully formatted string, which we'll combine with any number of additional parameters that represent the values to be formatted. An example of this would be printf We have written d lines of code so far., test Output...

PyCommands

The main method for executing Python inside Immunity Debugger is by using PyCommands.2 PyCommands are Python scripts that are coded to perform various tasks inside Immunity Debugger, such as hooking, static analysis, and various debugging functionalities. Every PyCommand must have a certain structure in order to execute properly. The following code snippet shows a basic PyCommand that you can use as a template when creating your own PyCommands Instantiate a immlib.Debugger instance imm Debugger...

Creating the FTP Protocol Skeleton

We'll use our knowledge of Sulley data primitives to turn Sulley into a lean, mean FTP server-breaking machine. Warm up your code editor, create a new file called ftp.py, and enter the following code. s_initialize user s_static USER s_delim s_string justin s_static r n s_initialize pass s_static PASS s_delim s_string justin s_static r n s_initialize cwd s_static CWD s_delim s_string c s_static r n s_initialize dele s_static DELE s_delim s_string c test.txt s_static r n s_initialize mdtm...

hippieeasypy

This is Nico's function that looks for the correct basic block that has our desired ret instruction this is used to find the proper hook point for RtlAllocateHeap def getRet imm, allocaddr, max_opcodes 300 addr allocaddr for a in range 0, max_opcodes op imm.disasmForward addr op imm.disasmBackward addr, 3 return op.getAddress addr op.getAddress A simple wrapper to just print out the hook results in a friendly manner, it simply checks the hook address against the stored addresses for...

Unpacking UPX with PEPyEmu

The UPX packer uses a fairly straightforward method for compressing executables it re-creates the executable's entry point so that it points to the unpacking routine and adds two custom sections to the binary. These sections are named UPX0 and UPX1. If you load the compressed executable into Immunity Debugger and examine the memory layout alt-M , you'll see that the executable has a memory map similar to what's shown in Listing 12-3 Listing 12-3 Memory layout of a UPX compressed executable....

Defeating Process Iteration

Malware will also attempt to iterate through all the running processes on the machine to determine if a debugger is running. For instance, if you are using Immunity Debugger against a virus, ImmunityDebugger.exe will be registered as a running process. To iterate through the running processes, malware will use the Process32First function to get the first registered function in the system process list and then use Process32Next to begin iterating through all of the processes. Both of these...

Installing PyEmu

Installing PyEmu is quite simple just download the zip file from http www . nostarch. com ghpython. htm. Once you have the zip file downloaded, extract it to C PyEmu. Each time you create a PyEmu script, you will have to set the path to the PyEmu codebase using the following two Python lines That's it Now let's dig into the architecture of the PyEmu system and then move into creating some sample scripts.

Sulley Installation

Before we dig into the nuts and bolts of Sulley, we first have to get it installed and working. I have provided a zipped copy of the Sulley source code for download at Once you have the zip file downloaded, extract it to any location you choose. From the extracted Sulley directory, copy the sulley, utils, and requests folders to C Python25 Lib site-packages . This is all that is required to get the core of Sulley installed. There are a few more prerequisite packages that we must install, and...

Hard Hooking with Immunity Debugger

Now we get to the interesting stuff, the hard hooking technique. This technique is more advanced, but it also has far less impact on the target process because our hook code is written directly in x86 assembly. With the case of the soft hook, there are many events and many more instructions that occur between the time the breakpoint is hit, the hook code gets executed, and the process resumes execution. With a hard hook you are really just extending a particular piece of code to run your hook...