Important!

Blog moved to https://blog.apdu.fr/

I moved my blog from https://ludovicrousseau.blogspot.com/ to https://blog.apdu.fr/ . Why? I wanted to move away from Blogger (owne...

Tuesday, March 14, 2017

PC/SC sample in Smart Card Connector on Chromebook

To continue the list of PC/SC wrappers initiated in 2010 with "PC/SC sample in different languages" I now present a sample in Smart Card Connector on Chromebook (or Chrome browser).

Smart Card Connector

Smart Card Connector is a Chrome extension developed by Google and available at https://chrome.google.com/webstore/detail/smart-card-connector/khpfeaanjngmcnplbdlpegiifgpfgdco.

It allows to use the PC/SC API from a JavaScript application in a Chromebook. The project is a port of pcsc-lite, libccid and libusb to ChromeOS and is available at chromeos_smart_card_connector under the Apache v2 license.

I do not have a Chromebook myself but it is possible to use the Chrome browser instead (with some limitations).

Installation

Go to https://chrome.google.com/webstore/detail/smart-card-connector/khpfeaanjngmcnplbdlpegiifgpfgdco and select "Add to Chrome".

You should see the "Smart Card Connector" application in your chrome://apps/.

If you click on the application icon you should see something like:

Since the "Smart Card Connector" application completely replaces pcsc-lite and the CCID driver the normal pcsc-lite provided by the system must be stopped. See "Troubleshooting Apps under desktop OSes" to know how to stop pcscd.

Sample application

I created a simple test application for ChromeOS. The application is available from google-smart-card-client-library-hello-world.

You need to fetch a client library google-smart-card-client-library.js from Google and also jQuery. Just follow the Building instructions.

My sample application is greatly inspired from the Hello World Chrome application and Example JavaScript Smart Card Client app. My contribution is (mainly) the last 4 JavaScript functions.

Sample source code

I only provide the source code for the file pcsc_appli.js.


/** @license
 * Copyright 2017 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * @fileoverview Entry point of the Smart Card Client App background script (see
 * <https://developer.chrome.com/apps/event_pages>).
 */

/**
 * Client title for the connection to the server App.
 *
 * Currently this is only used for the debug logs produced by the server App.
 * @const
 */
var CLIENT_TITLE = 'example_js_client_app';

/**
 * Context for talking to the Smart Card Connector app for making PC/SC API
 * requests.
 * @type {GoogleSmartCard.PcscLiteClient.Context}
 */
var apiContext = null;

/**
 * Object that allows to make PC/SC API requests to the Smart Card Connector
 * app.
 * @type {GoogleSmartCard.PcscLiteClient.API}
 */
var api = null;

var API = GoogleSmartCard.PcscLiteClient.API;


/**
 * PC/SC-Lite SCard context.
 * @type {int}
 */
var sCardContext = null;

function initialize() {
  myLog('Establishing connection to the Connector app...');
  console.log('Establishing connection to the Connector app...');
  apiContext = new GoogleSmartCard.PcscLiteClient.Context(CLIENT_TITLE);
  apiContext.addOnInitializedCallback(onInitializationSucceeded);
  apiContext.addOnDisposeCallback(contextDisposedListener);
  apiContext.initialize();
}

function onInitializationSucceeded(constructedApi) {
  myLog('Successfully connected to the Connector app');
  console.log('Successfully connected to the Connector app');
  api = constructedApi;
  establishContext();
}

function establishContext() {
  myLog('Establishing PC/SC-Lite context...');
  console.log('Establishing PC/SC-Lite context...');
  api.SCardEstablishContext(
      GoogleSmartCard.PcscLiteClient.API.SCARD_SCOPE_SYSTEM, null, null).then(
      function(result) {
        result.get(onContextEstablished, onPcscLiteError);
      }, onRequestFailed);
}

/** @param {int} establishedSCardContext PC/SC-Lite SCard context. */
function onContextEstablished(establishedSCardContext) {
  myLog('Established PC/SC-Lite context ' + establishedSCardContext);
  console.log('Established PC/SC-Lite context ' + establishedSCardContext);
  sCardContext = establishedSCardContext;
  listReaders();
}

function listReaders() {
  myLog('Obtaining list of PC/SC-lite readers...');
  console.log('Obtaining list of PC/SC-lite readers...');
  api.SCardListReaders(sCardContext, null).then(function(result) {
    result.get(onReadersListed, onPcscLiteError);
  }, onRequestFailed);
}

