Archives 2013

KitKat: Impact of the latest Android OS on card emulation

“Who controls the smartphone?” is the obvious question that can lead to generating profits from every transaction by the controlling parties.

NFC use on smartphones allows for 3 modes of operation:  tag reading/writing, peer-to-peer and card emulation. The card emulation mode is the most interesting mode for the companies involved in such developments because it immediately generates cash flow. The business model is simple: one just needs to replace the existing cards (payment, transportation, etc.). A fraction of the millions of transactions performed everyday by those cards can then be transformed into profit for those controlling the smartphone.

Since 2005-2006, when NFC made its start, we have been witnessing a war among manufacturers; between those controlling the hardware and/or controlling its operating system, neither of which have strong ties with final users; and the cellphone carriers who are controlling the SIM and have strong customer relations through subscription plans.

From each side of the battlefield, the same argument is always pointed out: a transaction implies security requirements, and a security requirement implies embedded applications in a secured processor. The cellphone carriers argue that the SIM card is the best choice, since it is a secured processor and it is already present without any additional cost. The manufacturers argue that a secured processor (Secure Element) has to be added on the motherboard, the extra cost being minimal and the user being able to freely change transaction service providers without having to transfer his or her telephone service to a new vendor requiring a new SIM card.

In the middle of the battle ground, a new contender has emerged: the TSM (Trusted Service Manager), provides a unique and portable service whatever the underlying technical context, for a fee of course.

Until last week, the position of each party had remained frozen since the war started in 2005-2006. And then KitKat arrived.

KitKat is the code name for Android’s new 4.4 Operating System. And in the presentation of KitKat, from the second paragraph, one can read:

