Windows Phone (WP) 8 and 8.1 are arguably two of the most secure mobile operating systems on the market at the time of this writing. Indeed, in contrast to other mobile operating systems such as iOS and Android, WP8 and 8.1 and their Original Equipment Manufacturer (OEM) devices have not been publicly vulnerable to a long string of jailbreaking and security vulnerabilities.
Windows Phone 8 and 8.1 are built on top of the NT kernel technology. The older Windows Phone OSes, 7.x (and the even older Windows Mobile OSes) differ from Windows Phone 8.x in that their cores were made up of the CE kernel instead.
The market has shifted recently. Whereas Windows Phones previously seemed quite far behind the rest of the mobile arena, their market share increase now places them in third place, one place higher than BlackBerry devices. This makes Windows Phone devices very viable options for Windows Phone development, and as a consequence, application security research.
In this book we stick to the more recent Windows Phone operating systems, WP8 and WP8.1, though much of the content we discuss in the following four chapters may be relevant when assessing legacy WP7 applications as well.
Before delving into attacking and code auditing Windows Phone 8 and 8.1 applications in Chapter 11, this chapter first explores Windows Phone 8 and 8.1’s various security features, and then covers how to build an environment suitable for carrying out security reviews and exploration activities on Windows Phone 8 and 8.1 apps.
It’s important to understand the host’s OS security model before carrying out application security assessments to gain an appreciation for how apps are able to interact with each other and with the OS at large. Windows Phone is not just Windows on a phone. It is a much more closed operating system than standard Windows, and apps are much more restricted.
This section introduces Windows Phone’s security model and other security-related aspects of the OS so that you become aware of how exposed an app and its data is to attacks by other apps (consider malicious apps on a device) and exploit attempts in general. Other security features are also introduced, including device encryption and exploit mitigation technologies.
Windows Phone 8, by default, is a closed computing platform. On locked devices (that is, non-developer unlocked) all code must first be signed by Microsoft in order to run, much the way Apple requires that code have a signed a binary for it to run on non-jailbroken iOS devices.
The majority of applications consumed by Windows Phone 8 users are obtained via the Windows Phone Store. All applications submitted to the Store are subject to a Microsoft-defined submission process (more on this later), before being accepted and code signed with a certificate issued by the aptly named Certification Authority, Microsoft Marketplace CA. Signed apps are then made available for purchase or free download to the general public who own Windows Phone 8 devices.
In addition to being code signed, applications from the Store are protected using the FairPlay DRM technology. Tampering with the XAP or APPX files being installed results in the installation being halted.
Note that not all applications have to be Microsoft signed to run on WP8 or 8.1 devices. When developer mode is unlocked on a device, applications can be sideloaded, but in the context of Store applications running on the device of a standard consumer, all apps must be signed. (More on sideloading and its applicability to penetration testing appears later in this chapter.)
In line with Windows Phone 8.x’s closed architecture, applications are sandboxed to control their access to system resources and to prevent them from accessing other applications’ data. In Windows Phone 8.x realm, all third-party applications from the Store run in AppContainers. This section briefly discusses what an AppContainer is and what it means for standard applications in terms of privileges, security, and segregation of applications.
The AppContainer at a high level can be considered a process-isolation mechanism that offers fine-grained security permissions governing which operating system resources, such as files, the registry, and other resources, that contained applications can access and interact with.
Because all third-party WP8 and WP8.1 applications run inside an AppContainer, each app can access only its own private file sandbox; any attempts to read or write outside of it, including into another application’s data sandbox, fail. Similarly, any attempts to write into the registry also fail, though some of the registry is readable by standard third-party apps.
The ability of an application to access functionality offered by the OS and its services, such as the camera or networking, is controlled by that app’s capabilities. The Windows Phone 8 security model is based on the concept of least privilege, and as such, every application on a device is running inside one of two distinct security chambers.
In the Windows Phone 8 and 8.1 security architecture, the two chambers are the Least Privilege Chamber (LPC) and the Trusted Computing Base (TCB). All applications run in the notional LPC chamber, whether they are Microsoft-written services, OEM services, or just third-party Store applications. Even some device drivers run in the LPC. The only code that runs in the TCB chamber are kernel components. Figure 10.1 represents this chamber architecture graphically.
Windows Phone 8 and 8.1 implement the principle of least privilege by quite severely restricting the freedom of applications running in the LPC, by default. By least privileges enforcement, so few permissions are granted to apps by default that tasks such as networking, camera use and access to user contacts (for example) are not possible. For an application to be able to undertake serious tasks that are expected of modern smartphone apps, privileges have to be granted to it. At install time, applications “ask” for additional privileges by requesting capabilities.
When developers create WP8 applications, they must specify which capabilities their application requires in order to carry out its tasks and provide its functionality. For example, here are several typical capabilities that Store Windows Phone apps commonly request:
ID_CAP_NETWORKING
—Outbound and inbound network accessID_CAP_PHONEDIALER
—Access to the dialer functionalityID_CAP_MICROPHONE
—Access to the microphone APIID_CAP_LOCATION
—Access to geolocation dataID_CAP_ISV_CAMERA
—Access to device’s built-in cameraIn the context of a Windows Phone 8.1 app, you can specify capabilities in its Package.appxmanifest
file and use different names; for example, internetClient
in APPX manifests provides similar capabilities as ID_CAP_NETWORKING
. Developers specify capabilities to be requested at install either via the Manifest Designer interface or by manually editing the application manifest XML files—WMAppManifest.xml
or Package.appxmanifest
. (You can find more information about these files, in the “Application Manifests” section of this chapter).
At install time for an application, its manifest file is parsed for capabilities. Certain privileges, such as ID_CAP_LOCATION
, result in the user’s being prompted for permission to grant the capability to the app, since geolocation data can be considered sensitive information. Other permissions such as ID_CAP_NETWORKING
, on the other hand, are granted automatically, thus any third-party may use the OS’ networking APIs without the device user having to specifically authorize it via an install time prompt. Requests for powerful capabilities that are only meant for Microsoft and OEM software, such as ID_CAP_INTEROPSERVICES
, are denied by the OS, and third-party apps requesting such capabilities will not install.
Once the capabilities have been parsed out from the manifest and granted or denied (either automatically or by the user’s acceptance or denial), the application’s chamber is then provisioned with these granted capabilities. The app is then accordingly restricted by the security boundary the chamber presents, and it cannot go beyond that container by attempting to access APIs that it does not have the capabilities for. This summarizes the least privileges principle; if an app does not have the correct capabilities to access a particular API, the OS will deny access to it if the app attempts to use it.
Each time the application runs, its process executes in an AppContainer whose privileges reflect those of the capabilities granted to it.
The access controls enforced by WP8.x’s security model have been implemented using NT kernel’s security primitives: tokens and Security IDs (SIDs), where every AppContainer has its own capability SID, which is used to check with Access Control Lists (ACLs) whether or not the process has permission to carry out the action requested.
When you are reviewing apps from a security standpoint it’s helpful to understand the current state of data encryption for the data stored on a Windows Phone 8.x device or on an accompanying SD card.
Chiefly, it’s important to know how well protected application data is if a device is lost or stolen, and an attacker extracts the flash storage module in an attempt to extract and use data on the device.
The current status quo for encryption on standalone (non-corporate) and even some corporate-enrolled devices may surprise some readers.
We’ll discuss the general status of device and SD card encryption in the following two short sections.
At the time of this writing, data on devices running both Windows Phone 8 and Windows Phone 8.1 is not encrypted by default. Moreover, at present, no public API is available to enable full device encryption on unmanaged devices, such as those used by non-business consumers. This is true even when a device has a password set on it; this does not mean that any whole storage encryption has been enabled.
The only documented method of encrypting the internal storage volume (i.e., the entire flash storage—the disk) is via corporate enrollment and correct configuration of Exchange ActiveSync policies. In particular, the policy setting of interest is RequireDeviceEncryption
, as documented in Microsoft’s WP ActiveSync overview (http://go.microsoft.com/fwlink/?LinkId=270085
).
When encryption is enabled via ActiveSync policy, device encryption in Windows Phone 8 and 8.1 is carried out by Microsoft’s BitLocker technology. According to Microsoft documentation, BitLocker uses Advanced Encryption Standard (AES) encryption in Chained Block Cipher (CBC) mode, using either a 128- or 256-bit key, in combination with the “Elephant” diffuser for security aspects that are particular to disk encryption. The full technical specifications of BitLocker’s encryption are available athttp://www.microsoft.com/en-us/download/confirmation.aspx?id=13866.
Given the lack of out-of-the-box storage volume encryption even when a password is applied to Windows Phone 8 and 8.1 devices, non-enterprise WP8.x phone users at the time of this writing are vulnerable to data theft in the event that their device is lost or stolen, assuming the would-be attacker is able to extract filesystem data from the flash drive.
When BitLocker is enabled on Windows Phone 8 and 8.1, it does not encrypt Secure Digital (SD) card contents.
In terms of applications themselves writing encrypted or unencrypted data to the SD card, the conclusion to the matter is quite simple. In Windows Phone 8, Store applications are not capable of writing to SD cards; they only have read-access to the device. Only OEM and Microsoft applications have read- and write-access to SD cards.
This has changed, however, in Windows Phone 8.1. Apps in WP8.1 with the removableStorage
capability are afforded read- and write-access to the SD card.
SD cards—as data entry points into applications—are discussed in more detail in Chapter 11.
As stressed previously, Windows Phone 8 is a closed computing platform. It therefore makes sense that in addition to enforcing a strict security model to sandbox apps, Microsoft also reviews all app submissions to the Store to ensure that they comply with certain security-related dos and don’ts that Microsoft defines.
Most obviously the Store submission screening process involves a certain degree of analysis to ensure that submitted apps are not malware. In this sense submitted applications are vetted for malicious code, and any code that Microsoft considers to be malicious leads to the app’s rejection.
Still, even if a submitted application is not coded to carry out blatantly malicious actions, certain questionable behaviors may be disallowed and lead to the app’s being rejected. For example, if an application attempted to read a file outside of its sandbox for seemingly innocuous purposes, the app would most likely be refused, even though the action would in the vast majority of cases fail anyway. Similarly, accessing registry keys that are readable may also be considered questionable, and could lead to rejection of the app submission. Exact patterns of behavior that are prohibited by Microsoft are not available to the general public, but even accidental or innocuous naïve attempts to breach the sandbox model would most likely be considered inappropriate and would be a reason for rejection.
Another pattern of behavior that could be implemented by a well-meaning developer but is prohibited includes “altering” an application’s behavior after the application has been accepted and certified by the Store. This may include an application’s downloading a JavaScript file and executing it, for example. Notably, this sort of behavior is allowed in iOS apps, for example, but not in WP8.x apps at the present time.
Although Windows Phone 8 and 8.1 fully support native code applications (such as C, C++), restrictions are imposed on the use of native-like features in C# applications. In particular, Store applications are not allowed to contain “unsafe” code, meaning code that uses the unsafe and fixed keywords to deal ‘directly’ with pointers. Microsoft also forbids calling into certain (but not all) Win32 APIs via C#’s P/Invoke interface, presumably for security reasons. See http://msdn .microsoft.com/en-us/library/windowsphone/develop/jj207198(v=vs.105) .aspx
for an exhaustive list of “allowed” APIs for invocation via P/Invoke.
Despite such restrictions on use of native code and features by managed apps (such as C#), rather interestingly there are technically no restrictions on the use of APIs such as strcpy()
, *sprintf()
, strcat()
, and so on. Although the use of potentially unsafe APIs may be flagged as errors by Visual Studio, such deprecation errors can be disabled, and Microsoft has not explicitly banned dangerous API usage in WP native apps at this time.
Equally, as with iOS apps, for example, behavior such as storing the user’s app password in cleartext is not actually prohibited, despite its being a bad security practice. In this sense, although the Store does vet for certain insecurities, the Store’s vetting process could be considered more of a screening for deliberate malware than for apps that are poorly written from a security perspective. The vetting process aims to catch attempts to engage in disallowed activity, but the process does not have heavy emphasis on preventing an app from being insecure in itself.
A notable difference in the submission procedure for WP8.1 apps versus WP8 apps is that APPX packages must pass the tests in the Windows App Certification Kit (WACK). This includes several security-related tests including BinScope binary analyzer tests, which test for the presence of security-related binary protections such as Address Space Layout Randomization (ASLR). Security checks that must pass for WP8.1 certification are available on MSDN (http://msdn.microsoft.com/en-us/library/windowsphone/develop/dn629257.aspx#background_security
).
To conclude this discussion of submission processes, it’s worth discussing and considering how successful Microsoft’s procedures and policies are at keeping malicious apps out of the Store in comparison to other mobile operating systems. As of May 2014, information on confirmed cases of malware is scarce. Based on Windows Phone 8’s initial release date, around October 2012, we could conclude that this is a good track record. This number fares slightly better than iOS, and very similarly to BlackBerry; both of these platforms also have proper submission vetting processes.
This number is also in stark comparison to Android, where some sources estimate that around 97% of mobile malware is targeted at the Android platform (http://www.forbes.com/sites/gordonkelly/2014/03/24/report-97-of-mobile-malware-is-on-android-this-is-the-easy-way-you-stay-safe/
). This statistic presents little surprise when one considers that the Google Play Store (formerly Marketplace) does not have genuine approval procedures.
Somewhat similarly, there have been several high profile malware outbreaks that have targeted jailbroken iOS devices in recent years. There are no comparable incidents that concerned Windows Phone devices, though absence of evidence does not constitute evidence of absence.
In addition to security requirements for certification a whole host of other non-security related dos and don’ts exist, many of which revolve around performance and management of the app’s resources, and not impeding the owner’s normal usage of the phone. For the interested reader a full list of certification requirements for Windows Phone 8/8.1 applications is available on MSDN at http://msdn.microsoft.com/en-us/library/windowsphone/develop/hh184844(v=vs.105).aspx
.
Similarly to most modern operating systems, the Windows Phone 8 and 8.1 platforms both feature a number of exploit mitigation technologies. Such technologies aim to raise the difficulty associated with exploiting memory corruption vulnerabilities. The days of simply overwriting a return address or Structured Exception Handler (SHE) entry in a stack overflow are all but gone, as are the days of exploiting the “write-what-where” primitive in a classic safe unlinking heap overflow.
Exploit mitigation features are present not only to stop buggy apps from being exploited, but also to try to prevent apps (such as malware and community home brew apps) from exploiting vulnerabilities in the underlying OS and kernel to carry out “jailbreak”-like attacks.
This section briefly discusses the portfolio of exploit mitigation features present in WP8 and 8.1, some details on how they work, and techniques that are used to sometimes bypass or overcome the protections each technology aims to provide. These discussions are only applicable to native code, because managed code is generally immune to memory corruption bugs in the traditional sense.
Bear in mind, however, that some Windows Phone 8 and 8.1 applications are written in a managed language but also call into native code modules. Consider a C# application, for example, that calls into native code via the P/Invoke interface.
Later this section also covers how you can check whether third-party applications have these mitigation features enabled on their binaries for when you are carrying out security assessments; see “Analyzing Application Binaries” later in this chapter.
Stack canaries, also known as stack cookies, are random values that are placed prior to critical data such as stack metadata (for example, return addresses). When the executing function returns, the value is checked to see whether it matches the expected value. If it does, the program execution continues, and if it does not, it has clearly been overwritten at some point during the function’s execution, and the application terminates immediately.
Stack canaries are placed between the last local stack variable and the padding that precedes the saved frame pointer (SFP). Figure 10.2 demonstrates the setup.
Clearly, if a stack overrun occurs (such as via an unsafe strcpy()
call), and the stack buffer’s bounds are breached, the cookie value will be overwritten, and the cookie check prior to function return will inevitably result in program termination, unless the attacker was extremely lucky and managed to guess the correct cookie value.
Stack cookie protection is enabled via the /GS
compiler flag. This option was first introduced in Visual Studio 2002, and is on by default, thus there is no need to manually enable it when compiling applications.
Although stack canary technology protects against traditional stack overflow exploitation techniques, the feature, in principle, wouldn’t guard against consequences of an overflow that may be exploitable before the application terminates. For example, an important pointer may be overwritten and written to before the cookie check happens. In practice, however, /GS
may also do variable reordering, precisely for the purpose of trying to prevent important pointers and variables from being overwritten and the protections being ineffective.
Address Space Layout Randomization (ASLR) is an exploit mitigation feature that revolves around randomizing the memory location of a process’s image and its various loaded DLL modules. That is to say, the base address of an application or loaded module will not stay constant between runs or loads, respectively.
The whole purpose of ASLR is to make accurately predicting the layout and overall structure of memory within a process very difficult for attackers. The value of doing this, though, is made apparent by considering how several classes of memory corruption vulnerabilities were traditionally exploited.
Take stack-based buffer overflows as an example. Before the advent of ASLR in highly targeted applications, exploit writers most often overwrote a stack frame’s return address with a hard-coded, predetermined address. The nature of the data at this address generally varies by the operating system being exploited. Most exploits for UNIX-like systems overwrite the return address in question with the location of their shellcode on the stack, or the address of a library function (so-called return-to-libc
).
The majority of Windows exploits writers tended to overwrite return addresses with the location of a CALL ESP
or JMP ESP
instruction for which they had predetermined the address on particular versions of Windows.
In both cases, return addresses (or function pointers) were overwritten with addresses that were known to be stable; hence, exploits had a good chance of succeeding even though the overwrite address was hard-coded.
However, with the introduction of ASLR into mainstream OSes, exploitation techniques have necessarily changed somewhat. When an application has ASLR enabled on its binary, attempts to redirect execution flow into stack-based shellcode via a hard-coded address is likely to fail, because the location in memory of the stack buffer in question will be randomized, and guessing it would be potluck.
In Windows exploits, where an attacker would often hardcode a return address that pointed to JMP ESP
or CALL ESP
instructions in KERNEL32.DLL
(for example), such an attack would be hard to use with ASLR, because the location of the function containing the JMP ESP
or other desired instruction would no longer be stable or even predictable.
Although this would appear to be a solid and unforgiving mitigation against fairly trivial memory corruption exploits, adoption problems have limited its range of effectiveness in the past.
When ASLR was introduced in Windows Vista Beta 2 (circa mid-2006), only Microsoft applications had ASLR support compiled into them, and this included applications and DLL modules. Software written by third-party developers had to opt into ASLR, by choosing to compile support into their binaries. So, if a hacker were trying to write an exploit for a stack overflow in Microsoft Office, the location of his previously predictable JMP ESP
(or whatever) instruction was now randomized, and his job as an exploit writer became somewhat more difficult.
In third-party software on the other hand, where ASLR was frequently not compiled in, the exploit writer’s job was often just as easy as before ASLR was even introduced into Windows. Applications and their modules would be loaded at their preferred, stable base address, and an attacker’s exploit methodology would remain the same as before.
Since then, however, Microsoft has standardized ASLR’s adoption of third-party native applications. Indeed, Visual Studio now enables ASLR’s compiler flag, /DYNAMICBASE
, by default, and a developer would have to deliberately disable it for the distributed binary to be unprotected (and there are legitimate reasons for doing so). Moreover, since a certain Windows 7 update, there has been a feature known as “Force ASLR,” which applications can opt into to ask the kernel to load modules at randomized addresses even when they have been built with the /DYNAMICBASE
flag. These features are also common to the more recent Microsoft mobile operating systems, WP8 and WP8.1.
This is definitely good news from a security perspective and means that native applications in Windows Phone 8 and 8.1 are likely to be in good shape in regard to thwarting the use of stable memory addresses in exploits.
That’s not to say that ASLR is perfect and can’t be effectively bypassed (for example, using pointer leaks or heap spraying/JIT spraying), but its implementation in Windows 8.x operating systems has seen various improvements since its introduction in Windows Vista, and as such, its use in WP8 and WP8 native applications by default (in Visual Studio compilation options) definitely makes exploitation efforts a bit harder from the attacker’s perspective. WP8.1 native modules must have ASLR enabled on binaries to pass the certification process (see http://msdn.microsoft.com/en-us/library/windowsphone/develop/hh184844(v=vs.105).aspx
).
Data Execution Prevention, known commonly as DEP, is an exploit mitigation feature whose job it is to prevent the processor from executing code that resides in memory regions known to contain data rather than code.
This is a desirable thing, because many exploits rely on redirecting program execution flow into shellcode that resides in stack or heap buffers. It is intuitively quite obvious that legitimate executable code should not reside in stack and heap memory regions (among others), because these memory areas are intended for application data. Hence, no good reason exists to allow code execution in these areas. This is the concept behind DEP: preventing code execution in memory spaces that are known to house data rather than code.
DEP is not exclusively a compiler-based and kernel-based option; its enforcement relies on CPU support as well. With binaries that are compiled for x86 processors, the /NXCOMPAT
flag informs the kernel to enforce DEP on the app if the host CPU supports the no-execute page-protection feature—No eXecute (NX) on AMD, and the Execute Disable Bit (XD) on Intel. In the context of Windows Phone 8 and 8.1 devices, whose processors are either ARMv6 or ARMv7, this bit is known as XN—eXecute Never.
When running on 64-bit architectures, the /NXCOMPAT
flag has no effect; all applications run with DEP enabled, unless the app is running in WOW64 mode—Windows 32-bit on Windows 64-bit, as documented by the Visual C++ team (http://blogs.msdn.com/b/vcblog/archive/2009/05/21/dynamicbase-and-nxcompat.aspx
).
Because DEP generally prevents immediate execution of shellcode given that it usually resides in pages with the NX or XD flags enabled, exploit writers have had to employ alternative routes to achieve meaningful code execution.
The methods most often used revolve around reusing code fragments that are already loaded into memory and reside in pages that do not have NX/XD/XN
flags enabled on them. This is known as Return-Oriented Programming (ROP), and the basis of this method involves chaining together small fragments of already-present code (known as ROP gadgets) until a useful task has been carried out. Some ROP chains are skillfully constructed (or via a tool such as ROPGadget; see http://shell-storm.org/project/ROPgadget/
) to make up complete shellcode-like instruction chains, whereas some result in a call to VirtualProtect()
to remove the NX/XD
bit from the page(s) containing the attacker’s shellcode, which will then be jumped into and executed, thereby bypassing DEP’s protection.
The ROP technique relies on non-ASLR modules being loaded into the process being exploited to use a source of ROP gadgets, but as noted earlier, this has been commonplace with third-party applications.
At present, OEM-supplied Windows Phone hardware is ARMv6- and ARMv7-based, and therefore 32-bit architectures. Visual Studio enables the /NXCOMPAT
compiler flag by default, thus third-party WP8 applications are likely to be built with DEP enabled. WP8.1 must necessarily be compiled with DEP enabled, as per Microsoft’s Store certification requirements for Windows Phone 8.1 apps (as per http://msdn.microsoft.com/en-us/library/windowsphone/develop/dn629257.aspx
).
The likely presence of DEP, especially when combined with ASLR, is a positive thing for WP security and adds another level of difficulty to real-world exploitation on the platform.
When Microsoft introduced stack cookie protection into its compiler (via the /GS
flag) in 2003, it soon became clear that the standard return address overwrite was no longer going to be reliable as a stack overrun exploitation method.
The core of the technique revolved around overwriting structured exception handling (SEH) metadata, and then causing an exception to be thrown. Each thread in a process has at least one SEH record on its stack; each exception handler is represented by an EXCEPTION_REGISTRATION_RECORD
structure, which consisted of a “Next” pointer and a function pointer to an exception handler. Figure 10.3 represents this concept graphically.
Because EXCEPTION_REGISTRATION_RECORD
structures are also located on the stack, along with the overflowable stack buffer, the idea was to overflow the susceptible buffer and keep overwriting until an EXCEPTION_REGISTRATION_RECORD
structure was reached, which would be at some pointer further down the stack. The function pointer in the EXCEPTION_REGISTRATION_RECORD
would then be overwritten with a value of the attacker’s choice. The attacker would then have to cause an exception to be thrown; a popular way to do this was to keep writing data until a guard page at the end of the stack was hit, causing a write access violation. The exception dispatcher would enumerate the list of exception handlers for the thread, and as a result the overwritten function pointer would be called into, giving execution flow control to the attacker.
This lead to Microsoft’s introducing the Safe Structured Exception Handling (SafeSEH) functionality into Visual Studio 2003, via the /SAFESEH
compiler flag. This exploit mitigation flag prevents the simple technique just summarized from succeeding by inserting code (at compile time) that validates that each SEH handler is found in a table of known exception handlers before being executed. Due to peculiarities in the protection, however, overwritten exception handlers will still be called if they do not point into the stack, and do not point into the memory space of a loaded module.
David Litchfield published a paper (available at http://www.blackhat.com/presentations/bh-asia-03/bh-asia-03-litchfield.pdf
) soon after the introduction of /SAFESEH
documenting a generic method for its bypass. The solution was to find a suitable instruction on the heap to overwrite the EXCEPTION_REGISTRATION_RECORD
function pointer that would, with details omitted for brevity, cause execution to end up in the attacker’s shellcode.
Given /SAFESEH
’s shortcomings, an accompanying exploit mitigation was introduced to further protect against SEH exploitation: SEHOP, which stands for Structured Exception Handling Overwrite Protection. SEHOP places a cookie at the end of the SEH chain, and then verifies that no EXCEPTION_REGISTRATION_RECORD
s have been modified by walking the chain and verifying that the cookie is the value expected. If this chain validation and cookie check fail, the exception handler is not allowed to execute. This works because each EXCEPTION_REGISTRATION_RECORD
’s Next pointer is situated in front of its function pointer, meaning that any overwrite of the structure trashes the Next pointer and the SEH chain is broken. Coupled with ASLR, guessing the correct Next pointer value could prove very difficult. No bypasses are known for SEHOP at the time of writing.
/SAFESEH
is enabled by default in all versions of Visual Studio that are used to compile WP apps, and SEHOP is also implemented in WP8 and 8.1.
In addition, WP8.1 native applications must be built with /SAFESEH
to pass the Store certification requirements, see http://msdn.microsoft.com/en-us/library/windowsphone/develop/dn629257.aspx
.
Prior to Windows XP SP2 (2004) and Windows 2003, heap overflow vulnerabilities were most often exploited by taking advantage of the unsafe unlinking by tactically overwriting doubly linked list back and forward pointers in an adjacent chunk’s metadata. This general method offered a powerful “write-what-where” exploitation primitive.
Since then, the various versions of Windows have seen progressive improvements to their heap manager implementations to the point where the comparatively simple heap overflow exploitation techniques from several years ago are no longer applicable in the more recent versions of Windows, except perhaps in custom heap manager implementations.
There are known exploitation techniques against the Windows 8 (and by extension, Windows Phone 8) heap manager, as discovered and presented by Chris Valasek and Tarjei Mandt (paper available at http://illmatics.com/Windows%208%20Heap%20Internals.pdf
), though these are understood to be non-trivial and the protection offered by Windows 8’s heap manager is far and away superior to those of yesteryear.
The heap manager in Windows 8.1 (and Windows Phone 8.1) addresses at least one of Valasek’s and Mandt’s techniques (according to http://blogs .technet.com/b/srd/archive/2013/10/29/software-defense-mitigation-heap-corruption-vulnerabilities.aspx
), and further hardens the userland heap against successful attacks.
Although an in-depth discussion on kernel exploit mitigations in Windows Phone 8 and 8.1 is beyond the scope of this book, it’s worth mentioning briefly that the 8 and 8.1 operating systems actually implement equivalent exploitation mitigation technologies that we’ve already discussed for protection against kernel space exploitation as well. There are also some protection features that are unique to the kernel, and in fact, the Windows 8 kernel.
Several of the anti-exploit features present in the WP8 and WP8.1 kernels are:
We’ve discussed the security model and features of the WP8 and 8.1 platform; now let’s look at some of the details of how applications are developed, the language options available to developers, how apps are distributed and installed, and how you as the reader can take advantage of these aspects in helping with analysis and security testing of WP8 and 8.1 third-party software.
On Windows 7 and Windows 8, XAP packages are the standard means of distributing the installing applications. An XAP file generally contains all the files required by the application for installation and operation, including its code in binary or .NET assembly form (DLLs), its resources (images, sound files, etc.), and the manifest file (WMAppManifest.xml
and/or Package.appxmanifest
), among other possible files. Although Windows Phone 7 and Windows Phone 8.x both use XAP files, they are not completely compatible across the two OS versions; a Windows Phone 7 XAP can be installed on Windows Phone 8.x, but a Windows Phone 8.x XAP cannot be installed on Windows Phone 7. XAP files are backward compatible.
Similarly to the distribution packages of other mobile platforms such as iOS (IPA) and Android (APK), XAP files are fundamentally zip files.
With the initial releases of Windows Phone 8.1, Microsoft has introduced the APPX package format, exclusively, however, for Windows Phone 8.1 and not Windows Phone 8. Although APPX is WP8.1’s preferred package format, WP8.1 is backward compatible and can install XAP packages intended for WP8.
Unzipping XAP and APPX files that have been downloaded from the Store is no trivial task, however, because they are DRM protected, and therefore encrypted. XAP and APPX files that are not Microsoft signed and DRMed can be unzipped and their contents inspected, including the application’s binaries themselves. (See Figure 10.4.)
The introduction of a package format just for WP8.1 and later, APPX, is due to the addition of new features in WP8.1 that are simply not available in WP8 (such as new APIs) but also to standardize package distribution between Windows Phone and standard Windows.
The Windows Phone 8 and 8.1 platforms support multiple programming languages as standard—and more. In fact, than all the other mainstream mobile OSes. Developers have the choice between using native code and writing their applications in managed languages.
The majority of applications can be placed in at least one of the following general categories:
Most applications available in the Store fit into a standard category and are most often developed in C# with XAML files comprising the interface. XAML, which stands for eXtensible Application Markup Language, is used by .NET apps to simplify the creation and representation of user interface components. Though most apps in this general category are developed in C#, some are written in C++ and Visual Basic.
Although developing games in C# is possible, the majority of games available for Windows Phone 8.x are developed in C++, and this is Microsoft’s recommended language for game apps. Many games call into Direct3d for their graphics generation and manipulation abilities.
Developers also have the ability to develop functional applications using HTML5 and JavaScript, often also utilizing some XAML for their interface components. Applications developed using JavaScript and HTML5 are not merely client-side web apps. The Windows Runtime (WinRT) exposes an entire API so that apps written in JavaScript can access much of the same functionality that a normal app can.
It’s not uncommon for apps to use a language such as C# yet also use JavaScript and HTML5 for various things, including (but not limited to) its interface components. These could be loosely termed hybrid apps. The term hybrid app could also be used to describe an app that is little more than a C# app (for example) which utilizes web-view type objects to render a web app and doesn’t call into much OS functionality at all.
The choice of language is up to the developer, but Microsoft offers some general guidelines on which languages are suitable for certain tasks (see http://msdn .microsoft.com/en-us/library/windowsphone/develop/jj714071(v=vs.105) .aspx#BKMK_Decidingonanapproach
, for example). Most proficient developers should be in a position to analyze the situation and determine a language’s suitability for themselves, however.
In general, using native code if an application needs to be highly optimized makes sense. Examples of such applications include games, which are generally written in C++, using Direct3d.
Another reason for writing applications solely in native code would be language familiarity; experienced C++ developers may find implementing functionality in C++ to be easier than learning a related but different language like C#. Equally, many developers may opt for the comfort of C# and then call into existing native libraries that are performance critical using the P/Invoke
interface.
It is generally known on an empirical basis that C# is the most commonly used language for Windows Phone application development. For this reason, we place the majority of our focus on reviewing C# apps, though most of the discussion can be applied to Windows Phone apps written in other languages.
As briefly mentioned earlier in this chapter, every Windows Phone app has a manifest file that contains details about the application. The information in an app manifest can be considered metadata, and among other things some of the more basic aspects of information found inside an app’s manifest are its App ID, publisher/author, the app’s name/title, a description of the app, and the relative path to the app’s logo.
Windows Phone 8.1 can install both XAP files and APPX files. Manifest files for apps that are deployed specifically from APPX packages are named Package .appxmanifest
, although APPX packages also contain a WMAppManifest.xml
file like XAP files as well. Windows Phone 8 devices can only install XAP packages, whose manifest file is WMAppManifest.xml
.
In addition to the basic app information already mentioned, application manifests also contain information that is somewhat more interesting from a security and exploration standpoint and as such manifests can serve as useful starting points for penetration testing and reverse engineering an app. As mentioned earlier (see Chambers and Capabilities) an app’s manifest also defines which permissions the application needs to be able to provide its functionality.
Although an application’s manifest holds much metadata that is needed to deploy the app correctly and in the way that the developer intended, we’ll focus mainly here on the aspects of the manifest that are useful from your perspective, as a penetration tester and/or a reverse engineer.
Both types of manifest, WMAppManifest.xml
and Package.appxmanifest
, are just standard XML files. The two types do differ in structure and in the tags that they use to present their app metadata. We’ll go through each one separately and explain how to glean information that is useful from a security and analysis point of view.
Manifest files support a number of parent and child XML elements, but rather than listing them all, we’ll consider several that are interesting for an initial attack surface and entry point analysis. A few of these are
<Capabilities>
—Defines the capabilities required by the application<FileTypeAssociation>
—Defines the file extensions that are associated with the app<Protocol>
—Defines URL schemes that the app wishes to register for<ActivatableClass>
—Defines classes that are used by the app that are external to it<Interface>
—Specifies interfaces that the app implements that are external to itWe’ll consider and analyze the following manifest file snippets as examples of how each of these elements are used, what they tell us about the application at a glance. The following capability tags were borrowed from the WMAppManifest .xml
file from a typical app (distributed in XAP format):
<Capabilities>
<Capability Name="ID_CAP_NETWORKING" />
<Capability Name="ID_CAP_LOCATION" />
<Capability Name="ID_CAP_SENSORS" />
<Capability Name="ID_CAP_MICROPHONE" />
<Capability Name="ID_CAP_PHONEDIALER" />
<Capability Name="ID_CAP_PUSH_NOTIFICATION" />
<Capability Name="ID_CAP_WEBBROWSERCOMPONENT" />
<Capability Name="ID_CAP_IDENTITY_DEVICE" />
<Capability Name="ID_CAP_IDENTITY_USER" />
<Capability Name="ID_CAP_CONTACTS" />
<Capability Name="ID_CAP_MEDIALIB_AUDIO" />
<Capability Name="ID_CAP_MEDIALIB_PHOTO" />
<Capability Name="ID_CAP_MEDIALIB_PLAYBACK" />
<Capability Name="ID_CAP_PROXIMITY" />
<Capability Name="ID_CAP_MAP" />
<Capability Name="ID_CAP_VOIP" />
<Capability Name="ID_CAP_PEOPLE_EXTENSION_IM" />
</Capabilities>
The child elements within the <Capabilities>
element clearly show which capabilities the application requests upon installation. This is useful for a number of reasons. First, if you see ID_CAP_NETWORKING
, for example, you know that the application contains functionality that talks to other systems over the network, most likely the Internet. Second, if the application you are installing is supposedly a calculator, yet you see that the application “requires” ID_CAP_CONTACTS
, you may become suspicious about the innocence of the app, and reverse engineer it as a potential malware suspect.
Moving on, a typical <FileTypeAssociation>
element in a manifest may look something like the following:
<Extensions>
<FileTypeAssociation Name="Windows Phone SDK test file type"
TaskID="_default" NavUriFragment="fileToken=%s">
<Logos>
<Logo Size="small" IsRelative="true">Assets/sdk-small-
33x33.png</Logo>
<Logo Size="medium" IsRelative="true">Assets/sdk-medium-
69x69.png</Logo>
<Logo Size="large" IsRelative="true">Assets/sdk-large-
176x176.png</Logo>
</Logos>
<SupportedFileTypes>
<FileType ContentType="application/sdk">.myExt1</FileType>
<FileType ContentType="application/sdk">.myExt2</FileType>
</SupportedFileTypes>
</FileTypeAssociation>
</Extensions>
If you were analyzing an application whose manifest contained the preceding snippet, you would know that the app has registered handlers for the .myExt1
and .myExt2
file extensions. File extension handlers are data entry points to the application, and are therefore good places to start looking for vulnerabilities. At this point, penetration testers would be on the lookout for file type handling code when they later begin their reverse engineering or code review activities.
Now consider the following WMAppManifest.xml
snippet, which shows a real-world example of the <Protocol>
element from the Windows Phone 8 Facebook application.
<Protocol Name="fb" NavUriFragment="encodedLaunchUri=%s"
TaskID="_default" />
<Protocol Name="fbconnect" NavUriFragment="encodedLaunchUri=%s"
TaskID="_default" />
It’s evident from the preceding snippet that the Facebook application registers two protocol handlers: fb://
and fbconnect://
. Knowing this, a penetration tester or reverse engineer would then know to search for and analyze protocol handlers during their review, because these handlers represent a potentially interesting entry point to the app.
Following is an example of <ActivatableClass>
, taken from the WMAppManifest .xml
of a VoIP app.
<ActivatableClasses>
<InProcessServer>
<Path>PhoneVoIPApp.BackEnd.DLL</Path>
<ActivatableClass
ActivatableClassId="PhoneVoIPApp.BackEnd.MessageReceivedEventHandler"
ThreadingModel="MTA" />
<ActivatableClass
ActivatableClassId="PhoneVoIPApp.BackEnd.BackEndTransport"
ThreadingModel="MTA" />
<ActivatableClass
ActivatableClassId="PhoneVoIPApp.BackEnd.BackEndAudio"
ThreadingModel="MTA" />
<ActivatableClass
ActivatableClassId="PhoneVoIPApp.BackEnd.CameraLocationChangedEventHandle
r" ThreadingModel="MTA" />
<ActivatableClass
ActivatableClassId="PhoneVoIPApp.BackEnd.BackEndCapture"
ThreadingModel="MTA" />
<ActivatableClass
ActivatableClassId="PhoneVoIPApp.BackEnd.IncomingCallDialogDismissedCallb
ack" ThreadingModel="MTA" />
<ActivatableClass
ActivatableClassId="PhoneVoIPApp.BackEnd.CallController"
ThreadingModel="MTA" />
<ActivatableClass
ActivatableClassId="PhoneVoIPApp.BackEnd.Globals" ThreadingModel="MTA" />
</InProcessServer>
<OutOfProcessServer ServerName="PhoneVoIPApp.BackEnd">
<Path>PhoneVoIPApp.BackEnd.DLL</Path>
<Instancing>multipleInstances</Instancing>
<ActivatableClass
ActivatableClassId="PhoneVoIPApp.BackEnd.OutOfProcess.Server" />
</OutOfProcessServer>
From the preceding code, you can tell that the application is registered to make use of external VoIP classes, PhoneVoIPApp.BackEnd.CallController
, for example. Knowing this, you may also consider these classes as candidates for reverse engineering and/or security review as well, because the app does use them for some of its functionality.
Finally, consider the following <Interface>
tags from the manifest of the same VoIP application:
<ProxyStub ClassId="{F5A3C2AE-EF7B-3DE2-8B0E-8E8B3CD20D9D}">
<Path>PhoneVoIPApp.BackEndProxyStub.DLL</Path>
<Interface
Name="PhoneVoIPApp.BackEnd.__IBackEndTransportPublicNonVirtuals"
InterfaceId="{F5A3C2AE-EF7B-3DE2-8B0E-8E8B3CD20D9D}" />
<Interface
Name="PhoneVoIPApp.BackEnd.__IBackEndTransportProtectedNonVirtuals"
InterfaceId="{044DEA28-0E8D-3A16-A2C1-BE95C0BED5E5}" />
<Interface
Name="PhoneVoIPApp.BackEnd.__IBackEndAudioPublicNonVirtuals"
InterfaceId="{DE465431-ED24-3298-A187-8F1AFBBBE135}" />
<Interface
Name="PhoneVoIPApp.BackEnd.ICallControllerStatusListener"
InterfaceId="{39126060-0292-36D6-B3F8-9AC4156C651D}" />
<Interface
Name="PhoneVoIPApp.BackEnd.__IBackEndCapturePublicNonVirtuals"
InterfaceId="{8313DBEA-FD3B-3071-8035-7B611658DAD8}" />
<Interface
Name="PhoneVoIPApp.BackEnd.__IBackEndCaptureProtectedNonVirtuals"
InterfaceId="{64B31D5B-1A27-37A8-BCBC-C0BBD5314C79}" />
<Interface
Name="PhoneVoIPApp.BackEnd.__ICallControllerPublicNonVirtuals"
InterfaceId="{06B50718-3528-3B66-BE76-E183AA80D4A5}" />
<Interface Name="PhoneVoIPApp.BackEnd.IVideoRenderer"
InterfaceId="{6928CA7B-166D-3B37-9010-FBAB2C7E92B0}" />
<Interface
Name="PhoneVoIPApp.BackEnd.__IGlobalsPublicNonVirtuals"
InterfaceId="{C8AFE1A8-92FC-3783-9520-D6BBC507B24A}" />
<Interface Name="PhoneVoIPApp.BackEnd.__IGlobalsStatics"
InterfaceId="{2C1E9C37-6827-38F7-857C-021642CA428B}" />
<Interface
Name="PhoneVoIPApp.BackEnd.OutOfProcess.__IServerPublicNonVirtuals" InterfaceId="{7BF79491-56BE-375A-BC22-0058B158F01F}" />
</ProxyStub>
The <Interface>
tags in the previous manifest fragments tell you that the app implements the preceding externally defined interfaces. This just tells you a little more about how the app works.
The preceding examples make it quite evident that a reasonable amount of information can be gleaned about an app through just a very cursory analysis of its manifest file, including its capabilities, some entry points, and external components that it calls into.
Several other tags and patterns are interesting from an attack surface assessment point of view. We recommend you refer to MSDN’s manifest file documentation for reference when analyzing manifest files to determine the nature of unfamiliar and possibly interesting tags you come across. See http://msdn .microsoft.com/en-us/library/windowsphone/develop/ff769509.aspx
.
Package.appxmanifest
files (from APPX packages) take on a similar format to WMAppManifest.xml
files. Microsoft encourages the use of the Package .appxmanifest
file in favor of WMAppManifest.xml
for some aspects such as capability definitions in the context of WP8.1 apps, but APPX packages also have a WMAppManifest.xml
file as well, so remember to review this file also.
Installed applications have two main directories that are used exclusively by them: the app’s install directory; where its binaries, .NET assemblies, and other assets are stored; and the app’s local storage directory, where the app can store data, and where web cache, cookies and other information is stored.
All installed apps have their own install directory, located at C:\Data\Programs\{GUID}\Install
, where {GUID}
is the app’s ID. You’ll make extensive use of applications’ install directory later for extracting apps from the device when you hack your device and gain full filesystem access to it. The install directories for all apps installed on the device can be explored by browsing at C:\Data\Programs
.
Each app also has its own local storage directory; this can be thought of as the app’s filesystem sandbox. The local storage directory tree for an app whose ID is GUID may be found at C:\Data\Users\DefApps\APPDATA\{GUID}
.
The local storage area for each app has the following directories in its tree:
Local
LocalLow
PlatformData
Roaming
FrameworkTemp
Temp
INetCache
INetCookies
INetHistory
Of these directories, Local
is generally the most used one. Local
is the directory most often used for data storage by apps.
INetCache
, INetCookies
, and INetHistory
are also interesting from a security perspective, since all of the above directories have the potential to hold data that constitute sensitive data leaks.
In the remainder of the Windows Phone sections in this book you’ll frequently browse applications’ install directories and local storage directories, for extraction of app binaries and assets, and for exploration of applications’ filesystem sandbox.
There are a few ways in which applications are distributed and installed. Of course, the most commonly used method is simply the Windows Phone Store, but there are other distribution mediums and installation methods that are interesting to developers and security reviewers. We’ll discuss these methods in the following five sections and their relevance to carrying out security assessments.
So far we’ve mentioned the Store for downloading Windows Phone applications several times. The Store application on the device itself is the standard means of downloading and installing applications.
The Store allows users to search for applications by keyword, and also by category; for example, education, business, entertainment, news, weather, and so on. The app also has tiles that allow users to view apps that are best-rated, top free, and top paid.
Although the vast majority of applications in the Store were developed and published by third-party vendors, Microsoft actually sells some of its own products in the Store as well. Examples include OneDrive, Lync, and Skype.
In addition to the apps section of the Store app, there are also sections for games and music. The Store app on some devices has a section specific for applications intended for devices made by that OEM only; for example, Store on Samsung devices has a “Samsung Zone” section to the app. Similarly, Store on Nokia devices has a “Nokia Collection” area, and HTC devices have an “HTC Apps” area. Some mobile network carriers may also have their own area that appears when the device is connected to their network. Figure 10.5 shows the splash screen for the Store app on a typical Samsung device running Windows Phone 8.
Similarly to the app stores for the other mainstream mobile operating systems (iOS, Android, BlackBerry), some apps are free of charge.
The Windows Phone Store has been so named since Windows Phone 7, before which it was known as the Windows Phone Marketplace, when Microsoft’s current mobile operating system was Windows Mobile, now deprecated.
Although the standard means of installing WP8 and WP8.1 applications is from the on-device Store app, applications can also be downloaded from a desktop system and then installed using an SD card. This method of installation is known as sideloading and presumably exists in case a user doesn’t have Internet access from a device but does have network access on a desktop or laptop system. Instructions for installing Store apps via sideloading are available at the Windows Phone site (http://www.windowsphone.com/en-gb/how-to/wp8/apps/how-do-i-install-apps-from-an-sd-card
).
In Windows Phone 8.1, you also have the option of installing an app directly to an SD card, as opposed to simply installing it onto the device from the SD card.
For applications developed for internal use at organizations, a distribution method known as “Company app distribution” allows the Store and Microsoft certification to be bypassed and apps to be published directly to the company’s employees. This method is available on Windows Phone 8 and 8.1.
This distribution and installation scheme requires companies to register a company account on the Windows Phone Dev Center and acquire an enterprise certificate for signing their apps. The company then develops its applications and signs them using the enterprise certificate it obtained. Many companies also develop a “Company Hub” application to act as a portal from which to download their internal apps.
Employees then enroll their phone for app distribution from their company, and at that point they’ll be able to install the internal apps signed with their company’s enterprise certificate. The full process has been documented in detail by Microsoft (see http://msdn.microsoft.com/en-us/library/windowsphone/develop/jj206943(v=vs.105).aspx
for more information).
Targeted app distribution is a means for publishing your application via the Dev Center while hiding your app from view in the Windows Phone Store.
All apps published via targeted app distribution are subject to the same vetting and certification process as regular Store apps. When Microsoft approves and certifies your app, you are then able to give users you select a link to the app so they can install it. Because the app will not be visible in the Store, yet is downloadable by users with a particular link, it is possible to allow downloads from only the users you choose, such as members of a common organization, club, or user group. The apps publisher can unhide an app published in this way so that any Store user can find and download it.
As with other distribution methods, Microsoft has official documentation on target app distribution on MSDN.
Note that applications containing company-sensitive information would probably be more securely distributed via Company Application Distribution than by this method, because even when an app is targeted and therefore hidden in the Store, if users somehow find the app’s link, they will be able to download it as any normal app.
Sideloading applications using developer functionality is the most general and easily available way of installing apps without code signing. Having this ability is practically a necessity as well from the standpoint of a developer, because truly knowing whether apps work on real phones without actually testing them is very difficult.
Installing applications as a developer requires the user to register for a developer account, and then register her device, thereby attaining “developer unlock.” The process is quick and easy and is carried out using the Windows Phone Developer Registration application (explained at http://msdn.microsoft.com/en-us/library/windowsphone/develop/ff769508(v=vs.105).aspx
), which comes as part of the WP8 and WP8.1 SDKs. Each developer account is capable of unlocking three devices. One device can be developer unlocked without having a developer account—all that is needed is a Live ID.
After the user has unlocked her device for development she can deploy application packages to it using the Application Deployment tool, which also comes bundled with Windows Phone SDKs. Applications being deployed do not need to be signed in any way; users are free to create app packages and distribute them to other users with developer-unlocked devices, and likewise install unsigned apps created by other developers, bypassing the Store and enterprise distribution. From a hacker’s point of view this is extremely useful for researching and developing capability unlock methods and subsequently developing home-brew applications for personal use and the rest of the Windows Phone hacking community.
Developer unlocking and sideloading (via the Application Deployment tool), and how it is carried out is discussed in more detail later in the “Developer Unlocking Your Device” section, where we discuss how to build an environment suitable for penetration testing, exploring, and reverse engineering Windows Phone applications.
As with all penetration testing and exploratory activities having a setup that facilitates a certain degree of probing into an application’s internals is necessary. Likewise, being well equipped with essential tools and familiar with how to use them and how they can be of use in your assessments is important.
Having the tools and knowledge is even more essential when assessing applications that are running on mobile platforms. Whereas standard desktop applications can usually be disassembled (that is, using IDA Pro) and their behavior observed using debugging, instrumentation utilities, most modern mobile operating systems are far less open.
To serve as an example, consider an application installed on a desktop Windows system, such as Windows 8. A penetration tester can trivially attach a debugger of his choice (Windbg, OllyDbg) and analyze the app’s behavior using tools like ProcMon.
Similarly, a user on Linux can attach and debug using GDB or Valgrind and can use strace
, ltrace
, and lsof
to observe various behaviors.
Testers in more open computing environments have far greater insight into how applications are behaving on the dynamic level and getting at binaries for static analysis is somewhat easier for them.
Most recent mobile operating systems are much more closed, and even though you may consider yourself the device’s owner and administrator you are still dealing with a closed-computing platform—at least in comparison to most desktop environments.
To assess the security aspects, having more involved access to a device than users were supposed to be able to have—for example, when we do not have source code available for the app being tested—is therefore beneficial and oftentimes necessary. This generally involves bypassing the blackbox nature that Windows Phone devices are intended to be by overcoming some of the security controls put in place by the vendor. In many cases the tester is more fortunate and will have access to source code of the application. Whichever is the case, the tester will be in much better stead to carry out assessment from a solid test environment with the right tools, and with favorable privileges and conditions.
This section guides you through the process of building such an environment, from obtaining SDK tools such as Visual Studio and the emulators, to unlocking application capabilities and getting access to the filesystem of a device.
SDK tools are core to development and security review activities on Windows Phone 8.x. Two of the most important tools included in the Windows Phone SDKs are Visual Studio and the emulator. You’re likely to find use of these tools in reviewing code (either original or reversed code) and running apps from source, respectively. In the next few sections we’ll discuss how to obtain these tools and give a general introduction to them.
SDKs are made available for Windows Phone 8 and Windows Phone 8.1 development by Microsoft for free of charge.
Choosing a suitable SDK package equipped for use in Windows Phone work depends on the version of Windows Phone that you are interested in; for Windows Phone 8.1, Microsoft provides a free Visual Studio Express 2013 package that includes the Phone 8.1 SDK, emulators, and other WP8.1 development tools, in addition to development environments for other types of apps.
For exclusively Windows Phone 8 activities that don’t include Windows Phone 8.1, Microsoft provides a free SDK 8.0 bundle that includes Visual Studio Express 2012 for Windows Phone, the complete SDK, emulators, and additional WP8 developer tools.
These two SDK options are available from http://dev.windowsphone.com/en-us/downloadsdk
, but we’ll just briefly summarize the differences between these two SDKs in the next three passages.
You should install the Windows Phone 8.1 SDK, because Windows Phone 8.1 SDK is equipped for both Windows Phone 8 and 8.1 development, and it’s likely that you will want to deal with both WP8 and WP8.1 applications. The Windows Phone 8.1 SDK is equipped for development of both WP8 and WP8.1 apps, but the converse is not true. It should be noted that the Windows Phone 8.1 SDK requires Windows 8.1 or later to be installed. Windows 8 is not supported.
The complete Windows Phone 8.1 SDK can be obtained by visiting the following link: http://www.visualstudio.com/downloads/download-visual-studio-vs#d-express-windows-8
. Alternatively, if you already have Visual Studio 2013 installed, you can simply install Update 3, which contains material needed for Windows Phone development, via this link: http://www.visualstudio.com/en-us/downloads#d-visual-studio-2013-update
. Both of these packages require at least Windows 8.1 x86 to be installed for Windows Phone 8.1 development; however, the emulators require at least Windows 8.1 Professional (x64) and a processor that supports Client Hyper-V and Second Level Address Translation.
If you aim to review only Windows Phone 8 applications, you can just download the Windows Phone SDK 8.0 directly from this URL: http://go.microsoft.com/fwlink/p/?LinkId=265772
, and you can also download and install any updates that are also available under the Windows Phone 8 heading on http://dev.windowsphone.com/en-us/downloadsdk
. Installation of the Windows Phone 8 SDK requires at least Windows 8 or later, and the emulators require a processor that supports Client Hyper-V and Second Level Address Translation.
Whichever package you choose, it will be downloaded as an MSI installer. Installation should be simple, assuming you have the necessary system specifications. Installation of any of the packages with the standard options is quite sufficient.
Visual Studio is Microsoft’s official integrated development environment, and it’s used for development of virtually all applications that use Microsoft technologies or run on Windows platforms. Windows Phone is no exception.
In addition to being ready for the development of the several kinds of standard Windows projects, the Visual Studio packages mentioned previously also integrate several features that are useful specifically for Windows Phone development. For example, various project templates are available when creating a new project via File New Project, as shown in Figure 10.6.
Existing solutions and projects are easy to open in the same way as other Visual Studio projects; either by double-clicking the solution or project file (for example, .sln
) in Explorer or by locating the solution using File Open Project.
You are likely to make extensive use of Visual Studio in your security assessments, particularly in the following areas:
For example, after a codebase has been developed or otherwise loaded into Visual Studio, running the application in the emulator with debugging (F5) or without debugging (Ctrl+F5) is a trivial task.
If the app is launched with debugging, any breakpoints set will be active, and the offending line of code will be shown with the runtime and/or register state if an unhandled exception occurs.
Having a working development and build environment at hand is useful for prototyping and testing code fragments. When testing and code reviewing applications from a security standpoint being able to observe exactly what happens when a certain piece of code executes is often handy, because API behavior can often be unclear from documentation and having proof of behavior generally serves to eliminate any doubt about whether suspect code is actually buggy.
A thorough introduction to Visual Studio’s many features is beyond the scope of this book, but Microsoft has many online resources discussing the software, its usage, and use of its features. See http://msdn.microsoft.com/en-gb/vstudio/aa718325(v=vs.110).aspx
and http://www.visualstudio .com/
for further references.
The Windows Phone emulators are invaluable tools that come bundled as standard with the WP8 and 8.1 SDKs. If you installed either or both of the SDK packages described in the previous section, you will now have the emulator for WP8, WP8.1, or both. In both cases the emulators are applications that provide Windows Phone environments using Microsoft’s native hypervisor, Hyper-V.
The execution environment provided by the emulators closely matches the environment you would typically find when executing applications on real Windows Phone devices. The emulator is not an emulator or simulator, like the iPhone simulator is, for example, but is in fact a genuine Windows Phone instance, albeit one running in a virtual machine instead of on a mobile device. So, for example, all the same sandbox and capabilities restrictions apply in the emulator just as they do when an app is deployed to a device.
There are two primary ways of running applications in the emulator:
After the Application Deployment application has been launched, the tool allows you to choose a target device, which includes several different emulator options. The user can then browse the filesystem and select which application package to deploy, and then click Deploy to install the app and launch the emulator.
Note that applications that have been downloaded from the Store cannot be run on the emulators, because they are DRM protected; these files can only be deployed to real devices. The emulator is useful in scenarios where you have access to a project’s source code, or you have been given an application package for testing that has been built and given to you without being put through Store certification first.
When carrying out experiments and security assessments, having the ability to run code on your device without having to get it signed first is important. This is where developer unlock is useful, as mentioned earlier in the “Developer Sideloading” section. Developer unlocking your device enables you to sideload unsigned apps onto your device.
However, reasons exist for why developer unlocking a device is useful from a security testing perspective. We mentioned earlier that having abilities that are not normally offered by the OS, such as being able to view the filesystem, is often necessary in mobile application assessments. Because things like “full” access to the filesystem are not normally offered by Windows Phone, hacker-types must exploit weaknesses in the OS and OEM software to obtain these kinds of abilities. However, to exploit such bugs, you need to be able to run code on the device that would certainly not be approved by the Store vetting process.
The next section (“Capability Unlocking and Beyond”) covers how exactly to gain these advanced abilities, but first we explain how to achieve developer unlock on your device, because it is a necessary precursor as we implied earlier. Follow these steps to developer unlock your WP8 or WP8.1 device:
Log in with the credentials for your Windows Live or Developer account.
If everything goes smoothly, the tool should successfully developer unlock the phone.
Because the device is now unlocked, you’re free to deploy unsigned application packages via the Application Deployment tool. This leads nicely into the next section, where we delve into gaining the sort of access and capabilities on the device that are necessary or at least helpful for in-depth exploration and security assessments.
To make a device useful for penetration testing activities, you need certain abilities. Since Windows Phone is a closed computing platform, users are not provided with a way to carry out explorative activities like browsing the filesystem, or viewing the registry.
Having a device that affords you these luxuries is absolutely essential to conducting a thorough and successful security review of an app, since having the ability to access the device’s filesystem allows you to extract an application’s assets from the device, including but not limited to its .NET assemblies, its binaries, and its manifest file. Extracted files can then be analyzed and reverse-engineered, and code-reviewed in the case of extracted .NET assemblies. A security assessment turns from being a blackbox app review, to a whitebox or code review.
In addition, full access to the underlying filesystem allows a penetration tester to discover what an application is storing on the filesystem, such as cookies, web cache, sensitive files that are unencrypted, and credentials in cleartext files. Having the ability to know what an app is storing on the filesystem, and whether such data is encrypted, is a vital part of a mobile app security assessment.
Having the ability to browse the registry is also very useful when reviewing non-third-party apps, such as those written by OEM vendors, because many such apps will have the ID_CAP_INTEROPSERVICES
capability and use that capability to write to the registry.
Gaining the ability to sideload applications with those not intended for third-party applications is known as “capability unlocking”. The ability to sideload arbitrary apps with the ID_CAP_INTEROPSERVICES
capability is particularly interesting because it grants sufficient privileges to browse most of the registry, and edit and add to large parts of it.
Capabilities such as ID_CAP_INTEROPSERVICES
were never intended to be granted to third-party apps; instead, they are normally accessible to OEM and first-party applications. Unlocking ID_CAP_INTEROPSERVICES
is known in the Windows Phone hacking community unanimously as interop unlock. Unlocking various high privilege capabilities also allows various community and homegrown hacking tools to be installed on your device that are useful whilst carrying out penetration tests.
Gaining access to privileged capabilities and gleaning filesystem access is possible on some Windows Phone devices on the market, in three general ways:
How you unlock high-privileged capabilities and gain filesystem and registry access depends on the brand and version of device you have, and the version of Windows Phone that is installed on the device.
At present, the following devices have been hacked to the point that at least the ID_CAP_INTEROPSERVICES
capability is available (to third-party apps), and filesystem access has been gained:
lordmaxey from XDA-Developers has also reportedly unlocked a Nokia Lumia for all capabilities provided by the OS, while the device was running Windows Phone 8. Readers who are well-versed in electronics may be able to reproduce these results, but we do not recommend it. The relevant thread on XDA-Developers is available at: http://forum.xda-developers.com/showthread .php?t=2713098
.
For penetration testing and other explorative purposes, we recommend that you obtain either a Samsung Ativ S GT-I8750 or a Huawei Ascend W1-U00. Both of these devices can be interop or fully unlocked, and filesystem access can be gained, on devices running both Windows Phone 8 and Windows Phone 8.1.
Since the latest release of Windows Phone at the time of this writing is 8.1, we strongly recommend that your testing device be running Windows Phone 8.1. This makes sense because an increasing number of app developers do and will continue to release their apps to target only 8.1 and higher (as APPX packages). With that being said, we advise following the instructions in the “Samsung Ativ Interop Unlock and Filesystem Access on Windows Phone 8.1 via Custom MBN” section (for readers with a Samsung Ativ I8750) or the “Huawei Ascend W1 Interop Unlock and Filesystem Access on Windows Phone 8.1” section (for readers with a Huawei Ascend W1).
We will, however, still give instructions and advice on preparing a device of these two models that is running Windows Phone 8.
We will now discuss how to prepare Samsung Ativ GT-I8750 and Huawei Ascend W1 devices for penetration testing activities, in the following few sections.
If you’re intent upon using a device running Windows Phone 8 (and not 8.1), the following instructions will unlock all capabilities provided by the OS, and will allow full filesystem access to the device via USB mass storage. Our recommendation, however, is that you upgrade to Windows Phone 8.1 and transform your device into a penetration testing-ready device via flashing an MBN (see “Samsung Ativ Interop Unlock and Filesystem Access on Windows Phone 8.1 via Custom MBN” later in this chapter).
With that being said, it’s possible to capability unlock the Samsung Ativ GT-I8750 when its running Windows Phone 8 with the update level at GDR2 or below (i.e., OS version 8.0.10327.77 or 8.0.10328.78). The unlock allows all capabilities offered by the OS to be unlocked for use by third-party applications.
The GDR3 update blocked access to the exploitable functionality, thus if you are running Windows Phone 8 GDR3 and above, you must first flash your Ativ back to GDR2 before the capability unlock procedure described in the link shown will work. Instructions and materials for flashing the device’s ROM back to GDR2 are available at several online resources, such as in this thread http://forum.gsmhosting.com/vbb/f200/samsung-ativ-s-i8750-wp8-hard-reset-tutorial-firmware-flashing-guide-1671518/
.
In particular, the core vulnerability that allows ID_CAP_INTEROPSERVICES
and others to be unlocked in ATIV devices is the Diagnosis application, which was written by Samsung, the device’s vendor. It has the ID_CAP_INTEROPSERVICES
capability and it provides powerful functionality such as registry writing, which is obviously interesting from a privilege escalation standpoint.
The Diagnosis application is not installed by default for obvious reasons but is installable via a secret dialer code. After you install it, you can use the Diagnosis app’s registry writing functionality to unlock ID_CAP_INTEROPSERVICES
and subsequently every capability in the OS.
The vulnerabilities and exploit apps used in Samsung device unlocks were researched and developed by several members belonging to the XDA-Developers forum. Some of these researchers include -W_O_L_F- and GoodDayToDie, who are perhaps jointly responsible for the Samsung Ativ S interop unlock; cpuguy is also due credit for discovering that reaching Diagnosis’ registry editor via a toast notification is possible.
Following the guidelines given here should, if carried out correctly, result in the Ativ’s being unlocked for the deployment of apps with all capabilities. Other interesting abilities, such as being able to browse the device’s entire filesystem as well as downloading and modifying files on it, should also be possible. We take no responsibility from any damages resulting directly or indirectly from following the instructions given here, because devices could possibly end up bricked if something goes wrong.
Download the Interop_Unlock_Helper_Debug_ARM.xap
application (http://forum.xda-developers.com/attachment.php?attachmentid=2526341&d=1390156486
) and sideload it to the developer-unlocked Samsung Ativ S using the Application Deployment SDK tool. (See Figure 10.9.)
This application is a helper app designed to leverage the secret registry editing functionality within the once-hidden Samsung Diagnosis tool.
Start the device’s dialer application and enter the secret dialer code to install Diagnosis. The code is ##634##. Diagnosis installs, and a new dialer screen reading Odyssey_...
appears. This is the Diagnosis app, which is now installing. Press the Windows button to exit it.
Run the Interop Unlock Helper app on the device and tap Next until the app’s screen reads Step 2.
Choose your Samsung model and tap Send toast. This sends a clickable toast notification that provides an entry point into Diagnosis’ registry editor functionality.
Tap the toast notification to enter Diagnosis’ registry editor. Navigate back to the unlock helper app without closing Diagnosis, and tap Next. In particular, the toast notification opens Diagnosis’ registry via the following URI: App://07a20ad9-a4f9-3de3-855f- dcda8c8cab39/_default#/WP8Diag;component/7_ETC/RegistryOperationsCheck.xaml
.
Put a check mark in the HKEY_LOCAL_MACHINE
and Check if value is DWORD boxes. Enter software\microsoft\devicereg\install
into the Registry Path To Operate field, enter MaxUnsignedApp
into the Key field, and enter some arbitrary value above 300 as the key’s new value. Click Write to write this new value. Even though an error message may appear indicating the write failed, this is common—ignore it. (See Figure 10.10.)
Untick the Check if value is DWORD box, ensure that HKEY_LOCAL_MACHINE
is still ticked, and then in the Registry path to operate field enter software\microsoft\devicereg
, and for Key type PortalUrlProd. For the key’s value enter the following string: http://127.0.0.1
, and click Write. See Figure 10.11.
Ensure that the Check if value is DWORD box is still unticked, ensure that HKEY_LOCAL_MACHINE
is still ticked, and then in the Registry Path To Operate field enter software\microsoft\devicereg
, and for Key enter PortalUrlInt. For the key’s value enter the following string: http://127.0.0.1
, and click Write.
The device is now interop unlocked; the registry editor and unlock helper app can both be exited. The next couple steps unlock the remainder of the OS’s privileges so that any capabilities can be used with newly sideloaded apps.
Download the BootstrapSamsung_Release_ARM.xap
app (http://forum.xda-developers.com/attachment.php?attachmentid=2258632&d=1379229845
), sideload it to the device using the Application Deployment software, and then run it. A success message appears. Exit the app.
Download the EnableAllSideloading_Release_ARM.xap
(http://forum.xda-developers.com/attachment.php?attachmentid=2258633&d=1379229845
) app, sideload it to the device using the Application Deployment software, and then run it. The app displays a success message, so now exit the app.
The Ativ is now unlocked for all capabilities.
With the device unlocked, it is possible to sideload devices requesting any capability the OS supports. This opens interesting possibilities for exploration of the device and security assessment of installed applications.
Assuming the device has at this stage been successfully capability unlocked, you can now install an XDA-Developers born home-brew application called SamWP8 Tools. The application was written by -W_O_L_F- from XDA-Developers.com and can be downloaded from http://forum.xda-developers.com/showthread .php?t=2435673
. This app requests privileged capabilities, so capability unlocking your device before attempting to install it is necessary.
Among other interesting features, this tool is able to apply a registry tweak that tells the Media Transfer Protocol (MTP) service to serve the C:\
root instead of just the media directories (that is, photos, music, and so on) as it usually does. A registry key is also modified so that the MTP service serves up the C:\
with LocalSystem
privileges, giving full filesystem access.
You can deploy SamWP8 Tools in the same manner as any home-brew XAP application—using the SDK Application Deployment tool. (See “Developer Unlocking Your Phone” for information on using the Application Deployment tool.)
The Full FS Access option is located on the “tweaks” screen of the SamWP8 app, accessed by opening the app and swiping left. The box should be ticked to apply the appropriate registry modification. (See Figure 10.12.)
After you tick the box, you should reboot the device.
At this point you can browse and modify files on the device’s filesystem by plugging the device into another system via USB as a normal mass storage device. Any standard file manager will suffice for viewing the device’s filesystem, including Explorer, a shell, or another file manager of your choice. Figure 10.13 shows an Ativ’s filesystem being browsed after using SamWP8 to carry out the MTP registry hack.
You can find a quasi-official thread for the tools used in the preceding process on the XDA-Developers.com forum at the following URL: http://forum.xda-developers.com/showthread.php?t=2435697
.
Several members of the XDA-Developers.com community have released MBN files that can be flashed to compatible Samsung devices running Windows Phone 8.1 to unlock the ID_CAP_INTEROPSERVICES
capability (and others) and apply registry hacks to allow full filesystem access.
MBN files, simply put, allow modifications to a phone’s settings, apps, and registry to be made. These changes are made when the MBN is flashed to the device. Several members of the Windows Phone hacking community have created MBN files so that when flashed to a device, various capabilities are unlocked and registry hacks are made so as to allow full filesystem access to the device via USB mass storage mode.
Typical MBN files released in the community also make other tweaks to the device’s settings, such as creating or removing tiles, and tweaking other device settings.
Most work in this area appears to be heavily based on -W_O_L_F-’s and GoodDayToDie’s work on unlocking capabilities and on _-WOLF-_’s MBN creation work.
There are a number of options available in terms of choosing which MBN file to flash to your Samsung Ativ device running Windows Phone 8.1, but our current favorites are Spavlin’s (also from XDA-Developers) -W_O_L_F-’s ROMs, so we’ll now discuss how to flash these MBNs to your device. We’ll also list some of the additional features and tweaks that these MBNs apply so that you can choose one.
Spavlin of XDA-Developers published an MBN that when flashed to a Samsung Ativ device, provides the following:
The UI skin appears as a gray/silver color, as in the screenshot below.
If you’d like to opt to use this MBN, you can download it from here, as Spavlin’s original thread: http://forum.xda-developers.com/showthread.php?t=2727667.
Either CMK or CMJ version will do.
Spavlin’s MBN is believed to be based on work by -W_O_L_F-, but may have included features that were not included in -W_O_L_F-’s original ROM, including interop unlock.
At this point, you can proceed to the “How to Flash the MBN to a Device” section, to flash the MBN to your device and thereby prepare it to serve as a penetration testing device.
-W_O_L_F- has also released an MBN. The MBN, version 2.1 at the time of this writing, introduces the following features to a phone that it is flashed on:
-W_O_L_F-’s MBN was quite possibly the first publicly released modification released by the Windows Phone hacking community. The MBN may be downloaded via this URL: http://forum.xda-developers.com/attachment.php?attachmentid=2703339&d=1398239287
. The official thread on XDA-Developers is here: http://forum.xda-developers.com/attachment.php?attachmentid=2703339&d=1398239287
.
Having chosen this MBN, you may now proceed to the next section, “How to Flash the MBN to a Device” to gain the MBN’s features, i.e., interop and full filesystem access among others, and thereby prepare your device for penetration testing.
Now that you’ve chosen either the -W_O_L_F- or Spavlin MBN, you can now proceed to flash it to your Samsung Ativ device.
Once the MBN has been flashed to the device, the device will be interop unlocked and will allow the tester to gain access to its filesystem. Flashing the MBN is trivial if done correctly; the steps below should be followed very closely, because omission of details could end in you bricking your device.
http://support.moulnisky.com/index.php?dir=Samsung/Firmwares/GT-I8750/Downloader/
.http://forum.xda- developers.com/attachment.php?attachmentid=2811394&d=1403430057
and unpack the archive. You use a fake ROM file because you don’t actually want to flash a ROM to the device. You just want to flash an MBN file and keep the device’s current ROM. As such, the fake ROM is just a file that is loaded into the flashing tool to make the tool happy.No
. This is very important. You do not want to flash a fake ROM to your device!At this point, your device will be quite well prepared for penetration testing already; your phone will be developer unlocked, interop unlocked, and various other interesting capabilities will be available when you are installing apps. Additionally, filesystem access is available when you plug the device into your computer via USB as a mass storage device. You have filesystem access by means of plugging the device into a computer via USB.
You can read the sections “Using Filesystem Access” and “Using Registry Access” to learn how to use your newly gained privileges and to begin the security-related exploration of your device.
A Windows Phone hacking community member named “reker” has produced a tool named rkBreakout, which capability unlocks (including ID_CAP_INTEROPSERVICES
) at least Huawei Ascend W1-C00 and Huawei Ascend W1-U00 devices that are running Windows Phone 8. This tool does not work for devices running Windows Phone 8.1.
We have not tested this tool, but according to the original thread, the tool works as advertised; the tool has been verified as working by various members of XDA-Developers.
The tool may be downloaded from the original thread, which is located at the following URL: http://forum.xda-developers.com/showthread.php?t=2707074
.
In addition to unlocking interesting high privilege capabilities, the registry is also hacked to similar effect as the aforementioned Samsung hacks, in that the MTP (Media Transfer Protocol service, i.e., which deals with USB mass storage) service runs as LocalSystem
and has its root set at C:\
.
WojtasXda, on XDA-Developers, has released a custom ROM intended for Huawei Ascend W1-U00 devices. The ROM has the following features:
The ROM and the flashing tool are available in the original thread by WojtasXda, which is located here: http://forum.xda-developers.com/showthread .php?t=2686053
.
The thread also contains instructions for flashing the ROM to your device.
We have not tested this ROM and its accompanying tool, but feedback in the thread firmly ascertains that the release works as advertised.
Once the instructions in the thread have been followed, your device should be fully capability unlocked, including interop unlocked, and will allow full filesystem access via USB mass storage mode.
After you’ve capability unlocked your device and hacked the device for filesystem access, you can begin browsing the filesystem.
Having this ability can be very useful in security assessments for a number of reasons, including:
The locations on the filesystem of particular interest for security reviews are:
C:\Data\Programs\{GUID}\Install
—This is where application binaries/ .NET assemblies are located, in addition to application assets and manifest files, where {GUID}
pertains to a particular application.C:\Data\Users\DefApps\APPDATA\{...}
—Application sandbox directories, where apps can store data, which could potentially be sensitive—where {GUID}
pertains to a particular application.The majority of files on the device can be both read and written, since the MTP service will be running as LocalSystem. Read access is obviously useful for extracting files and analyzing or reverse engineering them, and write access can be useful in the context of patching application files, among other things.
This ability to access the device’s filesystem will be a cornerstone for your penetration testing activities; you can use it to extract apps and their assets from your device, and you can also examine the contents of an app’s filesystem sandbox.
For example, once you extract .NET assemblies and native binaries from an application’s directory, you will then be able to use a .NET bytecode reverse engineering tool (.NET reflector, for example) or disassembler (i.e., IDA Pro) to reverse the app and then carry out a security review. You’ll also have the ability to analyze any data that is stored by the app in its local storage, to check for data leaks and absence of crypto use on sensitive data.
Figure 10.16 shows an application’s install directory being browsed.
The remainder of the Windows Phone sections rely quite heavily on you having filesystem access to your device so that you can extract its app binaries and view its filesystem sandbox.Examination of application binaries that have been extracted from the device’s filesystem will be revisited in the later section “Reverse Engineering.”
The best method for browsing the device’s registry at present is via GoodDayToDie’s Native Access Webserver. This app is a basic web server that runs on the device and provides an interface for browsing the device’s filesystem and registry.
There are two releases of this app; one with all capabilities enabled in its manifest, and one with a certain subset. If your device is running Windows Phone 8 (as opposed to 8.1), you will have to install an older version of the app, since later versions request capabilities that do not exist in Windows Phone 8. You can deploy the app using the Application Deployment tool, which is packaged with the SDKs.
The server listens on TCP port 9999 by default. Once the server is running, you can navigate to it either via your desktop or laptop browser (or indeed your device’s browser, if you wish).
You can obtain the app from its codeplex site: http://wp8webserver .codeplex.com/
.
At this stage, it is assumed that you now have a hacked test device and a suitable test environment with the SDK (i.e., Visual Studio and its accompanying tools, including the emulators).
Several tools that are likely to prove useful in Windows Phone hacking repertoire (and in penetration testing in general) are listed here, along with their use cases:
https://www.hex-rays.com
)https://www.hex-rays.com
)http://www.red-gate.com/products/dotnet-development/reflector/, http://ilspy.net
)http://reflexil.net
)http://wp8webserver .codeplex.com/
)http://wp8fileexplorer .codeplex.com/
)http://www.portswigger.net
)Once you’ve gained filesystem access to your test device, application binaries and .NET assemblies can be extracted, analyzed and reverse engineered. In cases where source code for an app is unavailable, the best method for carrying out a thorough security assessment is via reverse engineering; the app’s .NET assemblies and binaries can be extracted from your device, at which point you will reverse engineer them and begin your security review in an effort to uncover its internals and security aspects on the code level. When an app is comprised of .NET assemblies, it’s possible to recover an app’s code, allowing a relatively straightforward code review of the app. Accessing the device’s filesystem, extracting assets, and then reverse engineering or otherwise analyzing them will form one of the cornerstones of your security review methodology for Windows Phone apps.
The Windows Phone 8.x OSes store application binaries, .NET assemblies and other assets (including the manifest) in the app’s respective Install
directory C:\Data\Programs\
on the filesystem. Each application installed on the device has its own directory there, where its name is a GUID; for example, C:\Data\programs\{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}
.
Inside each app’s directory is an Install directory. Among other things, this folder houses the application’s native binaries and .NET assemblies. If you have gained filesystem access to your device, you can extract these binaries and begin reverse engineering them. Figure 10.16 shows a .NET assembly in the Install directory of a Samsung OEM app about to be disassembled with .NET reflector.
After binaries have been extracted from the device, they can be disassembled/decompiled and analyzed. Reverse engineering, coupled with manual testing, can represent a strong approach to security reviews, especially when source code is not available for review.
Managed .NET assemblies (DLLs) can be reversed back to accurate C# source code representations using tools like .NET reflector, and the resulting code can be analyzed using standard manual code review techniques.
When you encounter and extract native code components from a device, you can disassemble their code using high-quality tools like IDA Pro. Application internals can be studied by reviewing the outputted assembly code, optionally using the Hex-Rays plug-in for generation of C/C++ pseudo-code approximations, which may allow for more efficient code reviewing for some readers.
Any HTML and JavaScript files stored locally for use by an app can also be extracted from the device, and subsequently analyzed.
Chapter 11 discusses further activities involving reverse engineering and application patching.
When reviewing a Windows Phone native binary, whether it was extracted from the device via the methods discussed so far, or obtained from a client’s non-Store XAP/APPX file, checking for the presence of exploit mitigation features on the binary is a vigilant practice from a security perspective.
Exploit mitigation features were discussed earlier, see the “Exploring Exploit Mitigation Features” section for more information.
Microsoft released a useful tool named BinScope, available at http://www .microsoft.com/en-gb/download/details.aspx?id=11910
, the sole purpose of which is to analyze a native binary for use of recommended (or compulsory for some Stores) exploit protection features.
Among other problems, BinScope has the ability to test for
/GS
protections (stack cookies and other stack overflow protections such as variable reordering)NXCOMPAT
(DEP)SafeSEH
/DYNAMICBASE
(ASLR)When run against a binary, the BinScope tool generates an informative report that lists the results of the anti-exploit features.
BinScope tests are included in Microsoft’s Windows Phone 8.1 certification requirement tests to ensure that native 8.1 Phone binaries have all the flags that Microsoft demands, which in particular are
/SafeSEH
exception handling protectionAppContainerCheck
ExecutableImportsCheck
WXCheck
In addition, non-native .NET assemblies are scanned for presence of the AllowPartiallyTrustedCallersAttribute
attribute, which is disallowed.
For further information on BinScope’s catalog of tests, see http://msdn.microsoft.com/en-us/library/windowsphone/develop/dn629257 .aspx#binscope
.
This chapter introduced Windows Phone applications in general. You’ll have gleaned an appreciation of the sandboxing model, the various security features that the Windows phone operating systems have, as well as some app fundamentals.
Following the advice in this chapter, you’ll also hopefully have a test environment setup, which will allow you to begin security reviewing Windows Phone apps.