CHAPTER 17
Writing Secure BlackBerry Applications

The accepted wisdom made famous by initiatives such as Microsoft’s Security Development Lifecycle (https://www.microsoft.com/security/sdl/), SafeCode (http://www.safecode.org/), BSIMM (http://bsimm.com/), and similar is that in regard to software security an ounce of prevention is worth a pound of cure (if you work in imperial measurements still). In other words, if security is considered earlier in the development lifecycle you can significantly reduce the likelihood of finding issues late in the cycle, or worst-case, after release. Although this approach should begin in the requirements and design stages, consideration during development is equally important and thus this chapter.

In this chapter you look at how to write secure BlackBerry applications from a development perspective. To develop applications in a secure manner, understanding the features that you can implement is important from the outset so that you take the corresponding security and API selection considerations into account during development.

This chapter first looks at how to secure BlackBerry OS Legacy applications before looking at BlackBerry 10 native, Cascade, and HTML and JavaScript applications. It does not cover BlackBerry 10 Adobe AIR–based apps because support for it is depreciated in 10.3.1.

Securing BlackBerry OS 7.x and Earlier Legacy Java Applications

As you write BlackBerry OS 7.x and earlier legacy (or BlackBerry classic) applications in Java (this section does not consider packaged HTML5 and JavaScript), you do not need to consider certain classes of vulnerability such as memory corruption. However, you must consider an array of generic Java- and BlackBerry-specific issues. This chapter covers all the common security features available to developers while giving examples about how to use them, as well as any associated caveats.

General Java Secure Development Principals

Before addressing the BlackBerry OS 7.x–specific API considerations, it’s worth reading through the general principals outlined in the CERT Oracle Secure Coding Standard for Java (https://www.securecoding.cert.org/confluence/display/java/The+CERT+Oracle+Secure+Coding+Standard+for+Java). Although not all of them are relevant, a number of generic areas do apply, namely:

  • Subset of Input Validation and Data Sanitization (IDS)
  • Subset of Numeric Types and Operations (NUM)
  • Subset of Object Orientation (OBJ)
  • Subset of Methods (MET)
  • Subset of Miscellaneous (MSC)

After you have reviewed these sections you’re ready to understand the BlackBerry OS 7.x Java-specific practices.

Making Apps Work with the Application Control Policies

BlackBerry has a powerful control framework known as Application Control Policies (http://www.blackberry.com/newsletters/connection/it/i610/control_policies.shtml). These policies allow a rich set of controls to be placed around applications at either the BES (BlackBerry Enterprise Server) administrator’s or user’s behest. These areas include certain API access such as:

  • What happens when you insert your smartphone in a holster?
  • Is access to the Browser Filters API allowed?
  • Is access to the Email API allowed?
  • Is access to the Event Injection API allowed?
  • Is access to the File API allowed?
  • Is access to the GPS API allowed?
  • Is access to the Handheld Key Store allowed?
  • Is access to the Interprocess Communication API allowed?
  • Is access to the Phone API allowed?
  • Is access to the Media API allowed?
  • Is access to the Module Management API allowed?
  • Is access to the PIM API allowed?
  • Is access to the Screen, Microphone, and Video Capturing APIs allowed?
  • Is access to the Serial Port Profile for Bluetooth API allowed?
  • Is access to the User Authenticator API allowed?
  • Is access to the Wi-Fi API allowed?

As a result, developers wanting to write robust security-conscious applications should not automatically assume that their app will be granted access to all the APIs it requires. Instead the recommendation is that you use try/catch exception-handling extensively around APIs to which access can be controlled, especially if functionality in the app degrades gracefully if access is not granted.

By taking this defensive access control–aware approach to development you can ensure your application will continue to provide the user experience your users expect. If you don’t, a chance exists that when used in more risk-aware organizations or when configured by more risk-adverse users that your application will simply generate an unhandled exception and crash.

Memory Cleaning

In BlackBerry OS the possibility exists to have memory (RAM) cleaned of sensitive information in certain high-security situations such as during certain operations or after a period of time (http://docs.blackberry.com/en/smartphone_users/deliverables/36022/About_memory_cleaning_61_1587246_11.jsp).

This memory cleaning can be extremely useful if you want to guard against sophisticated threat actors and ensure that sensitive cleartext information of cryptographic key material does not persist when the device is not in active use.

To understand how to react to a memory cleaning event in your application you first need to understand when they typically occur:

  • When you insert your smartphone in a holster
  • When you do not use your smartphone for a specified period of time
  • When you synchronize with your computer
  • When you change the time or the time zone for your smartphone
  • When you lock your smartphone

The memory-cleaning feature is typically either configured by the organization’s administration through a BES management policy or alternatively by the user (http://docs.blackberry.com/en/smartphone_users/deliverables/ 36022/Turn_on_memory_cleaning_61_1720942_11.jsp). It is also important to remember that by default these memory cleaning callbacks will not be called if the system is not configured. If you want to ensure sensitive memory is cleaned, then you’ll have to implement your own event-driven or inactivity- driven solution.

If you want to support memory cleaning in your app using the OS support method then you need to implement a listener using (http://www.blackberry .com/developers/docs/7.0.0api/net/rim/device/api/memorycleaner/MemoryCleanerDaemon.html):

net.rim.device.api.memorycleaner.MemoryCleanerDaemon 

Specifically, you need to implement a listener via one of the following methods,

addListener(MemoryCleanerListener listener) 

or:

addListener(MemoryCleanerListener listener, boolean enable) 

When invoking either of these methods you pass an implementation of the interface MemoryCleanerListener (http://www.blackberry.com/developers/docs/7.0.0api/net/rim/device/api/memorycleaner/MemoryCleanerListener .html) to them. By calling these methods you start the memory-cleaning daemon if it is not already started upon invocation. Then within your interface implementation your responsibility is to securely erase any sensitive information. The best strategies are to

A final note with regard to memory cleaning is that you may want to build some form of malicious activity detection within your application and then invoke a memory clean programmatically via the previous registered listeners. If that is the case then you can do so by invoking net.rim.device.api .memorycleaner.MemoryCleanerDaemon.cleanAll(), which causes the process to begin.

Controlling File Access and Encryption

BlackBerry file storage is broken down conceptually into two stores (http://docs.blackberry.com/en/developers/deliverables/17952/Storing_files_in_the_file_system_1219757_11.jsp):

  • Internal device storage, such as those residing under file:///store/
  • External device storage, such as those residing under file:///SDCard

File access control and encryption on a BlackBerry device can typically occur via a number of possible routes:

Most developers will not want to override the user’s preferences in regard to the encryption of files. However, if you do want to implement controlled access then take the caveat noted in the previous list into consideration with regard to where the key still exists in the case of capable threat actors and the fact it won’t apply to internal storage. By far the most secure method is the use of DRM forward locking; however, carefully consider the impact on user experience. Your users won’t be able to move files between devices.

The following methods enable developers to have control over file encryption methods:

  • Controlled access—Achieved by calling the setControlledAccess method to set the code signing key to yours in the net.rim.device.api.io.file .ExtendedFileConnection interface.
  • DRM forward locking—Achieved by calling the enableDRMForwardLock() method in the net.rim.device.api.io.file.ExtendedFileConnection interface by casting the Connector object from javax.microedition.io.Connector.open (http://www.blackberry.com/developers/docs/7.0.0api/javax/microedition/io/Connector.html).

Before deploying access control and/or file encryption, note that there can be, albeit minimal on modern devices, a performance impact. Also obviously with any extra processing over and above the base OS and depending on usage, there could potentially be a battery life impact. As a result, a suggestion is that you measure performance when enabling access control or encryption to understand these impacts.

SQLite Database Encryption

BlackBerry has native support within its Java API since 5.x for SQLite databases. These databases can be created in memory or on persistent storage. Persistent storage may be physical internal to the device or a removable SD card. For these persistent SQLite databases a number of possible security options can be specified by DatabaseSecurityOptions (http://www.blackberry.com/developers/docs/7.0.0api/net/rim/device/api/database/DatabaseSecurityOptions .html):

The following list covers the BlackBerry OS database security options:

  • Not encrypted and accessible from any application (insecure).
  • Encrypted and accessible from any application but only on this device.
  • Encrypted and accessible only from applications that are signed with the code-signing key that created the database but only on this device (secure).

The DatabaseSecurityOptions are passed either at the point of creation or at the point of encryption using one of the methods in the DatabaseFactory class (http://www.blackberry.com/developers/docs/7.0.0api/net/rim/device/api/database/DatabaseFactory.html):

create(String id, DatabaseSecurityOptions securityOptions) 
create(String id, DatabaseSecurityOptions securityOptions, 
DatabaseOptions 
databaseOptions) 
create(URI fileURI, DatabaseSecurityOptions securityOptions) 
create(URI fileURI, DatabaseSecurityOptions securityOptions, 
DatabaseOptions databaseOptions) 

You can also encrypt and decrypt existing databases on an as-needed basis through the clearly named functions in the DatabaseFactory class.

If you intend to access these SQLite databases over USB while the device is mounted in mass storage mode, say, via a companion application on a PC, you may not be able to utilize database encryption and thus access control—that is, unless you implement your own IPC mechanism between the device-based app and the PC application using the USB port API (net.rim.device.api .system.USBPort).

Persistent Store Access Control and Encryption

The persistent store on a BlackBerry is an internal storage mechanism and format used for storing Java objects that are not directly accessible as traditional files via any means. BlackBerry describes it as follows:


The persistent store provides a means for objects to persist across device resets. A persistent object consists of a key-value pair. When a persistent object is committed to the persistent store, that object’s value is stored in flash memory via a deep copy. The value can then be retrieved at a later point in time via the key.

http://www.blackberry.com/developers/docs/ 7.0.0api/net/rim/device/api/system/ PersistentStore.html


This feature comes with two notable optional security features:

Content protection–provided encryption will only be enabled for an application if the following conditions are met: (http://developer.blackberry .com/bbos/java/documentation/content_protection_intro_1981828_11 .html):

  • The device has a password set.
  • A BES or user-configured policy has been applied enabling it.
  • The app subscribes and uses the content protection framework.

As with file encryption discussed earlier in this chapter, developers will unlikely want to override the user’s preferences in regard to data at rest. This should be especially true in the case of the persistent store because no alternate way exists to access its contents. However, the use of ControlledAccess should be considered. Without it a threat actor who can reverse-engineer your app can extract the ‘key’ (not be confused with an encryption key) and then simply use PersistentStore.getPersistentObject(key) to obtain access and thus read or write any contents.

Runtime Store Access Control

The runtime store on a BlackBerry is an internal storage mechanism and format used for storing Java objects that are not directly accessible as traditional files via any means yet are not persistent. BlackBerry describes it as follows:


Provides a central location for applications to share information.

The store is not persistent. If the device resets, then information stored in the store is lost.

http://www.blackberry.com/developers/docs/7.0.0api/ net/rim/device/api/system/RuntimeStore.html


Unlike with the persistent store no need should exist to encrypt the contents of the runtime store. However, as with the persistent control, a ControlledAccess you should use wrapper (http://www.blackberry.com/developers/docs/7.0.0api/net/rim/device/api/system/ControlledAccess.html).

Randomness Sources

The BlackBerry API provides two primary randomness APIs, one of which is better quality than the other. These randomness APIs are

The second of these two is the one you should use if you require a cryptographically strong randomness source and don’t have a specific preference for an algorithm.

On the other hand if you do have a specific pseudo-random algorithm that you prefer then there is the net.rim.device.api.crypto.PseudoRandomSource interface that the following classes implement (note all under the net.rim .device.api.crypto namespace):

  • AESCTRDRBGPseudoRandomSourceImplements a deterministic random bit generator (DRBG) using an approved AES block cipher algorithm in counter mode. This DRBG uses a 128-bit security strength.
  • ARC4PseudoRandomSourceImplements a pseudo-random number generator (PRNG) that uses the Alleged RC4 (ARC4) algorithm to expand a finite length seed into an arbitrarily long stream of pseudo-random bytes. BlackBerry implemented ARC4 as described in “Applied Cryptography,” by Bruce Schneier, in Section 17.1 (published 1996).
  • CTRPseudoRandomSourceImplements a symmetric key block cipher in Counter mode to provide a sequence of pseudo-random bytes. CTR mode is defined in FIPS SP 800-38A.
  • FIPS186PseudoRandomSourceImplements the pseudo-random number generator as found in FIPS 186-2.
  • OFBPseudoRandomSourceUses a symmetric key block cipher in Output Feedback mode to provide a sequence of pseudo-random bytes. OFB mode is defined in FIPS 81.
  • P1363KDF1PseudoRandomSourceImplements the key derivation function 1 (KDF1) found in the main section of P1363. The version BlackBerry implemented is from the draft 13 (“d13”) P1363 document.
  • PKCS1MGF1PseudoRandomSourceImplements the PKCS1 mask generation function (MGF1), using a digest to expand a finite length seed into an arbitrarily long stream of pseudo-random bytes.
  • PKCS5KDF1PseudoRandomSourceNot recommended for use!
  • PKCS5KDF2PseudoRandomSourceImplements PKCS #5 key derivation function (KDF) 2 pseudo-random number generation. BlackBerry implemented the PKCS5 KDF2 as per PKCS #5 version 2.0 (March 1999).
  • RFC2631KDFPseudoRandomSourceImplements the KDF found in RFC 2631, which is based upon the KDF in X9.42.
  • SPKMKDFPseudoRandomSourceImplements the KDF found in RFC 2025 but comes with caveats on the ability to call multiple times.
  • X942KDFPseudoRandomSourceImplements the KDF found in ANSI X9.42.
  • X963KDFPseudoRandomSourceImplements the KDF found in ANSI X9.63.

Unless you have a specific requirement for any of these algorithms, net .rim.device.api.crypto.PseudoRandomSource should suffice for your day-to-day use.

SSL, TLS Certificate, and Public Key Pinning in OS 7x and Earlier Legacy Java Applications

To mitigate rogue or compromised certificate authorities or intermediaries issuing forged SSL or TLS certificates for a domain/service that chain up and thus validate correctly, you may want to perform certificate or public key pinning. If you’re not familiar with the topic, look for the excellent write-up on the OWASP site on the attack and the defense concepts (https://www.owasp.org/index .php/Certificate_and_Public_Key_Pinning).

On BlackBerry, a certificate object (http://www.blackberry.com/developers/ docs/7.0.0api/javax/microedition/pki/Certificate.html) for a TLS connection is retrieved by calling net.rim.device.api.crypto.tls .tls10.TLS10Connection.getSecurityInfo() (http://www.blackberry .com/developers/docs/7.0.0api/net/rim/device/api/crypto/tls/tls10/TLS10Connection.html#getSecurityInfo()), and this returns a J2ME-specified SecurityInfo (http://www.blackberry.com/developers/docs/7.0.0api/javax/microedition/io/SecurityInfo.html) object that exposes the getServerCertificate() method. The certificate object is the J2ME-defined type and not the X.509 BlackBerry-defined type (http://www.blackberry .com/developers/docs/7.0.0api/net/rim/device/api/crypto/certificate/x509/X509Certificate.html), the impact of which is described shortly. The J2ME incarnation of a certificate exposes the following Distinguished Name (DN) attributes for X.509 server certificates:

  • Common name
  • Surname
  • Country name
  • Locality name
  • State/province name
  • Street address
  • Organization name
  • Organization business unit
  • E-mail address

In addition the following methods of use are exposed and provide further information:

  • getIssuer()
  • getSerialNumber()
  • getVersion()

However, no method is exposed that will provide the server certificate’s Subject Public Key Information (although this information is annoyingly present in the BlackBerry X.509 incarnation). As a result your ability to pin anything strong is somewhat limited and could potentially be subverted if a threat actor has control of an intermediary certificate authority signing certificate.

To do certificate/public key pinning on BlackBerry OS properly, you need to use the Legion of the Bouncy Castle (https://www.bouncycastle.org) implementation of TLS, which exposes all the required elements. You can see a good example of how to use Bouncy Castle to get the X509 certificate information for a particular connection in the article by Bored Wookie entitled, “How to Use Bouncy Castle Lightweight API’s TLSClient” (http://boredwookie.net/index .php/blog/how-to-use-bouncy-castle-lightweight-api-s-tlsclient/). In the example provided in the article, instead of calling the getEncoded() method you would call the getSubjectPublicKeyInfo() method from the Bouncy Castle API (https://www.bouncycastle.org/docs/pkixdocs1.5on/org/bouncycastle/cert/X509CertificateHolder.html). You are then able to retrieve the required Subject Public Key Information and thus pin your application to it.

Finally, before embarking on certificate pinning, recognizing the potential operational overhead is important. For example, in the most tightly coupled deployed app, each time the certificate is updated on the server the app will need to be updated. This can be extremely difficult and, given general user upgrade apathy, causes all manner of service or support issues. So although we have seen situations where certificate pinning has successfully mitigated attacks against the most sophisticated threat actors, unless you are a major service provider, government-orientated service, or financial institution, it is unlikely the additional overhead is proportionate to the risk you face.

Defending Against Module Squatting

There exists a theoretical attack on BlackBerry where someone “squats” on the name that your app will retrieve a handle from via CodeModuleManager .getModuleHandle() (http://www.blackberry.com/developers/docs/7.0.0api/net/rim/device/api/system/CodeModuleManager.html#getModuleHandle()) at a later point. The same attack is also possible when using CodeModuleManager .getModuleHandleForClass(). However, this attack is a little more unlikely if the class is packaged by default with your app; however, if it isn’t and is an optional installation, then the same risk applies.

You might be using modules in a dynamic manner similar to this in the case of certificate pinning. If so, you might choose to deploy the public key to the server in its own module to allow modular updating.

As a result if you are using either of these methods to dynamically load modules you produce, verify the signing key of the module before use. You can do this verification using the ControlledAccess.verifyCodeModuleSignature method (http://www.blackberry.com/developers/docs/7.0.0api/net/rim/device/api/system/ControlledAccess.html#verifyCodeModuleSignature (int, net.rim.device.api.system.CodeSigningKey)). This type of misuse of modules has been seen in public in the past by the firmware modding community. They used to rely on the ability to mismatch versions or replace modules entirely. As a result, robust checking around of all of these areas can be prudent using the methods exposed by CodeModuleManager (http://www.blackberry.com/developers/docs/7.0.0api/net/rim/device/api/system/CodeModuleManager.html), including timestamps, versions, vendors, and so on.

Obfuscation

Although it’s not strictly security related, if you have lots of sensitive intellectual property embedded in your application then due to the use of Java you may want to complicate the disassembly and thus recovery of it. Although obfuscation won’t stop determined or skilled individuals, it can stop the casual tinkering. You can use a variety of code/class obfuscators to protect BlackBerry Java applications.

BlackBerry WebWorks Security on BlackBerry OS 7 or Lower

BlackBerry WebWorks is best described by BlackBerry itself:


Provides a central location for applications to share information.

When you hear the words BlackBerry WebWorks, think HTML5, JavaScript, and CSS. Essentially, a BlackBerry WebWorks application is a web application that runs on a BlackBerry smartphone or BlackBerry PlayBook tablet.

http://developer.blackberry.com/bbos/html5/documentation/ what_is_a_webworks_app_1845471_11.html


We don’t cover how to secure WebWorks applications on BlackBerry 7 other than to say two things.

The first is that BlackBerry produced a guide with what you need to know in a knowledge base whitepaper titled, “How to secure your BlackBerry WebWorks Application” (http://supportforums.blackberry.com/rim/attachments/rim/browser_dev@tkb/52/2/BlackBerry%20WebWorks%20Tutorial_%20How-to-secure-your-BlackBerry-WebWorks%20application.pdf). It covers the permissions model of allowing you to expose nonweb-orientated API namespaces to JavaScript.

The second is that obviously where you are bridging web content with something like JavaScript and HTML, the risk exists of cross-site script and content injection or modification using man-in-the-middle attacks. As a result you need to be extremely careful about which namespaces you allow to be callable from your BlackBerry WebWorks application.

Securing BlackBerry 10 Native Applications

BlackBerry 10 native applications are POSIX-compatible applications written in C or C++ running under the QNX microkernel, and as such, potentially suffer from a class of vulnerabilities commonly referred to as memory corruption. Give special attention to defensive coding and to leveraging the available platform defenses in addition to any logic security considerations. In this section you look at how to write applications in a secure manner.

BlackBerry does provide a number of base considerations for BlackBerry 10 native applications that primarily cover some C language primitives such as structures, enums, and macros (http://developer.blackberry.com/native/documentation/core/com.qnx.doc.native_sdk.security/topic/security_overview.html). The exception is compiler and linker defenses, which we also discuss in this section.

General C/C++ Secure Development Principals

Before we address the BlackBerry OS 10.x–specific API and platform considerations, reading through the general principals outlined in the CERT C Coding Standard (https://www.securecoding.cert.org/confluence/display/seccode/CERT+C+Coding+Standard) and the underdevelopment CERT C++ Secure Coding Standard (https://www.securecoding.cert.org/confluence/pages/viewpage .action?pageId=637) is worth your time. If terms such as stack overflow, heap overflow, integer wrap, format string, race condition, uninitialized memory, and similar are all alien to you, then these readings are strongly recommended.

After you have reviewed these references you’re ready for the BlackBerry OS 10.x–specific isms.

Compiler and Linker Defenses

BlackBerry 10 native applications are standard ELF format binaries compiled with GCC, which are loaded via a loader as on Linux and BSD and so on. A number of compiler and linker defenses should be used to maximize the use of platform-provided, defense-in-depth security features. BlackBerry provides an overview of these features in their development documentation (http://developer .blackberry.com/native/documentation/core/com.qnx.doc.native_sdk .security/topic/using_compiler_linker_defenses.html#dho1384790657335). In the spirit of full disclosure, this guide was in part written by the author while at BlackBerry in 2011.

Here is a summary of these compiler and linker defenses and their high-level process:

  • Stack Cookies—Protect against stack-based overflows.
  • Relocations Read Only—Protects against overwrites of the relocation section, which contains, among other things, function pointers.
  • Bind Now—Loads all library dependencies at load time and resolves them allowing the Global Offset Table (GOT) to be set to read-only and thus protect against direct overwriting.
  • Position Independent Code/Executables—Allows libraries and program executables to benefit from address space layout randomization by not assuming it will load at a particular memory address.
  • Source Fortification—Provides compiler time–added source fortification to protect against certain memory corruption vulnerabilities.
  • Format String Warnings as Errors—Stops the compilation process with an error if a dangerous printf family function is observed.

Using all of these defenses in every native application is recommended. Although certain options such as Relocations, Read Only, and Bind Now will incur a load time performance impact, the defense in depth they contribute is in most cases worth the tradeoff.

Remember that the use of these options, with the exception of the last two, do not stop vulnerabilities from being present in the code. Instead they frustrate the exploitation of memory corruption vulnerabilities. An unsuccessfully exploited memory corruption vulnerability, while not yielding a compromise, may result in your application crashing and lead to a denial of service, requiring the user to restart.

Memory Cleaning

In regard to memory cleaning on BlackBerry 10, the only important thing to keep in mind is the default heap does not zero freed memory by default. As a result if you are a developer working with sensitive data then it is likely best to explicitly zero the memory using memset and verify that it was been zeroed correctly to ensure compiler optimizations do not override the intended functionality. For this reason, avoiding the use of functions such as realloc (http://www.qnx .com/developers/docs/660/topic/com.qnx.doc.neutrino.lib_ref/topic/r/realloc.html), which may in certain circumstances free memory and provide a fresh pointer without the old memory being zeroed, is also advisable.

Taking the same cautious approach when dealing with local and global stack variables and C++ objects in the most sensitive situations is likely also wise. Where the stack is being used for sensitive information again you should explicitly memset the contents prior to return from the function and verifying that it is indeed zeroed via memcmp. This memcmp will also help stop the memset being optimized out by the compiler.

File Access Control

The key question to answer when developing BlackBerry 10 native applications in regard to data storage is whether the files that your app will create need to be accessible to other apps on a permanent basis, on an invocation basis, or not at all (http://developer.blackberry.com/native/documentation/core/com .qnx.doc.native_sdk.devguide/topic/accessible_folders.html).

If your app’s files don’t need to be accessible to other applications on a permanent basis you should default to the application’s private data or temporary directories as appropriate. By doing so you ensure your application’s data is accessible to only it and not to other apps on the device, thus providing protection from information disclosure and manipulation. You can obtain the location of the app’s data directory by calling the homePath()API. Likewise you can obtain the location of the app’s temporary directory by calling the tempPath()API.

If your app’s files will be shared on an as-needed basis using the Invocation Framework (http://developer.blackberry.com/native/documentation/core/invocation_framework.html) then you can benefit from its secure file transfer mechanism. You can use the Invocation Framework’s file transfer feature (http://developer.blackberry.com/native/documentation/cascades/device_platform/invocation/data_transfer.html) to privately transfer files on an as-needed basis whereas general storage will be within the app’s private data directly.

BlackBerry provides a good overview of the invocation framework and its purpose.


When the framework receives an invocation request with a file:// URI, it inspects the URI to determine whether the request refers to a shared area. If the file is already shared, the invocation request passes the URI to the file in the shared area, as specified by the sender. However, if the Invocation Framework detects that the file is not shared, then by default it creates a read/write copy of the file in a private inbox for the target application. The client application can specify the file transfer mode attribute to override this behavior.

http://www.blackberry.com/developers/docs/7.0.0api/ net/rim/device/api/system/RuntimeStore.html


When you use this feature the file doesn’t have to be read/write; instead it can be read only. When files are shared using this mechanism, they actually end up residing under the Sandbox/<app name>/sharewith directory.

If your application needs to create files that will be shared with other apps on a permanent basis, you will need the access_shared permission in your application bar-descriptor.xml file (http://developer.blackberry.com/native/documentation/core/com.qnx.doc.native_sdk.devguide/topic/c_appfund_accessing_restricted_functionality.html). However this should be used with caution as this is the most insecure way of storing files due to the frequency with which apps are given access to shared files.

File Encryption

Data encryption in BlackBerry 10 is transparent, so unlike with BlackBerry OS 7.x legacy apps, developers need to do nothing to protect their data at rest if the user or the administrator enables it (http://docs.blackberry.com/en/admin/deliverables/63505/BES10_v10.2.2_BDS_Security_Technical_Overview_en.pdf).

Implementing your own encryption is left as an exercise for the reader. For key material, however, we recommend using a password-based key derivation function such as PBKDF2 with a high iteration count (in the tens of thousands) and then a strong cipher and mode such as XTS-AES.

Randomness Sources

On BlackBerry 10 there are two possible sources of randomness. The traditional POSIX sources such as rand() and srand() and the Security Builder API functions (http://developer.blackberry.com/native/reference/core/com .qnx.doc.crypto.lib_ref/topic/manual/about_rng_and_seeding.html). The Security Builder APIs stem from the Certicom acquisition.

BlackBerry provides a documented Security Builder example that is ANSI and FIPS compliant for Random Number Generator (RNGs) (http://developer .blackberry.com/native/reference/core/com.qnx.doc.crypto.lib_ref/topic/manual/about_rng_and_seeding.html) and shows how to correctly initialize the RNG.

When you need a strong RNG, use the FIPS-compliant RNG.

SSL, TLS Certificate, and Public Key Pinning in Blackberry 10 Native Applications

Because BlackBerry 10.x uses OpenSSL for its SSL/TLS transport implementation you can use the readily available examples. In this case we recommend looking at the OWASP implementation (https://www.owasp.org/index.php/Certificate_and_Public_Key_Pinning). It provides a heavily commented example of SSL/TLS public key pinning, which is trivial to integrate. However, ensuring that the public key file you are using is not stored in the shared directory is important because this might be updatable by other third-party applications. As discussed earlier in the “File Access Control” discussion, in this subsection use the homePath()API to retrieve the path of the app’s private data directory and load it from there.

Security Builder Encryption API

The Security Builder Encryption API (http://developer.blackberry.com/native/documentation/core/com.qnx.doc.crypto/topic/c_sb_ug_overview .html) is provided by the base BlackBerry platform. Suffice it to say, using this API for your cryptographic requirements is the recommended approach and will not be covered here due to the wealth of documentation.

Heap Robustness Against Corruption

QNX and thus BlackBerry 10 provide a number of standard library functions that you can use to influence the robustness of the heap. Although using these functions will in most cases come with a performance penalty, their use can further frustrate exploitation of certain heap memory corruption scenarios.

The function malopt() (http://www.qnx.com/developers/docs/660/topic/com.qnx.doc.neutrino.lib_ref/topic/m/mallopt.html) provides a couple of options that can be useful:

  • MALLOC_VERIFY_ON to turn on additional verification when using allocator routines. If a problem is found, an assert will be raised.
  • MALLOC_FREE_CHECK to protect against double frees.

Additionally, you can use the function mcheck() (http://www.qnx.com/developers/docs/660/index.jsp?topic=%2Fcom.qnx.doc.neutrino.lib_ref%2Ftopic%2Fm%2Fmcheck.html) to turn on consistency checks within allocators with an abort handler callback specified by the developer. This may be preferable to using malopt and MALLOC_VERIFY_ON, which will result in an assert. However, the level of integrity checking that will be performed is highly dependent on the version of the allocator that your app is linked against.

The following list covers the allocator version and depth of mitigations against memory corruption:

  • C library—Minimal consistency checking (although engineering has occurred to provide mitigation against some exploitation techniques).
  • Nondebug version of the malloc library—A slightly greater level of consistency checking.
  • Debug version of the malloc library—Extensive consistency checking, with tuning available through the use of the mallopt() function.

As a result of these varying degrees of protection, avoiding heap corruption vulnerabilities that rely on the heap manager to provide a significant degree of protection against a determined attacker is a better practice.

QNX Native IPC Mechanism Security Considerations

Because BlackBerry 10 is built on top of QNX a range of QNX isms that exist with regards to IPC (http://developer.blackberry.com/native/documentation/core/com.qnx.doc.neutrino.sys_arch/topic/ipc.html), which if used need some thought around security.

Following is a list of IPC security considerations and recommendations:

Most developers will likely stick to high-level constructs and also benefit from user/group separation within the operating system; as such, you may not have to be overly concerned with these.

Headless App Interprocess Communication

In BlackBerry 10.2.1 BlackBerry introduced the concept of headless apps (that is, background tasks) and a new API (http://developer.blackberry.com/native/documentation/cascades/device_platform/headless_apps/). From a security point of view the biggest consideration for developers is the Interprocess Communication (IPC) mechanism that will be used between the headless portion and user interface (UI).

BlackBerry offers this advice on the topic of IPC:


You can use any IPC technique you want to communicate between the parts of your headless app; it’s completely up to you. You should determine the communication needs of your app and choose a solution (or a combination of solutions) that makes the most sense for you.

http://developer.blackberry.com/native/documentation/ cascades/device_platform/headless_apps/


BlackBerry then goes on to suggest a number of options, which we’ve summarized and commented on from a security perspective:

  • Invocation Framework—This is only for UI-to-headless invocation. It cannot be used for headless-to-UI communication.
  • Local sockets—BlackBerry provides the option of using the QTcpSocket class (http://developer.blackberry.com/native/reference/cascades/qtcpsocket.html). Care must be taken when using TCP or UDP sockets for IPC mechanisms to ensure only legitimate local apps can communicate with your UI or headless portion. We recommend using this option as a last resort due to the risk of accidental exposure of interfaces to potential unauthorized access.
  • QSettings and file monitoring—BlackBerry provides another method of using the QSettings class (http://developer.blackberry.com/native/reference/cascades/qsettings.html). If using QSettings be sure to set the file in the app’s private data directory and not the shared files directory. This can be achieved with code similar to this:
QSettings setting(QDir::currentPath() + "/data/Settings/NCCGroup/NCCGroup .conf",  
QSettings::NativeFormat); 

Aside from those explicitly mentioned in the headless API, BlackBerry 10 also provides a number of lower-level options (http://developer.blackberry.com/native/documentation/core/com.qnx.doc.neutrino.sys_arch/topic/ipc .html) that are inherited from the QNX base.

The biggest question to ask yourself—whatever IPC mechanism you choose—is whether it can be misused by a local app or remote attacker and if so what the consequences would be. By considering this threat up front, you can select the most appropriate for your data transfer versus security requirements.

Securing BlackBerry 10 Cascades Applications

BlackBerry 10 Cascades applications are native applications built using the Qt framework (http://developer.blackberry.com/native/documentation/cascades/dev/fundamentals/) and as a result have a number of unique security considerations. BlackBerry, as with the development of native applications, has been proactive in providing security advice to developers who are using Cascades to avoid some of the pitfalls (http://developer.blackberry.com/native/documentation/cascades/best_practices/security/index.html) in addition to issues inherited from using C and C++.

The biggest risk over and above memory corruption and arguably easier to exploit is content injection attacks. The content injection attack risks arise from the fact that under the hood Cascades is JavaScript and HTML technology.

BlackBerry provides advice around the following topics with regards to secure Cascades based applications:

  • Strings—To protect against memory corruption.
  • Password fields—To ensure you don’t show the user’s password.
  • File paths—To mitigate against directory traversal.
  • Script injection—By way of malicious QScript or JavaScript with the following big warning:

When the QScriptEngine class is used to execute scripts, it is important that untrusted values are never appended to the string of the script that’s being executed. All scripts that are executed by a QScriptEngine should be predefined when developing the application and should never be altered dynamically when the application is running.

Furthermore, you should never use import, Loader, or XMLHttpRequest to load JavaScript code that you don’t control into QML. Running untrusted JavaScript code in QML can be equivalent to downloading and running a malicious application. Unlike a desktop browser, the JavaScript execution environment doesn’t restrict certain activities, such as accessing the local file system. For more information about QML and security, see QML Security.

http://developer.blackberry.com/native/documentation/ cascades/best_practices/security/index.html


  • HTML text formatting—Highlighting the risk of UI manipulation.

The QT project also provides specific further advice and examples around QML (http://qt-project.org/doc/qt-4.8/qdeclarativesecurity.html) that demonstrate the content injection attacks but also highlight what is safe. They aptly summarize the risk as follows:


The only reason this page is necessary at all is that JavaScript, when run in a web browser, has quite many restrictions. With QML, you should neither rely on similar restrictions, nor worry about working around them.

http://qt-project.org/doc/qt-4.8/ qdeclarativesecurity.html


Securing BlackBerry 10 HTML5 and JavaScript (WebWorks) Applications

BlackBerry 10 WebWorks applications as with their BlackBerry 7 cousins (see “BlackBerry WebWorks Security on BlackBerry OS 7 and earlier”) are HTML5 and JavaScript and so suffer the risk of a variety of content injection attacks such as cross-site-scripting and similar.

App Invocation Parameters

WebWorks applications by default do not allow parameters to be passed to them when being invoked. If you specify in the applications config.xml the <content> element with a rim:allowInvokeParams parameter this is no longer the case. Take care if you specify this parameter to then validate and sanitize as appropriate any supplied parameters due to the risk of content injection or redirection-style attacks.

For further information, we suggest going to this link: http://developer .blackberry.com/html5/documentation/v2_1/content_element.html.

Access App Configuration Option

WebWorks applications by default cannot access network resources or local file resources outside of the applications package. If you specify in the applications config.xml the <access> element this is no longer the case. Care should be taken on two fronts. The first is for network resources to avoid wildcards wherever possible and only specify fully qualified domains and indicate if subdomains as allowed. However, the ability to use wildcards comes with the following caveat for AJAX requests (this is covered in the next section):


The wildcard character (*) cannot be used for data accessed by XMLHttpRequest. To access data using the XMLHttpRequest, you must explicitly specify each domain.

https://developer.blackberry.com/html5/documentation/ v2_1/accessing_external_resources_webworks.html


The second point to consider is to always use HTTPS (that is, an SSL/TLS protected connection) wherever possible to mitigate against man-in-the-middle type attacks.

You can find further reading at

Websecurity App Configuration Option

WebWorks applications cannot by default specify wildcards for AJAX requests. However, a dangerous option exists that allows you to override this. Specifying this in the config.xml,

<feature id="FileName_blackberry.app"> 
   <param name="websecurity" value="disable" /> 
</feature> 

…then in the words of BlackBerry, it does the following:


… will turn off the security measures that protect your application from untrusted content.

Traditionally, a browser’s security model prevents content from different domains from interacting with each other, allowing developers to more easily include untrusted content without worrying about its effects. Content from a different domain (included via iframes, XHR, scripts or anything else) is limited from interacting with your content, reducing the risk posed by malicious code.

http://devblog.blackberry.com/2013/08/accessing- external-resources-in-a-blackberry-10-webworks- app-enterprise-dev-2/


What does this do in practice? It basically disables the same-origin policy (http://en.wikipedia.org/wiki/Same-origin_policy), which is one of the core foundations of web security. This is very dangerous and should be avoided if at all possible.

You can find further reading on this topic at

Content Injection Mitigations

Suffice it to say, with WebWorks apps the biggest risk is content injection attacks such as cross-site scripting or content-manipulation or interception due to the lack of SSL.

So going above and beyond application innovation and the access and web security configuration options, the primary method of defense will be to not use .innerHTML when constructing content within the DOM. Instead all HTML DOM objects should be built using CreateElement and the properties set with input validation where appropriate. Although taking this approach is more expensive in terms of development effort, it greatly reduces the likelihood of content injection being possible in your app.

Securing Android Applications on BlackBerry 10

Refer to the “Securing Android Applications” in Chapter 9 of this book.

Chapter 9 covers all the considerations one would expect. In terms of BlackBerry 10’s Android run time it’s important to recognize that the port is extensive. BlackBerry ported the binder Linux kernel driver used on traditional Android devices to a QNX Resource Manager. The Dalvik VM and Zygote concept were also ported across. As a result the ability to run native Android apps is indeed that native. A vast majority of the Android runtime is present allowing near seamless compatibility with a wide variety of apps.

As a result of this porting activity it is important to understand that the same inter-app attack paths (i.e., those that go via Android IPC mechanisms) translate due to the wholesale porting of the runtime and framework.

Summary

The security engineering that went into BlackBerry OS 7 and earlier was comprehensive, providing a rich and sophisticated functionality. However, it was also quite complicated to leverage all the built-in features to gain the maximum level of security. This statement is especially true when you compare it against securing BlackBerry 10 applications where a lot is taken care of by the operating system by default.

BlackBerry native applications bring with them a range of generic risks due to the use of C and C++. However, compared to other operating systems such as Android and their relatively rich and complex intents, services, binder and message interfaces, and broadcast receivers, BlackBerry is on the whole relatively simple to secure. This is especially true if you stick to the higher-level IPC constructs and be careful where you store files.

With Cascades applications, from a security perspective you need to concern yourself with the recommendations for native applications coupled with the risk of content injection attacks by virtue of the underlying functionality provided by the Cascades/QT framework and the reliance on JavaScript.

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

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