Debugging
There are many tools for
debugging applications on Windows Mobile devices. In addition to
straightforward single-step debugging, it is possible to remotely
enumerate the current state of the device, including the processes
running and the memory layout of the device. It is possible to debug
using an emulator or an actual device, if the device is connected to a
PC. Many of the best debugging tools are included with Visual Studio,
although some after-market options are available.
Debugging Application Code in Visual Studio
If you’re developing in
Visual Studio, debugging on an emulator is extremely straightforward and
very similar to debugging desktop applications. To debug in Visual
Studio, build the application, select an emulator image, and click the
Debug button. Visual Studio packages the application, copies it to the
device, and starts it. When a breakpoint is hit, Visual Studio brings up
the corresponding code. Console and Debug output will be displayed
within the Output window. Using the Memory and
Watch windows, you can modify process memory. For debugging an
application with source code, Visual Studio cannot be beat. If you’re
performing security testing, directly modifying process memory can be a
shortcut for simulating error conditions and working on
proof-of-concepts.
You have two ways of debugging a
process in Visual Studio: launching the process under the debugger and
attaching to a running process. When a process is launched under the
debugger, a breakpoint can be set on the initial entry point. Attaching
to a running process is a useful technique when the target process is
long lived and is exhibiting erratic behavior, such as a memory leak.
Unfortunately, the Visual
Studio debugger does have some limitations. First, the debugger does
not support debugging base platform or kernel code, such as drivers,
thus making tracing of cross-application or system calls difficult (use
Platform Builder when debugging kernel code). Second, Visual Studio
supports debugging of both managed and native code—but not both at the
same time. This limitation makes debugging managed/native
interoperability very frustrating.
Regardless of these
limitations, Visual Studio is an excellent debugging tool for Windows
Mobile applications and is very helpful when you’re learning how the
system works.
Remote Tools
Using the debugger is a great
way to analyze applications, but it can be a heavy weight when trying to
understand the basics of Windows Mobile. A more productive strategy is
to analyze the behavior of the process or the device using the Remote
Tools package bundled with Visual Studio. The package includes Remote
File Viewer, Remote Registry Editor, Remote Spy, and Remote Heap Walker.
All of these tools run on a Windows PC and connect to either the
cradled emulator or a cradled actual device. They are contained within
the Remote Tools Folder entry under the Visual Studio Start Menu.
To use these tools, cradle
the emulator or device and start the desired remote tool. The tool will
show a list of devices and ask which one to connect to. Once connected,
the tool copies over a small executable that runs and collects
information from the device. This executable is unsigned, and depending
on the security mode of the device, it may require acceptance of a
prompt before the connection completes.
Remote File Viewer
The Remote File Viewer
(RFV) allows for navigation of the device’s file system. Using RFV,
files can be copied to and from the device. An advantage of RFV over the
Windows integrated file browsing is that RFV will display the device’s
Windows directory. What’s more, RFV displays additional data about files
and directories; most notably, the file and directory attributes are displayed.
This information is very helpful when you’re analyzing applications or
the OS and trying to learn which files are protected with the SYSTEM
file attribute. Windows will show this when you’re viewing detailed file
properties, but RFV surfaces this information in a much more easily
accessible manner.
Remote Registry Editor
Remote Registry Editor (RRE) is
a basic tool for viewing and editing the registry on a device.
Considering that neither Windows Mobile nor the desktop components have a
registry editor, RRE is indispensable. Use RRE to browse the complete
registry; this is a great way to learn about the device, its
configuration, and the services installed.
Remote Spy
Windows UI components work
by processing window messages. Examples of window messages are a
keypress or a stylus click. There are also window messages unrelated to
user input (for example, Timer expiration notices). When these events
occur, the windowing subsystem determines the currently active window
and sends the appropriate window message. All graphical applications
have a messaging loop for receiving the messages and processing them.
Remote Spy displays all of the windows on a device and provides tools
for inspecting the window messages being sent. When you’re
reverse-engineering applications, Remote Spy is a great tool for
providing insight into what the application is doing and how it is
processing events.
Remote Heap Walker
Remote Heap Walker (RHW) is
another useful tool for reverse engineering applications on Windows
Mobile. RHW displays all the memory heaps on the device and their
associated processes. It is possible to drill down into any given heap
by double-clicking on the heap. All the heap blocks within the heap and
their current allocation statuses are then displayed. From there, you
can examine each block to see a hex and ASCII representation of the data
contained within the block. RHW is a great tool for learning about a
process’s memory layout and the data contained within the process’s
memory.
RHW does have a few shortcomings.
First of all, the device must be running with the security policy
disabled in order for you to see the actual data contained within the
heap blocks. Second, RHW does not have a means for searching heap data
for a string or byte pattern. This can make finding interesting data
time consuming. Finally, the process memory is a snapshot and is not
updated dynamically. Therefore, data contained within individual heap
blocks may change, and RHW will not pick up these changes automatically.
Despite these weaknesses, RHW provides great insight into current
system activity and is a fun way of exploring memory for interesting
treasures.
Disassembly
Several
options are available for disassembling Windows Mobile executables.
Disassembly of a complete program is often a daunting task; thankfully,
Windows Mobile programs are slightly smaller, and the Win32 API is very
large. By cataloging the Win32 calls used by a program, you can get a
fairly clear picture of how an application interacts with the system.
This section introduces some tools and concepts that are useful for
Windows Mobile reverse-engineering. For a more in-depth treatise on
Windows CE disassembly, the book Security Warrior, from O’Reilly Publishing, is a handy resource.
PE File Format
Windows Mobile executables
are derived from the Microsoft Portable Executable (PE) format. PE is
the primary executable format used in Microsoft’s desktop operating
systems. PE itself is an architecture-agnostic format and can be used
across systems regardless of the underlying processor architecture.
Learning about the PE file format is a worthwhile endeavor because of
the many insights to be gained about how the OS works and lays out a
process’s memory. This understanding is especially important because
almost all security vulnerabilities result from the mismanagement of
memory.
Several fields of the PE
header contain addresses. The addresses are relative virtual addresses
(RVAs). These addresses are relative to the base address of where the PE
file ends up being loaded. For example, if a PE file is loaded into
memory at 0x01000000 and an RVA of 0x256 is specified for a field in the
header, this actual address at runtime will be 0x01000256.
The DOS and File Headers
PE files start with the DOS
header. This header is a vestigial organ left over from the days when
Microsoft’s Disk Operating System (MS-DOS) was widely used. This header
is actually a mini program that will run on MS-DOS machines and report
that the executable is not valid to run on MS-DOS. The first two bytes
of the DOS header are “MZ,” the initials of Mark Zbikowski, one of the
original Microsoft OS developers. PE files are easily identified by
looking for these two telltale bytes. The DOS header contains an offset
to the NT_HEADER header; this header is composed of three parts: Magic,
the File header, and the Optional header. In most executables, the DOS
header and the NT_HEADER header are concurrent.
The File header contains
the image type, machine type, number of sections, characteristics about
the executable, and sizing information for the Optional header that
follows. For Windows Mobile, the image type is NT and expressed as the
bytes “PE.” The machine type is Thumb or ARM. The number of sections is
variable.
Characteristics
provide clues to the loader as to how to handle the file. For example,
the characteristics can mark an executable file as an executable, and
indicate that the file targets machines with 32-bit WORD sizes.
If you’re confused about whether
or not a given file is a PE file, look for the MZ and PE markers within
the first 100 bytes of the file. The presence of these bytes gives a
strong indication as to whether or not a file is a PE executable.
The Optional Header
After the File header comes
the Optional header. The name is extremely misleading because every PE
file has an Optional header—it is required. The Optional header contains
the entry-point RVA, alignment information, target OS version
information, and a list of data directories. The entry point can serve
as a reference of where to start actual code disassembly. Each data
directory contains the RVA of particular information within the PE file.
Interesting data directories include the Import Table, Export Table,
Resources, and Import Address Table. Each of these data directories
provides insight into how the executable relates to other components
installed on the device.
The Import Table contains a
listing of the libraries and functions that the executable relies on.
For example, the Import Table will contain an entry listing WinInet.dll
and the function name InternetOpenW. This function is used for
initializing a WinInet connection, and because it is imported there is a
high chance that this executable accesses the Internet. At load time,
the loader will enumerate the entries in the Import Table, load the
referenced DLLs, and resolve the functions in the DLL. The resolved
addresses are placed into the Import Address Table (IAT). Every static
DLL function call made by a program jumps through the IAT. The IAT is
required because DLLs may be loaded at different base addresses than the
addresses calculated by the Linker at link time. The Export Table lists
the functions exported by the executable. Each export is listed by name
and address. Most executables do not export functions; however, almost
all DLLs do. The Export Table listing of a DLL is a useful reference to
determine the purpose of a DLL. Functions in the Export Table can be
listed by ordinal or string name. The ordinal is a numeric value and is
used to save code space or to obfuscate the functions exposed by the
DLL.
Sections
Following the headers is a series
of “sections.” Each section is a logical storage area within the
executable, and there can be an arbitrary number of sections. The
sections are named, and the Microsoft convention is that the names start
with a period, although this period is not required. Most Windows
Mobile executables have four or five sections: .text, .rdata, .data,
.pdata, and optionally .rsrc (see Table 1).
Table 1. Description of the Major Sections Contained Within a PE Binary
Section | Description |
---|
.text | Contains the program’s executable code. The name is confusing. |
.rdata | Read-only data including string-literals, constants, debug data, and other static structures. |
.data | Initialized global and static data including the IAT. The .data section is Read/Writable. |
.rsrc | The Resource table which describes all of their resources contained within the binary and their offsets. |
Not
all of the sections are required, and the names can change; however,
the sections listed here exist in most executables generated by the
Visual Studio compiler. If you’re examining a PE file that has different
sections, this may indicate the PE file is packed or otherwise modified
to slow reverse-engineering and analysis. The loader will map all of
the sections into memory; then, depending on a flag in the section
header, it will mark each section as Read, Write, Executable, or
Read/Write.
Viewing PE Files
Several great tools are
available for exploring PE files. Most do not directly support
displaying ARM instructions, but because the PE format is common across
desktop Windows and Windows Mobile, the tools still work. A great freely
available tool is PEBrowse Professional from SmidgeonSoft (www.smidgeonsoft.com).
PEBrowse dissects the PE file and displays all of the interesting
portions, including resources. Start with it first when enumerating a
binary’s dependencies and capabilities. Unfortunately, PEBrowse does not
support ARM instructions, and the disassembly display cannot be relied
upon. Don’t be fooled into thinking it works!
IDA Pro
IDA Pro from Hex Rays (www.hex-rays.com)
is the best disassembly tool for reverse engineering Windows Mobile
binaries. IDA Pro Standard supports loading Portable Executable (PE)
files and includes an ARMV4 processor module. DLLs can also be
disassembled. To load a Windows Mobile executable or DLL into IDA,
select the PDA/Handhelds/Phones tab and choose either the Pocket PC ARM
Executable or Pocket PC ARM Dynamic Library database type. IDA will
parse the file and perform function analysis to identify the basic
blocks in the program.
IDA
Pro is a complicated tool, and disassembly is an involved process.
Before starting a full reverse-engineering process, make sure to examine
the PE file in PEBrowse and spend some time using the remote tools to
discover any files or registry keys used by the application.
Understanding how the application interacts with the device and the
network helps in identifying reverse-engineering start points and is
much more efficient than starting at the main entry point of an
application.
Visual Studio
When you’re learning how to read
a new assembly language, a good technique to use is to write a small
sample application and read the assembly instructions that a given C/C++
construct translates into. The Disassembly View in Visual Studio is an
excellent tool to use for this because it provides a view containing the
disassembly with the associated C/C++ source code displayed in-line.
Few other debuggers/disassemblers are able to show this combined view.
To use the Disassembly View in Visual Studio, write a sample
application, set a breakpoint on the interesting C/C++ code construct,
and start the process under the debugger. Once the breakpoint is hit,
click the Debug menu bar item, select the Windows subitem, and choose
the Disassembly window. Once the Disassembly View is displayed,
single-stepping works as normal, except that stepping is performed by
assembly instruction and not by source line. A minor annoyance is that
the Disassembly window is not selectable from the Debug menu until the
process is started and running under the debugger.
Visual Studio is not
recommended as a general-purpose disassembler because it does not have
the in-depth analysis capabilities of IDA Pro. Use Visual Studio when
the source for the target application is available. If the source code
is not available, use IDA Pro.