/** @param {!Array.<string>} readers List of reader names. */
function onReadersListed(readers) {
  myLog('List of PC/SC-Lite readers: ' + readers);
  console.log('List of PC/SC-Lite readers: ' + readers);

    // Use the 1st reader
    reader = readers[0];
    myLog('Using reader: ' + reader);

    myCode(reader);
}

function contextDisposedListener() {
  myLog('Connection to the server app was shut down');
  console.warn('Connection to the server app was shut down');
  sCardContext = null;
  api = null;
  apiContext = null;
}

/** @param {int} errorCode PC/SC-Lite error code. */
function onPcscLiteError(errorCode) {
  myLog('PC/SC-Lite request failed with error code ' + errorCode);
  console.warn('PC/SC-Lite request failed with error code ' + errorCode);
}

/** @param {*} error The exception that happened during the request. */
function onRequestFailed(error) {
  myLog('Failed to perform request to the Smart Card Connector app: ' +
               error);
  console.warn('Failed to perform request to the Smart Card Connector app: ' +
               error);
}


function myLog(text)
{
    $("#logs").append($("<li>").text(text));
}

function myCode(readerName)
{
    myLog('Connect to the reader: ' + readerName);
    api.SCardConnect(sCardContext,
        readerName,
        API.SCARD_SHARE_SHARED,
        API.SCARD_PROTOCOL_ANY).then(function(result) {
            result.get(onConnected, onPcscLiteError);
    }, onRequestFailed);
}

function onConnected(cardHandle, protocol)
{
    APDU_SELECT = [0x00, 0xA4, 0x04, 0x00, 0x0A, 0xA0, 0x00, 0x00, 0x00,
        0x62, 0x03, 0x01, 0x0C, 0x06, 0x01];

    myLog('Sending ' + dump(APDU_SELECT));
    api.SCardTransmit(
      cardHandle,
      protocol == API.SCARD_PROTOCOL_T0 ?
          API.SCARD_PCI_T0 : API.SCARD_PCI_T1,
      APDU_SELECT).then(function(result) {
        result.get(function (ioRecvPci, response) {
            myLog('response: ' + dump(response));

            // get the 2 last bytes
            sw = response.slice(-2);
            if (sw[0] == 0x90 && sw[1] == 0x00)
            {
                APDU_COMMAND = [0x00, 0x00, 0x00, 0x00];
                myLog('Sending ' + dump(APDU_COMMAND));
                api.SCardTransmit(
                    cardHandle,
                    protocol == API.SCARD_PROTOCOL_T0 ?
                    API.SCARD_PCI_T0 : API.SCARD_PCI_T1,
                    APDU_COMMAND).then(function(result) {
                        result.get(function(ioRecvPci, response) {
                            myLog('response: ' + dump(response));

                            // get the 2 last bytes
                            sw = response.slice(-2);
                            if (sw[0] == 0x90 && sw[1] == 0x00)
                            {
                                // convert to an ASCII string
                                result = "";
                                for (var i = 0; i < response.length; i++)
                                {
                                    result += String.fromCharCode(response[i]);
                                }
                                myLog('response: ' + result);
                            }
                        }, onPcscLiteError);
                    }, onRequestFailed);
            }
            }, onPcscLiteError);
      }, onRequestFailed);
}


function dump(bytes)
{
    return (bytes.map(function (x) {
        return ('00' + x.toString(16).toUpperCase()).substr(-2)
    })).join(" ");
}

window.onload = initialize;

Remarks

This API is very verbose and low level. You can compare it to the node-pcsclite project API, also in JavaScript, I used in a previous article "PCSC sample in JavaScript (Node.js)".

The API uses a lot of call back functions. But that is not surprising for a JavaScript code.

Installation

To install the application in Chrome go to chrome://extensions/ and click on the "Load non packaged extension" button (label translated from French so the real English text may be different) and select the root directory of the sample application.

You should then see a new "Hello World PC/SC" extension in the list. Click on the "Run" link to start the extension. A new window should be created as displayed in the Output section bellow.

Output

Conclusion

This API is useful mainly/only on Chromebook computers. I guess it is the only smart card interface for this kind of computer.

If you know a PC/SC wrapper that is not yet in my list then please contact me.