Signing email with an NFC smart card on Android

Last time we discussed how to access the SIM card and use it as a secure element to enhance Android applications. One of the main problems with this approach is that since SIM cards are controlled by the MNO any applets running on a commercial SIM have to be approved by them. Needless to say, that considerably limits flexibility. Fortunately, NFC-enabled Android devices can communicate with practically any external contactless smart card, and you can install anything on those. Let's explore how an NFC smart card can be used to sign email on Android.

NFC smart cards

As discussed in previous posts, a smart card is a secure execution environment on a single chip, typically packaged in a credit-card sized plastic package or the smaller 2FF/3FF/4FF form factors when used as a SIM card. Traditionally, smart cards connect with a card reader using a number of gold-plated contact pads. The pads are used to both provide power to the card and establish serial communication with its I/O interface. Size, electrical characteristics and communication protocols are defined in the 7816 series of ISO standards. Those traditional cards are referred to as 'contact smart cards'. Contactless cards on the other hand do not need to have physical contact with the reader. They draw power and communicate with the reader using RF induction. The communication protocol (T=CL) they use is defined in ISO 14443 and is very similar to the T1 protocol used by contact cards. While smart cards that have only a contactless interface do exist, dual-interface cards that have both contacts and an antenna for RF communication are the majority. The underlying RF standard used varies by manufacturer, and both Type A and Type B are common. 

As we know, NFC has three standard modes of operation: reader/writer (R/W), peer-to-peer (P2P) and card emulation (CE) mode. All NFC-enabled Android devices support R/W and P2P mode, and some can provide CE, either using a physical secure element (SE) or software emulation. All that is needed to communicate with a contactless smart card is the basic R/W mode, so they can be used on practically all Android devices with NFC support. This functionality is provided by the IsoDep class. It provides only basic command-response exchange functionality with the transceive() method, any higher level protocol need to be implemented by the client application.

Securing email

There have been quite a few new services that are trying to reinvent secure email in recent years. They are trying to make it 'easy' for users by taking care of key management and shifting all cryptographic operations to the server. As recent events have reconfirmed, introducing an intermediary is not a very good idea if communication between two parties is to be and remain secure. Secure email itself is hardly a new idea, and the 'old-school' way of implementing it relies on pubic key cryptography. Each party is responsible for both protecting their private key and verifying that the public key of their counterpart matches their actual identity. The method used to verify identity is the biggest difference between the two major secure email standards in use today, PGP and S/MIME. PGP relies on the so called 'web of trust', where everyone can vouch for the identity of someone by signing their key (usually after meeting them in person), and keys with more signatures can be considered trustworthy. S/MIME, on the other hand, relies on PKI and X.509 certificates, where the issuing authority (CA) is relied upon to verify identity when issuing a certificate. PGP has the advantage of being decentralized, which makes it harder to break the system by compromising  a single entity, as has happened with a number of public CAs in recent years. However, it requires much more user involvement and is especially challenging to new users. Additionally, while many commercial and open source PGP implementations do exist, most mainstream email clients do not support PGP out of the box and require the installation of plugins and additional software. On the other hand, all major proprietary (Outlook variants, Mail.app, etc) and open source (Thunderbird) email clients have built-in and mature S/MIME implementations. We will use S/MIME for this example because it is a lot easier to get started with and test, but the techniques described can be used to implement PGP-secured email as well. Let's first discuss how S/MIME is implemented.

Signing with S/MIME

The S/MIME, or Secure/Multipurpose Internet Mail Extensions, standard defines how to include signed and/or encrypted content in email messages. It specified both the procedures for creating  signed or encrypted (enveloped) content and the MIME media types to use when adding them to the message. For example, a signed message would have a part with the Content-Type: application/pkcs7-signature; name=smime.p7s; smime-type=signed-data which contains the message signature and any associated attributes. To an email client that does not support S/MIME, like most Web mail apps, this would look like an attachment called smime.p7s. S/MIME-compliant clients would instead parse and verify the signature and display some visual indication showing the signature verification status.

The more interesting question however is what's in smime.p7s? The 'p7' stands for PKCS#7, which is the predecessor of the current Cryptographic Message Syntax (CMS). CMS defines structures used to package signed, authenticated or encrypted content and related attributes. As with most PKI X.509-derived standards, those structures are ASN.1 based and encoded into binary using DER, just like certificates and CRLs. They are sequences of other structures, which are in turn composed of yet other ASN.1 structures, which are..., basically sequences all the way down. Let's try to look at the higher-level ones used for signed email. The CMS structure describing signed content is predictably called SignedData and looks like this:

SignedData ::= SEQUENCE {
version CMSVersion,
digestAlgorithms DigestAlgorithmIdentifiers,
encapContentInfo EncapsulatedContentInfo,
certificates [0] IMPLICIT CertificateSet OPTIONAL,
crls [1] IMPLICIT RevocationInfoChoices OPTIONAL,
signerInfos SignerInfos }

Here digestAlgorithms contains the OIDs of the hash algorithms used to produce the signature (one for each signer) and encapContentInfo describes the data that was signed, and can optionally contain the actual data. The optional certificates and crls fields are intended to help verify the signer certificate. If absent, the verifier is responsible for collecting them by other means. The most interesting part, signerInfos, contains the actual signature and information about the signer. It looks like this:

SignerInfo ::= SEQUENCE {
version CMSVersion,
sid SignerIdentifier,
digestAlgorithm DigestAlgorithmIdentifier,
signedAttrs [0] IMPLICIT SignedAttributes OPTIONAL,
signatureAlgorithm SignatureAlgorithmIdentifier,
signature SignatureValue,
unsignedAttrs [1] IMPLICIT UnsignedAttributes OPTIONAL }

Besides the signature value and algorithms used, SignedInfo contains signer identifier used to find the exact certificate that was used and a number of optional signed and unsigned attributes. Signed attributes are included when producing the signature value and can contain additional information about the signature, such as signing time. Unsigned attribute are not covered by the signature value, but can contain signed data themselves, such as counter signature (an additional signature over the signature value).

To sum this up, in order to produce a S/MIME signed message, we need to sign the email contents and any attributes, generate the SignedInfo structure, wrap it into a SignedData, DER encode the result and add it to the message using the appropriate MIME type. Sound easy, right? Let's how this can be done on Android.

Using S/MIME on Android

On any platform, you need two things in order to generate an S/MIME message: a cryptographic provider that can perform the actual signing using an asymmetric key and an ASN.1 parser/generator in order to generate the SignedData structure. Android has JCE providers that support RSA, recently even with hardware-backed keys. What's left is an ASN.1 generator. While ASN.1 and DER/BER have been around for ages, and there are quite a few parsers/generators, the practically useful choices  are not that many. No one really generates code directly from the ASN.1 modules found in related standards, most libraries implement only the necessary parts, building on available components. Both of Android's major cryptographic libraries, OpenSSL and Bouncy Castle contain ASN.1 parser/generators and have support for CMS. The related API's are not public though, so we need to include our own libraries.

As usual we turn to Spongy Castle, which is provides all of Bouncy Castle's functionality under a different namespace. In order to be able process CMS and generate S/MIME messages, we need the optional scpkix and scmail packages. The first one contains PKIX and CMS related classes, and the second one implements S/MIME. However, there is a twist: Android lacks some of the classes required for generating S/MIME messages. As you may know, Android has implementations for most standard Java APIs, with a few exceptions, most notably the GUI widget related AWT and Swing packages. Those are rarely missed, because Android has its own widget and graphics libraries. However, besides widgets AWT contains classes related to MIME media types as well. Unfortunately, some of those are  used in libraries that deal with MIME objects, such as JavaMail and the Bouncy Castle S/MIME implementation. JavaMail versions that include alternative AWT implementations, repackaged for Android have been available for some time, but since they use some non-standard package names, they are not a drop-in replacement. That applies to Spongy Castle as well: some source code modifications are required in order to get scmail to work with the javamail-android library.

With that sorted out, generating an S/MIME message on Android is just a matter of finding the signer key and certificate and using the proper Bouncy Castle and JavaMail APIs to generate and send the message:

PrivateKey signerKey = KeyChain.getPrivateKey(ctx, "smime");
X509Certificate[] chain = KeyChain.getCertificateChain(ctx, "smime");
X509Certificate signerCert = chain[0];
X509Certificate caCert = chain[1];

SMIMESignedGenerator gen = new SMIMESignedGenerator();
gen.addSignerInfoGenerator(new JcaSimpleSignerInfoGeneratorBuilder()
.setProvider("AndroidOpenSSL")
.setSignedAttributeGenerator(
new AttributeTable(signedAttrs))
.build("SHA512withRSA", signerKey, signerCert));
Store certs = new JcaCertStore(Arrays.asList(signerCert, caCert));
gen.addCertificates(certs);