Android 4.4 introduces new platform support for secure NFC-based transactions through Host Card Emulation (HCE), for payments, loyalty programs, card access, transit passes, and other custom services. With HCE, any app on an Android device can emulate an NFC smart card, letting users tap to initiate transactions with an app of their choice — no provisioned secure element (SE) in the device is needed.(http://developer.android.com/about/versions/android-4.4.html)

Technically nothing really new; BlackBerry offered the same principle in the latest version of its OS. But Android’s market share is significantly different from BlackBerry’s market share! With this support, developers of sector-specific applications (access control, loyalty) finally have a solution to develop the card emulation mode on smartphones easily and without depending on anyone.

A few technical points to keep in mind:

1.      Card emulation « within the host » (HCE) cannot work if the phone is turned off (deliberately turned off or out of battery), whereas within some SIM-centric or SE-centric architectures it is sometimes possible to perform a transaction with a turned off smartphone.

2.      The main processor of the smartphone (baseband) isn’t a secure processor. Applications requiring a critical level of security (i.e., whenever the profits from the fraud is higher than the cost of the fraud: payment, public transportation, high security level access control, ID cards...) shouldn’t be implemented in this mode.

3.      The transaction times may perform less well; furthermore, they may operate less consistently than a classic implementation within a secured processor – which by nature is independent from other applications running on the smartphone.

4.      The technical architecture is based on ISO 14443 layer 4, type A, ISO 7816-4 for APDUs formalism, and ISO 7816-5 for the application selection by the reader thanks to a unique AID. Any application out of this frame wouldn’t qualify for the HCE porting. This is especially the case of some French « public transportation » implementations for which the readers only implement ISO 14443 type B.

Now, how do you implement that in the real world?

Step one, own a smartphone or a tablet running Android 4.4. Step two, download the latest SDK (API version 19). Step three, start coding!

(http://developer.android.com/reference/android/nfc/cardemulation/HostApduService.html)

1.      Declare in the Manifest of your application that you want to create a HostApduService, and associate one or several AIDs,

2.      Implement the method processCommandApdu which receives the C-APDU from the reader – and has to return the R-APDU to be re-sent. The first C-APDU received is the SELECT AID that activated your application,

3.      Implement the method onDeactivated to perform the closing of the channel (reader lost, S-DESELECT reception, selection of another application).

JavaCard developers won’t be confused; the names are different but the overall mechanics are similar (except for the initial select).

Please note that processCommandApdu is called in the main thread of the application. If the answer isn’t immediately available (if it comes from a distant server or if a user input is needed, for example), the application logic has to return a “NULL”. In a second time the application will call the function sendResponseApdu to answer efficiently. In the meantime the OS and the NFC Chipset keep the reader waiting using S-WTX.

If you are interested in NFC applications, please check our NFC readers/encoders, H512 and NFC’Roll.

Firmware release 1.75 for H512 and NFC'Roll

A new firmware version (release 1.75.2) has just been published for SpringCard H512 and NFC'Roll.

This firmware improves the behaviour in card emulation and peer-to-peer (initiator) mode, allowing more reliable exchanges with most smartphones running either in reader or peer-to-peer (target) mode.

The same version will be released very soon for H663 and Prox'N'Roll PC/SC.

NFC'Roll

The new firmware is here: https://files.springcard.com/firmwares/springprox/1-75/2212_pn512_nfcroll-10_1-75.mot

The firmware upgrade procedure is here: https://tech.springcard.com/firmware-upgrade/csb6-firmware-upgrade/

H512

The new firmware is here: https://files.springcard.com/firmwares/springprox/1-75/uc3b0256_pn512_h512_1-75.hex

The firmware upgrade procedure is here: https://tech.springcard.com/firmware-upgrade/h663-h512-firmware-upgrade/

Using SCardControl under Linux and from a Java program

SCardControl is the PC/SC function that makes it possible for the application to invoke 'proprietary' functions, implemented either in the PC/SC reader itself (CSB6Prox’N'Roll PC/SCEasyFinger or CrazyWriter) , or in its driver running on the PC, or in the PC/SC middleware.

The prototype is:

LONG SCardControl(
  SCARDHANDLE hCard,
  DWORD dwControlCode,
  LPCVOID lpInBuffer,
  DWORD nInBufferSize,
  LPVOID lpOutBuffer,
  DWORD nOutBufferSize,
  LPDWORD lpBytesReturned
);

(see http://pcsclite.alioth.debian.org/api/group__API.html for the PCSC-Lite documentation, and http://msdn.microsoft.com/en-us/library/windows/desktop/aa379474%28v=vs.85%29.aspx for Microsoft's version).

The lpInbuffer / nInBufferSize parameters hold the command buffer that will be processed by either target -reader, driver, or PC/SC middleware-.

SpringCard PC/SC Readers do provide a few 'proprietary' functions (called 'Escape commands' in the USB CCID specification). For instance, an application would send the command 58 1E 01 00 to switch the reader's red LED ON. A question remains: what must the value of dwControlCode be, when the application wants to send the command right to the reader, bypassing both the PC/SC middleware and the driver? The answer varies with the operating system, which doesn't help implementing portable code.

Differences between Windows and PCSC-Lite implementations

Windows

In Microsoft's CCID driver (http://msdn.microsoft.com/en-us/library/windows/hardware/gg487509.aspx), the dwControlCode for the Escape command is defined as follows:

#define IOCTL_CCID_ESCAPE SCARD_CTL_CODE(3500)

SpringCard PC/SC Readers follow the CCID specification. SpringCard's CCID driver (SDD480) uses the same dwControlCode as Microsoft's.

Therefore, on Windows, the application would switch the red LED on this way:

#include <windows.h>
#include <winscard.h>

#define IOCTL_CCID_ESCAPE SCARD_CTL_CODE(3500)

(...)

const BYTE SET_RED_LED_ON[4] = { 0x58, 0x1E, 0x01, 0x00 };

SCARDCONTEXT hContext;
SCARDHANDLE hCard;
DWORD dwProtocol;
BYTE abResponse[256];
DWORD dwRespLen;
LONG rc;

(...)

/* Instanciate the winscard.dll library */
rc = SCardEstablishContext(SCARD_SCOPE_SYSTEM, NULL, NULL, &amp;hContext);
if (rc != SCARD_S_SUCCESS) { /* TODO: handle error */ }

/* Get a direct connection to the reader (we don't need a card to send Escape commands) */
rc = SCardConnect(hContext, szReader, SCARD_SHARE_DIRECT, 0, &amp;hCard, &amp;dwProtocol);
if (rc != SCARD_S_SUCCESS) { /* TODO: handle error */ }

/* Send the command */
rc = SCardControl(hCard, IOCTL_CCID_ESCAPE, SET_RED_LED_ON, sizeof(SET_RED_LED_ON), abResponse, sizeof(abResponse), &amp;dwRespLen);
if (rc != SCARD_S_SUCCESS) { /* TODO: handle error */ }

SCardDisconnect(hCard, SCARD_LEAVE_CARD);
SCardReleaseContext(hContext);

 

Important notes:

Working with MS' CCID driver

With Microsoft's CCID driver, the Escape feature is disabled by default.

In order to send or receive an Escape command to a reader, the DWORD registry value EscapeCommandEnable must be added and set to a non-zero value under one of the following keys.

  • HKLM\SYSTEM\CCS\Enum\USB\Vid*Pid*\*\Device Parameters (prior to Windows 7).
  • HKLM\SYSTEM\CCS\Enum\USB\Vid*Pid*\*\Device Parameters\WUDFUsbccidDriver (Windows 7 and later).

This is clearly explained in the Developer's Manual for every PC/SC reader.

Using SpringCard's SDD480 CCID driver shall be preferred.

Early versions of SDD480

Branch -Ax of SpringCard's SDD480 CCID driver uses a different value for the dwControlCode parameter.

#define IOCTL_CCID_ESCAPE SCARD_CTL_CODE(2048)

Switching to the latest version of SpringCard's SDD480 CCID driver (branch -Bx and onwards) shall be preferred.

Linux, MacOS and other Unix*

In Ludovic Rousseau's open-source CCID driver (http://pcsclite.alioth.debian.org/ccid.html), the dwControlCode for the Escape command is defined as follows:

#define IOCTL_CCID_ESCAPE SCARD_CTL_CODE(1)

(See http://anonscm.debian.org/viewvc/pcsclite/trunk/Drivers/ccid/SCARDCONTOL.txt?view=markup for details)

Therefore, when working with PCSC-Lite, the application would switch the red LED on this way:

#ifdef __APPLE__
#include <pcsc/winscard.h>
#include <pcsc/wintypes.h>
#else
#include <winscard.h>
#endif

#define IOCTL_CCID_ESCAPE SCARD_CTL_CODE(1)

(...)

const BYTE SET_RED_LED_ON[4] = { 0x58, 0x1E, 0x01, 0x00 };

SCARDCONTEXT hContext;
SCARDHANDLE hCard;
DWORD dwProtocol;
BYTE abResponse[256];
DWORD dwRespLen;
LONG rc;

(...)

/* Instanciate the winscard.dll library */
rc = SCardEstablishContext(SCARD_SCOPE_SYSTEM, NULL, NULL, &hContext);
if (rc != SCARD_S_SUCCESS) { /* TODO: handle error */ }

/* Get a direct connection to the reader (we don't need a card to send Escape commands) */
rc = SCardConnect(hContext, szReader, SCARD_SHARE_DIRECT, 0, &hCard, &dwProtocol);
if (rc != SCARD_S_SUCCESS) { /* TODO: handle error */ }

/* Send the command */
rc = SCardControl(hCard, IOCTL_CCID_ESCAPE, SET_RED_LED_ON, sizeof(SET_RED_LED_ON), abResponse, sizeof(abResponse), &dwRespLen);
if (rc != SCARD_S_SUCCESS) { /* TODO: handle error */ }

SCardDisconnect(hCard, SCARD_LEAVE_CARD);
SCardReleaseContext(hContext);

Enabling the Escape commands

With this CCID driver, the Escape feature is also disabled by default.

You'll have to edit the CCID driver's Info.plist file to enable this feature:

  • Open /usr/local/lib/pcsc/drivers/ccid/Info.plist in edit mode with root priviledge,
  • Locate the line <key>ifdDriverOptions</key>,
  • The following line is typically <string>0000</string>,
  • Define the new value: <string>0001</string>,
  • Save the file and restard pcscd.

(More details on http://ludovicrousseau.blogspot.fr/2011/10/featureccidesccommand.html)

Writing portable code

The idea is only to use a #ifdef to compile the correct value:

#ifdef WIN32
#define IOCTL_CCID_ESCAPE SCARD_CTL_CODE(3500)
#else
#define IOCTL_CCID_ESCAPE SCARD_CTL_CODE(1)
#endif

Java

The javax.smartcardio API provides Java methods that are stricly bound to the underlying PC/SC subsystem. The Card.transmitControlCommand method is the wrapper for SCardControl. The prototype is coherent:

java decode:true">public abstract byte[] transmitControlCommand(
  int controlCode,
  byte[] command)
    throws CardException

Now the same question: what must the value of controlCode be? The answer is short: it depends on the PC/SC stack! SCARD_CTL_CODE(3500) for Windows, and SCARD_CTL_CODE(1) for PCSC-Lite. But with another difference: the macro SCARD_CTL_CODE is not computed the same way between both systems!

 

As a consequence, the Java application must detect the OS, and compute the controlCode parameter accordingly.

Same example to switch the red LED on:

java decode:true">import javax.smartcardio.*;

(...)

static boolean isWindows()
{
  String os_name = System.getProperty("os.name").toLowerCase();
  if (os_name.indexOf("windows") > -1) return true;
  return false;
}

static int SCARD_CTL_CODE(int code)
{
  int ioctl;
  if (isWindows())
  {
    ioctl = (0x31 < < 16 | (code) << 2);
  } else
  {
    ioctl = 0x42000000 + (code);
  }
  return ioctl;
}

static int IOCTL_CCID_ESCAPE()
{
  if (isWindows())
  {
    return SCARD_CTL_CODE(3500);
  } else
  {
    return SCARD_CTL_CODE(1);
  }
}

static final byte[] SET_RED_LED_ON = { (byte) 0x58, (byte) 0x1E, (byte) 0x01, (byte) 0x00 };

(...)

String readerName;

/* Note that the reader's name vary with the OS too!!! */
if (isWindows())
  readerName = "SpringCard Prox'N'Roll Contactless 0";
else
  readerName = "SpringCard Prox'N'Roll (00000000) 00 00";

CardTerminal terminal = CardTerminals.getTerminal(readerName);

Card virtualCard = terminal.connect("DIRECT");

virtualCard.transmitControlCommand(IOCTL_CCID_ESCAPE(), SET_RED_LED_ON);

virtualCard.disconnect(false);

Of course this code works only if the Escape feature is enable by the underlying CCID driver, as seen above.