Click here to Skip to main content
15,881,027 members
Articles / Programming Languages / C#

A Virtual ISO7816 SmartCard

Rate me:
Please Sign up or sign in to vote.
4.95/5 (44 votes)
10 Apr 2014CPOL15 min read 73.3K   4.6K   41   33
An implementatio of an ISO 7816 Virtual SmartCard

Introduction

This article is linked to An UMDF Driver for a Virtual Smart Card Reader.

Reading this article is necessary only if you need detail about the virtual smart card reader driver. If you just need details about an ISO7816 implementation, you can skip the former reading.

Background

First of all: what is a smart card?

A smart card is a device that is becoming very common in many fields of of our everyday life: credit cards, ID cards, passports, driving licenses, SIM for mobile phones, enterprise badges: they are all examples of smart card, with different usage types, different interface, different format.

What do they have in common? A smart card is usually a "piece of plastic" (PVC, polycarbonate...) equipped with a microchip with a limited storage memory and some cryptographic capabilities. Data stored in memory is usually protected from "extraction" with any mean that is not explicitally allowed by the OS (yes, though very simple, the microchip has an OS). The interface can be contact (a metal pin pad is milled in plastic) or contactless (an antenna is embedded between plastic sheets and connected to the chip).

The cryptographic capabilities are very domain specific, but some standard have been set; some common algorithms are the following:

Asymmetric cryptography:

  • RSA
  • Elliptic curves

Symmetric cryptography:

  • DES / Triple DES
  • AES

Hashing:

  • SHA-1
  • SHA-256

If you do not already know them, you may want to take a look at these to understand some basics of cryptography and security, that is essencial to understand what a smart card can be used for. According to the specific domain you could use some or all of these algorithms, but in any case they are the building blocks of complex secure architectures.

Since this technology is very wide spread, a standard is needed. Standards provide a "common ground" for all actors involved in a complex environment, so they are essencial for interoperability. On smart card technology there are many standards involved; in this article we will focus on ISO 7816, that tells us many things (but not everything) about how a smart card should work.

ISO 7816 is divided in different parts, each one addressing a specific aspect: physical characteristics, electrical interface and transmission protocols, standard commands, etc. Since we are working on a virtual smart card we won't bother with physical stuff; the part we are interested is ISO7816 part 4: "Organization, security and commands for interchange". Unfortunately, this part of the standard is quite loose, since it's a "guideline" subject to many domain-specific specializations.

For this reason, to have a more specific reference, I'll refer to the specifications for Italian ID card (CIE: "Carta d'Identità Elettronica"). Even if the Italian ID card project has never reached a "mature" stage, much work was done in defining the smart card OS specifications, based in ISO 7816.

You can read the functional specification here: C.I.E. – Carta di Identità Elettronica Functional Specification Version 2.1

Smart card commands : APDU

The communication between a smart card and the "outer world" is acheived by means of simple commands called APDU (Application Protocol Data Unit).

An APDU encodes an instructions transmitted to the smart card. Essencially, an apdu is a byte string with some simple syntax rules. A smart cards that receives an APDU executes the command encoded and returns a response, composed of some data (optional) and a "status word", that is the result of the operation (OK or an error code).

The APDU syntax is quite easy:

  • byte 1: CLA byte - specifies if the command CLASS, if is an ISO command (00h), a proprietary command (80h) and if the command in signed/encrypted (xCh). Some cards could require special CLASS values in some stages of their life cycles.
  • byte 2: INS byte - specifies the operation type, i.e. select file, read file, encrypt data...
  • byte 3,4 : P1 and P2 bytes - specify some parameters of the requested operation, i.e. start offset for a read or update file operation, identifier of a Security Object...
  • byte 5 (optional) : LC - the length of Data field in bytes. If no data field is present LC can be 0 or absent
  • bytes 6 - (5+LC) (optional) : Data field - additional data needed to execute the command, i.e. data to be written to a file, or control parameters for a new Security Object
  • last byte (optional) : LE - the lenght of data expected as response, i.e. the numebr of bytes to read from a file, the length of a random requested to the card

According to the presence or absence of Data Field and LE we have 4 cases of apdu:

  • Case 1 : No Data Field, No LE - APDU is 4 bytes long
  • Case 2 : No Data Field, LE - APDU is 5 bytes long
  • Case 3 : Data Field, No LE - APDU is 5+LC bytes long
  • Case 4 : Data Field, LE - APDU is 6+LC bytes long

The encoding of the command is very context specific. For this article the document with CIE Functional Specifications provides all supported commands

The response returned by the card has a very simple format:

  • N bytes (optional) : response data (command specific)
  • last 2 bytes : Status Word