MimeMultipart mm = gen.generate(mimeMsg, "SC");
MimeMessage signedMessage = new MimeMessage(session);
Enumeration headers = mimeMsg.getAllHeaderLines();
while (headers.hasMoreElements()) {
signedMessage.addHeaderLine((String) headers.nextElement());
}
signedMessage.setContent(mm);
signedMessage.saveChanges();

Transport.send(signedMessage);

Here we first get the signer key and certificate using the KeyChain API and then create an S/MIME generator by specifying the key, certificate, signature algorithm and signed attributes. Note that we specify the AndroidOpenSSL provider explicitly which is the only one that can use hardware-backed keys. This is only required if you changed the default provider order when installing Spongy Castle, by default AndroidOpenSSL is the preferred JCE provider. We then add the certificates we want to include in the generated SignedData and generate a multi-part MIME message that includes both the original message (mimeMsg) and the signature. Finally we send the message using the JavaMail Transport class. The JavaMail Session initialization is omitted from the example above, see the sample app for how to set it up to use Gmail's SMTP server. This requires the Gmail account password to be specified, but with a little more work it can be replaced with an OAuth token you can obtain from the system AccountManager.

So what about smart cards?

Using a MuscleCard to sign email

In order to sign email using keys stored on a smart card we need a few things: 
  • a dual-interface smart cards that supports RSA keys
  • a crypto applet that allows us to sign data with those keys
  • some sort of middleware that exposes card functionality through a standard crypto API
Most recent dual-interface JavaCards fulfill our requirements, but we will be using a NXP J3A081 which supports JavaCard 2.2.2 and 2048-bit RSA keys. When it comes to open source crypto applets though, unfortunately the choices are quite limited. Just about the only one that is both full-featured and well supported in middleware libraries is the venerable MuscleCard applet. We will be using one of the fairly recent forks, updated to support JavaCard 2.2 and extended APDUs. To load the applet on the card you need a GlobalPlatform-compatible loader application, like GPJ, and of course the CardManager keys. Once you have initialized it, you can personalize it by generating or importing keys and certificates. After that the card can be used in any application that supports PKCS#11, for example Thunderbird and Firefox. Because the card is dual-interface, practically any smart card reader can be used on desktops. When the OpenSC PKCS#11 module is loaded in Thunderbird the card will show up in the Security Devices dialog like this:


If the certificate installed in the card has your email in the Subject Alternative Name extension, you should be able send signed and encrypted emails (if you have the recipient's certificate, of course). But how to achieve the same thing in Android?

Using MuscleCard on Android

Android doesn't support PKCS#11 modules, so in order to expose the cards crypto functionality we could implement a custom JCE provider that provides card-backed implementations of the Signature and KeyStrore engine classes. That is quite a bit of work though, and since we are only targeting the Bouncy Castle S/MIME API, we can get away by implementing the ContentSigner interface. It provides an OutputStream clients write data to be signed to, an AlgorithmIdentifer for the signature method used and a getSignature() method that returns the actual signature value. Our MuscleCard-backed implementation could look like this:

class MuscleCardContentSigner implements ContentSigner {

private ByteArrayOutputStream baos = new ByteArrayOutputStream();
private MuscleCard msc;
private String pin;
...
@Override
public byte[] getSignature() {
msc.select();
msc.verifyPin(pin);

byte[] data = baos.toByteArray();
baos.reset();
return msc.sign(data);
}
}

Here the MuscleCard class is our 'middleware' and encapsulates the card's RSA signature functionality. It is implemented by sending the required command APDUs for each operation using Android's IsoDep API and aggregating and converting the result as needed. For example, the verifyPin() is implemented like this:

class MuscleCard {

private IsoDep tag;

public boolean verifyPin(String pin) throws IOException {
String cmd = String.format("B0 42 01 00 %02x %s", pin.length(),
toHex(pin.getBytes("ASCII")));
ResponseApdu rapdu = new ResponseApdu(tag.transceive(fromHex(cmd)));
if (rapdu.getSW() != SW_SUCCESS) {
return false;
}

return true;
}
}

Signing is a little more complicated because it involves creating and updating temporary I/O objects, but follows the same principle. Since the applet does not support padding or hashing, we need to generate and pad the PKCS#1 (or PSS) signature block on Android and send the complete data to the card. Finally, we need to plug our signer implementation into the Bouncy Castle CMS generator:

ContentSigner mscCs = new MuscleCardContentSigner(muscleCard, pin);
gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(
new JcaDigestCalculatorProviderBuilder()
.setProvider("SC")
.build()).build(mscCs, cardCert));

After that the signed message can be generated exactly like when using local key store keys. Of course, there are a few caveats. Since apps cannot control when an NFC connection is established, we can only sign data after the card has been picked up by the device and we have received an Intent with a live IsoDep instance. Additionally, since signing can take a few seconds, we need to make sure the connection is not broken by placing the device on top of the card (or use some sort of awkward case with a card slot). Our implementation also takes a few shortcuts by hard-coding the certificate object ID and size, as well as the card PIN, but those can be remedied with a little more code. The UI of our homebrew S/MIME client is shown below.


After you import a PKCS#12 file in the system credential store you can sign emails using the imported keys. The 'Sign with NFC' button is only enabled when a compatible card has been detected. The easiest way to verify the email signature is to send a message to a desktop client that supports S/MIME. There are also a few Android email apps that support S/MIME, but setup can be a bit challenging because they often use their own trust and key stores. You can also dump the generated message to external storage using MimeMessage.writeTo() and then parse the CMS structure using the OpenSSL cms command:

$ openssl cms -cmsout -in signed.message -noout -print
CMS_ContentInfo:
contentType: pkcs7-signedData (1.2.840.113549.1.7.2)
d.signedData:
version: 1
digestAlgorithms:
algorithm: sha512 (2.16.840.1.101.3.4.2.3)
parameter: NULL
encapContentInfo:
eContentType: pkcs7-data (1.2.840.113549.1.7.1)
eContent: <absent>
certificates:
d.certificate:
cert_info:
version: 2
serialNumber: 4
signature:
algorithm: sha1WithRSAEncryption (1.2.840.113549.1.1.5)
...
crls:
<empty>
signerInfos:
version: 1
d.issuerAndSerialNumber:
issuer: C=JP, ST=Tokyo, CN=keystore-test-CA
serialNumber: 3
digestAlgorithm:
algorithm: sha512 (2.16.840.1.101.3.4.2.3)
parameter: NULL
signedAttrs:
object: contentType (1.2.840.113549.1.9.3)
value.set:
OBJECT:pkcs7-data (1.2.840.113549.1.7.1)

object: signingTime (1.2.840.113549.1.9.5)
value.set:
UTCTIME:Oct 25 16:25:29 2013 GMT

