CHAPTER 4
Windows Mobile Security

image

Windows Mobile is Microsoft’s operating system for mobile phones. First introduced in 2000 as Windows CE Pocket PC, the most current version is Windows Mobile 6.5 with Windows Mobile 7 expected in late 2010. Windows Mobile 6.5 is an incremental upgrade from Windows Mobile 6.1 which was itself an incremental upgrade from Windows Mobile 6. This chapter will refer to Windows Mobile 6.1 except for specific differences.

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 chapter 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 4-1 illustrates the layout of a Windows Mobile device.

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).

image


Figure 4-1 OS_Architecture.tif

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. A more in-depth exploration of the Kernel Layer, including its responsibilities and architecture, is contained in the “Kernel Mode and User Mode” section of this chapter.

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.

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, this chapter refers to both as the 5.x series. 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. More information about the security model is contained within the “Permissions and User Controls” section of this chapter.

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’s process 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 as services, 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:

image    Synchronization objects (Event, Waitable Timer, Mutex, and Semaphore)

image    File objects, including memory mapped files

image    Registry keys

image    Processes and threads

image    Point-to-point message queues

image    Communications devices

image    Sockets

image    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. More detail is contained within the “Permissions and User Controls” section of this chapter.

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.

Development and Security Testing

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 4-2). 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.

image


Figure 4-2 Microsoft Device Emulator running Windows Mobile 6 Classic

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 4-3). 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.

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 4-4). 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.

image


Figure 4-3 Microsoft Device Emulator Manager

image


Figure 4-4 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.

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 4-1). 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.

image

Table 4-1 Description of the Major Sections Contained Within a PE Binary

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.

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.

Permissions and User Controls

The Windows Mobile security model does not have an expressive permission or user control system. In fact, the concept of users does not even exist in Windows Mobile! Instead, permissions are assigned on a per-application basis. Windows Mobile Standard devices support two possible privilege tiers for applications to run at: Privileged and Normal. Windows Mobile Classic and Professional devices support only the Privileged tier. The privilege level is decided based on the device’s security policy and assigned to a process at start time. Network operators or the device owner are responsible for configuring and deploying this policy, which is stored on the device as XML.

Privileged and Normal Mode

Privileged mode applications are able to read and modify any data on the device, configure device settings, modify other processes, and switch to kernel mode. In short, they have total control over the device. Any application that is allowed to run on a Windows Mobile Classic or Professional device will run as Privileged.

The Normal privilege level was introduced so that mobile carriers and enterprise device administrators could have more control over their devices. Normal applications are unable to modify sensitive portions of the device’s configuration and file system, such as the security policy and driver configurations. Additionally, they cannot enter kernel mode or modify other processes. They are able to use much of the device’s functionality, including Phone, Mobile Office, and SMS. The Normal privilege tier is available only on Windows Mobile Standard devices; however, not all Standard devices use the two-tier privilege model. Changing the Privileged mode requires a complete flash of user data and is therefore not normally done during the device’s lifetime.

