Thursday 25 August 2011

Mobile Application Security: Security Testing


Mobile Application Security: Security Testing


The threat of classic C exploits is reduced, but not eliminated, by using high-level Objective-C APIs. This section discusses some best practices, such as using NSString rather than legacy string operations like strcat and strcpy to protect against buffer overflows. However, there are a few more subtle ways that things can go wrong.

Buffer Overflows

The buffer overflow is one of the oldest and most well-known exploitable bugs in C. Although the iPhone has some built-in preventative measures to prevent buffer overflow exploitation, exploits resulting in code execution are still possible (see http://www.blackhat.com/presentations/bh-europe-09/Miller_Iozzo/BlackHat-Europe-2009-Miller-Iozzo-OSX-IPhone-Payloads-whitepaper.pdf). At their most basic level, buffer overflows occur when data is written into a fixed-size memory space, overflowing into the memory around the destination buffer. This gives an attacker control over the contents of process memory, potentially allowing for the insertion of hostile code. Traditionally, C functions such as strcat() and strcpy() are the APIs most often abused in this fashion. Sadly, these functions are still sometimes used in iPhone applications today.
The simplest way for an Objective-C programmer to avoid buffer overflows is to avoid manual memory management entirely, and use Cocoa objects such as NSString for string manipulation. If C-style string manipulation is necessary, the strl family of functions should be used (seehttp://developer.apple.com/documentation/security/conceptual/SecureCodingGuide/Articles/BufferOverflows.html).

Integer Overflows

An “integer overflow” occurs when a computed value is larger than the storage space it’s assigned to. This often happens in expressions used to compute the allocation size for an array of objects because the expression is of the form object_size × object_count. Listing 1 shows an example of how to overflow an integer.
Listing 1. How to Overflow an Integer
int * x = malloc(sizeof (*x) * n);
for (i = 0; i < n; i++)
   x[i] = 0;

If n is larger than 1 billion (when sizeof(int) is 4), the computed value of
sizeof (*x) * n

will be larger than 4 billion and will result in a smaller value than intended. This means the allocation size will be unexpectedly small. When the buffer is later accessed, some reads and writes will be performed past the end of the allocated length, even though they are within the expected limits of the array.
It is possible to detect these integer overflows either as they occur or before they are allowed to occur by examining the result of the multiplication or by examining the arguments. Listing 2 shows an example of how to detect an integer overflow.
Listing 2. Detecting an Integer Overflow
void *array_alloc(size_t count, size_t size) {
  if (0 == count || MAX_UINT / count > size)
      return (0);

  return malloc(count * size);
}

It’s worth noting at this point that NSInteger will behave exactly the same way: It’s not even actually an object, but simply an Objective-C way to say “int.”

Format String Attacks

Format string vulnerabilities are caused when the programmer fails to specify how user-supplied input should be formatted, thus allowing an attacker to specify their own format string. Apple’s NSString class does not have support for the “%n” format string, which allows for writing to the stack of the running program. However, there is still the threat of allowing an attacker to read from process memory or crash the program.

Listing 3 shows an example of passing user-supplied input to NSLog without using a proper format string.
Listing 3. No Format Specifier Used
int main(int argc, char *argv[]) {

    NSString * test = @"%x%x%x%x%x%x%x%x%x%x%x%x%x%x%x%x";
    NSLog(test);
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    int retVal = UIApplicationMain(argc, argv, nil, nil);

   [pool release];
  return retVal;
}

Running this results in the following:
[Session started at 2009-03-14 22:09:06 -0700.]
2009-03-14 22:09:08.874 DemoApp[2094:20b]
000070408fe0154b10000bffff00cbfffef842a4e1bfffef8cbfffef94bffff00c0

Whoops! Our user-supplied string resulted in memory contents being printed out in hexadecimal. Because we’re just logging this to the console, it isn’t too big a deal. However, in an application where this output would be exposed to a third party, we’d be in trouble. If we change our NSLog to format the user-supplied input as an Objective-C object (using the “%” format specifier), we can avoid this situation, as shown in Listing 4.
Listing 4. Proper Use of Format Strings
int main(int argc, char *argv[]) {

    NSString * test = @"%x%x%x%x%x%x%x%x%x%x%x%x%x%x%x%x";
    NSLog(@"%@", test);
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    int retVal = UIApplicationMain(argc, argv, nil, nil);
     [pool release];
    return retVal;
}

NSLog makes for a good demo but isn’t going to be used that often in a real iPhone app (given that there’s no console to log to). Common NSString methods to watch out for are stringByAppendingFormat, initWithFormat, stringWithFormat, and so on.
One thing to remember is that even when you’re using a method that emits NSString objects, you still must specify a format string. As an example, say we have a utility class that just takes an NSString and appends some user-supplied data:
+ (NSString*) formatStuff:(NSString*)myString
{
    myString = [myString stringByAppendingString:userSuppliedString];
    return myString
}

When calling this method, we use code like the following:
NSString myStuff = @"Here is my stuff.";
myStuff = [myStuff stringByAppendingFormat:[UtilityClass
formatStuff:unformattedStuff.text]];

Even though we’re both passing in an NSString and receiving one in return, stringByAppendingFormat will still parse any format string characters contained within that NSString. The correct way to call this code would be as follows:
NSString myStuff = @"Here is my stuff.";
myStuff = [myStuff stringByAppendingFormat:@"%@", [UtilityClass
formatStuff:unformattedStuff.text]];

When regular C primitives are used, format strings become an even more critical issue because the use of the “%n” format can allow for code execution. If you can, stick with NSString. Either way, remember that you, the programmer, must explicitly define a format string.

Double-Frees

C and C++ applications can suffer from double-free bugs, where a segment of memory is already freed from use and an attempt is made to deallocate it again. Typically, this occurs by an extra use of the free() function, after a previously freed memory segment has been overwritten with attacker-supplied data. This results in attacker control of process execution. In its most benign form, this can simply result in a crash. Here’s an example:
if (i >= 0) {
  ...
  free(mystuff);
}
...
free(mystuff);

In Objective-C, we can run into a similar situation where an object allocated with an alloc is freed via the release method when it already has a retain count of 0. An example follows:
id myRedCar = [[[NSString alloc] init] autorelease];
...
[myRedCar release];

Here, because myRedCar is autoreleased, it will be released after its first reference. Hence, the explicit release has nothing to release. This is a fairly common problem, especially when methods are used that return autoreleased objects. Just follow the usual development advice: If you create an object with an alloc, release it. And, of course, only release once. As an extra precaution, you may wish to set your object to nil after releasing it so that you can explicitly no longer send messages to it.
Note
See http://weblog.bignerdranch.com/?p=2 for more information on debugging retain counts. The majority of information here is applicable to both OS X and the iPhone.

Static Analysis

Most commercial static analysis tools haven’t matured to detect Objective-C-specific flaws, but simple free tools such as Flawfinder (http://dwheeler.com/flawfinder/) can be used to find C API abuses, such as the use of strcpy and statically sized buffers. Apple has documentation on implementing “static analysis,” but it seems to have misunderstood this to mean simply turning on compiler warnings (seehttp://developer.apple.com/TOOLS/xcode/staticanalysis.html).
A more promising application is the Clang Static Analyzer tool, available at http://clang.llvm.org/StaticAnalysis.html. Like any static analysis tool, the clang analyzer has its share of false positives, but it can be quite useful for pointing out uninitialized values, memory leaks, and other flaws. To use this tool on iPhone projects, you’ll need to do the following:
  1. Open your project in Xcode. Go to Project | Edit Project Settings.
  2. Go to Build. Change “Configuration” to “Debug.”
  3. Change the Base SDK to “Simulator” of the appropriate OS version. “Valid Architectures” should change to “i386.”
  4. Go to Configurations and change the default for command-line builds to be “Debug.”
  5. In a terminal, cd to the project’s directory and run scan-build–view xcodebuild.
  6. When the build completes, a browser window will be opened to a local web server to view results.
Consult the clang documentation for more details on interpreting the results. Of course, you should not assume that the use of a static analysis tool will find all or even most of the security or reliability flaws in an application; therefore, you should consider developing fuzzers for your program’s various inputs.
The role of a fuzzer is to expose faults through violating program assumptions. For instance, given an application that parses an HTTP response and populates a buffer with its contents, over-long data or format strings can cause the program to fail in a potentially exploitable fashion. Similarly, integers retrieved via external sources could fail to account for negative numbers, thus leading to unexpected effects. You can craft fuzzers in the form of fake servers, fake clients, or programs that generate many test cases to be parsed by an application.

Mobile Application Security : Windows Mobile Security - Development and Security Testing (part 3)


Mobile Application Security : Windows Mobile Security - Development and Security Testing (part 3)

Code Security

The two primary development languages for Windows Mobile are C/C++ and .NET. However, several additional language runtimes have been ported to the platform, and developers can choose to write code targeting Python and others. For these alternative runtimes, application developers must have users install the runtime manually or they must include the runtime with the application.
C/C++ Security
C and C++ are the primary development languages for Windows Mobile. Both of these languages provide access to the entire Windows Mobile API set. Because programmers must manually manage memory in C/C++ and there is no intermediate runtime required for execution, Microsoft refers to code written in these languages as native code. Native code provides no protections against memory corruption vulnerabilities such as buffer overflows, integer overflows, and heap overflows. The onus is placed on the programmer to prevent these vulnerabilities through secure coding practices.
Fortunately, many of the protection technologies introduced first in desktop Windows have been ported to Windows Mobile. Using these technologies, developers can write more secure code that has a lower chance of being successfully exploited. The three main technologies are StrSafe.h, IntSafe.h, and Stack Cookie protection.
StrSafe.h
Many buffer overflows result from mishandling string data during copying, formatting, and concatenation operations. Standard string functions such as strcpy, strncpy, strcat, strncat, and sprintf are difficult to use, do not have a standard interface, and fail to provide robust error information. Microsoft introduced the StrSafe.h string-manipulation library to help developers working with strings by addressing all of these problems. StrSafe.h is included within the Windows Mobile 6 SDK and defines the following functions: StringXXXCat, StringXXXCatN, StringXXXCopy, StringXXXCopyN, StringXXXGets, StringXXXPrintf, and StringXXXLength. In the preceding function definitions, XXX is replaced with either Cch for functions that work with character counts or Cb for functions that require the number of bytes in either the input or output buffer.

StrSafe.h functions always require the size of the destination buffer and always null-terminate the output. Additionally, StrSafe.h returns detailed status through an HRESULT. Using StrSafe.h is as simple as including the StrSafe.h file in the target project. StrSafe.h undefines all of the functions it is designed to replace, thus leading to compile errors. These errors are eliminated by replacing the dangerous functions, such as strcpy, with their StrSafe.h equivalents. For more detail and full guidance on how to use StrSafe.h, review the Microsoft documentation on MSDN (http://msdn.microsoft.com/en-us/library/ms647466.aspx).
IntSafe.h
Integer overflows are another native code issue that often leads to security vulnerabilities. An integer overflow results when two numbers are added or multiplied together and the result exceeds the maximum value that can be represented by the integer type. For example, adding 0x0000FFFF to 0xFFFFFFF3 exceeds the maximum value that can be stored in a DWORD. When this happens, the calculation overflows and the resulting value will be smaller than the initial value. If this overflowed size is used to allocate a buffer, the buffer will be smaller than expected. A subsequent buffer overflow could result from this poorly sized buffer. The solution for integer overflows involves checking every mathematical operation for overflow. Although this seems straightforward, several potential problems can occur due to the complexity of C/C++’s type system.

IntSafe.h provides addition, subtraction, multiplication, and conversion functions for performing integer operations safely. Use these functions when doing any integer operations with user-supplied data. Each function returns an HRESULT value indicating whether the operation succeeded or if an integer overflow occurred. For more detail, review the IntSafe.h documentation on MSDN (http://msdn.microsoft.com/en-us/library/dd361843%28VS.85%29.aspx). The following sample code shows how to use the DWordAdd function properly:
//dwResult holds the output of the calculation.
DWORD dwResult = 0;

//dwUserData is supplied by the user
//0xFFFF is the value to add to dwUserData
if (FAILED(DWordAdd(dwUserData, 0xFFFF, &dwResult))
{
      //An integer overflow or underflow occurred.
      //Exit the program or handle appropriately.
}

Stack Cookie Protection
The final protection for native code is the Stack Cookie protection mechanism, also referred to as “/GS,” which is the compiler parameter used to turn it on. Stack Cookies are used to mitigate buffer overflows that occur when stack-based data is overwritten. Included on the stack are return addresses, and if these addresses are overwritten an attacker can gain control of a program’s execution. To mitigate this risk, the compiler places a “cookie” between user data and the return address. This cookie is a random value generated on application startup. In order to reach the return address, an attacker has to overwrite the cookie. Before using the return address, the application checks to see if the cookie has been modified. If the cookie has changed, the application assumes a buffer overflow has occurred and the program quickly exits. This mechanism has reduced the exploitability of many stack-based buffer overflows and continues to improve with each new version of Microsoft’s compiler.
Unlike StrSafe.h or IntSafe.h, enabling Stack Cookie protection does not require code modifications because the cookie-checking code is automatically inserted at compile time. Additionally, Stack Cookie protection does not actually remove vulnerabilities from code; it simply makes them more difficult to exploit. Non-stack-based buffer overflows, such as heap overflows, are not mitigated by Stack Cookie protection. Mitigating these vulnerabilities by fixing code is still a necessity. The Visual Studio 2005 compiler enables the /GS flag by default, and forces developers to explicitly disable it. Therefore, almost all recently compiled applications have Stack Cookie protection enabled.
NET Compact Framework Languages
Windows Mobile includes the .NET Compact Framework (.NET CF), a mobile version of Microsoft’s .NET Framework. The .NET CF consists of a runtime, which provides memory management capabilities, and an extensive class library to support application developers. The most current version is 2.0, which is included as part of the Windows Mobile OS. Prior versions of the .NET CF had to be distributed by application developers manually.
.NET CF supports writing code in both Visual Basic .NET (VB.NET) and C# (pronounced C-sharp). This code is referred to as managed code by Microsoft. All managed languages are compiled by the .NET CF to bytecode known as Microsoft Intermediate Language (MSIL). The .NET CF runtime runs MSIL to carry out the program’s instructions. The class library included with the .NET CF is expansive and includes functions for using the majority of the phone’s capabilities. Developers use this class library instead of the Windows Mobile Native API. For cases where the .NET CF does not include a function for using a phone platform, developers can use Platform Invoke (P/Invoke). This is a marshalling method for calling functions contained within native code.
Because the .NET CF runtime manages memory for developers, integer overflows and buffer overflows are very rare in .NET CF code. Generally, memory corruption vulnerabilities only occur when developers misuse P/Invoke functionality. This is because P/Invoke is similar to using the Native API directly, and it is possible to provide incorrect parameters to system calls, thus leading to memory corruption. If developers avoid using P/Invoke, code vulnerabilities should be limited to business logic flaws.
There is a performance impact to using managed code, and developers often choose to write native code for performance-critical applications. As mobile device memory and processing power increase, more developers will write managed applications, thus further reducing the potential for memory management errors.
PythonCE
PythonCE is a port of the popular Python scripting language to Windows Mobile. The runtime is freely available and includes much of the class library and functionality from Python 2.5. Because Python is a scripting language and does not require compilation, it is a useful tool for exploring Windows Mobile. PythonCE is not signed and runs at the Normal privilege level. To call Privileged APIs from PythonCE script, configure the security policy to Unlocked.
To call native platform APIs, use the ctypes interop package. This package can load DLLs, marshal parameters, and call platform methods. Due to a large distribution size and complexity in porting Python to Windows CE, PythonCE development has slowed. The project continues, but updates are slow in coming.

Application Packaging and Distribution

The methods for distributing Windows Mobile applications include CAB files, PC installers, and SMS download. The Cabinet (CAB) file format is used for packaging applications regardless of distribution mechanism. Applications can also be distributed through raw file copy to the device’s file system, but this presents two drawbacks: not having an installer and not having the application registered with the system’s program manager.
CAB Files
The CAB file format was originally developed for distributing desktop Windows installation media and is used in many Microsoft technologies. Each CAB file can contain multiple files and/or directories; optionally, the CAB file can be compressed. Unlike most archive file formats, CAB files are considered executables and are therefore subject to the same security policies. Developers bundle the application and any required resource files within the CAB file; this way, applications can be distributed as one single file. The desktop Windows Explorer supports the CAB file format, so CAB files can be easily opened and extracted on the PC.
Windows Mobile applications packaged in CAB files can also contain custom setup code, application provisioning information, and registry key information. This functionality is implemented not within the CAB format itself, but by including a special provisioning XML document the Windows Mobile application installer looks for. This document must be named _setup.xml and be stored in the root folder of the CAB archive. When the user installs the CAB file, Windows Mobile will open the _setup.xml file and carry out the provisioning instructions within.
The _setup.xml file contains wap_provisioning XML, and it’s capable of modifying much of the device’s configuration. The wap_provisioning format is documented in detail on MSDN and is relatively easy to read after the first couple of times. The registry and file elements are the most interesting when you are security-testing and reverse-engineering an application’s install process. The following XML blob shows the portion of a _setup.xml file used for installing files. Each node includes an XML comment describing the node’s purpose.
<!-- Mark the start of a file operation -->
<characteristic type="FileOperation">
    <!-- Signals a directory node named "\Windows" -->
    <characteristic type="\Windows" translation="install">
        <!-- Instruct the Installer to Create the Directory -->
        <characteristic type="MakeDir" />
        <!-- Signals a file node named "mypro_image.bmp" -->
        <characteristic type="cclark_image.bmp" translation="install">
            <!-- Instruct the installer to expand the file -->
            <characteristic type="Extract">
                <!-- The file "MYPRO~1.001" will be expanded to
                     "cclark_image.bmp" in the "\Windows" directory -->
                <parm name="Source" value="MYPRO~1.001" />
                <parm name="WarnIfSkip" />
            </characteristic>
        </characteristic>
    </characteristic>
</characteristic>

A minor annoyance is that all files stored within the Windows Mobile CAB archive must be named in the 8.3 file format (for example, MYPRO~1.001), a holdover from the format’s use during the days of MS-DOS. Truncated filenames make browsing the CAB file for executables or DLLs difficult. To work around this, either install the application to an emulator and copy the files off, or read _setup.xml to find executable files and their 8.3 sources. Either method involves manual effort, but unfortunately this is the only way.
Windows Mobile files can also contain a CE Setup DLL. This DLL contains native code that is invoked before and after installation. Installation authors use the setup DLL to perform custom installation steps that cannot be expressed using wap_provisioning XML. The DLL will run with the permissions of the CAB file granted by the device’s security policy.
CAB files can be signed with an Authenticode signature. The signature is embedded within the CAB file and maintains the integrity of the CAB file’s metadata and contents. The signature prevents tampering and enables users to make trust decisions based on the publisher of an application. To view the signature, use the Security Configuration Manager tool and select Check File Signature from the File menu. Browse to the desired CAB file and click Open. Security Configuration Manager will display the signature on the CAB file.
To generate CAB files, use the CabWiz.exe tool bundled with Visual Studio. To use this tool properly, an Information File (.INF) must be provided that lists the application’s publisher, files bundled with the application, registry keys and default values, and other information such as the shortcuts to create upon installation. CabWiz.exe consumes the .INF file, generates the appropriate _setup.xml file, renames installation files, and produces the output CAB file. This file can then be signed and deployed to devices.
Manual Deployment
To deploy CAB files manually, copy the CAB file to the device and navigate to the containing directory using the device’s File Explorer. Selecting the CAB file will invoke the installer and process the CAB file. After installation is complete, Windows Mobile displays a status message and adds the program to the device’s Program directory.
PC-based Deployment
Applications can be deployed from a PC when a device is cradled. To package these applications, developers create a Windows Installer package and device CAB package. When the Windows installer runs, it invokes the Mobile Application Manager (CeAppMgr.exe) and registers the application for installation the next time the device is cradled. When the user cradles a device, the Mobile Application Manager is launched and the application is pushed to the device for installation. The user is then able to manage the application through the Mobile Application Manager on their PC. The same signing requirements as manual deployment are enforced.
OTA SMS Deployment
Starting with Pocket PC 2003, applications can be deployed using SMS messages. The SMS messages appear within the user’s Message inbox. When a user reads the message, they can choose whether or not to install the application. If they select to install the application, the CAB file will be downloaded and then executed on the device. Some mobile software providers, such as Handango, distribute purchased applications using this technique.

Mobile Application Security : Windows Mobile Security - Development and Security Testing (part 2)


Mobile Application Security : Windows Mobile Security - Development and Security Testing (part 2)

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
SectionDescription
.textContains the program’s executable code. The name is confusing.
.rdataRead-only data including string-literals, constants, debug data, and other static structures.
.dataInitialized global and static data including the IAT. The .data section is Read/Writable.
.rsrcThe 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.

Mobile Application Security : Windows Mobile Security - Development and Security Testing (part 1)


Mobile Application Security : Windows Mobile Security - Development and Security Testing (part 1)


Several tools for developing Windows Mobile applications are available from Microsoft. Developers can choose between writing code in native C/C++ or in managed code targeting the .NET Compact Framework. Not all .NET languages are supported—only C# and VB.NET. It is not possible to use managed C++ or other .NET languages.

Coding Environments and SDKs

There are two primary development environments for writing Windows Mobile code: Visual Studio and Platform Builder. Visual Studio is for application developers, and Platform Builder is for developers building new embedded platforms or writing device drivers. Most developers will use Visual Studio, whereas OEMs and device manufacturers are more likely to use Platform Builder.
Visual Studio and the Microsoft SDKs
The most popular Windows Mobile development environment is Microsoft’s Visual Studio. Visual Studio includes “Smart Device” templates for creating Windows Mobile applications. Additionally, Visual Studio integrates application deployment and debugging technology to assist during the development cycle. Creating Windows Mobile applications without Visual Studio is possible, but the process is much more manual. Unfortunately, the Express editions of Visual Studio do not support embedded devices, so a paid Visual Studio license is required.
In addition to Visual Studio, the Windows Mobile SDK is required. The SDK contains all of the header files, libraries, and tools necessary to build and deploy applications. When a new version of Windows Mobile is released, Microsoft publishes a new SDK version. Newer SDK versions contain the definitions and libraries required to leverage new functionality. At the time of this writing, the most current version of the Windows Mobile SDK is the Windows Mobile 6 Professional and Standard SDK Refresh. The SDK installation process registers newly installed SDKs with Visual Studio, and the SDK will become selectable during the application-creation process.
Platform Builder
The secondary development environment for Windows Mobile is Microsoft’s Platform Builder. The name says a lot about what it does—Platform Builder enables developers to pick and choose the components they want for a particular embedded platform. If you’re doing Windows CE development and creating a new device, then Platform Builder is an absolute necessity. In the case of Windows Mobile, Microsoft itself assembles the platform and chooses the components to include. Windows Mobile device developers will also use Platform Builder to create their OALs. If you’re developing or testing user applications on Windows Mobile, avoid Platform Builder and use Visual Studio instead. The Platform Builder application must be purchased from Microsoft. Trial versions are available for download from Microsoft.com.

Emulator

Microsoft provides a device emulator and images that can be used to mimic almost any Windows Mobile device currently available on the market. These images only contain features present in the base operating system, and do not include any applications specific to device manufacturers or wireless operators. In addition to base image emulation and debugging, the emulator supports emulation of network cards, cell networks, GPS towers, and SD cards. Because the emulator allows so much control over a device’s functionality, it is a perfect test bed for evaluating Windows Mobile security features and the robustness of individual components.
Microsoft Device Emulator
The Microsoft Device Emulator, version 1.0, is included with Visual Studio 2005–2008 and can be downloaded for free from Microsoft’s website (see Figure 1).
Figure 1. Microsoft Device Emulator running Windows Mobile 6 Classic

The most current version available at the time of this writing is 3.0. If you’re developing on Windows Vista or above, version 2.0 or above is required to support cradling of the device.
The emulator includes several Windows Mobile images, and Microsoft provides new images whenever versions of Windows Mobile are released. Images are distributed for free from Microsoft’s website. All Windows Mobile SKUs are supported, so it is easy to test the differences in behavior among the various SKUs. The emulator can be run independently from Visual Studio or started from Visual Studio directly. If the emulator is linked to Visual Studio, then application deployment and debugging becomes a “one-click” affair.
To automate programs running on the emulator, use the Device Automation Toolkit (DATK). This toolkit includes tools for dumping the graphical elements of an application and then automating them using a .NET Framework API. The API is a little unwieldy, and tests can be difficult to debug. Although not perfect, the DATK can be very helpful when you’re trying to repeat application tests.
Device Emulator Manager
Use the Device Emulator Manager (dvcemumanager.exe) for choosing between images and controlling image power on/power off state (see Figure 2). This tool is installed with the emulator and can control all the currently installed images. Images can be started, stopped, and cradled from within this tool. There is also a command-line tool (DeviceEmulator.exe) for controlling individual images; this executable is installed in the emulator’s program files directory.
Figure 2. Microsoft Device Emulator Manager

In addition to the GUI and command-line interfaces, Device Emulator 3.0 introduces the IDeviceEmulatorManager COM interface. This interface can be used to discover currently installed images and control them. If you’re performing fuzzing or other repetition-based testing, the COM interface is helpful for controlling images.
Cellular Emulator
The Windows Mobile SDK includes a cellular emulator capable of emulating the voice, data, and SMS portions of the cellular network (see Figure 3). The cellular emulator communicates with the emulated device using the device’s serial ports. It is also possible to send fake SMS messages to the device to see how the device behaves.
Figure 3. Microsoft Cellular Emulator

The cellular emulator is helpful to evaluate the cellular features of Windows Mobile when a real device or cellular network is not available. The cellular emulator is included in the Tools portion of the Windows Mobile 6 SDK.

Windows Mobile


Windows Mobile Security - Introduction to the Platform



There are several Windows Mobile variants, and the most common are Windows Mobile 6 Classic, Windows Mobile 6 Standard, and Windows Mobile 6 Professional. The primary difference is that Standard devices do not have a touchscreen, whereas the Professional and Classic variants do. Classic devices may lack cell phone functionality; however, many have Wi-Fi. Windows Mobile includes Mobile Office and Outlook, Pocket Internet Explorer (IE), Windows Media Player, and the .NET Compact Framework 2.0. A robust application ecosystem has developed around Windows Mobile and users can choose between thousands of applications currently available.
Windows Mobile’s user interface and platform API are similar to the desktop variants of Windows, but those differences are only skin deep. The user interface was originally modeled on Windows 95 and even includes a “Start Menu” used to access applications and device settings. Windows Mobile 6.5 added a more touchscreen friendly launch screen, this was the first significant UI change in several versions. To program the device, developers can use a Win32-like API. The Win32 API was originally derived from the Windows 3.0 API and has been the primary API for all versions of Windows NT, including Windows XP and Windows Vista. The APIs and documentation are freely available to developers; however, the platform is not considered fully open because the operating system must be licensed from Microsoft. This licensing is done by device manufacturers on behalf of the end user, and users receive a license when purchasing a Windows Mobile device.

Relation to Windows CE

At the heart of Windows Mobile 6 is Microsoft’s Windows CE platform. Windows CE is a general-purpose embedded platform usable as a base for embedded devices, including cash registers, hand scanners, and industrial assembly robots. Optimized for devices with limited memory, CPU, and storage, Windows CE uses as few resources as possible. Because Windows CE targets so many different embedded uses, platform builders have a large amount of control over which operating system components they decide to include. These components (for example, Pocket IE, DCOM, and Microsoft Mobile Office) are the building blocks for the platform. Platform builders mix and match these components to create versions of Windows CE containing exactly what is required.
Windows Mobile is a Microsoft-assembled distribution of Windows CE containing the drivers and components necessary to serve as a mobile phone platform. Additionally, Microsoft has placed artificial barriers on the form factors and capabilities supported by Windows Mobile devices. By standardizing the components and form factors available, Microsoft enables developers to target all Windows Mobile devices. Because Windows Mobile is more specialized than the general-purpose Windows CE, Windows Mobile does not support all of the functionality possible in Windows CE.
Windows Mobile devices target the ARMV4 and ARMV4I platforms exclusively. However, Windows CE can support alternative platforms, including MIPS, x86, and Super-H. Depending on mobile processor innovations, Windows Mobile may be adapted to these platforms in the future.
The most current Windows CE version is Windows CE 6.0. This version contains a significant re-architecture of the kernel designed to support the larger processing and memory capabilities of modern portable devices. Windows Mobile 6 is still based on the Windows CE 5.2 kernel. This confusing nomenclature can be blamed on the parallel development timelines for Windows Mobile 6.0 and Windows CE 6.0. The CE 6.0 kernel became available late in the Windows Mobile 6.0 development cycle and it was too risky to adopt the unproven kernel. Because a Windows Mobile operating system based on Windows CE 6.0 has not yet been released, the kernel-level descriptions contained within this article describe Windows CE 5.2. Microsoft has stated that Windows Mobile 7 will be based on the Windows CE 6.0 kernel.

Device Architecture

Windows Mobile devices, regardless of hardware, implement a layered OS design, with Microsoft providing the majority of software components and device manufacturers supplying the driver software required to interface with the device’s hardware. Mobile network operators may add additional hardware, but it is not required. Figure 1 illustrates the layout of a Windows Mobile device.
Figure 1. OS_Architecture.tif

Hardware Layer
The hardware layer represents the actual physical hardware on the device. Windows Mobile is agnostic to this layer and knows nothing about it except as capabilities exposed through the OEM Abstraction Layer (OAL).
OEM Abstraction Layer (OAL)
A main difference between PC platforms and Windows Mobile platforms is the introduction of an OEM Abstraction Layer (OAL). This layer contains the boot loader, platform configuration files, and drivers used by Windows Mobile to communicate with the device’s hardware. The OAL is what allows Windows Mobile to run on such a broad range of hardware platforms. Each device has a device-specific OAL that drives the device’s individual hardware. The OAL accepts standard messages from the kernel and maps these to messages understood by the hardware. In this way, the OAL is similar to the Hardware Abstraction Layer (HAL) that exists in Windows NT. To simplify OAL creation, Microsoft has released the Production Quality OAL. This library provides a base OAL implementation into which OEMs can more easily add device-specific code.
The OAL’s bootloader loads the OS image from storage and jumps to the OS start point. A bootloader is not required, and the same functionality can be integrated into the device’s reset process.
Kernel Layer
The Kernel Layer manages the overall system and physical resource allocation. The kernel provides standard services to user applications and interfaces with the OAL to manipulate hardware. In addition to nk.exe, which is the main kernel executable, several other critical services run within the Kernel Layer. The Object Store is also implemented within this layer.
User Application Layer
The User Application layer is where user or OEM installed applications execute. Each application resides within its own address space and uses kernel interface to control the device.

Device Storage

Storage on a Windows Mobile device is very different from storage on a Windows desktop PC. Read-only memory (ROM) and random access memory (RAM) exist on every device. System files and OEM-supplied applications are stored within ROM and cannot be modified while the device is running. RAM is divided into two areas: memory used by applications and memory used by the Object Store. Additional storage locations, such as a flash memory card, are device specific and not required to exist.
The Object Store
The Object Store contains user and system data and is a virtualized view of the device on top of the file system and the registry. Contained within nonvolatile RAM, the Object Store persists user data, even when the primary power to the device is lost. This data is combined with system data when the device undergoes a warm reboot. In this type of reboot, the device is reset, but all data is not wiped from the Object Store. A cold reboot or hard reset is when all power, both primary and backup, has been exhausted. In these cases, the Object Store reverts to the copy stored in ROM. The Object Store appears as a file system within the device but is often implemented as storage. Users and the systems can store data within this file system.
ROM
All of the operating system and OEM-provided files are stored within the device’s ROM image. Generally, this ROM image is only flashable through OEM device-flashing methods. ROM persists even when all power to the device has been exhausted.

Windows Mobile Security - Kernel Architecture


Windows Mobile 6 uses the Windows CE 5.2 kernel. The 5.1 version of this kernel served as the basis for Windows Mobile 5. Because the behaviors of the 5.1 and 5.2 CE kernels are so similar.
Windows Mobile 6.1 confused the situation further by tweaking memory management but not updating the actual CE kernel version. Notable differences between the Windows CE 5.x and Windows CE 6.0 kernels will be called out when appropriate. Remember the CE 6.x kernels are not in use for any currently available Windows Mobile devices.
Windows CE was developed specifically for embedded applications and is not based on the Windows NT kernel used in Microsoft’s desktop and server operating systems. Even though the two platforms are different, those familiar with the Windows NT kernel will recognize many of the primitives and concepts used by the Windows CE kernel. The devil remains in the details, and those familiar with how Windows NT manages security are recommended to forget that information promptly. The same security model does not apply in the mobile world.
The Windows CE 5.x kernel is a fully preemptive and multithreaded kernel. Unlike Windows NT, Windows CE is a single-user operating system. Security is handled by assigning each process a trust level that is tracked and managed by the kernel. Common Windows NT primitives such as security descriptors (SDs) and access control lists (ACLs) do not exist. 
The Windows CE kernel handles memory management as well as process and thread scheduling. These services are implemented within the nk.exe executable. Other kernel facilities such as the file, graphics, and services subsystems run within their own processes.

Memory Layout

Windows Mobile 6.x uses a unique “slot-based” memory architecture. When a Windows Mobile device boots, the kernel allocates a single 4GB virtual address space that will be shared by all processes. The upper 2GB of this virtual memory (VM) address space is assigned to the kernel. The lower 2GB region is divided into 64 slots, each 32MB large.
The lower 32 slots contain processes, with the exception of Slot 0 and Slot 1. Slot 0 always refers to the current running process, and Slot 1 contains eXecute-in-Place (XiP) dynamic link libraries (DLLs).
DLLs contain library code loaded at application runtime and referenced by multiple running applications. Sharing code with DLLs reduces the number of times that the same code is loaded into memory, reducing the overall memory load on the system. XiP DLLs are a special kind of DLL unique to Windows CE and Windows Mobile. Unlike normal DLLs, XiP DLLs exist in ROM locations and therefore are never loaded into RAM. All DLLs shipped in the ROM are XiP, which goes a long way toward reducing the amount of RAM used to store running program code. Above the process slots is the Large Memory Area (LMA). Memory-mapped file data is stored within the LMA and is accessible to all running processes.
Above the LMA is a series of reserved slots. Windows Mobile 6 has only one reserved slot, Slot 63. This slot is reserved for resource-only DLLs. Windows Mobile 6.1 added four additional slots: Slot 62 for shared heaps, Slots 60 and 61 for large DLLs, and Slot 59 for Device Manager stacks. These additional slots were added to address situations where the device would have actual physical RAM remaining but the process had exhausted its VM address space.
A process’s slot contains non-XiP DLLs, the application’s code, heap, static data, dynamically allocated data, and stack. In Windows Mobile 6.1, some of the non-XiP DLLs may be moved into Slots 60 and 61. Moving the non-XiP DLLs into these slots removes them from the current process’s memory slot, freeing that virtual memory to be used for application data. Even though DLLs are loaded into the same address space for all processes, the Virtual Memory Manager (VMM) prevents applications from modifying shared DLL code.
To maintain the reliability and security of the device, the VMM ensures that each process does not access memory outside of its assigned slot. If processes could read or write any memory on the system, a malicious process could gain access to sensitive information or modify a privileged process’s behavior. Isolating each application into its own slot also protects the system from buggy applications. If an application overwrites or leaks memory, causing a crash, only the faulting application will terminate and other applications will not be affected. The check is performed by verifying the slot number stored in the most significant byte of a memory address.
OEM and other privileged applications can use the SetProcPermissions, MapCallerPtr, and MapPtrProcess APIs to marshal pointers between processes (refer to http://msdn.microsoft.com/en-us/library/aa930910.aspx). These APIs are not exposed as part of the Windows Mobile SDK and are only used by device driver writers. To call these APIs, applications must be running at the Privileged level.
When Windows CE was first introduced, embedded devices with large amounts of RAM were very rare, and it was unlikely that a process could exhaust all of its VM space. Modern devices have much more memory, and the Windows CE 6.0 kernel abolishes the “slot” layout in favor of providing each process with a full 2GB VM address space. This new architecture is much more robust and closely resembles a traditional desktop OS architecture.

Windows CE Processes

A process in Windows CE is a single instance of a running application. The Windows CE 5.x kernel supports up to 32 processes running at any one time. Thirty-two is a bit of a misnomer because the kernel process (nk.exe) always occupies one slot, leaving 31 slots available for user processes. Each process is assigned a “slot” in the kernel’sprocess table. Some of the slots are always occupied by critical platform services such as the file system (filesys.exe), Device Manager (device.exe), and the Graphical Windowing Environment System (GWES.exe). The Windows CE 6.0 kernel expands this limit to 32,000. However, there are some restrictions that make this number more theoretical then practical. Additionally, the previously mentioned critical platform services have been moved into the kernel to improve performance.
Like in Windows NT, each process has at least one thread, and the process can create additional threads as required. The number of possible threads is limited by the system’s resources. These threads are responsible for carrying out the process’s work and are the primitives used by the kernel to schedule execution. In fact, after execution has begun, the process is really only a container used for display to the user and for referring to a group of threads. The kernel keeps a record of which threads belong to which processes. Some rootkit authors use this behavior to hide processes from Task Manager and other system tools.
Each thread is given its own priority and slice of execution time to run. When the kernel decides a thread has run for long enough, it will stop the thread’s execution, save the current execution context, and swap execution to a new thread. The scheduling algorithm is set up to ensure that every thread gets its fair share of processing time. Certain threads, such as those related to phone functionality, have a higher priority and are able to preempt other running threads when necessary. There are 256 possible priority levels; only applications in privileged mode are able to set the priority level manually.

Services

Some applications start automatically and are always running in the background. These processes, referred to asservices, provide critical device functionality or background tasks. Service configuration information is stored within the registry, and services must implement the Service Control interface so that they may be controlled by the Service Configuration Manager (SCM).

Objects

Inside the kernel, system resources are abstracted out as objects. The kernel is responsible for tracking an object’s current state and determining whether or not to grant a process access. Here are some examples of objects:
  • Synchronization objects (Event, Waitable Timer, Mutex, and Semaphore)
  • File objects, including memory mapped files
  • Registry keys
  • Processes and threads
  • Point-to-point message queues
  • Communications devices
  • Sockets
  • Databases
Objects are generally created using the Create*() or Open*() API function (for example, the event-creation API, CreateEvent). The creation functions do not return the actual objects; instead, they return a Win32 handle. Handles are 32-bit values that are passed into the kernel and are used by the Kernel Object Manager (KOM) to look up the actual resource. This way, the kernel knows about and can manage all open references to system objects. Applications use the handle to indicate to the kernel which object they would like to interact with.
Applications can choose to name their objects when creating or referencing them. Unnamed objects are generally used only within a single process or must be manually marshaled over to another process by using an interprocess communication (IPC) mechanism. Named objects provide a much easier means for multiple processes to refer to the same object. This technique is commonly used for cross-process synchronization. Here’s an example:
  1. Process 1 creates an event named FileReadComplete.
  2. The kernel creates the event and returns a handle to Process 1.
  3. Process 2 calls CreateEvent with the same name (FileReadComplete).
  4. The kernel identifies that the event already exists and returns a handle to Process 2.
  5. Process 1 signals the event.
  6. Process 2 is able to see the event has been signaled and starts its portion of the work.
In Windows Mobile, each system object type exists within its own namespace. This is different from Windows NT, where all object types exist within the same namespace. By providing a unique namespace per object type, it is easier to avoid name collisions.
The KOM’s handle table is shared across all processes on the system, and two handles open to the same object in different processes will receive the same handle value. Because Win32 handles are simply 32-bit integers, malicious applications can avoid asking the kernel for the initial reference and simply guess handle values. After guessing a valid handle value, the attacker can close the handle, which may cause applications using the handle to crash. In fact, some poorly written applications do this accidently today by not properly initializing handle values.
To prevent a Normal-level process from affecting Privileged-level processes, the object modification APIs check the process’s trust level before performing the requested operation on the handle’s resource. These time-of-use checks stop low-privileged processes from inappropriately accessing privileged objects, but they do not stop malicious applications from fabricating handle values and passing those handles to higher privileged processes. If the attacker’s application changes the object referred to by the handle, the privileged application may perform a privileged action on an unexpected object. Unfortunately, this attack cannot be prevented with the shared handle table architecture (refer to http://msdn.microsoft.com/en-us/library/bb202793.aspx).
Windows CE 6.0 removes the shared handle table and implements a per-process handle table. Handle values are no longer valid across processes, and it is not possible to fabricate handles by guessing. Therefore, attackers cannot cause handle-based denial-of-service conditions or elevate privileges by guessing handle values and passing them to higher privilege processes.
Remember that Windows Mobile does not support assigning ACLs to individual objects. Therefore, any process, regardless of trust level, can open almost any object. To protect certain key system objects, Windows Mobile maintains a blacklist of objects that cannot be written to by unprivileged processes. This rudimentary system of object protection is decent, but much data is not protected. 

Kernel Mode and User Mode

There are two primary modes of execution on Windows CE 5.x devices: user mode and kernel mode. The current execution mode is managed on a per-thread basis, and privileged threads can change their mode using the SetKMode() function. Once a thread is running in kernel mode, the thread can access kernel memory; this is memory in the kernel’s address space above 0x8000000. Accessing kernel memory is a highly privileged operation because the device’s security relies on having a portion of memory that not all processes can modify. Contained within this memory is information about the current state of the device, including security policy, file system, encryption keys, and hardware device information. Reading or modifying any of this memory completely compromises the security of the device.
The concept of kernel mode and user mode is not unique to Windows Mobile—most operating systems have a privileged execution mode. Normally the OS uses special processor instructions to enter and exit kernel mode. Windows Mobile differs because the actual processor execution mode never changes. Windows Mobile only changes the individual thread’s memory mapping to provide a view of all memory when the thread enters kernel mode.
Application threads most often run in user mode. User mode threads do not have total access to the device and must leverage kernel services to accomplish most of their work. For example, a user mode thread wishing to use the file system must send a request through the kernel (nk.exe) to the file system process (FileSys.exe).
The request is carried out by using Windows CE’s system call (syscall) mechanism. Each system API is assigned a unique number that will be used to redirect the system call to the portion of system code responsible for carrying out the work. In many cases, this code is actually implemented in a separate process. The entire syscall mechanism works as follows:
  1. An application thread calls a system API (for example, CreateFile).
  2. The CreateFile method is implemented as a Thunk, which loads the unique number that identifies this call to the system. This number is a 32-bit number representing an invalid memory address.
  3. The Thunk jumps to this invalid memory address, causing the processor to generate a memory access fault.
  4. The kernel’s memory access handler, known as the pre-fetch abort handler, catches this fault and recognizes the invalid address as an encoded system call identifier.
  5. The kernel uses this identifier to look up the corresponding code location in an internal table. The code location is the actual implementation of the system API. In the case of CreateFile, this code resides within the memory space of FileSys.exe.
  6. If the kernel wants to allow the call, it changes the thread’s mode to kernel mode using SetKMode().
  7. The kernel then sets the user mode thread’s instruction pointer to the system API’s code location.
  8. The system API carries out its work and returns. When the process returns, it returns to an invalid address supplied by the kernel. This generates another memory access fault, which is caught by the kernel.
  9. The kernel recognizes the fault as a return address fault and returns execution to the user mode thread. The kernel also sets the thread’s execution mode back to user mode.
Throughout this process, the application code is always running on the same thread. The kernel is performing some tricks to change which process that thread executes in. This includes mapping pointers between the source process and the target process. One potential security problem is that a process could pass pointers to memory that it doesn’t have access to. For example, a malicious program is running in the memory range 0x880CB0C4 and passes a pointer in the range 0xD6S7BE42. After the kernel has performed operations on the malicious pointer, the memory in Process 2 would be modified—a clear security issue. The kernel prevents this attack by checking the top byte of the memory address against the process’s memory slot to verify that the calling process actually has access to the memory.
The system call process is complex and incurs a severe performance penalty due to the time required to handle faults, perform lookups, map memory, and jump to the corresponding locations. If the thread is already executing in kernel mode, the fault-handling process can be bypassed and the thread can jump directly to the system call implementation. Some Windows CE 5.x drivers do this. The Windows CE 6.0 kernel is significantly faster because core services such as Devices.exe, GWES.exe, and FileSystem.exe have been moved into the kernel, reducing the number of syscalls.