object: messageDigest (1.2.840.113549.1.9.4)
value.set:
OCTET STRING:
0000 - 88 bd 87 84 15 53 3d d8-72 64 c7 36 f8 .....S=.rd.6.
000d - b0 f3 39 90 b2 a4 77 56-5c 9f e4 2e 7c ..9...wV\...|
001a - 7d 2e 0b 08 b4 b7 e7 6c-e9 b6 61 00 13 }......l..a..
0027 - 25 62 69 2a bc 08 5b 4c-4f c9 73 cf d3 %bi*..[LO.s..
0034 - c6 1e 51 c2 5f c1 64 77-3b 45 e2 cb ..Q._.dw;E..
signatureAlgorithm:
algorithm: rsaEncryption (1.2.840.113549.1.1.1)
parameter: NULL
signature:
0000 - a0 d0 ce 35 46 8c f9 cd-e5 db ed d8 e3 f0 08 ...5F..........
...
unsignedAttrs:
<empty>

Email encryption using the NFC smart card can be implemented in a similar fashion, but this time the card will be required when decrypting the message.

Summary

Practically all NFC-enabled Android devices can be used to communicate with a contactless or dual-interface smart card. If the interface of card applications is known, it is fairly easy to implement an Android component that exposes card functionality via a custom interface, or even as a standard JCE provider. The card's cryptographic functionality can then be used to secure email or provide HTTPS and VPN authentication. This could be especially useful when dealing with keys that have been generated on the card and cannot be extracted. If a PKCS#12 backup file is available, importing the file in the system credential store can provide a better user experience and comparable security levels if the device has a hardware-backed credential store. 

Using the SIM card as a secure element in Android

Our last post introduced one of Android 4.3's more notable security features -- improved credential storage, and while there are a few other enhancements worth discussing, this post will slightly change direction. As mentioned previously, mobile devices can include some form of a Secure Element (SE), but a smart card based UICC (usually called just 'SIM card') is almost universally present. Virtually all SIM cards in use today are programmable and thus can be used as a SE. Continuing the topic of hardware-backed security, we will now look into how SIMs can be programmed and used to enhance the security of Android applications.

SIM cards

First, a few words about terminology: while the correct term for modern mobile devices is UICC (Universal Integrated Circuit Card), since the goal of this post is not to discuss the differences between mobile networks, we will usually call it a 'SIM card' and only make the distinction when necessary. 

So what is a SIM card? 'SIM' stands for Subscriber Identity Module and refers to a smart card that securely stores the subscriber identifier and the associated key used to identify and authenticate to a mobile network. It was originally used on GSM networks and standards were later extended to support 3G and LTE. Since SIMs are smart cards, they conform to ISO-7816 standards regarding physical characteristics and electrical interface. Originally they were the same size as 'regular' smart cards (Full-size, FF), but by far the most popular sizes nowadays are Mini-SIM (2FF) and Micro-SIM (3FF), with Nano-SIM (4FF) introduced in 2012. 

Of course, not every smart that fits in the SIM slot can be used in a mobile device, so the next question is: what makes a smart card a SIM card? Technically, it's conformance to mobile communication standards such 3GPP TS 11.11 and certification by the SIMalliance. In practice it is the ability to run an application that allows it to communicate with the phone (referred to as 'Mobile Equipment', ME, or 'Mobile Station', MS in related standards) and connect to a mobile network. While the original GSM standard did not make a  distinction between the physical smart card and the software required to connect to the mobile network, with the introduction of 3G standards, a clear distinction has been made. The physical smart card is referred to as Universal Integrated Circuit Card (UICC) and different mobile network applications than run on it have been defined: GSM, CSIM, USIM, ISIM, etc. A UICC can host and run more than one network application (hence 'universal'), and thus can be used to connect to different networks. While network application functionality depends on the specific mobile network, their core features are quite similar: store network parameters securely and identify to the network, as well as authenticate the user (optionally) and store user data. 

SIM card applications

Let's take GSM/3G as an example and briefly review how a network application works. For GSM the main network parameters are network identity (International Mobile Subscriber Identity, IMSI; tied to the SIM), phone number  (MSISDN, used for routing calls and changeable) and a shared network authentication key Ki. To connect to the network the MS needs to authenticate itself and negotiate a session key. Both authentication and session key derivation make use of Ki, which is also known to the network and looked up by IMSI. The MS sends a connection request and includes its IMSI, which the network uses to find the corresponding Ki. The network then uses the Ki to generate a challenge (RAND), expected challenge response (SRES) and session key Kc and sends RAND to the MS. Here's where the GSM application running on the SIM card comes into play: the MS passes the RAND to the SIM card, which in turn generates its own SRES and Kc. The SRES is sent to the network and if it matches the expected value, encrypted communication is established using the session key Kc. As you can see, the security of this protocol hinges solely on the secrecy of the Ki. Since all operations involving the Ki are implemented inside the SIM and it never comes with direct contact with neither the MS or the network, the scheme is kept reasonably secure. Of course, security depends on the encryption algorithms used as well, and major weaknesses that allow intercepted GSM calls to be decrypted using off-the shelf hardware were found in the original versions of the A3/A5 algorithms (which were initially secret). Jumping back to Android for a moment, all of this is implemented by the baseband software (more on this later) and network authentication is never directly visible to the main OS.

We've shown that SIM cards need to run applications, let's now say a few words about how those applications are implemented and installed. Initial smart cards were based on a file system model, where files (elementary files, EF) and directories (dedicated files, DF) were named with a two-byte identifier. Thus developing 'an application' consisted mostly of selecting an ID for the DF that hosts its files (called ADF), and specifying the formats and names of EFs that store data. For example, the GSM application is under the '7F20' ADF, and the USIM ADF hosts the EF_imsi, EF_keys, EF_sms, etc. files. Practically all SIMs used today are based on Java Card technology and implement GlobalPlatform card specifications. Thus all network applications are implemented as Java Card applets and emulate the legacy file-based structure for backward compatibility. Applets are installed according to GlobalPlatform specifications by authenticating to the Issuer Security Domain (Card Manager) and issuing LOAD and INSTALL commands.

One application management feature specific to SIM cards is support for OTA (Over-The-Air) updates via binary SMS. This functionality is not used by all carries, but it allows them to remotely install applets on SIM cards they have issued. OTA is implemented by wrapping card commands (APDUs) in SMS T-PDUs, which the ME forwards to the SIM (ETSI TS 102 226). In most SIMs this is actually the only way to load applets on the card, even during initial personalization. That is why most of the common GlobalPlatform-compliant tools cannot be used as is for managing SIMs. One needs to either use a tool that supports SIM OTA, such as the SIMalliance Loader, or implement APDU wrapping/unwrapping, including any necessary encryption and integrity algorithms (ETSI TS 102 225). Incidentally, problems with the implementation of those secured packets on some SIMs that use DES as the encryption and integrity algorithm have been used to crack OTA update keys. The major use of the OTA functionality is to install and maintain SIM Toolkit (STK) applications which can interact with the handset via standard 'proactive' (in reality implemented via polling) commands and display menus or even open Web pages and send SMS. While STK applications are almost unheard of in the US and Asia, they are still heavily used in some parts of Europe and Africa for anything from mobile banking to citizen authentication. Android also supports STK with a dedicated STK system app, which is automatically disabled if the SIM card has not STK applets installed.

Accessing the SIM card

As mentioned above, network related functionality is implemented by the baseband software and what can be done from Android is entirely dependent on what features the baseband exposes. Android supports STK applications, so it does have internal support for communicating to the SIM, but the OS security overview explicitly states that 'low level access to the SIM card is not available to third-party apps'. So how can we use it as an SE then? Some Android builds from major vendors, most notably Samsung, provide an implementation of the SIMalliance Open Mobile API on some handsets and an open source implementation (for compatible devices) is available from the SEEK for Android project. The Open Mobile API aims to provide a unified interface for accessing SEs on Android, including the SIM. To understand how the Open Mobile API works and the cause of its limitations, let's first review how access to the SIM card is implemented in Android.

On Android devices all mobile network functionality (dialing, sending SMS, etc.) is provided by the baseband processor (also referred to as 'modem' or 'radio'). Android applications and system services communicate to the baseband only indirectly via the Radio Interface Layer (RIL) daemon (rild). It in turn talks to the actual hardware by using a manufacturer-provided RIL HAL library, which wraps the proprietary interface the baseband provides. The SIM card is typically connected only to baseband processor (sometimes also to the NFC controller via SWP), and thus all communication needs to go through the RIL. While the proprietary RIL implementation can always access the SIM in order to perform network identification and authentication, as well as read/write contacts and access STK applications, support for transparent APDU exchange is not always available. The standard way to provide this feature is to use extended AT commands such AT+CSIM (Generic SIM access) and AT+CGLA (Generic UICC Logical Channel Access), as defined in 3GPP TS 27.007, but some vendors implement it using proprietary extensions, so support for the necessary AT commands does not automatically provide SIM access.

SEEK for Android provides patches that implement a resource manager service (SmartCardService) that can connect to any supported SE (embedded SE, ASSD or UICC) and extensions to the Android telephony framework that allow for transparent APDU exchange with the SIM. As mentioned above, access through the RIL is hardware and proprietary RIL library dependent, so you need both a compatible device and a build that includes the SmartCardService and related framework extensions. Thanks to some work by they u'smile project, UICC access on most variants of the popular Galaxy S2 and S3 handsets is available using a patched CyanogenMod build, so you can make use of the latest SEEK version. Even if you don't own one of those devices, you can use the SEEK emulator extension which lets you use a standard PC/SC smart card reader to connect a SIM to the Android emulator. Note that just any regular Java card won't work out of the box because the emulator will look for the GSM application and mark the card as not usable if it doesn't find one. You can modify it to skip those steps, but a simple solution is to install a dummy GSM application that always returns the expected responses.

Once you have managed to get a device or the emulator to talk to the SIM, using the OpenMobile API to send commands is quite straightforward:

// connect to the SE service, asynchronous
SEService seService = new SEService(this, this);
// list readers
Reader[] readers = seService.getReaders();
// assume the first one is SIM and open session
Session session = readers[0].openSession();
// open logical (or basic) channel
Channel channel = session.openLogicalChannel(aid);
// send APDU and get response
byte[] rapdu = channel.transmit(cmd);

You will need to request the org.simalliance.openmobileapi.SMARTCARD permission and add the org.simalliance.openmobileapi extension library to your manifest for this to work. See the official wiki for more details.

<manifest ...>

<uses-permission android:name="org.simalliance.openmobileapi.SMARTCARD" />

<application ...>
<uses-library
android:name="org.simalliance.openmobileapi"
android:required="true" />
...
</application>
</manifest>

SE-enabled Android applications

Now that we can connect to the SIM card from applications, what can we use it for? Just as regular smart cards, an SE can be used to store data and keys securely and perform cryptographic operations without keys having to leave the card. One of the usual applications of smart cards is to store RSA authentication keys and certificates that are used from anything from desktop logon to VPN or SSL authentication. This is typically implemented by providing some sort of middleware library, usually a standard cryptographic service provider (CSP) module that can plug into the system CSP or be loaded by a compatible application. As the Android security model does not allow system extensions provided by third party apps, in order to integrate with the system key management service, such middleware would need to be implemented as a keymaster module for the system credential store (keystore) and be bundled as a system library. This can be accomplished by building a custom ROM which installs our custom keymaster module, but we can also take advantage of the SE without rebuilding the whole system. The most straightforward way to do this is to implement the security critical part of an app inside the SE and have the app act as a client that only provides a user-facing GUI. One such application provided with the SEEK distribution is an SE-backed one-time password (OTP) Google Authenticator app. Since the critical part of OTP generators is the seed (usually a symmetric cryptographic key), they can easily be cloned once the seed is obtained or extracted. Thus OTP apps that store the seed in a regular file (like the official Google Authenticator app) provide little protection if the device OS is compromised. The SEEK GoogleOtpAuthenticator app both stores the seed and performs OTP generation inside the SE, making it impossible to recover the seed from the app data stored on the device.

Another type of popular application that could benefit from using an SE is a password manager. Password managers typically use a user-supplied passphrase to derive a symmetric key, which is in turn used to encrypt stored passwords. This makes it hard to recover stored passwords without knowing the passphrase, but naturally security level is totally dependent on its complexity. As usual, because typing a long string with rarely used characters on a mobile device is not a particularly pleasant experience, users tend to pick easier to type, low-entropy passphrases. If the key is stored in an SE, the passphrase can be skipped or replaced with a simpler PIN, making the password manager app both more user-friendly and secure. Let's see how such an SE-backed password manager can be implemented using a Java Card applet and the Open Mobile API.

DIY SIM password manager

Ideally, all key management and encryption logic should be implemented inside the SE and the client application would only provide input (plain text passwords) and retrieve opaque encrypted data. The SE applet should not only provide encryption, but also guarantee the integrity of encrypted data either by using an algorithm that provides authenticated encryption (which most smart card don't natively support currently) or by calculating a MAC over the encrypted data using HMAC or some similar mechanism. Smart cards typically provide some sort of encryption support, starting with DES/3DES for low-end models and going up to RSA and EC for top-of-the-line ones. Since public key cryptography is typically not needed for mobile network authentication or secure OTA (which is based on symmetric algorithms), SIM cards rarely support RSA or EC. A reasonably secure symmetric and hash algorithm should be enough to implement a simple password manager though, so in theory we should be able to use even a lower-end SIM.

As mentioned in the previous section, all recent SIM cards are based on Java Card technology, and it is possible to develop and load a custom applet, provided one has access to the Card Manager or OTA keys. Those are naturally not available for commercial MNO SIMs, so we would need to use a blank 'programmable' SIM that allows for loading applets without authentication or comes bundled with the required keys. Those are quite hard, but not impossible to come by, so let's see how such a password manager applet could be implemented. We won't discuss the basics of Java Card programming, but jump straight to the implementation. Refer to the offical documentation, or a tutorial if you need an introduction.

The Java Card API provides a subset of the JCA classes, with an interface optimized towards using pre-allocated, shared byte arrays, which is typical on a memory constrained platform such as a smart card. A basic encryption example would look something like this:

byte[] buff = apdu.getBuffer();
//..
DESKey deskey = (DESKey)KeyBuilder.buildKey(KeyBuilder.TYPE_DES_TRANSIENT_DESELECT,
KeyBuilder.LENGTH_DES3_2KEY, false);
deskey.setKey(keyBytes, (short)0);
Cipher cipher = Cipher.getInstance(Cipher.ALG_DES_CBC_PKCS5, false);
cipher.init(deskey, Cipher.MODE_ENCRYPT);
cipher.doFinal(data, (short) 0, (short) data.length,
buff, (short) 0);

As you can see, a dedicated key object, that is automatically cleared when the applet is deselected, is first created and then used to initialize a Cipher instance. Besides the unwieldy number of casts to short (necessary because 'classic' Java Card does not support int, but it is still the default integer type) the code is very similar to what you would find in a Java SE or Android application. Hashing uses the MessageDigest class and follows a similar routine. Using the system-provided Cipher and MessageDigest classes as building blocks it is fairly straightforward to implement CBC mode encryption and HMAC for data integrity. However as it happens, our low end SIM card does not provide usable implementations of those classes (even though the spec sheet claims they do), so we would need to start from scratch. Fortunately, since Java cards can execute arbitrary programs (as long as they fit in memory), it is also possible to include our own encryption algorithm implementation in the applet. Even better, a Java Card optimized AES implementation is freely available. This implementation provides only the basic pieces of AES -- key schedule generation and single block encryption, so some additional work is required to match the Java Cipher class functionality. The bigger downside is that by using an algorithm implemented in software we cannot take advantage of the specialized crypto co-processor most smart cards have. With this implementation our SIM (8-bit CPU, 6KB RAM) card takes about 2 seconds to process a single AES block with a 128-bit key. The performance can be improved slightly by reducing the number of AES round to 7 (10 are recommended for 128-bit keys), but that will both lower the security level of the system and result in an non-standard cipher, making testing more difficult. Another disadvantage is that native key objects are usually stored in a secured memory area that is better protected from side channel attacks, but by using our own cipher we are forced to store keys in regular byte arrays. With those caveats, this AES implementation should give us what we need for our demo application. Using the JavaCardAES class as a building block, our AES CBC encryption routine would look something like this:

aesCipher.RoundKeysSchedule(keyBytes, (short) 0, roundKeysBuff);
short padSize = addPadding(cipherBuff, offset, len);
short paddedLen = (short) (len + padSize);
short blocks = (short) (paddedLen / AES_BLOCK_LEN);

for (short i = 0; i < blocks; i++) {
short cipherOffset = (short) (i * AES_BLOCK_LEN);
for (short j = 0; j < AES_BLOCK_LEN; j++) {
cbcV[j] ^= cipherBuff[(short) (cipherOffset + j)];
}
aesCipher.AESEncryptBlock(cbcV, OFFSET_ZERO, roundKeysBuff);
Util.arrayCopyNonAtomic(cbcV, OFFSET_ZERO, cipherBuff,
cipherOffset, AES_BLOCK_LEN);
}

Not as concise as using the system crypto classes, but gets the job done. Finally (not shown), the IV and cipher text are copied to the APDU buffer and sent back to the caller. Decryption follows a similar pattern. One thing that is obviously missing is the MAC, but as it turns out a hash algorithm implemented in software is prohibitively slow on our SIM (mostly because it needs to access large tables stored in the slow card EEPROM). While a MAC can be also implemented using the AES primitive, we have omitted it from the sample applet. In practice tampering with the cipher text of encrypted passwords would only result in incorrect passwords, but it is still a good idea to use a MAC when implementing this on a fully functional Java Card.

Our applet can now perform encryption and decryption, but one critical piece is still missing -- a random number generator. The Java Card API has the RandomData class which is typically used to generate key material and IVs for cryptographic operations, but just as with the Cipher class it is not available on our SIM. Therefore, unfortunately, we need to apply the DIY approach again. To keep things simple and with a (somewhat) reasonable response time, we implement a simple pseudo random number generator (PRNG) based on AES in counter mode. As mentioned above, the largest integer type in classic Java Card is short, so the counter will wrap as soon as it goes over 32767. While this can be overcome fairly easily by using a persistent byte array to simulate a long (or BigInteger if you are more ambitious), the bigger problem is that there is no suitable source of entropy on the smart card that we can use to seed the PRNG. Therefore the PRNG AES key and nonce need to be specified at applet install time and be unique to each SIM. Our simplistic PRNG implementation based on the JavaCardAES class is shown below (buff is the output buffer):

Util.arrayCopyNonAtomic(prngNonce, OFFSET_ZERO, cipherBuff,
OFFSET_ZERO, (short) prngNonce.length);
Util.setShort(cipherBuff, (short) (AES_BLOCK_LEN - 2), prngCounter);

aesCipher.RoundKeysSchedule(prngKey, (short) 0, roundKeysBuff);
aeCipher.AESEncryptBlock(cipherBuff, OFFSET_ZERO, roundKeysBuff);
prngCounter++;

Util.arrayCopyNonAtomic(cipherBuff, OFFSET_ZERO, buff, offset, len);

The recent Bitcoin app problems traced to a repeatable PRNG in Android, controversy around the Dual_EC_DRBG PRNG algorithm, which is both believed to be weak by design and is used by default in popular crypto toolkits and finally the low-quality hardware RNG found in FIPS certified smart cards have highlighted the critical impact a flawed PRNG can have on any system that uses cryptography. That is why a DIY PRNG is definitely not something you would like to use in a production system. Do find a SIM that provides working crypto classes and do use RandomData.ALG_SECURE_RANDOM to initialize the PRNG (that won't help much if the card's hardware RNG is flawed, of course).

With that we have all the pieces needed to implement the password manager applet, and what is left is to define and expose a public interface. For Java Card this means defining the values of the CLA and INS bytes the applet can process. Besides the obviously required encrypt and decrypt commands, we also provide commands to get the current state, initialize and clear the applet.

static final byte CLA = (byte) 0x80;
static final byte INS_GET_STATUS = (byte) 0x1;
static final byte INS_GEN_RANDOM = (byte) 0x2;
static final byte INS_GEN_KEY = (byte) 0x03;
static final byte INS_ENCRYPT = (byte) 0x4;
static final byte INS_DECRYPT = (byte) 0x5;
static final byte INS_CLEAR = (byte) 0x6;

Once we have a working applet, implementing the Android client is fairly straightforward. We need to connect to the SEService, open a logical channel to our applet (AID: 73 69 6d 70 61 73 73 6d 61 6e 01) and send the appropriate APDUs using the protocol outlined above. For example, sending a string to be encrypted requires the following code (assuming we already have an open Session to the SE). Here 0x9000 is the standard ISO 7816-3/4 success status word (SW):

Channel channel = session.openLogicalChannel(fromHex("73 69 6d 70 61 73 73 6d 61 6e 01"));
byte[] data = "password".getBytes("ASCII");
String cmdStr = "80 04 00 00 " + String.format("%02x", data.length)
+ toHex(data) + "00";
byte[] rapdu = channel.transmit(fromHex(cmdStr));
short sw = (short) ((rapdu [rapdu.length - 2] << 8) | (0xff & rapdu [rapdu.length - 1]));
if (sw != (short)0x9000) {
// handle error
}
byte[] ciphertext = Arrays.copyOf(rapdu, rapdu.length - 2);
String encrypted= Base64.encodeToString(ciphertext, Base64.NO_WRAP);

Besides calling applet operations by sending commands to the SE, the sample Android app also has a simple database to store encrypted passwords paired with a description, and displays currently managed passwords in a list view. Long pressing on the password name will bring up a contextual action that allows you to decrypt and temporarily display the password so you can copy it and paste it into the target application. The current implementation does not require a PIN to decrypt passwords, but one can easily by provided using Java Card's OwnerPIN class, optionally disabling the applet once a number of incorrect tries is reached. While this app can hardly compete with popular password managers, it has enough functionality to both illustrate the concept of an SE-backed app and be practially useful. Passwords can be added by pressing the '+' action item and the delete item clears the encryption key and PRNG counter, but not the PRNG seed and nonce. A screenshot of the award-winning UI is shown below. Full source code for both the applet and the Android app is available on Github.


Summary

The AOSP version of Android does not provide a standard API to use the SIM card as a SE, but many vendors do, and as long as the device baseband and RIL support APDU exchange, one can be added by using the SEEK for Android patches. This allows to improve the security of Android apps by using the SIM as a secure element and both store sensitive data and implement critical functionality inside it. Commercial SIM do not allow for installing arbitrary user applications, but applets can be automatically loaded by the carrier using the SIM OTA mechanism and apps that take advantage of those applets can be distributed through regular channels, such as the Play Store.

Thanks to Michael for developing the Galaxy S2/3 RIL patch and helping with getting it to work on my somewhat exotic S2.

CURB THE TAXIS, CUT THE COSTS

Freelance journalist and editor of Public Sector Travel Betty Low wrote a great feature for Buying Business Travel recently called ‘The Art of Persuasion’.  She argued that it’s time for travel managers to start managing travellers rather than suppliers.


Why? Because it’s travellers who are responsible for racking up a multitude of hidden expenses and, by controlling those, you may end up making bigger cost savings than constantly trying to squeeze already-squeezed suppliers.

Hidden, or unmanaged, spend is also the subject of a recent report by BCD Travel, which revealed that it accounts for a massive 26% of all travel budgets, supporting Betty Low’s opinion that it is this that holds the key to cost savings.

The BCD report claims hidden spend can be broken down into three areas:
  •           Dining and entertaining – accounting for 16%
  •           Ground transportation – accounting for 6%
  •           Mobile – accounting for 4%

If we look at ground transportation first, it quickly becomes obvious how managing the traveller can make a massive difference. This area of hidden spend may account for just 6% now, but if taxi fares continue to rise as they have been over the last five years, it’s about to hijack an even larger share of the pot and become an even bigger problem.


Thanks to rising fuel prices, the cost of London black cabs, for example, have risen on average 18% in the last five years and by 42% over a four-mile journey. The fixed rate fare from Heathrow to London is now £65, up £10 from 2008. Buying Business Travel recently highlighted the world’s most expensive airport transfers. Travelling into Tokyo from Narita is close to £200. 

And faced with indisputable facts like this it’s hard to question the importance of traveller management and the only question to remain is how do we manage the traveller once they have left the office and are out of the travel manager’s reach?

According to the BCD Travel report, this can be partially tackled psychologically as many travellers choose options based on ‘the bandwagon effect’.

“Social norms are massively powerful because we ultimately seek the approval of others. In fact, travellers, like everyone else, are often quick to abandon their own best judgment if they feel out of step with others. Use this lever to steer travellers toward public transportation, by, for example, sending out an email: From: Travel Manager Subject: Get on the Bandwagon 80% of your co-workers have switched to using public transportation in New York City. When are you going to join them?”
And of course, increasingly the answer to traveller management is through mobile technology and the introduction of apps that are designed to encourage travellers to make cost-efficient and compliant choices once they arrive at a destination and not just during the booking process and before they leave.

Whichever method travel managers opt for, it’s clear that, if cost savings are ever to be maximised, then the end of rogue travellers must be nigh.


David Chapple is event director for the Business Travel Show. www.businesstravelshow.com  

IS FREE HOTEL WI-FI A DIVINE RIGHT FOR BUSINESS TRAVELLERS?

Many business travellers believe that free hotel Wi-Fi is a divine right - traveller Dean Barrett blogs about it here. And many corporate travel managers would agree with them, investing valuable resources in negotiating free Wi-Fi during the RFP season, of which we are still in the midst.

But according to a Databank league table in Buying Business Travel magazine, it would be an understatement to say that all hotels are on their side. And what’s even more interesting is the huge discrepancies between countries throughout Europe when it comes to giving away the Holy Grail of business travel as part of the rack rate.

The following table shows the percentages of hotels offering free Wi-Fi in the best-served 20 countries in Europe. You’ll see that the UK comes in at a disappointing 14th place. Turkey, however, excels in its complimentary internet provision. The Mediterranean countries fare worst.
  
Why such discrepancies exist it’s hard to say. It could be telecoms costs, hotel rates or just the cultural norm. But what is useful about this league is the power it gives corporate travel managers when it comes to negotiating those add-ons during the RFP process. Such vital information about travel patterns can help them direct their resources more effectively when planning a global programme. This league shows, for example, that there is very little point demanding free Wi-Fi for travellers to Turkey, when nearly 85 per cent of hotels include it for free anyway. It may be wiser to ask, instead, for free parking, late checkout and early check in, free breakfast, gym passes or airport transfers? 

So is free hotel Wi-Fi the divine right of all business travellers? Well Turkey seems to think so. And with a little strategic strong-arming from travel managers across Europe, hopefully it won’t be too long before the rest of the continent follows suit.


David Chapple is event director for the Business Travel Show, which is the leading conference and exhibition in Europe for the corporate travel market. www.businesstravelshow.com 

Credential storage enhancements in Android 4.3

Our previous post was not related to Android security, but happened to coincide with the Android 4.3 announcement. Now that the post-release dust has settled, time to give it a proper welcome here as well. Being a minor update, there is nothing ground-breaking, but this 'revenge of the beans' brings some welcome enhancements and new APIs. Enough of those are related to security for some to even call 4.3 a 'security release'. Of course, the big star is SELinux, but credential storage, which has been a somewhat recurring topic on this blog, got a significant facelift too, so we'll look into it first. This post will focus mainly on the newly introduced features and interfaces, so you might want to review previous credential storage posts before continuing.

What's new in 4.3

First and foremost, the system credential store, now officially named 'Android Key Store' has a public API for storing and using app-private keys. This was possible before too, but not officially supported and somewhat clunky on pre-ICS devices. Next, while only the primary (owner) user could use the system key store pre-4.3, now it is multi-user compatible and each user gets their own keys. Finally, there is an API and even a system settings field that lets you check whether the credential store is hardware-backed (Nexus 4, Nexus 7) or software only (Galaxy Nexus). While the core functionality hasn't changed much since the previous release, the implementation strategy has evolved quite a bit, so we will look briefly into that too. That's a lot to cover, so lets' get started.

Public API

The API is outlined in the 'Security' section of the 4.3 new API introduction page, and details can be found in the official SDK reference, so we will only review it briefly. Instead of introducing yet another Android-specific API, key store access is exposed via standard JCE APIs, namely KeyGenerator and KeyStore. Both are backed by a new Android JCE provider, AndroidKeyStoreProvider and are accessed by passing "AndroidKeyStore" as the type parameter of the respective factory methods (those APIs were actually available in 4.2 as well, but were not public). For a full sample detailing their usage, refer to the BasicAndroidKeyStore project in the Android SDK. To introduce their usage briefly, first you create a KeyPairGeneratorSpec that describes the keys you want to generate (including a self-signed certificate), initialize a KeyPairGenerator with it and then generate the keys by calling generateKeyPair(). The most important parameter is the alias, which you then pass to KeyStore.getEntry() in order to get a handle to the generated keys later. There is currently no way to specify key size or type and generated keys default to 2048 bit RSA. Here's how all this looks like:

// generate a key pair
Context ctx = getContext();
Calendar notBefore = Calendar.getInstance()
Calendar notAfter = Calendar.getInstance();
notAfter.add(1, Calendar.YEAR);
KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(ctx)
.setAlias("key1")
.setSubject(
new X500Principal(String.format("CN=%s, OU=%s", alais,
ctx.getPackageName())))
.setSerialNumber(BigInteger.ONE).setStartDate(notBefore.getTime())
.setEndDate(notAfter.getTime()).build();

KeyPairGenerator kpGenerator = KeyPairGenerator.getInstance("RSA", "AndroidKeyStore");
kpGenerator.initialize(spec);
KeyPair kp = kpGenerator.generateKeyPair();

// in another part of the app, access the keys
KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
keyStore.load(null);
KeyStore.PrivateKeyEntry keyEntry = (KeyStore.PrivateKeyEntry)keyStore.getEntry("key1", null);
RSAPublicKey pubKey = (RSAPublicKey)keyEntry.getCertificate().getPublicKey();
RSAPrivateKey privKey = (RSAPrivateKey) keyEntry.getPrivateKey();

If the device has a hardware-backed key store implementation, keys will be generated outside of the Android OS and won't be directly accessible even to the system (or root user). If the implementation is software only, keys will be encrypted with a per-user key-encryption master key. We'll discuss key protection in detail later.

Android 4.3 implementation

This hardware-backed design was initially implemented in the original Jelly Bean release (4.1), so what's new here? Credential storage has traditionally (since the Donut days), been implemented as a native keystore daemon that used a local socket as its IPC interface. The daemon has finally been retired and replaced with a 'real' Binder service, which implements the IKeyStoreService interface. What's interesting here is that the service is implemented in C++, which is somewhat rare in Android. See the interface definition for details, but compared to the original keymaster-based implementation, IKeyStoreService gets 4 new operations: getmtime(), duplicate(), is_hardware_backed() and clear_uid(). As expected, getmtime() returns the key modification time and duplicate() copies a key blob (used internally for key migration). is_hardware_backed will query the underlying keymaster implementation and return true when it is hardware-backed. The last new operation, clear_uid(), is a bit more interesting. As we mentioned, the key store now supports multi-user devices and each user gets their own set of keys, stored in /data/misc/keystore/user_N, where N is the Android user ID. Keys names (aliases) are mapped to filenames as before, and the owner app UID now reflects the Android user ID as well. When an app that owns key store-managed keys is uninstalled for a user, only keys created by that user are deleted. If an app is completely removed from the system, its keys are deleted for all users. Since key access is tied to the app UID, this prevents a different app that happens to get the same UID from accessing an uninstalled app's keys. Key store reset, which deletes both key files and the master key, also affects only the current user. Here's how key files for the primary user might look like:

1000_CACERT_ca
1000_CACERT_cacert
10248_USRCERT_myKey
10248_USRPKEY_myKey
10293_USRCERT_rsa_key0
10293_USRPKEY_rsa_key0

The actual files are owned by the keystore service (which runs as the keystore Linux user) and it checks the calling UID to decide whether to grant or deny access to a key file, just as before. If the keys are protected by hardware, key files may contain only a reference to the actual key and deleting them may not destroy the underlying keys. Therefore, the del_key() operation is optional and may not be implemented.

The hardware in 'hardware-backed'

To give some perspective to the whole 'hardware-backed' idea, let's briefly discuss how it is implemented on the Nexus 4. As you may now, the Nexus 4 is based on Qualcomm's Snapdragon S4 Pro APQ8064 SoC. Like most recent ARM SoC's it is TrustZone-enabled and Qualcomm implement their Secure Execution Environment (QSEE) on top of it. Details are, as usual, quite scarce, but trusted application are separated from the main OS and the only way to interact with them is through the controlled interface the /dev/qseecom device provides. Android applications that wish to interact with the QSEE load the proprietary libQSEEComAPI.so library and use the functions it provides to send 'commands' to the QSEE. As with most other SEEs, the QSEECom communication API is quite low-level and basically only allows for exchanging binary blobs (typically commands and replies), whose contents entirely depends on the secure app you are communicating with. In the case of the Nexus 4 keymaster, the used commands are: GENERATE_KEYPAIR, IMPORT_KEYPAIR, SIGN_DATA and VERIFY_DATA. The keymaster implementation merely creates command structures, sends them via the QSEECom API and parses the replies. It does not contain any cryptographic code itself.

An interesting detail is that, the QSEE keystore trusted app (which may not be a dedicated app, but part of more general purpose trusted application) doesn't return simple references to protected keys, but instead uses proprietary encrypted key blobs (not unlike nCipher Thales HSMs). In this model, the only thing that is actually protected by hardware is some form of 'master' key-encryption key (KEK), and user-generated keys are only indirectly protected by being encrypted with the KEK. This allows for practically unlimited number of protected keys, but has the disadvantage that if the KEK is compromised, all externally stored key blobs are compromised as well (of course, the actual implementation might generate a dedicated KEK for each key blob created or the key can be fused in hardware; either way no details are available). Qualcomm keymaster key blobs are defined in AOSP code as shown below. This suggest that private exponents are encrypted using AES, most probably in CBC mode, with an added HMAC-SHA256 to check encrypted data integrity. Those might be further encrypted with the Android key store master key when stored on disk.

#define KM_MAGIC_NUM     (0x4B4D4B42)    /* "KMKB" Key Master Key Blob in hex */
#define KM_KEY_SIZE_MAX (512) /* 4096 bits */
#define KM_IV_LENGTH (16) /* AES128 CBC IV */
#define KM_HMAC_LENGTH (32) /* SHA2 will be used for HMAC */

struct qcom_km_key_blob {
uint32_t magic_num;
uint32_t version_num;
uint8_t modulus[KM_KEY_SIZE_MAX];
uint32_t modulus_size;
uint8_t public_exponent[KM_KEY_SIZE_MAX];
uint32_t public_exponent_size;
uint8_t iv[KM_IV_LENGTH];
uint8_t encrypted_private_exponent[KM_KEY_SIZE_MAX];
uint32_t encrypted_private_exponent_size;
uint8_t hmac[KM_HMAC_LENGTH];
};

So, in the case of the Nexus 4, the 'hardware' is simply the ARM SoC. Are other implementations possible? Theoretically, a hardware-backed keymaster implementation does not need to be based on TrustZone. Any dedicated device that can generate and store keys securely can be used, the usual suspects being embedded secure elements (SE) and TPMs. However, there are no mainstream Android devices with dedicated TPMs and recent flagship devices have began shipping without embedded SEs, most probably due to carrier pressure (price is hardly a factor, since embedded SEs are usually in the same package as the NFC controller). Of course, all mobile devices have some form of UICC (SIM card), which typically can generate and store keys, so why not use that? Well, Android still doesn't have a standard API to access the UICC, even though 'vendor' firmwares often include one. So while one could theoretically implement a UICC-based keymaster module compatible with the UICC's of your friendly neighbourhood MNO, it is not very likely to happen.

Security level

So how secure are you brand new hardware-backed keys? The answer is, as usual, it depends. If they are stored in a real, dedicated, tamper-resistant hardware module, such as an embedded SE, they are as secure as the SE. And since this technology has been around for over 40 years, and even recent attacks are only effective against SEs using weak encryption algorithms, that means fairly secure. Of course, as we mentioned in the previous section, there are no current keymaster implementations that use actual SEs, but we can only hope.

What about TrustZone? It is being aggressively marketed as a mobile security 'silver bullet' and streaming media companies have embraced it as an 'end-to-end' DRM solution, but does it really deliver? While the ARM TrustZone architecture might be sound at its core, in the end trusted applications are just software that runs at a slightly lower level than Android. As such, they can be readily reverse engineered, and of course vulnerabilities have been found. And since they run within the Secure World they can effectively access everything on the device, including other trusted applications. When exploited, this could lead to very effective and hard to discover rootkits. To sum this up, while TrustZone secure applications might provide effective protection against Android malware running on the device, given physical access, they, as well as the TrustZone kernel, are exploitable themselves. Applied to the Android key store, this means that if there is an exploitable vulnerability in any of the underlying trusted applications the keymaster module depends on, key-encryption keys could be extracted and 'hardware-backed' keys could be compromised.

Advanced usage

As we mentioned in the first section, Android 4.3 offers a well defined public API to the system key store. It should be sufficient for most use cases, but if needed you can connect to the keystore service directly (as always, not really recommended). Because it is not part of the Android SDK, the IKeyStoreService doesn't have wrapper 'Manager' class, so if you want to get a handle to it, you need to get one directly from the ServiceManager. That too is hidden from SDK apps, but, as usual, you can use reflection. From there, it's just a matter of calling the interface methods you need (see sample project on Github). Of course, if the calling UID doesn't have the necessary permission, access will be denied, but most operations are available to all apps.

Class smClass = Class.forName("android.os.ServiceManager");
Method getService = smClass.getMethod("getService", String.class);
IBinder binder = (IBinder) getService.invoke(null, "android.security.keystore");
IKeystoreService keystore = IKeystoreService.Stub.asInterface(binder);

By using the IKeyStoreService directly you can store symmetric keys or other secret data in the system key store by using the put() method, which the current java.security.KeyStore implementation does not allow (it can only store PrivateKey's). Such data is only encrypted by the key store master key, and even the system key store is hardware-backed, data is not protected by hardware in any way.

Accessing hidden services is not the only way to augment the system key store functionality. Since the sign() operation implements a 'raw' signature operation (RSASP1 in RFC 3447), key store-managed (including hardware-backed) keys can be used to implement signature algorithms not natively supported by Android. You don't need to use the IKeyStoreService interface, because this operation is available through the standard JCE Cipher interface:

KeyStore ks = KeyStore.getInstance("AndroidKeyStore");
ks.load(null);
KeyStore.Entry keyEntry = keyStore.getEntry("key1", null);
RSAPrivteKey privKey = (RSAPrivateKey) keyEntry.getPrivateKey();

Cipher c = Cipher.getInstance("RSA/ECB/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, i privateKey);
byte[] result = cipher.doFinal(in, o, in.length);

If you use this primitive to implement, for example, Bouncy Castle's AsymmetricBlockCipher interface, you can use any signature algorithm available in the Bouncy Castle lightweight API (we actually use Spongy Castle to stay compatible with Android 2.x without too much hastle). For example, if you want to use a more modern (and provably secure) signature algorithm than Android's default PKCS#1.5 implementation, such as RSA-PSS you can accomplish it with something like this (see sample project for AndroidRsaEngine):

AndroidRsaEngine rsa = new AndroidRsaEngine("key1", true);

Digest digest = new SHA512Digest();
Digest mgf1digest = new SHA512Digest();
PSSSigner signer = new PSSSigner(rsa, digest, mgf1digest, 512 / 8);
RSAKeyParameters params = new RSAKeyParameters(false,
pubKey.getModulus(), pubKey.getPublicExponent());

signer.init(true, params);
signer.update(signedData, 0, signedData.length);
byte[] signature = signer.generateSignature();

Likewise, if you need to implement RSA key exchange, you can easily make use of OAEP padding like this:

AndroidRsaEngine rsa = new AndroidRsaEngine("key1", false);

Digest digest = new SHA512Digest();
Digest mgf1digest = new SHA512Digest();
OAEPEncoding oaep = new OAEPEncoding(rsa, digest, mgf1digest, null);

oaep.init(true, null);
byte[] cipherText = oaep.processBlock(plainBytes, 0, plainBytes.length);

The sample application shows how to tie all of those APIs together and features an elegant and fully Holo-compatible user interface:



An added benefit of using hardware-backed keys is that, since they are not generated using Android's default SecureRandom implementation, they should not be affected by the recently announced SecureRandom vulnerability (of course, since the implementation is closed, we can only hope that trusted apps' RNG actually works...). However, Bouncy Castle's PSS and OAEP implementations do use SecureRandom internally, so you might want to seed the PRNG 'manually' before starting your app to make sure it doesn't start with the same PRNG state as other apps. The keystore daemon/service uses /dev/urandom directly as a source of randomness, when generating master keys used for key file encryption, so they should not be affected. RSA keys generated by the softkeymaster OpenSSL-based software implementation might be affected, because OpenSSL uses RAND_bytes() to generate primes, but are probably OK since the keystore daemon/service runs in a dedicated process and the OpenSSL PRNG automatically seeds itself from /dev/urandom on first access (unfortunately there are no official details about the 'insecure SecureRandom' problem, so we can't be certain).

Summary

Android 4.3 offers a standard SDK API for generating and accessing app-private RSA keys, which makes it easier for non-system apps to store their keys securely, without implementing key protection themselves. The new Jelly Bean also offers hardware-backed key storage on supported devices, which guarantees that even system or root apps cannot extract the keys. Protection against physical access attacks depends on the implementation, with most (all?) current implementations being TrustZone-based. Low-level RSA operations with key store managed keys are also possible, which enables apps to use cryptographic algorithms not provided by Android's built-in JCE providers.

Multiplication Freezer Frenzy Freebie & A Back To School SALE!

Hopefully today's post finds you either settled in nicely to your new school year or getting excited about going back.  Either way, the TpT giant BACK TO SCHOOL SALE is happening this weekend...Sunday and Monday, Aug. 18th and 19th.  Be sure to visit your favorite stores and grab items for as much as 28% off.  I put EVERYTHING in my store on sale.  Be sure to check out a real steal on the BRAND NEW Accountable Talk Prompts.  There are 24 accountable talk stems that are sure to keep students engaged in the text...a goal of Common Core.  *Don't forget to use the PROMO CODE. Sellers will mark most of their items 20% off.  You'll get the additional 8% by using the PROMO code!  (See the beautiful button created by the very talented Krista Wallden at Creative Clips for PROMO code...Thank you, Krista!)

  


Teaching multiplication this year?  Be sure to grab my latest FREEBIE...Multiplication Facts Freezer Frenzy! My way of saying THANK YOU for your never ending friendship and support in the blogging world!  As students learn their facts, let them earn and add the corresponding ice cream to their base cone.  As a REAL incentive, I bought my students an ice cream from the cafeteria when they mastered all their facts!  Hmmmm....thinking I'll make a trip to Baskin Robbins tonight!  :-)


Bananas for incredible deals on TpT this weekend!  Happy Shopping!

THE BLEISURE PRINCIPLE - COURTESY OF BUYINGBUSINESSTRAVEL.COM

On Buying Business Travel, freelance travel journalist Nick Easen has written a really interesting comment piece on 'bleisure travel', or 'bizcations' as they are also known. We have posted it here in full - you can also read it here


There’s business travel, and then there’s travel. Nick Easen reports on the trend that provides the overworked road warrior with the best of both worlds
YOU MAY OR MAY NOT like the concept – and probably don’t like the word – but ‘bleisure’ is here to stay.

Both word and concept are a blurring of ‘business’ and ‘leisure’ (some call it ‘bizcation’). In our time-pressed existences it is not unusual for work lives to summarily bleed into social ones, and vice versa – helped along by being constantly connected via smart devices. So it wouldn’t be surprising to see bleisure travel on the rise – though perhaps tempered by financial and policy constraints.

This is how it works: if you’re sent on a two-day business trip, you take time off at the end and tag on a few days of rest and relaxation. You might invite your partner to come along, too – if you’ve been booked in to a double room, why not make the most of it and pay extra only for the air fare, or for extending the hotel stay? Given the current state of the British economy, executives are being asked to do more and take less time off. This phase in the economic cycle could be ripe for bizcations.
Yet there is little research in this area, as it is neither business travel nor leisure. It’s hard to define, and there’s no formal sector in the UK. Some in the industry claim it is static or even declining, while others say it is in rude health. “Although expenditure was initially reined in during the downturn, we have seen year-on-year growth since 2010,” says Julian Munsey, head of strategic business development at Hillgate Travel. “Although demand is not great, where it’s permitted by the corporation we have seen a small increase in the number of extended stays.”
In the post-recession era, higher flight and holiday costs would imply that it makes sense to extend a business trip. “It’s a great way to minimise your personal short break budget,” says LeRoy Sheppard, UK sales director at Maritim Hotels. “This is about ensuring the effective use of your time and maximising your personal ROI [return on investment].”
A survey of 1,000 business travellers last year by Jurys Inn showed 35 per cent see an overnight business trip as a break from the office routine, with 19 per cent looking forward to exploring a new city – which implies taking time out to have a bizcation-type experience.
In the US, where the working population gets fewer holidays compared to the Brits – a week or two versus our four weeks – it’s not surprising that Americans are keen to tag on a few days holiday. For instance, 72 per cent of business travellers surveyed in the US said that they take extended executive trips that have a leisure component, according to an Orbitz trend report last year, which polled over 600 business travellers, and that 81 per cent planned to. In addition, 43 per cent had a significant other accompany them on a business trip.
MIXING IT UP Adding a few days at the end of a European city business trip is popular. In some cases executives will head off from their city of business to a more leisure-focused destination – for example, business in Frankfurt, then take time off in Wurzburg; a weekend in Salzburg after work in Vienna; Bruges after Brussels; or Cannes after Marseilles.
This is where frequent flyer and hotel point schemes come into their own. If a traveller’s company is aligned to a brand then the executive will do all that is possible to stay at, for example, a Hilton hotel or fly British Airways so they can get personal points. “Guests who have been staying for a long time or are regulars will generally be offered favourable rates,” says Joanna Fisher, marketing director at serviced apartment operator Ascott.
Points do mean prizes. Executives can easily fly significant others on air miles or have an extended hotel stay. “We also see people decide to have a bleisure break relatively near to the date of travel – it is not planned a long time in advance in many cases,” says Maritim’s Sheppard.
A TRICKY QUESTION
Bizcations are not positively encouraged as a formal policy. Years of ratcheting up compliance, talking up travel policies and scrutinising budgets means that there is little scope for a few sly days on a beach using a corporate credit card.
There are challenges for TMCs as they have to justify all arrangements within agreed guidelines and ensure all reservations are policy compliant. Few TMCs wanted to contribute to this article for that reason – the fact is there is little room for the bizcation in the vocabulary of managed travel these days. “This is an informal or discretionary thing that companies do not want written into formal policy,” explains Adam Knights, group sales director at ATPI.
For many buyers, business is business and they are keen to show that the leisure part of any stay is separate to the corporate trip, and funded separately, too. Larger corporations are also sensitive to the implications of being involved in bleisure. “The potential for a taxable benefit to be incurred, and for other staff to believe personal travel was being undertaken at the company’s expense, has made this an unnecessary challenge many want to avoid,” explains Paul Gardner, owner/director of Amity Travel. Amity is ranked 45th in Buying Business Travel’s annual 50 Leading TMCs, and lists leisure travel among its services offered.
“Things are different if they are travelling as part of an incentive reward for hitting a performance target,” adds De Vere Hotels commercial marketing director Calum Russell. “Also, rates can sometimes be higher for leisure stays as business trips are usually based on a bulk negotiated rates.”
CUTTING BOTH WAYS
However, there are occasions when extending a trip can be beneficial to the company.
For example, many economy class fares to the US have restrictions if booked at the last minute. “But by extending to Saturday night, the fare can often be reduced by 50 per cent – this far outweighs the additional hotel costs,” says Gardner.
There are also informal incentives. One travel buyer says: “There is sometimes the scenario where the company says: ‘We know you have worked extremely hard for the last week – why doesn’t your wife fly out at the end of your trip and we will pick up the hotel bill?’ But these situations are always discretionary.”
DIFFERING NEEDS
It’s certainly a difficult market to nail down – each customer’s needs are different and are in many ways opportunistic, based on how leisure time can be fitted around business meetings. “Bizcations are unique for each customer, so it can be a challenge to offer the right package,” explains Maritim’s Sheppard.
Many deals for partners and family are purchased at arm’s length to the corporate buying, so are beyond analysis. Yet some travel management companies have VIP services that cater for all the needs of their business clients, blurring business and leisure, whether it be chartering a yacht in Monaco or organising tickets to the Abu Dhabi Grand Prix, while others have specific leisure departments that deal with this type of travel, albeit passed on from their business travel division.
For example, Travel without Boundaries is a programme created for Advantage TMCs to manage the holiday market for clients alongside corporate travel bookings. Advantage is a founder member of the Worldwide Independent Travel Network (WIN), a global travel agency partnership with more than 6,000 outlets around the world. WIN head of supplier relations Julie Janzen says: “We’ve negotiated leisure benefits for executives wanting to extend their stay across key cities and it is all bookable through the GDS on a unique rate code.”
Certainly, booking a bleisure break seamlessly alongside that conference in Munich or a client meeting in Hong Kong is symptomatic of the modern age, and Travel without Boundaries reflects this model.
If everything else is integrated in a road warrior’s life, from their smartphone and work diaries to their Skype chats with clients, it makes sense for their bizcation to be part of this arrangement, too.
As long as everyone’s aware that there’s a clear divide between work and pleasure in terms of who pays, who arranges it and how time is accounted for, then the committed business traveller should be able to take that well-earned break – and why not?
THE TMC’S VIEW
Adam Knights, group sales director for ATPI
What’s happening with bizcations?
Many companies rely on employees to be available 24/7, therefore there is a growing trend towards informal time in lieu, or family support. This often results in us being asked to change a hotel in, say, Dubai, to one of the beach properties for the weekend if a partner or family are joining.
Who takes them and when?
Increasingly, people are working around half-term holidays with the family, so that an executive can do a week overseas while the family fly in at the beginning or end. The key thing customers have in common is that they are all frequent travellers and tend to be older.
What challenges do you face? 
Some senior travellers ask our teams to book bleisure, but normally this goes through our separate leisure group. Clients don’t want agents distracted and business services to falter. However, there are always exceptions and, if the PA to the chief executive asks one of our agents to book extra flights for the family, we would normally do this. There are rarely compliance issues as a client’s personal card is used; however, we always take the lead from our client and discreetly check with our main contact whether this is acceptable.
THE TRAVELLER’S VIEW
A leading global consumer goods company senior manager
Do you see bizcations as a benefit? 
It is a huge benefit, but it is harder to take longer breaks because of work pressures these days. I’ve taken a bizcation a number of times, and it’s allowed me to visit the Taj Mahal and extend to a weekend safari in Kenya.
What kind of trips do you mix up?
It’s actually about grabbing opportunities and the destination – I’ve done a week-long training course in Budapest and had my partner join me on the Friday for a long weekend; similarly I’ve had my partner join an Indian business trip for a week extension.
Are you doing more of it now?
I want to try and spend as little time as possible in airports and in transit, so it makes sense to add a break on to an executive trip.
Are there compliance or other issues? 
It is critical to separate all costs of a personal nature. I think it’s also important to let line management know in advance any intention to add a personal side trip to a business trip. I tend to take these few days at the beginning of a trip so the company benefits as well – I get over the jetlag in my own time and am ready to perform 100 per cent.



This article has been reproduced with kind permission from Buying Business Travel. Thank you to Panacea Publishing for allowing us to share it. You can find the original - and a lot more fantastic business travel articles - here.