To block access to the device’s configuration, certain APIs and file and registry locations are only available in Privileged mode. The list of Privileged APIs is included within the SDK and maintained by Microsoft. To see the most current list of Privileged APIs and protected locations, read the “Privileged APIs” topic within the Windows Mobile 6 SDK documentation on MSDN (http://msdn.microsoft.com/en-us/library/aa919335.aspx).

Authenticode, Signatures, and Certificates

The device decides the privilege level based on the application’s Authenticode signature. Authenticode is a Microsoft technology for attaching cryptographic signatures to various file types. The signature uses public key cryptography to ensure that the application has not been modified. If the application is tampered with, the signature will be invalidated. Associated with the key pair is a X.509 certificate. This certificate includes information about the developer of the application and is issued by a Certification Authority (CA). The CA is responsible for verifying who the developer is before issuing the certificate. After verifying the developer’s identity, the CA signs the developer’s certificate using the CA root certificate. A developer’s certificate signed by a CA root certificate is “chained to” that root. Multiple CAs are currently issuing certificates, and there are many types of certificates. All certificates are cryptographically equivalent and are only differentiated by their marked usages. The certificates used by Windows Mobile are marked valid for code signing.

On Windows Mobile devices, the common file types with signatures are CAB files, EXE executables, and DLLs. Before releasing an application, the application’s developer generates the signature and signs the application using Authenticode. Once an application is signed, the application cannot be modified without invalidating the signature. Users and the Windows Mobile OS can make trust decisions based on a valid signature and whether or not the application developer is trusted. Not all applications must be signed, and not all signed applications can be trusted. Whether or not the application should run is up to the device’s security policy and, in some cases, the user.

Signed applications can still have security vulnerabilities or be malicious. The signature process only adds accountability. Because the publisher information is included in the Authenticode signature, users can see who actually wrote the application. Once users choose to run the application, all bets are off, and the application can perform any operation allowed by its privilege level.

Certificate Stores

Each Windows Mobile device has several collections of certificates, called certificate stores. Each store is named and can contain either CA root certificates, developer certificates, or a combination thereof. The certificates are stored with their associated public keys. If a certificate is valid for a particular usage on the device, it will be placed into the appropriate store. The code-execution certificate stores are populated by privileged code; for two-tier devices this means the content is generally fixed before the device is sold to the end user. The following table outlines the application certificate stores and their usages; there are other certificate stores, but these are not used for determining an application’s privilege level.

Public Key Cryptography

Public key cryptography, also known as asymmetric cryptography, requires a key pair consisting of two parts: a public key and a private key. The two are linked mathematically. The public portion can be freely distributed whereas the private portion must be kept secret. Data encrypted with the public key can only be decrypted by the associated private key, and vice versa. Cryptographic signatures use a one-way hash function to generate a unique hash of the body; this hash is then encrypted with the private key. This encrypted hash is referred to as the signature. The signature and the data are sent to users. When verifying a signature, the user uses the one-way hash function to generate a hash from the data. Then using the public key, the user decrypts the signature, which yields the original hash. These hashes are compared; if they do not match, the data has been modified.

image

Mobile2Market Certificates

Many different mobile providers offer Windows Mobile devices. Remember that providers are responsible for the shipped contents of a device’s certificate stores. To avoid having developers sign applications for each different provider, Microsoft created the Mobile2Market (M2M) program. This program identifies CA root certificates that should be included on every Windows Mobile device. Developers can then get a certificate from a M2M CA and be confident that their signature will be valid on any Windows Mobile device. The CA and Microsoft publish M2M developer requirements. Developers meeting these standards are able to purchase M2M certificates for signing their applications.

There are two tiers of M2M: Normal and Privileged. At the time of this writing, all Windows Mobile 6 devices include the Normal M2M certificate. Most operators include the M2M certificate; however, the requirements for obtaining these certificates are much more stringent, and developers must submit their applications for testing and evaluation.

Emulator and Developer Certificates

The Windows Mobile emulator images contain test certificates, and the private keys for these certificates are distributed along with the Windows Mobile SDK. Developers can sign their applications with these certificates during the development process to test out application behavior without having to purchase a certificate. Most mobile operators also run a developer program, where developers can get development certificates. The CA root certificates for these certificates are not installed on production devices. It is a good security practice to sign applications with an emulator or development certificate during development and testing. The actual code-signing certificate should be kept secure and only be present on the machine used to create release builds. This prevents the certificate from being stolen or accidently disclosed and used to create sign malicious code. For best results, rotate certificates once per every two major releases. This way, the amount of code signed by a protected certificate can be minimized and incident response is hopefully much easier.

Revoking Applications

If an application is unreliable or malicious, the application can be revoked and will not be allowed to run. All applications by a publisher are revoked by disallowing the publisher’s certificate. Unsigned applications or a single app by a publisher are revoked by creating a one-way hash of the application and distributing the hash using XML policy. Individual CAB files may also be revoked using the same mechanism.

Revocation is performed using the revoke.exe tool included with the Windows Mobile SDK. The tool creates an XML blob that the mobile operator pushes out through their network. Upon receiving the XML, the device updates the revocation store to prevent the publisher’s applications, individual applications, and installations from running. Mobile operators may use this functionality to block the spread of viruses through their networks or kill applications that have violated the network’s development agreements. If a device is already compromised, revocation may not be effective because the device can ignore revocation messages.

Running Applications

Each device has a security policy that decides which applications will be allowed to run. The security policy is only updatable by privileged applications or by the wireless operator pushing out new policy via SMS. The policy is a collection of various settings, but the setting combinations detailed in Table 4-2 are the most common.

The prompts presented for unsigned applications are rudimentary and grant access to the application based on the current security policy (see Figure 4-5). For example, on a One-Tier Prompt device, the application will run at the Privileged level. If a user cancels a prompt, the application will not run.

image

Table 4-2 Standard Device Security Policies

Once a user accepts a prompt, Windows Mobile stores a cryptographic hash of the application, and the user will never be prompted again for that application. If the application is recompiled, the hash will change and the user must once again accept the prompt. This policy prevents the user from having to answer multiple prompts for the same application.

Locking Devices

Devices may contain sensitive corporate data that, when lost, is very damaging. To prevent misuse, users can lock a device, preventing all use of the device. To unlock the device, users can specify either a numerical PIN code or a strong alphanumeric code. The lock can be activated manually or after an inactivity timeout. In a large enterprise, device administrators often push out a security policy requiring devices to lock after a specified amount of time. Administrators can also specify that a device should wipe data if a certain number of invalid PIN codes are entered. Removable storage cards are not wiped. Interestingly, Windows Mobile contains an interstitial screen between each PIN attempt. This way, a user’s device won’t be accidently wiped if it is in the user’s bag or pocket and the PIN is accidently pressed. In an enterprise environment, the device PINs can be escrowed through Exchange so that they can be recovered in case they are forgotten. If the device is wiped, data on the device cannot be recovered.

image


Figure 4-5 Windows Mobile 6 prompt when running an unsigned application

The lock code prevents the device from being accessed when cradled in a PC. If the device is locked and then cradled, the user will have to enter the PIN code on the device before the cradling operation can complete. The code is entered on the device so that it is never disclosed to the PC. The cradle security mechanisms prevent an attacker from finding a device and then pulling all the data off it using a PC.

Managing Device Security Policy

While you’re developing and performing security testing, playing around with a device’s security policy can provide a lot of insight into how the application works. To make managing security policies simple, Microsoft provides the Security Configuration Manager PowerToy (see Figure 4-6). This tool can be downloaded from Microsoft’s website (http://www.microsoft.com/downloads/details.aspx?FamilyID=7e92628c-d587-47e0-908b-09fee6ea517a&displaylang=en). The tool can be used against real devices and the emulator.

To use the Security Configuration Manager PowerToy, install it, cradle the device, and start the tool. On the right side, the tool shows the device’s current security policy. On the left side, there is a drop-down list containing common security policies. After selecting a policy, click Provision and the policy will be pushed to the device. The policy is pushed by generating a CAB Provisioning File (CPF) containing the policy and signing the CPF with a development certificate. If the development certificate root is not installed on the device, the device may show a prompt. At the bottom of the tool are several tabs showing the contents of the device’s certificate stores. New certificates can be added through the Device menu.

image


Figure 4-6 The Security Configuration Manager PowerToy setting a device’s security policy

The tool can also be used to display the signature on a package. To do so, click the File menu, select Check File Signature, browse to the file, and click OK. The tool will display the package’s signature and relevant information. Signing with the development certificates is also possible using this tool.

If you are using Visual Studio 2008, the Security Configuration Manager PowerToy is integrated directly into Visual Studio and is much easier to use. To use the Visual Studio 2008 version, follow these steps:

1. Either start an emulator or connect a device to the computer.

2. Start Visual Studio 2008.

3. Select Tools | Device Security Manager. In the left panel will be a list of the currently connected devices.

4. Choose the desired security configuration from the list of security configurations in the right panel.

5. Click Deploy to push the new configuration to the device.

Use the security configuration tools to experiment with security policies. This will help drive home the information you’ve learned in this chapter.

Local Data Storage

Windows Mobile supports storing information in the device’s nonvolatile memory and on external flash memory cards, if they are available. The data in nonvolatile memory will persist until the device is hard reset or cold booted. Developers have several options available for storage encryption.

Files and Permissions

Files can be stored in either the Object Store, internal flash memory, or on external flash memory cards. Because there are no users, there are no file-level permissions. However, some files can be written only by processes running at the Privileged level. These files are marked with the SYSTEM file attribute and include system files or sensitive device configuration data. All files are readable by all processes, regardless of privilege level. Most of the user’s data, including Outlook and application data, is accessible to all applications running on the device.

Much like its desktop counterparts, Windows Mobile has a registry that contains device configuration information. The registry is laid out as a tree structure with each node called a key. Each node can have multiple named values. There are several possible data types for values, and they are what hold the actual configuration data. The tree’s root nodes are hives. The two main hives are HKEY_LOCAL_MACHINE (HKLM) and HKEY_CURRENT_USER (HKCU). HKLM holds device-wide configuration, and HKCU holds user-specific information. It doesn’t make much sense to have HKCU on a Windows Mobile device because there is only one user; still, it exists.

The entire registry is readable by all applications, so it is not possible to hide data within the registry. However, certain locations can only be updated by Privileged processes. These locations include device configuration information that either mobile operators don’t want users to update or that could be leveraged by malicious applications to elevate to Privileged level. For example, certificate stores are in the registry and should not be updated by applications running at the Normal privilege level. The write permissions on the registry keys are checked when the application calls one of the update registry APIs: RegSetValueEx, RegCreateKeyEx, RegDeleteKey, or RegDeleteValue.

The following keys are only accessible when running at Privileged level:

image

Stolen Device Protections

As mentioned earlier, Windows Mobile devices can be locked with a PIN that, if misentered, will cause the device to wipe itself. Any data on removable storage cards will not be wiped. Windows Mobile 6 adds support for encrypting data on removable storage cards; this feature is covered in more detail later in this chapter. Enterprise device administrators can also wipe data remotely by pushing out policy through Exchange. When the device syncs, it will receive the wipe policy and delete all non-storage card data.

Structured Storage

Windows Mobile 6 includes Microsoft Compact SQL Server 3.5 as part of the OS ROM image. Compact SQL Server is a full relational database engine and is file based (SDF files). Users connect to the database using a standard SQL connection string, and the database is manageable using SQL Management Studio.

SQL Server 3.5 supports password-based database encryption and integrity protection. The entire database file is encrypted using AES 128 and integrity protected using SHA-1. To enable encryption, include “Password=password” in the database connection string. The responsibility for managing the password is placed on the application developer, and the encryption option must be specified at database creation time.

Encrypted and Device Secured Storage

Windows Mobile does not support encryption of the entire device. However, encryption of removable storage cards is supported starting in Windows Mobile 6. Protection of on-device data is provided by prohibiting access to the device unless the proper unlock code is specified. All data is wiped from the device when a hard reset or cold boot is performed, which is the only way to bypass the PIN. Therefore, the data is protected while the device is running. An attacker could hack the hardware to gain access to in-memory data, a sophisticated attack which is not currently mitigated.

Encryption of removable cards works by generating a key and storing that key in memory using the Data Protection API (DPAPI), a technology that will be discussed shortly. The key is erased upon hard reset, and the card is only usable in that particular device. The encryption algorithm used by default is AES 128, although RC4 may be used as well. When files are transferred to a desktop PC from the device, they are decrypted before transfer.

Data Protection API (DPAPI)

DPAPI is a technology ported from the Windows desktop OS. It includes two APIs: CryptProtectData, for encrypting data, and CryptUnprotectData, for decrypting data. Multiple keys can be used to encrypt data: the SYSTEM key and the USER key. Both keys are generated by the device automatically and stored in kernel memory. If the device is hard reset, both keys will be lost and the data cannot be decrypted. Only Privileged applications can use the SYSTEM key. DPAPI uses AES 128 for encryption and SHA-1 for integrity protection. Applications using DPAPI protect the data using CryptProtectData and receive back an encrypted blob; the application is responsible for storing the blob.

Because DPAPI only has two keys, there is no way to prevent one application from decrypting another application’s data. Therefore, all applications running at Normal level can unprotect all blobs protected with the USER key. Regardless, DPAPI provides a good technology for storing data securely on a device. Users unable to run arbitrary code or only able to browse the file system and registry will be unable to decrypt DPAPI-protected data.

Crypto API

Windows Mobile includes a subset of the Crypto API (CAPI), a general-purpose cryptographic API. With the CryptXXX series of functions, CAPI provides symmetric and asymmetric encryption support, one-way hash functions, and HMAC support. Developers can use these functions to perform advanced encryption operations.

CAPI also includes the CertXXX collection of functions for manipulating certificates and performing certificate operations. CAPI is very powerful and reasonably documented, so developer have a good option available when performing cryptographic operations.

Networking

Windows Mobile includes several options for networking, and most programming is performed through the standard WinSock API. All Windows Mobile devices support data plans allowing complete Internet access. Recently, an increasing number of devices are able to use Wi-Fi when associated with a local access point. Additionally, Windows Mobile devices can use a PC’s network connection when cradled. This feature is called passthrough networking.

Connection Manager

Windows Mobile devices can exist on several different networks at any one time. The Connection Manager (CM) component is responsible for managing network connections and determining the most efficient, secure, and cost-effective route. CM performs the hard work of juggling the different networks that a mobile device travels between. Connection Manager is accessible through the Win32 API and the ConnMgrXXX group of functions.

To manage network security, CM maintains a security level for each connection and network. This security level is represented by a DWORD on a sliding scale, with 1 being the most secure. Applications can request that CM provide a network connection with a minimum security level. If no connection exists at the desired security level, CM will attempt to find a network and create a connection at the desired security level. If no connection is available, CM will return an error code. Regardless of the security level managed by CM, application developers must always be aware of the end network that their traffic will travel across and design their applications accordingly. For example, the most secure type of connection is a Desktop-Passthrough (DTPT) connection. Most DTPT connections eventually route to the Internet, so although the actual device-to-computer connection may be secure, the end path is not.

WinSock

Included in Windows Mobile is a complete Berkeley Sockets API implementing the standard socket functions (connect, recv, send, accept, and so on). This API supports generic sockets and is used for IPv4, Bluetooth, and Infrared Data Access (IrDA) connections. Both client and server roles are possible. A complete IPv4 stack is provided with support for the TCP and UDP transport layer protocols.

IrDA

On devices with an infrared port, Windows Mobile supports infrared networking for in-range devices. To interface with IrDA, the standard WinSock API is used with the AF_IRDA address family. A major difference between IrDA networking and standard IPv4 networking is name resolution. IR devices tend to move in and out of range, so standard name-to-address resolution would not work very well. Instead, addressing information is contained in-band. To discover devices, use the WinSock connect method and request an IAS_QUERY of the surrounding area. Windows Mobile will perform a sweep of the IR network, discover devices, and return available addresses.

Bluetooth

Bluetooth support is included using the WinSock API. To use Bluetooth, use the AF_BTH address family with the WinSock APIs. Windows Mobile can manage the pairing of devices, but it may be up to a particular application to accept a PIN on behalf of a user. For more information, consult the WinSock and Bluetooth documentation on MSDN.

HTTP and SSL

Windows Mobile includes a port of the Windows Internet (WinInet) library. This library is the HTTP backend for Pocket Internet Explorer (IE) but is usable by application developers as well. WinInet includes client support for HTTP, HTTPS, and FTP. As an API, WinInet can be a little bit complicated, and it is obvious that it was originally designed as the internal backend for IE.

WinInet supports authentication using NTLM and basic authentication. More authentication types can be added by catching HTTP 401 (Forbidden) errors and managing the authentication headers manually. Kerberos and domain-joined authentication functionality are not supported.

The Secure Channel (SChannel) Security Support Provider (SSP) implements a complete SSL stack with support for client certificates. WinInet uses SChannel for SSL functionality. Application developers wishing to create SSL tunnels can do so by manually using SChannel and the Security Support Provider Interface (SSPI) functions.

To create a secure SSL connection, the identity of the server’s certificate must be cryptographically verified and “chained” to a root certificate. Windows Mobile keeps a collection of root certificates in an internal certificate store. You can view this store by launching the Settings application, choosing the System tab, and starting the Certificates application. To add new certificates, use ActiveSync. Certain carriers may prevent certificate installation.

Be very judicious when adding certificates to the Root Store because these certificates are completely trusted, and the presence of an attacker’s certificate in the Root Store could allow the attacker to spoof websites.

Conclusion

Windows Mobile is a mature platform for application developers and includes a large amount of security functionality. Unfortunately, the platform was not architected with security from the start, and the security model is not as user friendly or as advanced as the ones found in the more modern mobile operating systems. Changes in the Windows CE 6.x kernel will provide a more secure and robust foundation for future versions of Windows Mobile.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.222.111.243