The meaning of status words is defined in ISO 7816. Anyway, the use of a particular Status Word in a specific situation is very vendor-specific, so you can never be sure about it. The only universal Status Word is the OK code: 90h 00h

Smart card file system : EF, DF, BSO...

Many implementations of smart cards (but not all) have a simple file system to organize data stored in memory. This file system is very similar to the one we use on our PC: there are files, directories, and some more. Let's see which objects we use in smart cards:

  • MF (Master File) : The root directory of the smart card, that contains all other directories and files
  • DF (Dedicated File) : a directory that can contain other files and objects. The MF is a DF
  • EF (Elementary File) : a file that contains data. But not necessarily a simple array of bytes, like on PC file system; an EF can contain variable length or fixed length recordes.
  • BSO (Base Security Object) : that's where the real difference comes out: a BSO contains data that must never go out from the card, but are essential for cryptographic operations, like PINs or Private Keys
  • SE (Security Environment) : A "serivice" object that mantains a reference to the BSO used in some cryptographic operations

Our implementation will handle all of these. Some smart card OS could use also other types of objects.

A very peculiar feature of smart card is the use of Access Conditions and Secure Messaging Conditions.
Access Conditions define the conditions that must be met in order to execute a specific operation on an object. An access condition could have the following values:

  • Always (00h) : the operation is free and can always be performed, i.e. read the content of an EF containing the smart card serial
  • Never (FFh) : the operation con never be performed, i.e. update the content of an EF containing the smart card serial
  • A reference to a BSO (XXh) : the operation can be performed ONLY if a security test has been performed, i.e. a BSO containig a private RSA key can be used ONLY if the user PIN, in a different BSO (XXh), has been verified

Secure Messaging defines the symmetric keys that should be used to encrypt and sign an APDU or its response:

  • No SM (FFh) : the command can be executed with an APDU in clear (CLA = 00h)
  • A reference to a BSO (XXh) : the command/response should be encrypted using the symmetric key contained in a BSO (XXh)

Secure Messaging

Secure messagong is a technique used in many smart cards to ensure confidenciality of data passed between the terminal and the card. It simply relies on data encryption and signature to authenticate APDUs and make them unreadable for ana attacker.

Secure Messaging has different implementations, that share the common ground of being based on symmetric keys, but according to the domain there are many specificities.

It's worth to mention the fact that in some cases, like in Italian CIE on which we are focusing, keys are fixed and stored on the card; In some other cases, like ICAO MRTD application, Secure messaging keys are shared by means of a Diffie-Hellman key agreement protocol, and keys are not fixed but dinamically generated at each session. Moreover, ICAO implementation of secure messaging if session-oriented: once SM keys for a session are shared, all commands in that session will be protected by those keys. Instead, in our implementation, secure messaging is object-oriented: Secure messaging must be used to performa a specific action on a specific object, as defined in the object's Secure Messaging conditions.

Details on rules to encode an APDU in secure messaging can be found on CIE Functional Specification.

The Virtual Smart Card Application

Having set the domain of interest, we are ready to model the classes of the application that simulates a smart card behaviour. First of all, let's identify the logic blocks of the domain:

  • the simulation environment: the application that hosts simulated cards and manages the connection with the virtual smart card reader driver
  • the driver connection module
  • the simulated card

The simulated card consists in:

  • an UI module to display the status of the smart card and, optionally, allow the user to modify its contents
  • a card handler module that manages interactions with applications (receives and process APDUs and return responses)

In case of an ISO7816 card we also have:

  • a file system (MF, DF, EF and BSO)

Note that not all smart cards have this type of file system-like organization. So the virtual smart cards application doesn't knows anything on how data is organized internally.

Since the application can handle different types of cards, I decided to use a plugin structure to provide smart card implementations; a plugin is an assembly that exposes one or more smart card implementations.

This is a screenshot of the application:

Image 1

This is a simple .net winform application that provides the "playfield" for our smart card game Smile | :) .
It's developed as a MDI multi document application where each view contains a simulated card, and handles communications between the cards and the virtual smart card readers.

From top to bottom of the MDI form we can see the following components:

- A list of virtual smart card readers intalled in the system
If you install a virtual smart card reader described in my previous article, it will be recognised and displayed here. If you select a virtual reader, it will communicate with the virtual smart cards, and all applications in the system will seamlessy use the virtual smart card as it was real

- A list of card plugins
Selecting a card type supplied by a plugin will create a instance of that card. from this moment on the card is ready to receive commands, either from the UI or from a virtual reader. At the moment only the ISO7816 card plugin is provided

- The reset button
A simple command to reset security status of the card. It's like turning power off and on again (but connections with the card are not lost)

