CHAPTER 5
BlackBerry Security

image

BlackBerry devices are produced by Research In Motion (RIM), a Canadian company who first introduced the BlackBerry in 1999 as a messaging pager and PDA that could be used to access corporate e-mail. In 2002, the BlackBerry 5810 was the first device to add phone features. RIM designs all BlackBerry devices and produces the proprietary BlackBerry OS. The first BlackBerry devices had a distinctively boxy shape with a full QWERTY keyboard and side-mounted scroll wheel. The combination of a complete keyboard, enterprise management features, and robust e-mail integration have made the BlackBerry very popular.

Introduction to Platform

Modern BlackBerry devices are more consumer friendly than their predecessors and have consumer features, including GPS, camera, full web browser, and media player. RIM released its first touch-screen device, the BlackBerry Storm, in 2008. BlackBerry OS versions more recent than 4.6 include a full HTML/JavaScript/CSS2-capable web browser and can be used to browse most Internet sites, including those that use AJAX technologies. Versions of the browser prior to 4.2 are incomplete and do not support advanced web functionality.

RIM encourages third-party application development and provides fairly complete documentation and developer support via forums. The BlackBerry OS is primarily Java and supports J2ME Mobile Information Device Profile (MIDP) 1.0, a subset of MIDP 2.0, Wireless Application Protocol (WAP) 1.2, and Connected Limited Device Configuration (CLDC) profiles natively. A RIM proprietary Java API for using device-specific features is required to take complete advantage of the BlackBerry platform. Applications are able to use RIM, MIDP, and CLDC APIs all at once, but RIM’s UI classes can only be used within CLDC applications because their GUI threading model conflicts with MIDP applications. For that reason, most BlackBerry-specific Java applications are CLDC based and use RIM’s proprietary APIs. RIM calls these applications “RIMlets” (http://developers.sun.com/mobility/midp/articles/blackberrydev/). Developers may also write applications using alternate development technologies, including a data-driven web service model targeting the Mobile Data System (MDS) runtime.

Most mobile devices “poll” the server on an intermittent basis to check for new messages; the BlackBerry uses a “push” technology, where the server initiates the communication immediately after a message arrives. Proprietary RIM server software monitors users’ e-mail accounts and initiates the push. Policy, applications, and other messages can also be sent using this mechanism. To save on bandwidth, the server compresses messages before sending them to the device. The “push” architecture prolongs battery life and decreases message delivery latency because the device does not burn the battery by pinging the server to ask for new messages.

Every BlackBerry device has a globally unique personal identification number (PIN) that identifies the device for both messaging and management. Unlike a bank account’s PIN, the BlackBerry PIN is public. Users employ PINs to find each other over BlackBerry Messenger, and administrators can use PINs to identify the devices they are managing.

BlackBerry Enterprise Server (BES)

Most organizations with BlackBerry-equipped employees will install BlackBerry Enterprise Server (BES). BES integrates with corporate e-mail servers (including Exchange, Lotus Notes, and Novell Groupware), monitors users’ accounts, and pushes out e-mail and attachments once they arrive. Administrators can also use BES to control devices and deploy applications, author device policy, and force a remote device wipe. The high level of control afforded by BES pleases control-happy administrators and makes BlackBerry the current leader in enterprise manageability of devices.

Once a device is associated with a BES instance, an encrypted tunnel is created between the device and its BES. All traffic flows over this tunnel, with the BES acting as a bridge between the carrier’s mobile network, the Internet, and the company’s intranet. The Mobile Data System (MDS) component of BES is responsible for actually performing the internal routing and bridging.

Most public BlackBerry security research has focused on the BES/device relationship because BES provides a bridge between the trifecta of the Internet, intranet, and carrier networks. This chapter takes a different approach and covers the on-device security itself, especially as it relates to applications. For an in-depth security analysis of BES, refer to RIM’s documentation, FX’s BlackHat presentation (http://www.blackhat.com/presentations/bh-europe-06/bh-eu-06-fx.pdf), and Praetorian Global’s Defcon presentation (http://www.praetoriang.net/presentations/blackjack.html).

BlackBerry Internet Service (BIS)

For consumers and small businesses without BES, RIM operates the BlackBerry Internet Service (BIS). Every BlackBerry purchased with a data plan can associate with BIS and access the Internet and personal POP3/IMAP e-mail accounts. BIS is branded per-carrier but the service is actually run by RIM and includes MDS and the BlackBerry Attachment Service (BAS). Unlike an enterprise BES, BIS does not push out policy and leaves it up to users to control and manage their devices.

Device and OS Architecture

RIM tightly controls information about BlackBerry internals, making few details publically available. At the time of this writing, version 4.7 is the most current version of the BlackBerry OS, and BlackBerry OS 5.0 has been announced. Despite the large swings in version numbers, the core architecture has not changed dramatically.

Original BlackBerry pager devices used Intel 80386 processors, and RIM provided a low-level C API to developers. Preventing security coding errors and controlling application behavior are really difficult when writing code in unchecked native languages. So when the 5810 was introduced, the 80386 processor and C API were abandoned in favor of ARM 7 or 9 processors and a JME runtime environment. To increase speed, RIM created a custom Java Virtual Machine (JVM) that supports the standard JME instruction set and several RIM JVM-specific instructions. A complete list of these opcodes is available from Dr. Bolsen’s GeoCities website at www.geocities.com/drbolsen/opcodes.txt. Only the device and JVM are still written in C/C++ and assembly. All other applications, such as messaging and the browser, are written using Java.

The BlackBerry OS is a modern OS with features such as multitasking, interprocess communication (IPC), and threads. All OS and device features are accessed using RIM and J2ME APIs. Security is enforced using a combination of signatures, Java verification, and class restrictions. The JVM does not support Java native invocation (JNI) or reflection, which should prevent attackers from controlling the device in ways that RIM did not intend.

The security system is intended to control access to data and does not prevent applications from consuming an unfair share of memory or CPU time. The OS does not enforce limitations on the number of objects an application can create, and developers are responsible for minimizing the amount of memory and system resources that they use. When the JVM is no longer able to allocate storage space for objects, Java garbage collection runs to remove unused objects from memory. At some point, memory will simply be exhausted, resulting in a JVM OutOfMemoryError.

Each Java object has an object handle that is used as a JVM global identifier for that object. If the application chooses to persist the object, the JVM creates a persistent object handle. The maximum number of possible handles is dictated by the size of the device’s memory. On a device with 32MB of memory, it is possible to have 65,000 persistent object handles and 132,000 object handles. The number of possible object handles is always greater than the number of possible persistent object handles because there is always more SRAM than flash memory. With a system-wide cap on the number of objects, developers must be conscious of how many objects they create or risk negatively impacting other applications. The number of implementation handles is BlackBerry OS version specific and can only be found by consulting the documentation.

Each BlackBerry has two different types of memory: flash and SRAM. Flash memory is nonvolatile and persists even when the device’s power runs out. The BlackBerry OS, applications, and long-lived data such as e-mail are stored within flash memory. Compared to volatile SRAM, flash memory chips are comparatively expensive, so each device has a limited amount. Newer devices have 64MB of flash. SRAM is used for storing runtime object data and holds information only as long as the device has power. Some BlackBerry devices have slots for external flash memory cards, which are used for storing larger objects such as documents and media files.

Development and Security Testing

All third-party applications written for the BlackBerry must be written in Java or use one of RIM’s alternate application development runtimes. The universal use of managed runtimes sacrifices a small amount of speed in favor of reducing the device’s attack surface and increasing developer productivity.

In addition to the Java application runtime, there is the MDS runtime. MDS applications are built using a Visual Studio plug-in, a data-driven presentation language, JavaScript, and specially written web services. Enterprises develop MDS applications to interact with backend systems, such as their inventory or sales systems. These applications are very specialized and will not be discussed in detail in this chapter.

Coding Environment

RIM provides two free Java IDEs: the BlackBerry Java Development Environment (JDE) and the BlackBerry JDE plug-in for Eclipse. The choice of toolset comes down to developer preference because both are similar and freely downloadable from RIM (http://na.blackberry.com/eng/developers/javaappdev/devtools.jsp). For those that abhor GUIs, or have an automated build environment, a command-line toolset is available. For all tools, free registration may be required. The toolset works best on Windows, with some tools not working completely or at all on other operating systems. Some enterprising hackers have reported success running under a Windows emulator such as WINE.

The Java development environments include all of the tools and simulators needed to develop and test BlackBerry Java applications. Prior to each BlackBerry OS release, the JDE is updated with new simulators, libraries, and documentation. From within the JDE or the Eclipse plug-in, you can select the OS version to target, build applications, deploy to the simulator, and debug application code. For more information on configuring and installing the JDE, see RIM’s developer documentation. Applications targeted for older versions of the JDE will still run on newer devices, so developers typically build with the first version of the JDE that includes all of the features they need.

NOTE

When you’re writing a BlackBerry application in Eclipse, the project must be “Activated for BlackBerry.” This can be done by right-clicking on the project in the Package Explorer and verifying that the Activated for BlackBerry option is enabled. This may be the root cause of a project refusing to deploy to a device and is directly to blame for this author’s hair loss.

Java code compiled for the BlackBerry goes through the following steps using the tools mentioned:

1. Code is compiled using the javac.exe compiler, and an application JAR file is generated. At this point, all Java methods, constructs, and classes are fair game.

2. The preverify.exe tool is run against the generated JAR files and looks for code constructs that are not allowed in JME applications (for example, calls to Java native invocation or invalid Java instructions). The pre-verifier is used in both BlackBerry and JME development. Once the pre-verifier step completes, the classes are marked as verified.

3. RIM’s compiler, rapc.exe, converts the verified JAR file to a BlackBerry executable COD file. Rapc is an optimizing compiler that removes symbolic information and adds RIM proprietary instructions to the binary in order to reduce size and improve performance.

4. If the application is going to be deployed to a real device or to a simulator with security enabled, the COD file is signed using the RIM Signature Tool and the developer’s signing keys. For more details on BlackBerry code signing, see the section titled “Permissions and User Controls.”

Simulator

The RIM BlackBerry simulator (a.k.a. fledge.exe) emulates all BlackBerry functionality. Convienently, the simulator and images are bundled with both the Eclipse plug-in and the JDE or are downloadable as a separate package. The simulator natively supports GPS emulation, cellular calls, holstering, and anything else that one would want to do with a BlackBerry.

By default, the BlackBerry simulator files are installed and bundled along with the JDE. To launch the simulator from Eclipse, create a BlackBerry project in the development environment, write the application’s code, and then run the DebugServer profile by clicking on the “play” icon in the toolbar. Eclipse will automatically push the compiled application to the simulator, and it will be available on the Applications screen. If there are any errors, the application will not be loaded and the icon will not show up in the BlackBerry’s Applications menu.

To control the behavior of the simulator, select and configure the Run profile within Eclipse or the JDE. Simulator options are on the Simulator tab of the Run profile and are divided into even more options. The following options are the most relevant when you’re performing security testing:

image    Simulator tab | General tab | Enable Device Security By default, the simulator does not enforce device security requirements. Enabling this option will cause the BlackBerry simulator to enforce signature checks and cause the security subsystem to behave like an actual device.

image    Simulator tab | General tab | Launch Mobile Data System Connection Service (MDS-CS) with Simulator Unless the device is configured for direct Internet access, MDS is required to browse the web and make network connections. For simple application testing, it is easiest to launch the MDS-CS emulator, which proxies emulator network traffic through the PC’s network connection.

When doing security testing, create one simulator profile with device security enabled and one without. This makes it easier to toggle between the two modes to learn more about how the BlackBerry device’s security system works.

Debugging

Debugging live code is a great way to learn about application and operating system internals. Thankfully, both Eclipse and the JDE include a debugger for runtime analysis of BlackBerry Java applications running in either the simulator or on an actual device. To launch custom application code in either environment, click the Debug button on the toolbar. The IDE will launch the simulator, deploy the application, and connect the debugger. After the application is launched, any breakpoints or unhandled exceptions will cause the debugger to break, thus providing you an opportunity to inspect or modify variables and to control execution.

To debug applications on a live BlackBerry device, connect the device to the computer using a USB cable. Within the IDE, select the BlackBerry Device profile. If the device is not automatically detected, open up the property pages and ensure that the appropriate BlackBerry device is associated with this debug profile. To do this, open the debug profile’s property page and click the BlackBerry Device tab. Select the appropriate device from the dropdown list. Remember that all real-world BlackBerry devices enforce code signing, and applications that access privileged APIs will be blocked from running unless they are signed.

Eclipse and the JDE do not allow debugging of applications without source code or “.debug” symbol files. When an exception occurs in a program without debug information, the IDE will display an error. The IDE will not display any disassembly because it is not capable of disassembling the BlackBerry JVM’s proprietary instructions. Despite this limitation, the debugger is a valuable reverse engineering tool for figuring out how the BlackBerry OS works.

For example, create an application which accesses contact information through the javax.microedition.pim.ContactList JME class. Build the application, skip signing, and deploy it on a security-enabled simulator with the debugger attached. The BlackBerry will display a prompt asking if the application should be granted permissions to access personal data. Deny this prompt and a JVM security exception will occur and cause the debugger to break. Here is where it gets interesting; the debugger will show the following stack trace in the Thread information window:

MIDletSecurity.checkPermission(int, boolean, boolean, boolean,
String) line: 518
MIDletSecurity.checkPermission(int) line: 382
PIMImpl.openPIMList(int, int) line: 80
ContactTestScreen.OpenContactItem() line: 112
ContactTestApp.<init>() line: 66
ContactTestApp.main(String[]) line: 49

This experiment reveals several details about what is going on under the covers. First, PIMImpl.openPIMList is the class actually implementing the ContactList functionality. Second, the MIDletSecurity class performs the security check upon object open and not at application startup. Last of all, the names of the internal security classes are revealed, and we know where to look to find out more about the permission system.

NOTE

The behavior for MIDP2 and RIM Controlled classes is different. Unsigned applications that use RIM Controlled classes will fail to load and a security message will be displayed to the user. More information is provided in the section “Permissions and User Controls.”

Disassembly

The BlackBerry JVM uses an extended JME instruction set and a custom package format called a COD file. To make reversing more difficult and improve performance, RIM’s compiler removes debug information and collapses member names when compiling code. The custom instruction set and executable file format are not officially documented, and what is known is spread across the Internet in various blog posts and message boards. All these hurdles make things look pretty rough to the aspiring BlackBerry engineer.

Thankfully, some members of the reverse-engineering community have released information about COD files and some tools to disassemble BlackBerry applications. Most notable are Dr. Bolsen for his coddec tool and Stephen Lawler for updates and instructions. Coddec will do a half decompile/half disassemble on BlackBerry COD files. The disassembly is actually created by modified versions of classes that were decompiled from RIM’s rapc compiler.

Unfortunately, coddec does not come with much documentation, and getting it to build can be slightly challenging. To build and run the tool, follow these instructions, which are based on Stephen Lawler’s work:

1. Install the Java Development Kit (JDK); these instructions are tested with JDK 1.6.0 R13. Also install the BlackBerry JDE, because coddec uses it in its disassembly.

2. Download coddec from Dr. Bolsen’s website (http://drbolsen.wordpress.com/2008/07/14/coddec-released/) and extract the coddec archive to a local directory. For this example, we will call that directory c:coddec.

3. Download Stephen Lawler’s coddec patch (www.dontstuffbeansupyournose.com/?p=99).

4. Apply the patch using the GNU patch command or TortoiseMerge.

5. The patch has one mistake in it, so manually change the code

c c1 = new c(l, j, i1, dataoutputstream1);

in et im oolscompilerexecc.java to the following:

c_static c1 = new c_static(l, j, i1, dataoutputstream1);

6. Copy net_rim_api.jar from Program FilesResearch In MotionBlackBerry JDE 4.7.0lib to the c:coddec directory. This file contains APIs that will be referenced by coddec.

7. Collect a list of files by running the following command in the c:coddec directory:

dir /s /b *.java > files.txt

8. Run the following command from a Windows command prompt that has the Java compiler in the path:

for /f %x in (files.txt) do
(javac.exe -Xlint:unchecked -cp .;c:coddec %x)

This command compiles all of the files. There will be lots of warnings (about 100) but there should be no errors.

9. Run coddec from the command prompt in the c:coddec directory by typing java -cp . net.rim.tools.compiler.Compiler HelloWorld.cod. HelloWorld.cod is the name of the COD file to be decompiled.

10. The results will be output into the c:coddecdecompiled directory.

Coddec’s output is a combination of decompilation and disassembly of files. Consider the following sample source code (of a thread function that should only be written by those testing threads):

public void run() {
    while(true) {
        try {
            Thread.sleep(3000);
            if (dier == 1) { return; }
        } catch (InterruptedException e) { }
    }
}

Coddec is able to reconstruct the following listing from the COD file. (All comments have been added manually by this chapter’s author to clarify the disassembly.)

//Notice that the method name has been recovered.
public final run(com.rim.samples.device.helloworlddemo.PrimeThread);
{
    enter_narrow
//Top of the while loop
Label1:
    sipush 3000
    i2l
    //Invoke the Thread.sleep function
    invokestatic_lib sleep(long) // Thread
    aload_0_getfield dier
    iconst_1
    //Compare the “dier” field to constant 1
    if_icmpne Label1
    return
    astore_1
    goto Label1
}

This disassembly will certainly not win a beauty competition, but it is definitely an improvement over raw binary in COD files and is usable for reversing applications. The decompiler and custom patching can also be used to further explore the OS using the simulator—for example, decompiling some of the network classes, changing their behavior, recompiling, and then substituting the modified Java class in the original JAR. The modified code can now be run in the simulator. This trick will not work on real devices because they enforce code signing for OS code.

As a final note, individual COD files have a maximum size of 64KB. When a file exceeds this maximum, the rapc compiler will break the file apart, append a piece number to the filename (for example, HelloWorld-1.COD, HelloWorld-2.COD), and create a new COD file containing the parts. These generated COD files are actually ZIP files in disguise and can easily be recognized by the “PK” marker in the first few bytes of the file. To decompile these files, change the file extension to .zip, open the file in an archive manager, and extract the individual parts. There is no obvious method to how classes are divided between COD file parts, and each part must be decompiled manually.

Code Security

Only the BlackBerry JVM and lowest-level firmware are written in native code (C/C++, ASM), which eliminates a large portion of the BlackBerry’s attack surface that may be vulnerable to buffer overflows and other memory corruption issues. This is proven by the fact that there are no publicly reported BlackBerry memory corruption vulnerabilities—an impressive track record for any device manufacturer.

To stop buffer overflows and control the behavior of BlackBerry Java applications, RIM disallows Java native invocation (JNI) and Java reflection. JNI allows Java code to bridge to native C/C++ code, and allowing its use would enable Java applications to access unintended functionality or corrupt memory. Java reflection can be used to circumvent the public/private access restrictions on Java classes, and its use could allow applications to invoke internal system methods. Disabling both of these Java features is standard for JME devices.

Application Packaging and Distribution

BlackBerry applications can be installed via desktop connection, BlackBerry browser, BlackBerry Desktop Manager, and BES. How applications are packaged depends on the installation method. Each installation method requires a code file (in the form of a COD or JAR) and a manifest (either ALX or JAD). The manifest contains information about the application, and the code file contains the actual application code itself.

More information about deploying applications and the various packaging methods is included in the How to Deploy and Distribute Applications Guide (found at http://na.blackberry.com/developers/resources/A70_How_to_Deploy_and_Distribute_Applications_V1.pdf).

Over-The-Air (OTA) BlackBerry Browser Installation

Applications can be installed via an application distribution point directly using the BlackBerry browser. To do this, create a Java Application Description (JAD) file and place the file on your web server. The JAD file contains metadata about the application, including the vendor and application names as well as where to download the actual binary files from. When the user browses to the JAD file, they will see a screen similar to the one shown in Figure 5-1.

The application’s signature is verified and the application is then installed onto the BlackBerry. The signature contained within the COD or JAR file ensures application integrity and makes it safe to download the application over HTTP. Before installation, the user is presented with a dialog where they can edit security permissions and set the proper security policy for the application.

Interestingly, the BlackBerry does not execute the JAR files directly. Instead, the MDS transparently transcodes the JAR into a COD file while it is being downloaded. The MDS is careful to include all security information, and the data is integrity-protected by the MDS-to-BlackBerry encrypted tunnel. The MIDP specification allows this scenario explicitly.

BlackBerry Desktop Manager

Like most smartphone platforms, the BlackBerry has special software that can be used to manage it from the desktop. RIM’s version is the BlackBerry Desktop Manager (BDM), which includes modules for backing up and transferring data between devices and for installing packaged applications.

image


Figure 5-1 Downloading a BlackBerry application OTA

BDM requires an .alx XML manifest file in order to install applications. The ALX file describes the application, including vendor, dependencies, and which COD files actually make up the application. Any code signatures are not applied to ALX files because the signature is contained within the associated COD file. To generate ALX files by using the JDE or Eclipse plug-in, right-click on the application’s project and select Generate ALX File.

BlackBerry Application Web Loader

The BlackBerry Application Web Loader is a non-SiteLocked ActiveX control for installing applications from a web page to devices connected to the computer. This control has been one of the dark spots on RIM’s security record, with a stack-based overflow reported in February 2009 that could be used to compromise systems with the control installed. The advantage of the Application Web Loader is that users are not required to install BDM. For some people this is valuable enough; others may question the wisdom of having the web push applications to one’s phone.

NOTE

SiteLock is a Microsoft technology that restricts the sites allowed to load a particular ActiveX control. Non-SiteLocked controls may be loaded by any website, including malicious ones.

To deploy applications using the Application Web Loader, create a JAD file and place the JAD and COD file on an accessible web server. Then create a web page that uses the Application Web Loader page. The BlackBerry must be attached to the computer via a USB connection. A complete example is available within the How to Develop and Distribute Applications Guide mentioned previously in this chapter.

BES Installation

BES administrators can manage applications, application updates, and policy to associated devices through the BES Applications menu. The ability to deploy updates and blacklist applications is a clear security advantage of BES. Carriers can do the same through BIS, but there has not yet been a major security outbreak necessitating such a response.

Permissions and User Controls

Permissions are determined per-application and assigned based on the application’s signature or a policy specified by the user. Most APIs are not considered sensitive and can be accessed by unsigned applications. The sensitive API set includes APIs for accessing personal information manager (PIM) data, phone features, operating system configuration, and the network. Applications that use these APIs may have to be signed, depending on whether the sensitive API is an MIDP or CLDC API, or a RIM proprietary API. Sensitive APIs that are proprietary to RIM and not part of MIDP2 are known as RIM Controlled APIs.

Remember when testing on simulator that unless security is explicitly enabled, none of the security behavior discussed in this section will be enforced. Make sure to turn on simulator security when exploring how the OS and permission systems behave.

RIM Controlled APIs

RIM Controlled APIs are divided into different API sets, each with a unique signing authority. The three most common signing authorities are abbreviated as follows:

image    RCR (RIM Cryptographic Runtime) Includes the majority of RIM’s cryptographic APIs. Public key cryptography APIs require a different signing key from Certicom.

image    RRT (RIM Runtime API) Provides access to sensitive platform functionality, such as the Application Permission Manager.

image    RBB (RIM BlackBerry Apps API) Provides control of built-in BlackBerry applications (for example, the BlackBerry browser).

Applications that use more than one controlled API set are signed with multiple signatures. For example, an application that uses the BlackBerry browser and the Application Permission Manager will have both RRT and RBB signatures. The signing infrastructure is extensible, and third-party developers can add their own signing authorities to control access to their APIs by using the BlackBerry Signing Authority Tool. Regardless of the signing key required, the security behavior is the same. So for the rest of this chapter, the term RIM Controlled API is used for any API that requires a signature from a signing authority. When developers purchase signing keys from RIM, they receive authorization for signing from the RCR, RRT, and RBB authorities.

In addition to signatures required for accessing RIM Controlled APIs, two BlackBerry OS features also require signatures: applications that automatically launch on BlackBerry startup and BlackBerry system modules. If these features were allowed, unsafe code could run as startup and either monitor the user’s actions or commit an effective spoofing attack to steal important information.

Before an application is allowed to run, it must pass a Java verification stage to ensure that the application uses well-formed Java instructions and does not use dangerous Java features such as Java native invocation or reflection. Disallowing these features ensures that the application does not load dangerous code or bypass class access restrictions to call or create prohibited methods. There are three stages to this validation:

image    Compile Time Verification All code instructions and class references are verified using standard Java verification. This step ensures that well-formed Java instructions are used throughout.

image    Link Time Verification When the COD is loaded onto the BlackBerry, it is linked with the platform APIs. If the COD file links against any RIM Controlled APIs and does not have an appropriate signature, then the linker refuses to link the binary. The application will still be loaded onto the device, but will fail immediately upon startup (see Figure 5-2).

image


Figure 5-2 Error displayed when loading an unsigned application that uses RIM Controlled APIs.

image    Run Time Verification Checks are performed whenever the application invokes a RIM Controlled API. These checks prevent malicious code, or legitimate code that has been exploited, from accessing RIM Controlled APIs or bypassing the application permissions system.

The combination of verified Java code, code integrity, and per-API access control is powerful for security. These mechanisms enable sandboxed applications and enable users to control how those applications use data on the device.

Before getting too excited about the BlackBerry’s signature-based security architecture, remember that code-signing certificates are cheap and do not require an extensive authentication process. Requiring signatures increases accountability and enables code integrity, but a signature does not guarantee the signed code is well written or nonmalicious. The only foolproof mechanism to avoid malware is to avoid installing third-party applications altogether.

Signatures are required for at least one class contained within each of the following RIM packages:

image

Signing BlackBerry Applications

BlackBerry signatures use public key cryptography and a RIM-managed online signing service. To sign code, developers must have a public/private keypair and have registered that keypair with RIM. The following step-by-step guide describes how to get RIM signing keys and what happens along the way:

1. Go to RIM’s code signing website (www.blackberry.com/go/codesigning).

2. Hidden on the web page is a small link to an order form for requesting keys (www.blackberry.com/SignedKeys/).

3. Fill out the form and provide payment information. As part of this registration process, a PIN will be required. This PIN is essentially a password for the user account and will be used by the signing authority to associate cryptographic keys with the account.

4. After the form is submitted, a few days will pass while RIM processes your order. Assuming that everything is acceptable, the signing infrastructure will send three e-mails—one for each of the RCR, RRT, and RBB signing authorities.

5. Attached are CSI files. These are text files that include the developer ID, the nickname of the signing authority (for example, RCR), and the URL for the signing web service. If the JDE is installed, CSI files are automatically associated with RIM’s Signature Tool. Double-clicking on the CSI file will launch the Signature Tool and start the key-registration process. These CSI files don’t really have any key material in them and are used to tell the Signature Tool about the signing authorities that exist.

6. Once the Signature Tool opens the CSI file, it checks to see if the developer already has a public/private keypair. If not, the developer will be asked whether they want to generate one. This is pretty fun, because RIM makes you move the mouse and pound the keyboard to collect entropy. At the end of the generation process, a password is required. This is used to encrypt the keypair and protect it on disk.

7. Once the public/private keypair is generated, the signature tool asks for your RIM signing authority PIN.

8. The PIN and the public key are used to create a message that is then sent via HTTP POST to RIM’s signing authority servers. This message contains the public key, the developer’s signing authority ID, and cryptographic data to ensure the message’s integrity. The curious can watch these messages in Wireshark. The server records the relationship between the user ID and the public key. This way, RIM does not need to generate the private key directly. The same public/private keypair can be registered with all three signing authorities.

9. Steps 5–8 must be repeated for each CSI file until all signing authorities are registered.

Getting signing keys is the first step in creating RIM signed applications. To actually sign code, use the RIM Signature Tool, which is bundled with the JDE and Eclipse plug-in. To run the tool from Eclipse, build the application and then select Request Signatures from the BlackBerry menu. This will launch the Signature Tool with the currently selected project already loaded, as shown next. If you’re not using the Eclipse plug-in, the Signature Tool can be launched as SignatureTool.jar from the JDE’s bin directory. The COD file will have to be loaded manually. To do so, click the Add button and browse to the COD file.

image

An individual application may not necessitate code signatures from every signing authority. For example, if the application does not use cryptography, then a RIM Cryptographic Runtime (RCR) signature is not required. The Signature Tool inspects the application and determines which keys are required. To request signatures from the required signing authorities, click the Request button and enter the private key’s password. Behind the scenes, the private key is used to create a digital signature of the application, which is then sent via HTTP POST to the appropriate signing authorities. If they accept the signature, they will sign the response and return a signature of the signature. The Signature Tool adds this to the COD file.

By being online, RIM is able to monitor the signing process and control the number of times an individual signing key may be used. RIM can also respond to compromise and refuse signatures if a key is known to be compromised. Every time a signature is requested, an e-mail will be sent to the signature key’s owner summarizing what was signed and who signed it. This e-mail also contains the number of signatures remaining. Standard developer keys may be used a little over two billion times.

Programmatically Managing Permissions Using
the Application Permissions Manager

If an administrator or user has denied an application permission to access certain functionality, the application can read or request permissions using the net.rim.device.api.applicationcontrol.ApplicationPermissionsManager class. This class is a RIM Controlled API and is therefore restricted to signed applications.

The following example demonstrates requesting access to use Bluetooth and the Phone APIs:

ApplicationPermissions ap = ApplicationPermissionsManager.getInstance()
            .getApplicationPermissions();
ap.addPermission(ApplicationPermissions.PERMISSION_BLUETOOTH);
ap.addPermission(ApplicationPermissions.PERMISSION_PHONE);
ApplicationPermissionsManager.getInstance().invokePermissionsRequest(ap);

For a more in-depth example, review the ApplicationPermissionsDemo project included with the JDE.

Carrier and MIDLet Signatures

MIDLets are applications that use only MIDP2 and CLDC APIs and are not specifically targeted at BlackBerry devices. Signatures and permissions for these applications are handled following MIDP2 specifications, and signature verification is slightly different from the behavior of BlackBerry applications. Unsigned MIDP applications that use sensitive MIDP or CLDC APIs (for example, javax.microedition.pim.Contact) will be allowed to run, but the user will be presented with annoying prompts each time the application uses a sensitive API (see Figure 5-3). The user’s answer to the prompt is not remembered, and a malicious application could run in an infinite loop prompting the user all day. A conspiracy theorist might even suggest that RIM made its so unsigned application behavior so obnoxious so that developers would sign their applications or not use controlled APIs.

Each device has a carrier certificate installed that is used when verifying the signature on MIDP applications. Most carriers will install a certificate chained to VeriSign, but this is not guaranteed, and some carriers have their own code-signing processes. Once an application is signed with a carrier certificate, the application is “trusted” and the BlackBerry will not prompt the user when the application is installed or uses sensitive APIs, unless the device policy specifically requires it.

image


Figure 5-3 Prompt shown when an MIDP application attempts to access contact information

Handling Permission Errors in MIDP Applications

As shown in the earlier section on debugging, the BlackBerry JVM performs permission checking for MIDP APIs at runtime. When a security error occurs, a java.lang.SecurityException is thrown by the offending API and the application has a chance to handle it. Developers can detect the security error and either disable the offending functionality or show more information to the user. For example, a Solitaire application could disable the high score upload feature if the user blocks network access (see Listing 5-1).

Listing 5-1 Manually Handling a SecurityException Using Try/Catch

try {

    //Opening a ContactList will cause a java.lang.SecurityException if the
    //user denies the “Access personal information” prompt.

    ContactList contactList =
    ContactList)PIM.getInstance().openPIMList(PIM.CONTACT_LIST,
        PIM.WRITE_ONLY);
} catch (PIMException e) {
     //Handle PIMException
} catch (SecurityException secE) {

    //Show dialog to the user or disable functionality
}


Locking Devices

Users and BES administrators can require a password to be entered every time a user wants to unlock a device or connect it to a PC. By default, a password is not required to unlock the phone, and the password is never required to answer incoming phone calls. To keep attackers out, the user specifies the maximum number of times an invalid password can be entered. If this number is exceeded, then the device is fully wiped; all contacts, messages, and media files are first deleted and then the memory is explicitly overwritten to delete any traces that may remain in the flash memory. The user has to type in blackberry between every couple of invalid login attempts. This keeps one’s pockets (or children) from wiping the device by accident.

To specify a password, follow these steps:

1. Open Options | Security Options | General Settings.

2. Change the Password setting to Enabled.

3. Exit the menu by pressing the Escape key.

4. Select Save.

5. Specify and confirm the password.

Once a password is specified, the user must supply the password when unlocking the device or changing any of the security options. Note that the password for the Password Keeper application is unrelated to the password specified in the General Settings dialog.

Managing Application Permissions

Users can control which permissions are allowed for which applications, and these permissions apply even to signed applications. Deep within the BlackBerry device’s options is an Application Permissions menu that lists each installed application and its associated permissions. Permissions can be changed on the device or pushed down by the enterprise administrator through BES. Because IT administrators rule all, BES policies have precedence over user-specified device policies. Here’s how to manually change permissions for an application:

1. Open the Application Permissions menu (Options | Security Options | Application Permissions).

2. Select the application you want to control permissions for.

3. Click the BlackBerry key and choose Edit Permissions. The overall device permissions can be changed by opening this menu and selecting Edit Default Permissions. The default permissions will be applied when an explicit permission definition for an application does not exist.

4. Choose the corresponding permission and set it to Enable/Disable/Prompt. If Prompt is chosen, you will be shown a prompt the first time the application uses a controlled API that requires the corresponding permission. The BlackBerry will remember your choice and not show the prompt again unless the permission policy is changed back to Prompt.

5. If a permission is changed to be more restrictive, the device may reboot to ensure the new permission set is enforced.

Local Data Storage

The BlackBerry’s file system is a virtualized view of flash memory and external media cards. Data is saved on the file system using the MIDP2 record store or IOConnector classes, or RIM’s proprietary PersistentObject interface. The file system is relatively flat, but there are security rules as to which areas of the system signed and unsigned applications can read from and write to. For the security nut, almost everything can be encrypted using the BlackBerry locking password.

Files and Permissions

The BlackBerry OS’s file system is laid out somewhat like a traditional Unix file system, with the exception that there is no root directory. “File:” URLs are used for referring to individual files, and URLs must contain the physical storage location. For example, file:///store/home/user/pictures/pretty_picture.png references an image file within the user’s home directory on the device’s internal storage, also known as “store.” Other storage locations include SDCard and CFCard.

The BlackBerry implements simple file-access restrictions, and not all files are readable or writable by all applications. For example, unsigned applications can write files under the file:///store/home/user directory but not under the operating system location file:///store/samples. To explore the file system, download and install BBFileScout from http://bb.emacf1.com/bbfilescout.html. BBFileScout is a donation-supported application for browsing the file system and performing basic management tasks, including copying, deleting, and moving files. Because BBFileScout is signed, it provides a lot of information about what signed applications are able to do on the file system.

Programmatic File System Access

BlackBerry Java applications use the javax.microedition.io.file.FileConnection API to directly access the file system. For security reasons, some file locations are inaccessible by this API, including application private data, system directories and configuration files, and RMS application databases (http://www.blackberry.com/developers/docs/4.7.0api/javax/microedition/io/file/FileConnection.html). Unsigned applications can browse the file system, but the user will be prompted each time the application accesses the file system.

To test the ability to read and write individual files, use the following sample code:

try {
    String fileURL = “file:///store/home/user/pictures/my_pic.png”;
    FileConnection fileConn =
(FileConnection)Connector.open(fileURLs[i]);
    // If no exception is thrown, then the URI is valid,
    // but the file may or may not exist.
    if (!fileConn.exists()) {
        System.out.println(“File does not exist”);
        fileConn.create(); // create the file if it doesn’t exist
        System.out.println(“Was able to create file”);
    } else {
        System.out.println(“File exists”);
        if (fileConn.canRead()) {
            System.out.println(“File is readable”);
        }
        if (fileConn.canWrite()) {
            System.out.println(“File is writable”);
        }
    }
    fileConn.close();
} catch (IOException ioe) {
    System.out.println(ioe.getMessage());
}

Structured Storage

The BlackBerry OS provides three forms of structured storage: MIDP2 RecordStores (a.k.a. RMS databases) and RIM’s proprietary PersistentStore and RuntimeStore.

RMS databases have the advantage of being MIDP2 platform compatible and usable by unsigned applications. The downside is that they can only store 64KB of data per store and require the application to manually marshal objects to and from byte arrays. Pretty archaic, but still useful. To program RMS, use the javax.microedition. rms.RecordStore class. Each RecordStore is named with a unique identifier that must be local to the MIDlet suite, but does not have to be unique to all applications on the device. On other MIDP2 platforms, you can share RMS databases between applications by publishing a RecordStore with a well-known name. The BlackBerry only allows sharing between the same MIDlet suite.

To share data between applications, store more data, and not have to worry about byte array serialization, use RIM’s PersistentStore or RuntimeStore classes. These are RIM Controlled APIs. The PersistentStore is stored in flash memory, but the RuntimeStore lives in RAM and will be erased when the device resets. To use the PersistentStore, classes must implement the net.rim.device.api.util.Persistable interface, which describes any special serialization actions required.

Objects are uniquely identified using a data identifier that is stored as a JME type long. By default, objects are readable to anyone who knows the object’s data identifier. To keep objects private, wrap them in a ControlledAccess access object and associate a CodeSigningKey with the wrapped object. Only applications signed with the public key represented by the CodeSigningKey will be allowed to access the persisted object.

Encrypted and Device Secured Storage

The popularity of the BlackBerry in government and enterprises makes on-device encryption a necessity, and the BlackBerry’s secure storage options are extremely advanced.

Content Protection

To encrypt sensitive messaging and contact data stored on the BlackBerry, use the BlackBerry’s content-protection feature. Content protection encrypts data when it is written to flash memory using a key generated from the unlock password. Because there would be no way to generate the key without a password, the user is required to specify an unlock password. All communication data is encrypted by default, including e-mail, calendar information, browser history, memos, tasks, and SMS messages. Users can optionally encrypt the address book, which has the interesting side effect of causing caller ID to not show the name of incoming callers when the device is locked.

Three keys are used by content protection to protect data (refer to http://na.blackberry.com/eng/deliverables/3940/file_encryption_STO.pdf). There’s an ephemeral AES key for unlocking keys, a 256-bit AES key for persistently stored data, and an Elliptical Curve Cryptography (ECC) public/private keypair used for encrypting data when the device is locked. The length of the ECC key can be changed in security options and can be up to 571 bits long. The ephemeral AES key is generated from the device lock password and is therefore only as strong as the password itself. The ECC public key is kept in memory while the device is locked and encrypts all incoming data. The public key has to be used because the AES storage key is wiped from memory as soon as the device is locked. By only keeping a public key in memory, the BlackBerry protects against attackers who are able to read the device’s memory directly. When the user unlocks the device with their password, the ephemeral key is used to decrypt the AES storage key and the ECC private key. The ECC private key is then used to decrypt all of the data that arrived while the device was locked; before being written to persistent storage this cleartext is encrypted with the AES storage key. It is a lot of jumping around, so simply remember this: Data is encrypted with a key that comes from the unlock password, so have a good password!

Keys must be held in accessible memory for some period of time if they are going to be used to perform all of these encryption operations. The BlackBerry can be configured to scrub sensitive data from memory when the device is locked, holstered, or idle. To enable the “Memory Cleaner,” open Options | Security Options | Memory Cleaning and change the Status setting to Enabled. The time window and events that determine when the Memory Cleaner daemon runs can be adjusted, although the defaults are probably adequate. Also notice the list of registered cleaners. The Memory Cleaner system is extensible, and applications can register for memory-cleaning events using the net.rim.device.api.memorycleaner.MemoryCleanerDaemon RIM Controlled API. Once registered, the application will be alerted whenever the daemon runs and should then clear its memory of any sensitive information. When handling encryption keys and other sensitive data, make sure to take advantage of this functionality.

Removable Media Protections

Many BlackBerry devices include memory card slots for storage expansion. The smaller these cards physically get, the easier they are to lose, and the more protected they need to be. BlackBerry can encrypt documents and media files stored on removable media using the same content protection mechanism as is used on the primary device. Not all file types written to the memory card are encrypted, and neither are files written to the card by another source (for example, a computer).

There are three modes for protecting external media:

image    Device The BlackBerry uses a cryptographic random number generator to generate the external memory encryption key. If the card goes missing, but the device stays in the owner’s possession, then anyone who finds the memory card will be unable to read it because the key is still on the device.

image    Security Password The user’s device password is used to generate an encryption key for the device. This is the weakest form of protection because users choose poor passwords and attackers who get the Secure Digital (SD) card can perform offline grinding attacks against the encryption key. The grinding attack does not work against the main BlackBerry device password because the device will wipe itself after the specified number of invalid attempts.

image    Security Password + Device A combination of the device password and a randomly generated per-device key is used to encrypt the memory card. The combination of the two key-generation methods prevents the attacks possible against each one alone.

Cryptographic APIs

The BlackBerry cryptographic suite is comprehensive and includes classes for working with low-level primitives (such as AES and SHA-1) and high-level constructs [for example CMS messages and Secure Sockets Layer (SSL)]. All cryptographic APIs are RIM controlled, and most of the public/private key APIs require a Certicom signature. Unlike many other portions of the RIM’s software development kit (SDK), the Crypto API is extremely well documented. For more information about the Crypto API, review the documentation at http://www.blackberry.com/developers/docs/4.7.0api/net/rim/device/api/crypto/package-summary.html. For a sample application that performs 3DES encryption and decryption, review the cryptodemo included with the JDK.

Networking

The BlackBerry has a fully functioning network stack that implements the MIDP 2.0 networking APIs, including raw and secure socket support and an HTTP library. Although the APIs may be the same in signature, there are some important security differences underneath. This section enumerates the security strengths and weaknesses in the BlackBerry network stack. For more information on general MIDP 2.0 networking, see Chapter 6, which covers JME.

Device Firewall

The BlackBerry does not have a standard network firewall, but this is not uncommon because most mobile devices do not listen on the network. Instead, the BlackBerry has a messaging firewall that can be used to block unwanted e-mail, SMS, and BlackBerry Internet Service (BIS) messages. When the firewall blocks a message, it is simply not shown to the user. All messages can be blocked or the set of allowable addresses can be restricted to those in the owner’s address book. If content protection of the address book is enabled, it is not possible to restrict incoming messages by address. This restriction happens because the firewall does not have access to the password-derived AES key required to unlock the address book.

The firewall provides a real security benefit for keeping spam and malicious messages off the device. The only downside is that you may not receive those enticing offers for products you didn’t even know you wanted.

SSL and WTLS

To communicate with the Internet and corporate intranet, the BlackBerry creates an encrypted tunnel with either BIS or the enterprise’s BES. By default, SSL/Transport Layer Security (TLS) connections are terminated at the server; then the response is compressed and sent to clients. This is more risky than standard end-to-end SSL/TLS because the BlackBerry server is acting as a man-in-the-middle and could act maliciously or be compromised. Thankfully, the BlackBerry now supports proper end-to-end SSL/TLS.

Follow these instructions to enable proper SSL/TLS:

1. Open Options | Security Options | TLS.

2. Change the TLS Default setting from Proxy to Handheld.

3. Set the Encryption Strength to Strong Only.

4. Ensure that Prompt for Server Trust and Prompt for Domain Name are set to Yes. If these options are not enabled, the browser will not prompt when the server’s certificate is untrusted or does not match the domain name.

Now that proper SSL/TLS is enabled, it’s time to change the configuration of its wicked cousin, WTLS. WTLS is a proxy encryption protocol that is popular among mobile phones that do not have a lot of processing power or bandwidth to perform encryption operations. BlackBerry devices no longer fall into this category, so leaving weak versions of WTLS enabled is an unnecessary risk.

To disable weak WTLS, follow these steps:

1. Open Options | Security Options | TLS.

2. Change Encryption Strength to Strong Only.

3. Make sure that Prompt for Server Trust is set to Yes.

Conclusion

BlackBerry is an advanced platform with many security features for users and application developers. When compared against the other mobile platforms, BlackBerry is the clear leader in on-device security and manageability. Applications are easily isolated from each other, and users or administrators are able to control how applications interact. The strong device security may be the reason why so much of the security community’s efforts have been focused on BES, because well-written applications should stand up well even against determined attackers.

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

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