- The Driver Connected and Card Present buttons
If you select a virtual reader from the first combo box you will see the communication state. The Driver Connectd checkbox will be turned on by the application if the communication with the reader is succesfully estabilished. The Card Present checkbox can be checked or unchecked to simulate card insertion/removal events.

- Log enabled
If this checkbox is checked, all events will be logged in the log list, on the bottom of the window. Events logged are APDU commands and responses and possibly exceptions

- APDU textbox and Send button
In case the card is not connected to a virtual reader, you can use the APDU textbox to write commands to send to the virtual card.

- Card View
The main part of the form is reserved to the card UI, and is managed by the card plugin. In case of the ISO7816 card plugin, the UI consists of a visual representation of card's file system, with a tree view on the left and selected object's properties on the right.

-Log list
The bottom part of the window displays the log. If you double click a row, its content will be cpied to the clipboard.

Now, let's see the application components in detail:

The virtual Smartcard application

First of all the application discovers all the plugin assemblies inside the "cards" folder and registers them. Each plugin must expose a class derived from ICardPlugin that contains all the smart card implementations contained in it. The ICardPlugin contains just one method:

C#
IEnumerable<ICardImplementation> Implementations { get; }  

This function is called just once at application startup to get implementation details of all simulated cards. The ICardImplementation contains the following members:

C#
ICard GetCardObject();   

The GetNewCard method creates a new instance of the simulated card and returns its ICard interface.
The ICard interface exposes the real card functionalities:

C#
ICardImplementation Implementation { get; }
event Action<Object> log;
void Log(object logMsg);
void Log(byte[] logMsg);
 
Control GetUI();
ICardHandler Handler { get; }
string Name { get; set; }
 
void NewCard();
byte[] ATR { get; } 

The Implementation property returns the ICardImplementation from which this object was created.
The log event is to provide logging events to the caller application, while the Log methods are simple helpers to raise the event.
The Handler property returns an objects that will be used by the communication module to "talk" to the virtual reader.

The GetUI() method returns a Control (that can be a UserControl or a CustomControl) that is displayed in the associated view. The Control can be used to interact with the user to provide a WYSIWYG representation of the card content, and show status updates based on APDUs received by the card. In my implemetation UI update was acheived using an Observer pattern-like strategy: all commands that update card's file system raise an event that is listened by the UI module to update the tree view accordingly.

The NewCard method resets this instance to its initial state.
The ATR property returns the ATR of the simulated smart card.
The ICardHandler interface contains the following methods:

C#
byte[] ProcessApdu(byte[] apdu);
byte[] ResetCard(bool warm);
byte[] ATR { get; }
The processAPDU method is the real heart of the simulated card: it receives a command from the communication module, processes it and returns the response to the caller.
The ATR Property returns the ATR of the simulated card.
The Reset method sends a warm or cold reset to the simulated card, clearing its securityt context.All the interfaces above are defined in a separated assembly (CardInterfaces.dll), since you need to reference them in your virtual card plugin.

The driver communication modules are shaped around the virtual smart card driver provided in the referenced article (An UMDF Driver for a Virtual Smart Card Reader). At the moment we have two implementations, one based on TCP-IP and one based on Named Pipes. The application is responsible for discovering the smart card readers available, check if they are real or simulated readers and instanciate the correct communication module.

The CardPresent event should be raised when the simulated card is inserted or removed to inform the virtual reader of the event.

The simulated card

This is where the actual simulation work begins. I provided in implementation of a file system-based ISO7816 card that handles all commands in the CIE specs (see introducion).

Since many smart card implementations are file system-based (eg. ICAO passport), I derived the ICard interface to the more specific IISO7816Card, that also provide properties and methods to handle the file system:

C#
MF MF { get; }
CreateEF()
CreateDF()
CreateBSO()
...    

The File System

The file system is implemented with this class hierarchy:

Image 3
The card contains an MF object that is the root of the file system.

The Card handler

The card Handler is the "heart" of the virtual smart card, since it defines its behaviour. It is invoked by the ProcessCommand method, that performs the following tasks:

  • Get the correct command object, based on CLA and INS of incoming APDU
  • Check if the commands requires to be decrypted with secure messaging, according to the current context, and figure out which keys should be used
  • If needed, decrypt the command and get the APDU in clear
  • Use che command object to execute the APDU

Each command object has its specificities. The behaviour of each command is defined in CIE specifications seen above. Each command deserves a specific discussion, we'll focus just on a some interesting aspects concerning cryptography:

  • Perform Security Operation: This command is used to use keys on the smart card to sign or encrypt data. More generally, it's needed to perform a symmetric or asymmetric encryption (or decryption) using key data stored in a BSO. So, for example, computing a digital signature consists in encrypting the document's hash using the private part of an RSA key pair, whose public part is stored in a digital certificate, often also stored on the card, but in a freely-readable EF.
    In case of RSA cryptography I decided not to rely on Microsoft CSP, but to directly use big number arithmetics (thanks to Chew Keong TAN for his very good BigNumber class), since I don't like to mess around user's key store. DES cryptography is implemented using .net's TripleDESProvider.
  • Verify: There are different kinds of BSO verification; PIN verification is strightforward (just memory comparison), while external authentications relies on symmetric/asymmetric encryption. Base mechanisms are the same of PSO operations.


Conclusions

Smart card infrastructures are far very complex. What we have seen in this and my previous article is just a brief a look to a wide world, that is composed also of Certification Authorities, Card minidrivers, Credential providers, personalization system and so on. Simulate a part of the process gives the possibility to make tests without having to lift a very heavy boulder.

In my next article I'll try to focus on the implementation of a Smart card minidriver, possibly based on a virtual smart card.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Engineer
Italy Italy
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionNot Detecting a Reader Pin
Maximiliano Cesan5-Oct-18 2:46
Maximiliano Cesan5-Oct-18 2:46 
QuestionDigital Sign in PDF Pin
Maximiliano Cesan4-Oct-18 15:09
Maximiliano Cesan4-Oct-18 15:09 
QuestionCongratz! Pin
Maximiliano Cesan4-Oct-18 15:03
Maximiliano Cesan4-Oct-18 15:03 
QuestionAPDU Testing Pin
flyingknee23-Nov-17 14:22
flyingknee23-Nov-17 14:22 
QuestionVirtual Smart Card Driver not detected Pin
Sowrab26-Mar-17 19:38
Sowrab26-Mar-17 19:38 
AnswerRe: Virtual Smart Card Driver not detected Pin
Fabio Ottavi30-Mar-17 23:40
professionalFabio Ottavi30-Mar-17 23:40 
GeneralRe: Virtual Smart Card Driver not detected Pin
Member 794131912-Sep-17 9:09
Member 794131912-Sep-17 9:09 
QuestionLettura smart card CNS Pin
Randolphcarter28-Apr-16 2:15
Randolphcarter28-Apr-16 2:15 
AnswerRe: Lettura smart card CNS Pin
Fabio Ottavi28-Apr-16 4:45
professionalFabio Ottavi28-Apr-16 4:45 
GeneralRe: Lettura smart card CNS Pin
Randolphcarter28-Apr-16 4:54
Randolphcarter28-Apr-16 4:54 
GeneralRe: Lettura smart card CNS Pin
Randolphcarter29-Apr-16 5:06
Randolphcarter29-Apr-16 5:06 
AnswerRe: Lettura smart card CNS Pin
Fabio Ottavi1-May-16 23:17
professionalFabio Ottavi1-May-16 23:17 
QuestionThanks for the article, but a troyan is detected by Eset. Pin
Member 804765410-Jul-15 2:22
Member 804765410-Jul-15 2:22 
AnswerRe: Thanks for the article, but a troyan is detected by Eset. Pin
Fabio Ottavi13-Jul-15 22:54
professionalFabio Ottavi13-Jul-15 22:54 
QuestionThanks for the great article! Pin
Member 977932712-Jan-15 0:19
Member 977932712-Jan-15 0:19 
AnswerRe: Thanks for the great article! Pin
Fabio Ottavi13-Jul-15 23:09
professionalFabio Ottavi13-Jul-15 23:09 
QuestionGreat Article. Pin
Member 1130122010-Dec-14 6:01
Member 1130122010-Dec-14 6:01 
AnswerRe: Great Article. Pin
Fabio Ottavi10-Dec-14 11:14
professionalFabio Ottavi10-Dec-14 11:14 
SuggestionGood job Pin
Ady Lee31-Jul-14 17:49
Ady Lee31-Jul-14 17:49 
AnswerRe: Good job Pin
Fabio Ottavi31-Jul-14 22:08
professionalFabio Ottavi31-Jul-14 22:08 
GeneralRe: Good job Pin
Member 993073229-Dec-14 12:12
Member 993073229-Dec-14 12:12 
AnswerRe: Good job Pin
Fabio Ottavi6-Jan-15 23:09
professionalFabio Ottavi6-Jan-15 23:09 
GeneralRe: Good job Pin
Member 993073212-Jan-15 7:51
Member 993073212-Jan-15 7:51 
GeneralVery generous Pin
Adriaan de Haan3-May-14 3:00
Adriaan de Haan3-May-14 3:00 
GeneralMy vote of 5 Pin
gtrotta1-May-14 0:17
gtrotta1-May-14 0:17 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.