User Guide
User Guide
www.netsolutions.gemalto.com
July 2008
Table of contents
Table of contents ............................................................................................................................... 2 1 2 .NET Card Technology Overview ............................................................................................... 6 Smart Card Background............................................................................................................. 7 2.1 Smart Card Basics ........................................................................................................................ 7 2.2 Smart Card Hardware .................................................................................................................. 7 2.2.1 Smart Card ........................................................................................................................... 7 2.2.2 Device/Interface ................................................................................................................... 9 2.3 Smart Card Software .................................................................................................................... 9 2.3.1 Operating System ................................................................................................................. 9 2.3.2 Applications .......................................................................................................................... 9 2.4 Smart Card Standards and Specifications..................................................................................... 10 Gemalto .NET Card................................................................................................................... 12 3.1 Background ............................................................................................................................... 12 3.1.1 Why .NET on a Smart Card? ................................................................................................ 12 3.1.2 Gemalto .NET Card Application Development ........................................................................ 12 3.2 Gemalto .NET Card Characteristics .............................................................................................. 13 3.3 Card Contents ........................................................................................................................... 14 3.3.1 File System ......................................................................................................................... 14 3.3.2 CardConfig.xml File ............................................................................................................. 15 3.3.3 Pre-loaded Applications ....................................................................................................... 16 3.3.4 Additional Contents ............................................................................................................. 16 3.3.5 Assemblies ......................................................................................................................... 16 3.3.6 Data Files ........................................................................................................................... 16 3.4 Smartcard Profile ....................................................................................................................... 17 3.4.1 .NET Card Specifications ...................................................................................................... 18 3.4.2 Gemalto .NET Card Certifications ......................................................................................... 18 3.5 Common Language Runtime (CLR) ............................................................................................. 18 3.5.1 Common Language Runtime (CLR) Responsibilities ............................................................... 18 3.6 Differences from .NET ................................................................................................................ 19 Concepts and Models ............................................................................................................... 21 4.1 Assemblies ................................................................................................................................ 21 4.1.1 Assemblies on the Gemalto .NET .......................................................................................... 21 4.1.2 Assembly Security ............................................................................................................... 21 4.1.3 Loading Assemblies ............................................................................................................. 22 4.2 Application Domains .................................................................................................................. 22 4.2.1 Implementation .................................................................................................................. 22 4.2.2 Differences between Gemalto .NET Application Domains and Standard .NET Application Domains 22 4.3 Application Lifecycle ................................................................................................................... 23 4.3.1 Implementation .................................................................................................................. 23 4.4 Remoting .................................................................................................................................. 24 4.4.1 Remoting in the .NET Smart Card Framework ....................................................................... 24 4.4.2 Channels and Ports ............................................................................................................. 24 4.4.3 Example ............................................................................................................................. 25 4.5 Using Custom Sinks ................................................................................................................... 28 4.5.1 Why Make a Custom Sink? ................................................................................................... 29 4.5.2 What Are the Limitations?.................................................................................................... 29 4.5.3 Designing a Custom Sink ..................................................................................................... 29
4.5.4 Using a Custom Sink ........................................................................................................... 29 4.6 Garbage Collection ..................................................................................................................... 30 4.6.1 Garbage Collection .............................................................................................................. 30 4.6.2 The GCControlAttribute ....................................................................................................... 30 4.7 File System................................................................................................................................ 31 4.7.1 Key Points about the Gemalto .NET File System .................................................................... 31 4.7.2 Example ............................................................................................................................. 31 4.8 Data Storage ............................................................................................................................. 32 4.8.1 Data Stored in Persistent Memory ........................................................................................ 32 4.8.2 Data Stored in Volatile Memory ............................................................................................ 32 4.8.3 MemoryStreams .................................................................................................................. 32 4.9 Transactions .............................................................................................................................. 32 4.9.1 Why Transactions? .............................................................................................................. 32 4.9.2 How Transactions Work ....................................................................................................... 33 4.9.3 Out-of-Transaction Objects .................................................................................................. 33 4.10 Security .................................................................................................................................... 35 4.10.1 Access Manager .................................................................................................................. 35 4.10.2 Application Security ............................................................................................................. 36 4.10.3 Data Security ...................................................................................................................... 39 4.11 Supporting Legacy Infrastructure ................................................................................................ 40 4.11.1 Who Should Read This Section? ........................................................................................... 40 4.11.2 The Problem with Legacy Applications .................................................................................. 41 4.11.3 Using Attributes to Manage APDU's ...................................................................................... 41 4.11.4 Returning Data from the Card .............................................................................................. 42 4.11.5 Handling Incorrect Requested Lengths ................................................................................. 42 4.12 Card Reset Event ....................................................................................................................... 42 4.12.1 What Does a Reset Mean? ................................................................................................... 42 4.12.2 Handling the Reset Event .................................................................................................... 43 4.13 Preloaded Services ..................................................................................................................... 43 4.13.1 ContentManager ................................................................................................................. 43 4.13.2 SampleAccessManager ........................................................................................................ 44 5 Card Explorer ........................................................................................................................... 46 5.1 Introduction .............................................................................................................................. 46 5.1.1 Starting Card Explorer ......................................................................................................... 46 5.1.2 Connecting to the Gemalto .NET Card .................................................................................. 46 5.1.3 Toolbar .............................................................................................................................. 47 5.1.4 Tab Layout ......................................................................................................................... 48 5.1.5 Select Smartcard Reader Dialog Box..................................................................................... 50 5.2 Explorer Tab.............................................................................................................................. 51 5.3 Services Tab .............................................................................................................................. 52 5.3.1 Access Manager .................................................................................................................. 53 5.4 Card Element Properties ............................................................................................................. 54 5.4.1 Card Properties ................................................................................................................... 55 5.4.2 Folder/Directory and File Properties...................................................................................... 57 5.4.3 Public Key Tokens ............................................................................................................... 60 5.5 Managing Folders and Files ........................................................................................................ 61 5.5.1 Managing Folders ................................................................................................................ 61 5.5.2 Managing Files .................................................................................................................... 62 Visual Studio .NET Integration ................................................................................................ 64 6.1 Managing the .NET Card Add-in .................................................................................................. 64 6.1.1 How to Manage the Card Explorer Add-in ............................................................................. 64 6.2 Add-in vs. Standalone Differences ............................................................................................... 65 6.3 Templates ................................................................................................................................. 65 3
6.3.1 6.3.2 7
Getting Started ........................................................................................................................ 68 7.1 Using Templates to Make a Server Application ............................................................................. 68 7.1.1 Creating a New Solution ...................................................................................................... 68 7.1.2 Opening an Existing Solution ............................................................................................... 69 7.1.3 Creating a Gemalto .NET Card Server Application .................................................................. 69 7.1.4 Debugging .......................................................................................................................... 71 7.1.5 Loading the Server onto the Card......................................................................................... 72 7.1.6 Starting a Service ................................................................................................................ 72 7.1.7 Deleting a Service ............................................................................................................... 72 7.2 Using Templates to Make a Client Application .............................................................................. 72 7.2.1 Creating a New Solution ...................................................................................................... 73 7.2.2 Opening an Existing Solution ............................................................................................... 73 7.2.3 Creating a Client Application to Access a Service Running on a Gemalto .NET Card ................. 74 7.3 Creating an on-Card Application without Templates ..................................................................... 76 7.3.1 Creating an Access Manager Project Using No On-Card Templates ......................................... 76 7.4 Building a Project from the Command Line .................................................................................. 80 7.4.1 Compiling Your Application with csc ..................................................................................... 80 7.5 Building with NAnt ..................................................................................................................... 81 7.5.1 Compiling Your Application Using NAnt ................................................................................. 81 7.6 Running Your On-card Application with a Microsoft Debugger....................................................... 81 7.6.1 Steps.................................................................................................................................. 81 7.6.2 Server-Side Code Changes ................................................................................................... 81 7.6.3 Client-Side Code Changes .................................................................................................... 82 7.6.4 Changes to the Project Settings ........................................................................................... 83 Code Samples .......................................................................................................................... 84 8.1 AudioStreamMP3 Sample ........................................................................................................... 85 8.1.1 Description ......................................................................................................................... 85 8.1.2 Execution ........................................................................................................................... 85 8.1.3 Code Sample ...................................................................................................................... 85 8.2 EncryptionSink Sample ............................................................................................................... 86 8.2.1 Description ......................................................................................................................... 86 8.2.2 Execution ........................................................................................................................... 86 8.2.3 Discussion .......................................................................................................................... 86 8.2.4 Code Extract ....................................................................................................................... 86 8.3 SecureSession Sample ............................................................................................................... 87 8.3.1 Description ......................................................................................................................... 87 8.3.2 Running the Sample ............................................................................................................ 88 8.3.3 Code Extract ....................................................................................................................... 88 8.4 APDUAttribute Sample ............................................................................................................... 90 8.4.1 Description ......................................................................................................................... 90 8.4.2 Execution ........................................................................................................................... 91 8.4.3 Code Extract ....................................................................................................................... 91 8.5 Transactions Sample .................................................................................................................. 91 8.5.1 Description ......................................................................................................................... 91 8.5.2 Execution ........................................................................................................................... 91 8.5.3 Code Extract ....................................................................................................................... 92 Client-Side Components .......................................................................................................... 93 9.1 SmartCard_Stub ........................................................................................................................ 93 9.1.1 Referencing the ContentManager from Your Project .............................................................. 93 9.2 SmartCard.Runtime ................................................................................................................... 94 9.2.1 Client Remoting Components ............................................................................................... 94 Gemalto .NET v2/v2+ User Guide 4
9.2.2 CardAccessor Class ............................................................................................................. 94 9.2.3 IAccessManagerClient Interface ........................................................................................... 94 9.3 C++ Marshaller ......................................................................................................................... 94 9.3.1 Why a C++ Marshaller? ....................................................................................................... 94 9.3.2 Using the Marshaller............................................................................................................ 95 10 Troubleshooting....................................................................................................................... 96 10.1 Communication Problems ........................................................................................................... 96 10.1.1 The Easy Checklist .............................................................................................................. 96 10.1.2 Further Steps ...................................................................................................................... 96 11 References and Resources ...................................................................................................... 97
The documentation provided here for .NET Card Technology assumes a general understanding of .NET Framework concepts, and focuses on components and tools that are unique to the .NET Smart Card Framework. This documentation does not repeat topics covered in the .NET Framework documentation, which is available from the Microsoft .NET Framework Developer's Center.
The plastic media of the card may be printed to include a range of information, including company logos and photos (for example, for scenarios in which the smart card will also serve as an identification badge). The working part of the smart card is the chip embedded at left center and includes: Electrical contacts defined by ISO 7816-2, Identification Cards - Integrated Circuit(s) Cards with Contacts - Dimensions and Location of the Contacts. The CPU (integrated circuit microprocessor). The chip in most smart cards is an 8- or 16-bit microprocessor, usually using the Motorola 6805 or Intel 8051 instruction set, with clock speeds up to 5 MHz. The chip in the Gemalto .NET card is a 32-bit microprocessor. A cryptographic coprocessor, which adds on-card capacity to perform the complex calculations needed for cryptographic operations. Three types of memory: o o
Random Access Memory (RAM), volatile, mutable memory; content in RAM is not preserved when
power to the card is removed.
Read-Only Memory (ROM), persistent, nonmutable memory into which the fixed program of the card is loaded and stored during manufacturing. ROM contains the card's operating system routines, permanent data, and permanent user applications. Content in ROM is preserved when power to the card is removed. Electrical Erasable Programmable Read-only Memory (EEPROM), persistent, mutable memory
used for data storage on the card. Content in EEPROM is preserved when power to the card is removed.
2.2.2 Device/Interface
The most commonly deployed device to connect a smart card with a host system in order to exchange data is a smart card reader. The reader is attached to the host system using a serial, USB, or PC Card connection. The smart card is inserted into the reader and when the card's contact points are correctly aligned, communication between the smart card and the host system can be initiated. A contactless smart card communicates with the host system using electromagnetic fields using an antenna that is built into the card. Physical proximity to a card reader/terminal that also includes an antenna triggers initiation of a communication protocol that allows data exchange. Because USB-capable smart cards incorporate the USB interface electronics normally found in a smart card reader on the card itself, a USB-capable smart card interfaces directly with the host system through a USB port. A conventional form factor USB-capable card uses a special receptacle (resembling a standard smart card reader but containing no electronics) plugged into a USB port, while a cut-down format USB-capable card is inserted into a dongle that plugs directly into the USB port.
2.3.2 Applications
In order for a smart card to be useful, it must perform some operations that are understood by a terminal or other external smart card reader. Smart card applications range from a simple electronic purse to implementation of complex cryptographic algorithms for digital security. Traditionally, smart card applications were developed for a specific chip, and were written in C by a specialized community of smart card developers. These applications would be written to the chip at production time, and could not be changed after the card was issued. This model of application development had some deficiencies. Moving your application to a new type of chip meant rebuilding and possibly redesigning your application for the new chip. Since applications needed to be written to the chip at production time, the entire lifecycle of the smart card needed to be known in advance there would be no way to change the application in the field. In the late 1990's, smart card application development changed radically. Smart card companies released smart cards known as Java Cards, which contained a Java interpreter. By writing applications in Java, smart card developers could insulate themselves from the details of the specific chip hardware. Also, Java applications were stored in non-volatile but erasable memory, so new applications could be loaded to the card even after the card was in the hands of a user. Although the Java Card represented a significant step forward Gemalto .NET v2/v2+ User Guide 9
in smart card development, it did not completely isolate the developer from the protocols of the smart card. Developers were still responsible for managing the communication between the card and the off-card terminal. The Gemalto .NET Card contains an IL interpreter that allows users to develop applications for the smart card using the ECMA .NET standard. Applications can be developed in any language that can be compiled to IL. The following two software components are present only on smart cards that have interpreters:
2.3.2.2 Loader
Since applications on cards with runtime environments can be loaded after the card is produced, there must be a software component that is responsible for loading these components to the card. The Loader on the Gemalto .NET Card is responsible for several tasks: 1. Verifying that the IL being loaded to the card is safe to run. 2. Verifying that the assembly being loaded to the card is properly signed. 3. Ensuring that all types used by the assembly are already present on the card The Loader is also responsible for removing applications from the card.
9. Synchronous cards ECMA ECMA-335 Defines the Common Library Infrastructure (CLI), which ensures that applications written in multiple high-level languages may be executed in different system environments without the need to rewrite the application to take into consideration the unique characteristics of those environments. Defines low-level device interfaces and deviceindependent application APIs as well as resource management, to allow multiple applications to share smart card devices attached to a system. Open interface standard providing a common interface between PCs and peripherals. (European Telecommunications Standards Institute) Telecomm specifications for smart cards used in public and cellular telephone systems. (Europay, MasterCard, and Visa) Banking industry specification that defines a set of requirements to ensure interoperability between chip cards and terminals on a global basis, regardless of the manufacturer, the financial institution, or where the card is used. Common Criteria v2.1/ISO 15408 (Common Criteria for Information Security Technology) A new world standard for security specifications and evaluations. The standard defines general concepts and principles of IT security evaluation and presents a general model of evaluation. (Federal Information Processing Standard) Specifies the security requirements that will be satisfied by a cryptographic module utilized within a security system protecting sensitive but unclassified information.
PC/SC
USB ETSI
EMV
Common Criteria
National Institute of Science and Technology (NIST) Computer Security Research Center(CSRC)
FIPS 140-2
11
3.1 Background
Gemalto .NET Card is a new type of post-issuance programmable smart card. First demonstrated in 2002, the card is designed to work with .NET platform applications.
In addition, a key benefit to developing applications for the Gemalto .NET Card is the communication model, which enables developers to move away from the APDU-centric communication architecture that is an underlying constraint on other programmable smart card platforms. Instead, communication between the Gemalto .NET Card and the host system uses a subset of the .NET Remoting feature, which is potentially capable of supporting standard, widely-understood protocols (for example, XML, SOAP, HTTP), as well as the traditional 7816-4 protocol APDU commands.
12
13
The file system contains these base folders: C:\Gemalto (Gemalto executables and libraries) C:\Pub (public) C:\System (contains the class libraries and any other libraries that are meant to be accessible to all applications) D:\Pub (public; preloaded with the CardConfig.xml file, which identifies aspects of the card's capability to work with host-side applications)
* Note that while the CardConfig.xml file is found in the D:\pub directory, which is readable by all users on the card, its contents can be changed only by the cards admin user.
14
New files and folders can be added to the file system, subject to user permissions. Files and folders can also be deleted from the card.
15
ContentManager
3.3.5 Assemblies
Applications (.exe files) and libraries (.dll files) can be added to the card. While execution of applications on the Gemalto .NET Card is not subject to user permissions, managing applications and libraries (for example, adding new application files) on the card is based on role-based access to the folders in which the application files are found. Default card permissions permit the initially-configured user guest to add applications and libraries to the \pub folders only. The default admin user can add applications and library files anywhere in the file system. Other users can add applications and libraries as permitted by the user-code, path-access definition configured for each user on the card at user creation time. The rules that govern applications permissions to access other applications or libraries are based on the public key token list of the requested resource. Application and library files are uploaded to the card using the Card Explorer tool, either as a stand-alone application or as a Visual Studio .NET Add-in. In the Card Explorer, identify a folder on the card to which you have access, right-click the folder, and select Add > New File. In the Open dialog box, navigate to the application or library file on the host system that you want to add to the card, and click Open. The file is copied to the selected folder on the card.
16
Data files are added to specific folders within the D: file system, subject to user permissions. Default card permissions permit the initially-configured user guest to add files to the D:\pub folder only. The default admin user can add data files anywhere in the D: file system. Other users can add data files as permitted by the user-data, path-access definition configured for each user on the card at user creation time. Data files can be uploaded to the card using the Card Explorer tool. In the Card Explorer, identify a folder on the card to which you have access, right-click the folder, and select Add > New File. In the Open dialog box, navigate to the file on the host system that you want to add to the card, and click Open. The file is copied to the selected folder on the card. Data files can also be copied to the card using the standard Windows Explorer drag-and-drop mechanism.
The graphic shows the relationship between the libraries and the three current .NET profiles.
The Smartcard profile includes a strict subset of the two .NET libraries that make up the Kernel profile, plus one new, smartcard-focused library. File mscorlib.dll Description Strict subset of the .NET mscorlib.dll
17
system.xml.dll SmartCard.dll
Other responsibilities of the CLR are more closely related to the Gemalto .NET Card implementation. Evidence-based security implementation The evidence-based security implementation ensures the integrity and authenticity of Gemalto .NET Card assemblies during load to the card and during execution of the loaded applications. For more information about the security implementation in the .NET Smart Card Framework CLR, see the Concepts and Models, Evidence-based Security section. Transaction management The .NET Smart Card Framework supports a persistent transaction model that ensures the integrity of data on the Gemalto .NET Card, despite frequent and sometimes unpredictable physical removal of the card from the system or terminal with which it is communicating. The transaction management system includes a new caching technology that greatly increases the speed of writes to EEPROM, while still maintaining data integrity. For more information about the transaction management implementation in the .NET Smart Card Framework CLR, see the Concepts and Models, Transactions section. Code access security Very similar to data security; that is, a public key token is required for an assembly to access a dependent library. To enable a library to be shared with another assembly, the corresponding public key token must be added as an attribute. Security policy is determined by the Access Manager.
19
Assembly scope names are ignored in the .NET Smart Card Framework, and types are identified by their name alone. Two types with the same name in different assemblies are considered to be identical. Only the method signature default calling convention is supported. There are no implicit types in the .NET Smart Card Framework CLR. All types are explicitly defined in the metadata loaded into the CLR. In the presence of multiple loaded assemblies, it is possible to have multiple definitions for types that might normally be implicit. However, the CLR treats these multiple definitions as if there was a single one; there is no way to distinguish if there is one definition or several. Asynchronous calls are not supported in the .NET Smart Card Framework. Only BeforeFieldInit type-initializers are supported the .NET Smart Card Framework; all other initializers are considered to be errors. Finalizers are not supported in the .NET Smart Card Framework. New slot member overriding is not supported in the .NET Smart Card Framework. The existing slot for member overriding is supported. (Class Layout) Only autolayout of classes is supported in the .NET Smart Card Framework. (The loader is free to lay out the class in any way it sees fit.) The zero init flag is not supported in the .NET Smart Card Framework; local and memory pools are never initialized to zero. Locks and threads are not supported the in .NET Smart Card Framework; therefore, any types associated with these constructs are not supported. The security descriptor method state is not supported in the .NET Smart Card Framework.
20
4.1 Assemblies
Compiled .NET software is typically distributed in the form of assemblies. Assemblies perform a number of different functions in .NET, including containing the executable code as well as defining type, security, and reference boundaries. MSDN provides detailed documentation of various aspects of .NET assemblies. We assume that you are familiar with concepts related to Microsoft .NET assemblies. The Gemalto .NET Card uses assemblies in the same manner as a Microsoft .NET environment. However, Gemalto .NET assemblies go through a conversion process in order to optimize for space usage and to ensure that the assembly does not use types that are unsupported on the card. This conversion process is hidden from the user, and is performed automatically at compilation time when developing an application using Visual Studio .NET.
21
For more details on the CardAccessor API, see the Gemalto .NET SmartCard Client API documentation.
4.2.1 Implementation
The .NET Smart Card Framework uses the type System.AppDomain to isolate running instances of applications from one another by executing each instance in an isolated environment. The safety and integrity of each application is assured, because data in one application domain cannot directly reference data in another domain. An application domain serves as the container for assemblies and types when loaded into memory at runtime. It can be useful to think about an application domain as the logical equivalent of a process in a Win32 application. Similar to processes, application domains can be started and stopped independently.
4.2.2 Differences between Gemalto .NET Application Domains and Standard .NET Application Domains
There are some key differences to keep in mind between application domains on the Gemalto .NET and normal .NET application domains. On the Gemalto .NET Card: The ExecuteAssembly method of an AppDomain can only be executed from off the card, either through the Card Explorer or through the SmartCard.CardAccessor.CardAccessor API (see the .NET SmartCard Client API documentation). An instance of AppDomain cannot be created by an application on the card. If an application domain does not create a service, the application domain will be garbage collected. For example, if application alpha.exe does not create a service, the .exe file will remain on the card after execution, but there will be no running application domain. If alpha.exe DOES create a service, the alpha.exe application domain continues to run (even after the Main method exits) until the service is deleted. One application domain can communicate with another application domain indirectly by using Activator.GetObject to obtain a reference to a remoted object in the other application domain. For more details on this process, see the documentation on Remoting. An application domain can delete itself by using the static AppDomain.Unload method. An application might be interested in unloading itself if it were an application that were time- or usage-based (such
22
as a coupon application), or if the application were to reach an unrecoverable situation due to a security breach. For example:
if (timesUsed > 10) AppDomain.Unload(AppDomain.CurrentDomain);
4.3.1 Implementation
4.3.1.1 Loading
A Gemalto .NET Card application can be created using any supported .NET programming language (for example, C# or VisualBasic.NET). After the code is written, it is compiled to .NETs Microsoft intermediary language (MSIL) format. This compilation produces a standard .NET assembly. Before it is loaded onto the card, the .NET assembly is converted from its standard compiled form to the .NET Smart Card Framework's card-resident binary format, which produces a much smaller (by a factor of 4) binary than a full .NET assembly. The converted binary is called a card-resident binary. The converted binary must be strong-name signed. This is the application file that is loaded onto the Gemalto .NET Card.
4.3.1.2 Installation
Each executable binary has a single entry point, a method of the following form:
public static int Main
After successfully loading and linking a new binary onto the card, the Main method is called to execute an application-specific installation. The application must also register its remote types with the .NET Smart Card Framework runtime to allow clients to remote call methods on the newly installed application. See Concepts and Models, Remoting for more information about remoting.
4.3.1.3 Execution
The .NET Smart Card Framework implements a client/server model, in which the host system or terminal is the client, and the Gemalto .NET Card is the server. Interaction is always initiated by the client using a request/reply protocol. Server applications running on the card are persistent; that is, the applications do not terminate when power is turned off (when the card is removed from the reader or terminal) or the card is reset. If one of these events occurs, when the card is reconnected, the application's state has not changed from its previous state. See Concepts and Models, Transaction Model for more information about transaction persistence.
4.3.1.4 Termination
A service on the card stops running when the service is unregistered. You can do this both programmatically and by using the Card Explorer tool. When the service is unregistered, the running instance will be deleted, and its memory will be reclaimed by the garbage collector.
23
4.3.1.5 Unloading
After a service has been terminated, the binary containing that service can be removed from the card. A loaded assembly that is still exposing a service cannot be unloaded. The service must be terminated first.
4.4 Remoting
Remoting in the .NET Framework allows one operating system process or program to communicate with another process running on the same computer, or on two computers connected by a local network or the Internet.
.NET remoting provides an abstract approach to interprocess communication that separates the remotable object from a specific client- or server-application domain and from a specific mechanism of communication. As a result, it is flexible and easily customizable. The .NET Smart Card Framework extends standard .NET remoting and allows a program executing on a PC to communicate with a process running on a Gemalto .NET Card, and also allows a program running in one application domain to access code or data in a process running in another application domain within the Gemalto .NET Card.
24
The above figure illustrates how the client and server communicate using channels and named ports in the .NET Framework. In the .NET Smart Card Framework, identifying a specific port to associate with a channel is not always feasible, so a new mechanism for specifying the channel mode has been created. See the Server Sample Code for details about creating a .NET Smart Card Framework server that makes objects available for remoting. In the .NET Framework, your client code also creates a channel associated with a specific port, and then uses the Activator class to obtain a reference to the remote object. You identify a remote object with the URL of the computer on which it is located, the name of the remote class, and a URI that you assign. In the .NET Smart Card Framework, you also use the Activator class to obtain a reference to the remote object, using the new mechanism for specifying the channel mode previously mentioned. The APDUChannel supports URL's of the format:
"apdu://<name of the smart card reader>:<the port on which the service is registered>/<the name of the service>"
For example:
"apdu://Gemalto Reflex USB v2:2222/CardService"
In addition to explicitly naming the reader to connect to, you can also use the reserved names "promptDialog" and "selfDiscover". The promptDialog mechanism will display a dialog box and allow the user to select which reader to use. The selfDiscover mechanism attempts to find the requested service by attempting to connect to any .NET smart cards attached to the machine. A simple .NET Smart Card Framework remoting example follows.
4.4.3 Example
4.4.3.1 Server Sample Code
First, create the server, which listens for calls from clients and connects them to the remotable class. Here's what the code does: 1. Creates a new APDUServerChannel; in the sample code:
APDUServerChannel chan = new APDUServerChannel()
25
2. Registers the channel with the .NET Smart Card Framework infrastructure; in the sample code:
ChannelServices.RegisterChannel(chan)
The arguments to this call are: o o o The first argument identifies the class being registered; in the sample code:
typeof(MyRemoteClass)
The second argument specifies the URI for the class; in the sample code: "MyServiceURI". The client will use this URI when calling the class. The third argument specifies that if there are multiple calls to the class (from more than one client), they will all be serviced by the same instance of the class, in the sample code: WellKnownObjectMode.Singleton. The two available modes are:
SingleCall - Single Call objects service one and only one request coming in. Single Call objects
are useful in scenarios where the objects are required to do a finite amount of work. Single Call objects are usually not required to store state information, and they cannot hold state information between method calls.
Singleton - Singleton objects service multiple clients and, hence, share data by storing state
information between client invocations. They are useful in cases in which data needs to be shared explicitly between clients and also in which the overhead of creating and maintaining objects is substantial. The sample server code follows.
using System; using System.Runtime.Remoting.Channels; using SmartCard.Runtime.Remoting.Channels.APDU; namespace RemotingDemoServer{ public class MyRemoteClass : MarshalByRefObject { public MyRemoteClas() { } public String SayHello(string name) { return "Hello" + name; } public static void Main() { APDUServerChannel chan = new APDUServerChannel(); ChannelServices.RegisterChannel(chan); RemotingConfiguration.RegisterWellKnownServiceType(typeof(MyRemoteClass), "MyServiceURI", WellKnownObjectMode.Singleton); } } }
26
Mode
prompt
Description
Application displays a Select Card Reader dialog box requiring the user to select which reader to use. Specifies the reader that will be used, for example, Reflex CCID 0. The exact string for each reader that can be specified matches the reader options that display in the Select Card Reader dialog box drop down list. This mode is appropriate only if you know which reader will be used with your application. The application searches for a card containing the service that the application is requesting. If the application does not find a suitable card, the Select Card Reader dialog box is displayed, and the user must select the reader to use. The application searches for a card containing the service that the application is requesting. If the application does not find a suitable card, an exception is thrown. This mode is primarily used for an application that is not allowed to display dialog boxes, for example, Windows services.
<hard-coded reader>
SelfDiscover
SelfDiscoverNoPrompt
The URI associated with the remote class, which must match the URI established by the server; in the sample code: MyServiceUri.
27
using System.Runtime.Remoting.Channels; using System.Runtime.Remoting.Channels.APDU; using RemotingServerDemo; namespace RemotingClientDemo { public class Client { public static int Main(string [] args) { APDUClientChannel chan = new APDUClientChannel(); ChannelServices.RegisteredChannel(chan); MyRemoteClass obj = (MyRemoteClass) Activator.GetObject(typeof(RemotingServerDemo.MyRemoteClass), "apdu://prompt/MyServiceUri"); Console.WriteLine(obj.SayHello("John"); return 0; } } }
This diagram shows the .NET remoting architecture with custom sinks sitting between the formatter and transportation sinks on both the client and server.
28
On the server side, you create your sink provider and place it after the APDUClientFormatterSinkProvider. Then, when you register a channel, you register the APDUServerFormatterSinkProvider as the parameter to the channel that you will be using.
29
// Create an encryption sink provider as the second sink in the chain IClientChannelSinkProvider newProvider = new APDUClientFormatterSinkProvider(); newProvider.Next = new EncryptionClientSinkProvider(properties); // Register the communication channel ChannelServices.RegisterChannel(new APDUClientChannel("EncryptionSinkClient", newProvider));
Note that unlike garbage collection on other platforms, the .NET Smart Card Framework garbage collection does not take place during execution of an application or during allocation of objects or arrays, nor does garbage collection automatically execute when the system runs out of memory. This means that if you are creating a large group of objects and setting them to null, they will not be collected until the end of the remoting call. Because of this constraint, you need to design your application in such a way that it does not rely on memory being freed immediately after objects are set to null or no longer referenced. Since a smart card is a resource-constrained device, it is recommended that you should try to keep object creation and deletion to a minimum. More object creation and deletion implies more garbage collection time, which might impact the performance of the application.
Normally, garbage collection would not be invoked after this method, since there is no object allocation in the method. However, in this case, garbage collection will still be invoked because we've used the GCAttribute Gemalto .NET v2/v2+ User Guide 30
with the GCControlMode.Force parameter. This might be useful if myMemberArray was large, and we wanted this memory to be available for the next remoting call. Alternatively, we might want to skip garbage collection on a given method:
[GCControl(GCControlMode.Skip)] void MyMethod() { myMemberArray = new byte[3]; }
Normally the above method would invoke garbage collection since there has been an object allocation. However, for performance reasons, a developer might want to skip garbage collection for this method. Using GCControlMode.Skip causes the system to skip garbage collection for this method.
4.7.2 Example
The following example shows on-card manipulation of the file system by attempting to create a file in each of the subdirectories of D:\Pub
public void Example(string filename, byte [] data) { string [] dirs = Directory.GetDirectories(@"D:\Pub"); foreach (string directory in dirs) { FileStream fs = new FileStream(@"D:\Pub\" + directory + @"\" + filename, FileMode.Create); fs.Write(data, 0, data.Length); fs.Close(); } }
31
4.8.3 MemoryStreams
There exists a special case of objects that exist in both persistent and volatile memory. The MemoryStream object itself is in persistent memory, but the data to which it is pointing will exist in volatile memory. When a card is reset, any memory streams will be disposed, and the data to which those streams pointed will be lost. Memory streams provide a fast mechanism for manipulating arrays of byte data because the data is manipulated in fast volatile memory rather than slower persistent memory.
4.9
Transactions
The .NET Smart Card Framework supports a persistent transaction model that ensures the integrity of data on the Gemalto .NET Card, despite frequent and sometimes unpredictable physical removal of the card from the system or terminal with which it is communicating.
object fields. For example, you might be updating an address in an object. If you update the "street" field, but the card is removed before you update the "city" field, you could end up with an address that is completely incorrect. You need a way to ensure that either all of the updates take place, or none of them do. Card removals aren't the only interruption that you might worry about. You might be concerned that an exception could be thrown in the middle of some field updates that could leave the card in an inconsistent state. In this case, you would want a mechanism for rolling back any field updates to the original state.
4.9.2.1 Example
In this example, the Increment method is marked as a transaction using the Transaction attribute.
[Transaction] private void Increment () { counter++; if (counter > 10) { throw new BadCountException(); } }
In the example, a counter is incremented, and if the counter is greater than 10, an exception is thrown. The exception is not caught in this method. (It is intended to be caught by the caller.) Because executing the method results in an uncaught exception, the sub-transaction aborts and any changes made by this method are rolled back. The result is that the value of the counter will never exceed 10.
33
using System; using System.Diagnostics; using SmartCard; using SmartCard.Services; public class MySecureCounter { [OutOfTransaction] byte counter; public void Increase() { counter++; } public byte Value { get { return counter; } } } public class Test { MySecureCounter secCount = new MySecureCounter() [Transaction] public void TestWithAbortedTransaction() { secCount.Increase(); throw new Exception(); // abort } public void TestWithoutTransaction() { secCount.Increase(); throw new Exception(); // abort } static void Main() { Test test = new Test(); Debug.WriteLine("initial value = " test.secCount.Value); // expect test.secCount.Value = 0 try { test.TestWithoutTransaction(); } catch {} Debug.WriteLine("second value = " test.secCount.Value); // expect test.secCount.Value=1 try { test.TestWithAbortedTransaction(); } catch {}
34
4.10 Security
Security in the Gemalto .NET Card is generally discussed in one of three contexts: Access Manager. The Gemalto .NET Card supports an extensible access management system that allows developers and card deployers to define user roles that can manage the card. These user roles control the deployment of new assemblies to the card, as well as control over the .NET card file system. Application Security. Applications deployed to the Gemalto .NET Card are always signed assemblies. The public key token of these signed assemblies is used to grant or deny privileges to a given application. For example, a library assembly installed on the card might restrict unknown assemblies from using its API. Data Security. Data for Gemalto .NET applications can be stored either internally to the application or in the Gemalto .NET file system. Applications making use of the file system can be assured that file-based data is secured by access control lists associated with the public key tokens of on-card assemblies.
35
made the new AccessManager and the path to the assembly containing the implementation class are passed as arguments. If the current AccessManager does not entertain this request, an UnauthorizedAccessException is thrown. Since the above-mentioned methods of the AccessManager service are invoked whenever a resource is accessed, it is recommended that implementors of the AccessManager service should pay special attention to performance requirements and memory consumption. Also, when designing an AccessManager service, the policies to delegate control to a new AccessManager should be known in advance and be well thought out. The Gemalto .NET SDK also provides a flexible and extensible mechanism for client applications to communicate with an AccessManager service on the card. An interface called IAccessManagerClient in Gemalto.SmartCard.Runtime.dll is provided that should be implemented and registered. A new AccessManager client application is registered by adding the path to its assembly in the Config.xml file, which is located in the "[INSTALLDIR]\Gemalto\NET SmartCard Framework SDK\v1.1.*\bin" directory. In the next release of the SDK, a graphical interface will be provided to register new AccessManager clients. The SmartCard.Acessor.CardAccessor class of SmartCard.Runtime.dll provides methods to determine the correct AccessManager client. Toolbar buttons of the Card Explorer, provided in the SDK, change their behavior depending on the AccessManager client registered. The Gemalto .NET Card shipped in the SDK contains an AccessManager service called SampleAccessManager, which uses username/password-based authentication and controls the access to resources using a role-based security mechanism. It has been described in detail here.
Figure 1. Interim binary Note that the metadata for a card-resident binary consists only of name and version information for the binary (in contrast to the metadata in a full .NET assembly, which includes a much larger set of data describing the assembly). 2. A hash is computed (using the SHA1 algorithm) based on the interim binary's components, and then the hash is encrypted using the private key associated with the interim binary's public key pair. The encrypted hash (which is also called the signature) is stored as part of the binary. The components of the binary after addition of the signature are:
metadata code public key signature
36
Figure 2. Final binary ready for upload to the card A binary that includes a signature is ready for upload to the Gemalto .NET Card, where it will become a cardresident binary. The binary can be loaded using the CardManager service, the Card Explorer, or the CardAccessor library, which provides a wrapper for CM methods. During upload of the binary to the card, each block of data is checked for accuracy (unrelated to integrity/authenticity). If all blocks are loaded successfully, a hash is computed using the public key, which has been extracted from the binary on the card. The encrypted hash (signature) loaded onto the card is then decrypted, also using the public key. If the decrypted signature matches the hash computed on the card using the public key, both the integrity and authenticity of the data are proven. Integrity is demonstrated because the hash values match. Authenticity is demonstrated because the public key can only be in the .binary loaded onto the card if the private key was known. If the values do not match, the data integrity and authenticity of the binary cannot be assured, and a BadImageFormatException exception is thrown. (The binary is not loaded to the card.)
Figure 3. Original .NET assembly components, pre-conversion When the original .NET assembly is converted to the card-resident binary format, the resulting binary file (.bin) is stored in the original assembly as a resource. After the .bin file is embedded, the original .NET assembly is re-signed so that the data in the .bin file is accounted for in the original .NET assembly's encrypted hash (signature).
metadata code public key .bin resource new signature
Figure 4. Original .NET assembly components, post-conversion The .NET assembly hash is stored in the converted binary and gets loaded onto the card along with the rest of the data in the card-resident binary. If needed, this hash value can be used to match the card-resident binary to the original .NET assembly on the desktop.
37
A new public key token can be added as an attribute from the properties page for the assembly. Open the properties page for assembly A2, click the Security tab, and then click Add to add the new public key token by selecting assembly A1 from the list, or click New to add the new public key token by typing or pasting the public key token for assembly A1. Access rules enforced by the current Access Manager define who is able to add public key token attributes to an assembly.
38
Figure 5. Dialogs for managing the public key tokens of an assembly If an assembly does not have any public key token (PBTK) attributes, it is considered to be public; that is, the assembly is accessible by all other assemblies. For example, assemblies located in C:\Gac (including mscorlib.dll, SmartCard.dll, and System.Xml.dll) are accessible to all assemblies. You can confirm that an assembly is public by viewing its properties; click the Security tab and verify that the Public Key Tokens list is empty.
39
directly is an advantage from a security perspective, but it can be a disadvantage from a performance perspective.
This mechanism of data storage has two key advantages. It makes an application separate from the data that it operates on. This would allow you to delete an application and install a new version without having to worry about serializing or otherwise preserving data. It simplifies sharing data. For example, one application might have information about the shipping address of the card owner. If this were stored in a file that was accessible to other applications, the same shipping address would be accessible to those applications.
The fact that the file system can be used for data sharing requires that there be policies in place to enforce ownership and sharing privileges on files in the file system. Data files in the Gemalto .NET card are protected using a public key token system that is very similar to that used by Applications. Each file has two sets of privileges associated with it. The first, its public privileges, defines what any application can do to the file. For example, a file could have a public Read privilege, which would allow any application to read from the file. The second set of privileges are the private privileges. These privileges are assigned to individual public key tokens. For example, a file might assign read privileges to a particular public key token that is trusted by the application. By default, when a file is created using the System.IO namespace, no public privileges are assigned to that file, and the public key token of the assembly that created the file is the only public key token in the private privileges set. The creating assembly has full privileges to control the file. If an assembly with a public key token that is not in the private privileges set attempts to perform an operation that is forbidden in the public set, an UnauthorizedAccessException is thrown.
40
Broadly, here's what this does: It defines a method GenerateKeyPair that returns no data and in the normal remoting world would be expecting as arguments 3 bytes, followed by an unsigned short, followed by a byte array. If you wanted to invoke this method using remoting, you'd use:
myRemoteObject.GenerateKeyPair(priIndex, pubIndex, algId, keySize, bData);
However, if instead of using remoting, you send an APDU to the card that matches the APDU attribute, the following happens: 1. The P1 byte from the APDU is packed into the first argument. 2. The P2 byte from the APDU is packed into the second argument. 3. The first DATA byte is packed into algID. 4. The second two data bytes are packed into keySize. 5. The remainder of the DATA from the APDU is packed into the Data array. 6. If a CryptographicException is thrown by the method, it will be translated to a SW of 0x6512. 7. If any other exception is thrown by the method, it will be translated to a SW of 0x6514. What does it mean for an APDU to match the APDUattribute? Basically the check is:
if ((incomingAPDU & (~Mask)) == APDUAttribute)
So, in our example, any APDU of the form B0300x0x would be dispatched to this method. Here are the rest of the rules you need to know for writing APDU's from your Gemalto .NET application: 1. Your method must either return void, byte[] or MemoryStream 2. Your method must take as parameters only basic numeric types (byte, short, int, long or their unsigned variants) or a byte array.
41
3. If your method takes a byte array as a parameter, the byte array must be the last parameter, and there can only be one array parameter. 4. The URI of the application that you marshal when you install the application should be a string containing the hexadecimal AID (e.g. private const string REMOTE_OBJECT_URI = "A00000000101";. By doing this, your application will respond to standard select APDU's. In the case of the above sample, 00 A4 04 00 06 A0 00 00 00 01 01 would select the assembly. Additionally, you can define a method to be called anytime that your application is selected using APDU's.
[APDU("SELECT")] public void Select(MemoryStream AID) { // Do anything you want to do when selected here... }
When the card receives "00 B2 00 00 04 12 34 56 78", it will respond with "61 0C", and it will be the responsibility of the terminal to send a GetResponse to retrieve the data.
42
All open FileStream objects are closed. Further attempts to use these objects will result in an ObjectDisposedException being thrown. All open MemoryStream objects are closed. MemoryStreams ObjectDisposedException if you attempt to use them after a reset. will also throw an
A CardReset event is triggered. An application can listen for this event to perform any operations that might be necessary to reset the card. For example, you might wish to reset data or fields that might be specific to your session.
In the preceding example, the iSessionCounter will be reset back to zero every time the card is reset.
4.13.1 ContentManager
The Content Manager service is installed on the card during personalization at the factory. This service allows you to manage the lifecycle of the card by managing the file system, setting card properties, and loading/unloading assemblies. The Content Manager can be used either from on-card applications or off-card applications. To access the Content Manager from off-card applications, you can obtain a proxy to the Content Manager using standard remoting techniques, or you can use the off-card SmartCard.CardAccessor library, which provides an interface to the on-card ContentManager application and does not require the calling application to use remoting directly.
4.13.1.1 Features
Broadly, the ContentManager application allows you to do the following:
43
Manage files on the card. This includes creating/deleting both directories and files, getting/setting properties associated with files, and managing the security settings associated with a given file or directory. Manage assemblies on the card. The API provides support for loading applications, executing assemblies, and unregistering services. Manage card properties. For example, you can set the chip speed, the communication speed, or the historical parts of the ATR. In addition, you can read information about the version of the card, free memory available, etc.
4.13.1.2 Examples
Here's an example of using the ContentManager from an off-card application:
ContentManager cm = (ContentManager)Activator.GetObject(typeof (ContentManager),"apdu://selfDiscover/ContentManager"); int speed = cm.ChipSpeed;
Note the close similarities. The on-card application is using the same remoting mechanisms that the off-card application is using.
4.13.2 SampleAccessManager
The SampleAccessManager service extends the SmartCard.AccessManager class and is the default selected AccessManager for the smart card. The Access Manager is responsible for controlling access to system resources such as the file system and card properties.
4.13.2.1 Features
You can use the SampleAccessManager application to programmatically log on to the card as a user. This service is responsible for granting or denying privileges to system resources. You can replace the SampleAccessManager application with a different service that extends SmartCard.AccessManager. For more details about the AccessManager model, see the Access Manager documentation.
From within the SampleAccessManager client tools, you can create new users and assign them to one of these roles.
44
45
5 Card Explorer
The Card Explorer is the tool available to manage Gemalto .NET Cards.
5.1 Introduction
The Card Explorer is a tool (also available as an add-in to Visual Studio .NET) that simplifies Gemalto .NET Card management, including viewing a card's content; managing the card's assemblies, data files, and directories; managing authentication according to the requirements of the current Access Manager; and creating and deleting services on the card.
In the Select Smart Card Reader dialog box, select the name of the reader in which the Gemalto .NET Card is inserted. If necessary, click Details and select other options (see Select Smart Card Reader dialog box). Click OK. In the Card Explorer toolbar, the Log on icon becomes available. 3. Click (Log on) to invoke the authentication method of the current Access Manager on the card. The authentication method might require the user to provide some sort of input (for example, a user name and password, or a biometric like a fingerprint) using a client application. If this is the case, an appropriate dialog box or other graphical user interface is displayed after the user clicks the Log on icon. For example, if the authentication method for the current Access Manager requires the user to specify a user name and password to access the card, clicking the Log on icon might result in display of a dialog box similar to the following one to gather and submit the required information.
46
If authentication is successful according to the requirements of the current Access Manager, the card contents are displayed in the Explorer tab of the Card Explorer.
5.1.3 Toolbar
The Card Explorer toolbar provides convenient access to perform routine card management tasks.
Tooltip help is available when you pause the pointing device over one of the toolbar icons. Icon Tooltip Connect (Authenticate) Description Links to the Smartcard Reader dialog box, in which you identify the reader into which the Gemalto .NET Card is inserted. Invokes the authentication method of the current Access Manager on the card. (The tooltip associated with the icon is defined by the current Access Manager; for example, the tooltip might be "Log on".) Refreshes the information displayed in the active Card Explorer tab. Enables access management (for example, user access) according to the rules specified by the current Access Manager on the card. (The tooltip associated with the icon is defined by the current Access Manager; for example, the tooltip might be "Add/Remove Users".) When the Card Explorer is in VisualStudio.NET add-in mode, executes the build file for the current project. When the Card Explorer is run as a standalone application, displays a Select Build File dialog box, and then executes the selected build file. Links to the Smartcard.NET help documentation. Launches your web browser and links to the Gemalto User Discussion Forums home page. (www.flexforum.com/cgibin/dcforum/dcboard.cgi)
Run NAnt
47
See Explorer Tab for more information about the elements on the Explorer tab.
48
The Services tab provides a view of services running on the Gemalto .NET Card, and provides features to manage services.
See Services Tab for more information about the elements on the Services tab. This is the bottom bar of the Card Explorer window:
The following information is displayed in the three fields in the bottom bar: Current reader (Gemalto Reflex USB V3 0) Information pertaining to the current Access Manager, for example, the name of the current user. Free space on the card in bytes (92952)
The bottom bar information is always displayed, regardless of which tab is active.
49
After clicking Details, you have the following options: Element Reader name Description Select the name of the reader in which the Gemalto .NET Card is inserted.
PreSelected Readers
Select this check box to cause the application to attempt to find a card containing the service that the application is requesting. If the service is available on an attached card, the application connects to the card without user intervention. (Otherwise, if the service is not located on the card, the Select Smartcard Reader dialog box displays.) Select this check box to save the selections you just made.
Remember Settings
50
In the Explorer tab, when an element in the display is selected, a context-sensitive menu specific to that element becomes available. If you are using a mouse, this menu is available when you right-click a displayed element. These are the context-sensitive menu options available for elements on the Explorer tab. Note: All menu options are visible to all users, but a menu option can be invoked only if the user's permissions allow the action on the selected element. Card Element Type Card Menu Option Restart Memory Mapping Properties Volume/Drive Directory/Folder New Folder Delete New Folder Load File Description Equivalent of removing and then re-inserting the card Blue designates bytes currently allocated; white designates free memory in EEPROM on the card. See Card Element Properties for details. Add a new folder to the selected directory. Remove the selected folder from the card. Add a new folder to the selected folder. Load a new file to the card. See Loading a File to the
51
Card for details. Properties Executable (.exe) Execute Delete Properties Library (.dll) or other nonexecutable file (e.g., xml file) Delete View Content Properties See Card Element Properties for details. Run the selected executable file. Remove the selected file from the card. See Card Element Properties for details. Remove the selected file from the card. Opens the file in the application configured for the file type on the machine. See Card Element Properties for details.
The Services tab displays a list of services currently running on the card. By default, each card includes the following two services: Service ContentManagerM (C:\System\SmartCard.dll) SampleAccessManager (C:\Gemalto\SampleAccessManager.exe) Description Card Manager service Note that the SampleAccessManager service is marked with an asterisk. This denotes that 52
SampleAccessManager is the default Access Manager for the card. The card can also contain additional services, for example, an alternative Access Manager. Each time you instantiate a service on the card, the display changes to list the new service on the Services tab. If you right-click the name of a service listed in the Services tab, some services display one or both of the following options: Menu Option Set as Access Manager Delete Description See Access Manager for more information about this option. Deletes a service. If you select a service and your permissions allow you access to the folder in which the application is located, the service is deleted. Note that this does not delete the server application from the card; if you want to re-instantiate the service, go to the Explorer tab, and either double-click the .exe or right-click the .exe, and select Execute.
The Card Manager and active Access Manager services display no options. These services cannot be deleted from the card.
53
If you click Properties, a Properties sheet specific to the card element type is displayed. The ability to view information is based on permissions for the logged on user. Each label is always displayed, but if permissions for the current user do not allow access to the information, the details are not visible. Following are the property details that are displayed for each card element type.
54
These are the elements on the General tab for the card object. Property Product Common Language Runtime Operating System Description Name, version, and vendor information about the .NET Smart Card Framework, taken from the cardconfig.xml file on the card. Name, version, and vendor information about the CLR on the card, taken from the cardconfig.xml file on the card. Name, version, and vendor information about the card's operating system, taken from the cardconfig.xml file on the card. Vendor, version, and serial number of the chip, taken from the cardconfig.xml file on the card.
Hardware
55
These are the elements on the Advanced tab for the card object: Property Maximum connection speed (bps) Description Admin only may set this value. The list of allowable values is taken from the cardconfig.xml file. Typically, this value is set to the maximum speed at which negotiation between the card and the reader driver is successful. If the card and the reader are having trouble negotiating at this speed, selecting a different maximum connection speed is sometimes useful. Set as a percentage. Setting a slower chip speed results in slower card transactions. Taken from the cardconfig.xml file.
56
These are the elements on the General tab for the folder object: Property Type Location Size Public Key Token Description For example, Directory, Executable Assembly, Library Assembly, XML Document, Text Document. File path to the object on the card. Size of the object in bytes. Each assembly (.exe or .dll) has an associated public key token. See Public Key Tokens for more information. For other objects (folders and non-assembly files), this field is blank. Public (any application may access the folder or file) or Not Public (only applications identified by one of the public key tokens listed on the Security tab may access the folder or file). If checked, the file is read-only. If checked, the properties for the object cannot be changed (for example, in the Security tab, no public key tokens may be added to the list).
File Access
Read-Only Un-Editable
57
This is the Security tab for a folder/directory (properties are the same for a file on the card):
These are the elements on the Security tab for the folder object: Property Public Key Tokens Description For folders: the public key tokens for applications that are currently permitted to write files to the selected folder. For executables: the public key tokens for applications that are permitted to execute the selected application. For libraries: the public key tokens for applications that are permitted to access the selected library. For other files: the public key tokens for applications that are permitted to write to the selected file. Add a new public key token to the list by selecting an assembly (an .exe or .dll file) from the list (the public key token for the selected assembly is added to the list). Remove the selected public key token from the list. A list of the permissions associated with the public key token. The type of permissions listed depends on the type of file being examined. To change the permissions associated with the public key token.
Add
Remove Permissions
Modify
58
The Share with... dialog allows you to add a public key token to the public key token list on the Security tab. There are three basic sources of public key tokens: Using the public key token from an assembly that is already on the card Using the public key token from an assembly that is off the card (selecting this option will allow you to browse for the assembly). Entering a new 8-byte hexadecimal key token.
You can also use this dialog to select the permissions associated with the assembly.
59
The following tables show the types of permissions that can be set for different types of files. The following permission types apply to an assembly: Permission Execute Manage Description Whether or not the assembly can be executed. Whether or not the public key token has permission to change the security parameters of the assembly.
The following permission types apply to a folder: Permission Add Delete Enumerate Manage Description Whether or not the public key token can add files to the folder. Whether or not the public key token can delete files from the folder. Whether or not the public key token can list the files in the folder. Whether or not the public key token can change the security parameters of the folder.
The following permissions apply to a non-assembly file: Permission Read Write Manage Description Whether or not the public key token can read from the file. Whether or not the public key token can write to the file. Whether or not the public key token can change the security parameters of the file.
match the Public Key Token list on the Security tab for the object. This is true whether the access needed is to run an executable, access a library, or write to a file. In addition, this mechanism controls whether assemblies or files may be loaded to a selected folder on the card. (User access is set at the folder level, so constraining placement of uploaded assemblies or files to a particular location enables this access enforcement mechanism to work as intended.) The Security tab's Public Key Token list can be modified as needed, using the Add, New, and Remove buttons described above.
5.5.1.1 Delete
When you right-click any folder on the card, the menu choice Delete is available. If you click Delete, a Confirm Folder Delete message asks you to confirm that you want to delete the folder. If you click Yes and your permissions allow you to access the selected folder, the folder is deleted from the card. Note that you cannot delete a folder that is not empty.
Both assemblies (.exe and .dll files) and data files can be loaded on the card. Navigate to the file you want to add to the card, and click Open. If the Access Manager allows the operation and if there is room on the card, the operation succeeds.
5.5.1.4 Properties
When you right-click any folder on the card, a menu option to view Properties is available. See Card Element Properties for information about the properties associated with folders.
62
5.5.2.1 Execute
When you right-click any executable file on the card, the menu option Execute is available. If you click Execute and your permissions allow you to access the selected file, the file is executed.
5.5.2.2 Delete
When you right-click any file on the card, a menu choice Delete is available. If you click Delete, a Confirm File Delete message asks you to confirm that you want to delete the object. If you click Yes and your permissions allow you to access the selected file, the file is deleted from the card. Note that you cannot delete an assembly that is hosting an active service. If the assembly hosts a service, you must first delete the service. See Services Tab for information about deleting a service.
5.5.2.4 Properties
When you right-click any file on the card, the menu option Properties is available. See Card Element Properties for information about the properties associated with files.
5.5.2.5 Restrictions
You are able to perform actions according to the permissions associated with your logon identity. For example, if you are logged on as a user guest, with permission for adding files only in the D:\Pub directory, you will be unable to add files in the C:\Gemalto directory, even if you follow the instructions correctly. 63
The CardExplorer add-in module is listed in the Available Add-ins column. Note that if additional add-in modules to Visual Studio .NET are installed and registered on your computer, your display will list those addins, in addition to the CardExplorer module.
64
Use the Add-in Manager to perform the following tasks: To unload the CardExplorer add-in, deselect the check box at the left of the add-in name, and then click OK. Note that unloading the add-in does not uninstall the software. To load the CardExplorer add-in, select the check box at the left of the add-in name, and then click OK. To specify that the CardExplorer add-in should be loaded at environment startup time, select the check box in the Startup column, and then click OK. It is recommended that you uncheck the command line option for the tool.
Note: The Command Line check box has no meaning. You can clear the check box if you wish. See the Visual Studio .NET help for additional information about using the Add-in Manager.
6.3 Templates
The .NET Smart Card Framework SDK provides templates that can be used to create applications for the Gemalto .NET Card. Depending on install-time selections, (see Installing the .NET Smart Card Framework SDK), you might have Visual C# templates, Visual Basic templates, or both installed on the machine. For each programming language, these templates are available: netCard Server (use this template to create a server project) netCard Client Console (use this template to create a client project)
65
When you start a project using the netCard Server template, application code and project files are automatically created as a starting point. See the Creating Your First Server Application walkthrough for instructions about using the template to create a simple server application, and for a list of files created by the template and at compile time.
66
When you start a project using the netCard Client Console template, application code and project files are automatically created as a starting point. See the Creating Your First Client Application walkthrough for instructions about using the template to create a simple client application, and for a list of files created by the template and at compile time.
67
7 Getting Started
The walkthroughs provide instructions and examples of applications written for specific purposes.
2. In the New Project dialog box, type in a name for the new solution and select a location for the solution's files, and then click OK.
68
The following solution directories and files are created at the location specified:
[solution_location]\SolutionName\ [solution_location]\SolutionName\SolutionName.sln [solution_location]\SolutionName\SolutionName.suo
In the Visual Studio .NET Solution Explorer, the Solution is displayed like this:
Solution 'SolutionName' (0 projects)
Type in a name for the new project and select a location for the project's files (by default, the project files are stored under the solution), and then click OK. The following project directories and files are created at the location specified in the New Project dialog box:
[project_location]\ProjectName\AssemblyInfo.cs
69
[project_location]\ProjectName\DummyKeyPair.snk [project_location]\ProjectName\MyServer.cs [project_location]\ProjectName\MyServices.cs [project_location]\ProjectName\nant.build [project_location]\ProjectName\ProjectName.csproj [project_location]\ProjectName\ProjectName.csproj.user [project_location]\ProjectName\Readme.txt [project_location]\ProjectName\bin\Debug\ [project_location]\ProjectName\obj\Debug\ [project_location]\ProjectName\obj\Debug\ProjectName.projdata [project_location]\ProjectName\obj\Debug\temp\ [project_location]\ProjectName\obj\Debug\TempPE
The DummyKeyPair.snk file is related to strong name signing. All applications added to the card must be signed. DummyKeyPair.snk is a key pair that you can use to test your application. Before you distribute your finished application, replace DummyKeyPair.snk with a specific, non-test key pair. In the Visual Studio .NET Solution Explorer, the server project is displayed like this:
ProjectName References mscorlib netCard System.Xml AssemblyInfo.cs MyServer.cs MyServices.cs nant.build Readme.txt
3. In Solution Explorer, double-click MyServer.cs to open the server application source code file.
using using using using System; System.Runtime.Remoting; System.Runtime.Remoting.Channels; SmartCard.Runtime.Remoting.Channels.APDU;
namespace Server { /// <summary> /// Summary description for MyServer. /// </summary> public class MyServer { /// <summary> /// specify the exposed remote object URI. /// </summary> private const string REMOTE_OBJECT_URI = "myServerUri"; /// <summary> /// Register the server onto the card. /// </summary> /// <returns></returns> public static int Main() { // Register the channel the server will be listening to. ChannelServices.RegisterChannel(new APDUServerChannel());
70
4. Make changes if you prefer, and save. 5. In Solution Explorer, double-click nant.build to open the build-time server configuration file. The nant.build file is the basis for the Run nant.build icon in the Card Explorer window. The directory property defines the directory in which the assembly will be uploaded, and the service name is the name of the service in your application.
<?xml version="1.0"?> <project name="netCardProject" default="build"> <target name="build" description="load and execute assembly"> <load file="bin\debug\netCard Server1.exe" todir="C:\Pub" execute="true" reload="true" serviceName="myServerUri"/> </target> </project>
Make changes to reflect any changes you made in the MyServer.cs file, and then save. Specifically, if you've updated the service name or executable name, you'll need to update these elements. More information about nant 6. Build the server application. See the Visual Studio .NET help for instructions about building an application. The following files are added to the project:
[project_location]\ProjectName\bin\Debug\ProjectName.exe [project_location]\ProjectName\bin\Debug\ProjectName.hive [project_location]\ProjectName\bin\Debug\ProjectName.hmap [project_location]\ProjectName\bin\Debug\ProjectName.pdb [project_location]\ProjectName\bin\Debug\stub\AssemblyInfoTemp.cs [project_location]\ProjectName\bin\Debug\stub\MyServices.cs [project_location]\ProjectName\bin\Debug\stub\ProjectName_stub.dll [project_location]\ProjectName\obj\Debug\ProjectName.exe [project_location]\ProjectName\obj\Debug\ProjectName.pdb
7.1.4 Debugging
The system log, D:\Pub\Console.log, helps in debugging applications. To enable this feature, include the System.Diagnostics namespace so that you have access to the Debug class. Strings logged to Debug.WriteLine() appear in the file after the program has executed. The logging feature is disabled if you compile the code in Release mode. Gemalto .NET v2/v2+ User Guide 71
You can also debug your card application by developing it in the .NET Framework on the host side first. This practice makes the host's debugging tools available.
72
2. In the New Project dialog box, type in a name for the new solution and select a location for the solution files, and then click OK. The following solution directories and files are created at the location specified:
[solution_location]\SolutionName\ [solution_location]\SolutionName\SolutionName.sln [solution_location]\SolutionName\SolutionName.sno
In the Visual Studio .NET Solution Explorer, the Solution is displayed like this: Solution 'SolutionName' (0 projects)
73
7.2.3 Creating a Client Application to Access a Service Running on a Gemalto .NET Card
1. In Solution Explorer, right-click the name of the solution and select Add > New Project. 2. In the New Project dialog box, click Visual C# Projects, and then click netCard Client Console.
Type in a name for the new project and select a location for the project files (by default, the project files are stored under the solution), and then click OK. The following project directories and files are created at the location specified in the New Project dialog box:
[project_location]\ProjectName\AssemblyInfo.cs [project_location]\ProjectName\MyClient.cs [project_location]\ProjectName\ProjectName.csproj [project_location]\ProjectName\ProjectName.csproj.user [project_location]\ProjectName\Readme.txt [project_location]\ProjectName\bin\Debug\ [project_location]\ProjectName\obj\Debug\ [project_location]\ProjectName\obj\Debug\ProjectName.projdata [project_location]\ProjectName\obj\Debug\temp\ [project_location]\ProjectName\obj\Debug\TempPE\
In the Visual Studio .NET Solution Explorer, the client project is displayed like this:
ProjectName References netCard.Runtime.Remoting
74
3. In Solution Explorer, double-click MyClient.cs to open the client application source file.
using using using using System; System.Runtime.Remoting; System.Runtime.Remoting.Channels; SmartCard.Runtime.Remoting.Channels.APDU;
// Make sure you add the reference to your server stub dll. // The stub file is automatically generated for you, under // [Server Project Output]\Stub). namespace Client { /// <summary> /// Summary description for MyClient. /// </summary> public class MyClient { private const string URL = "apdu://promptDialog/myServerUri"; public MyClient() { // Create proxy of server Server.MyServices myServices = new Server.MyServices(); // Example: invoke MyServiceExample. string result = myServices.MyServiceExample(); // and display the result on the console output. Console.WriteLine(result); } #region Main Method implementation public static void Main() { APDUClientChannel channel = new APDUClientChannel(); // register the communication channel ChannelServices.RegisterChannel(channel); // request access to server object RemotingConfiguration.RegisterWellKnownClientType(typeof (Server.MyServices), URL); new MyClient(); // unregister the communication channel ChannelServices.UnregisterChannel(channel); } #endregion } }
75
4. Make changes to reflect any changes you made in the server application source code file, and save. The sample code shows communication to the card using the APDU protocol using the PromptDialog mechanism, which means that the application will prompt the user to identify the reader in which the Gemalto .NET card is inserted. Two other alternatives are available: o SelfDiscover--an attempt is made to automatically select a reader in which a Gemalto .NET card is inserted; if a reader is not automatically selected, the user is prompted to identify the reader. SelfDiscoverNoPrompt--an attempt is made to automatically select a reader in which a Gemalto .NET card is inserted; if a reader is not selected, the user is not prompted to identify the reader, and an exception is thrown.
5. Before building the client application, you must create a link to the server application be referencing the *_stub.dll file created when the server was built. In Solution Explorer, right-click the client project's \ProjectName\References, and select Add Reference. In the Add Reference dialog box, in the .NET tab, click Browse, and then navigate to the server project's ProjectName\bin\Debug\ProjectName_stub.dll file, click Open in the Browse dialog box, and then click OK. The serverProjectName_stub.dll file is added to the project in the client project [project_location]\ProjectName\bin\Debug directory and in the Visual Studio .NET Solution Explorer Client Project References. 6. Build the client application. See the Visual Studio .NET help for instructions about building an application. The following files are added to the project:
[project_location]\ProjectName\bin\Debug\ProjectName.exe [project_location]\ProjectName\bin\Debug\ProjectName.pdb [project_location]\ProjectName\obj\Debug\ProjectName.exe [project_location]\ProjectName\obj\Debug\ProjectName.pdb
Note: If you will build a project including both a server application and a client application, set the client application project to be the startup project (right-click the client project and select Set as Setup Project).
77
3. In the New Project dialog box, make the following choices: o o In the Project Types pane, click Visual C# Projects. In the Templates pane, click Empty Project.
An example follows:
4. Enter a name for the project in the Name field, and click OK. 5. In the Microsoft Visual Studio window, click Project | Properties. 6. In the left pane of the Property Pages dialog box, click Configuration Properties. 7. Under Configuration Properties, click Advanced.
78
8. Change the value of Do not use Mscorlib to True as shown in the following example:
This action is required because you must use the version of Mscorlib provided with the .NET Framework SDK. The following steps discuss how to load the proper version of Mscorlib. 9. In the Property Pages dialog box, click OK. 10. In the Microsoft Visual Studio window, open the Solution Explorer if it is not already open. 11. In the Solution Explorer, right-click References. 12. From the pop-up menu, click Add Reference.
79
13. In the Add Reference dialog box, click .NET Smart Card Oncard mscorlib.dll, and click Select, as shown in the following example:
14. In the Add Reference dialog box, click OK. 15. Continue adding your classes to the project as normal.
80
Note that in the preceding example, /nodistlib instructs the compiler to not use the Microsoft mscorlib. The following switch instructs the compiler to instead use the version of mscorlib provided with the .NET Smart Card Framework SDK:
/r:"C:\Program Files\Gemalto\NET Smartcard Framework SDK\v1.1.201\Libraries\On Card\Framework Libraries\mscorlib.dll"
7.6.1 Steps
To build an application that runs properly in both TCP and APDU mode, you need to take the following steps:
to
81
using System; using System.Runtime.Remoting; using System.Runtime.Remoting.Channels; #if MICROSOFT using System.Runtime.Remoting.Channels.Tcp; #else using SmartCard.Runtime.Remoting.Channels.APDU; #endif
3. In your Main method, you need to add another conditional compile to set up either a Tcp or an APDU channel, so
ChannelServices.RegisterChannel(new APDUServerChannel());
becomes
#if MICROSOFT ChannelServices.RegisterChannel(new TcpServerChannel(2222)); #else ChannelServices.RegisterChannel(new APDUServerChannel()); #endif
4. When running in TCP mode, the server will shut down as soon as the Main method exits. We could avoid this problem by only running in debug mode and putting break points in, but an easier way to do this is to put a Console.ReadLine into the Main method before returning. So add:
#if MICROSOFT Console.ReadLine() #endif right before the return 0; line.
82
#if MICROSOFT TcpClientChannel channel = new TcpClientChannel(); #else APDUClientChannel channel = new APDUClientChannel(); #endif
7.6.4.2
1. In each project, undefine MICROSOFT in the preprocessor. 2. In the server project, under the Advanced tab of the Configuration Properties, you need to set "Do not use Mscorlib" to true. 3. In the references section of the server project, change references from the Microsoft libraries to the Gemalto on-card libraries. 4. In the references section of the client project, link to the server stub that is generated by the Gemalto .NET build process. 5. Compile both projects, and you can now load the server to the card.
83
8 Code Samples
The .NET Smart Card Framework SDK includes a rich set of developer guidelines: sample code, and hints and workarounds. After installation, the sample code can be found here:
[install_location]\[product version]\Samples\[sample name]
Be sure to check the Gemalto .NET Homepage for more examples. NOTE: The documentation provided here supersedes the documentation that was previously released in a Word document in the samples directory. Samples provided with the SDK Sample AudioStreamMP3 EncryptionSink SecureSession APDUAttribute Transactions Description Uses the Gemalto .NET Card to do streaming decoding of an MP3 file. Provides an implementation of an encryption sink on the card. Shows how to use sinks to set up a secure session on the card. Shows how to communicate with a .NET smart card application using both remoting and legacy APDU's Shows how transactions can be used to roll back changes in case of card removal or uncaught exceptions. Also shows the use of objects that are "out of transaction".
General Instructions The samples are shipped as VS.NET projects, and have not been compiled. Since the samples aren't compiled, the reference table in the client portion of the sample must usually be updated by hand. Take the following steps to build the projects: Build the server project. In the "References" folder, note the name of the stub link. Delete the reference. Add a new reference to the same stub, which will have been generated when you compiled the server project. You can find the stub file in the "stub" directory under the output directory for the server (debug or release). Compile the client project.
84
8.1.1 Description
The Gemalto .Net Card supports symmetric algorithms that can be used for encrypting/decrypting streams. In this example, we use these features to show audio playback when the card is decrypting data. The card is currently not fast enough to decrypt all the data; therefore, there are two configuration parameters. The first parameter is the block length to be read from the card. The second parameter is the frequency of encryption/decryption. So if the block length is set to 128 and the frequency is set to 20, this means every 20th block of 128 bytes is encrypted. This project uses a music library called Bass. This is not a free library, and if you want to use this in a commercial application, you have to go to www.un4seen.com to find the license terms. Important: The bass.dll library needs to be in your library search path (moving it to the same directory as the client executable would work fine).
8.1.2 Execution
Put the AppConfig.xml in D:\Pub\ and install the AudioServer.exe on the smart card. Now execute the MP3Client. After choosing the reader to use, you have to set the encrypt block and the block size values. The default values are to encrypt every 20th block of 128 bytes. If you click on the encrypt button, you should choose an MP3 file. The program then creates a file called FileName.mp3.enc where some of the blocks have been encrypted. You can now click the play button and choose the encrypted file to play it. You can also click the Run Tests button, which will ask you for an MP3 file, create the encrypted file and then proceed to play back the encrypted file automatically. Note: There is no example MP3 file distributed with this project. You will have to provide one yourself if you want to execute the sample. Also note that it will not play WMA files.
85
symmCryptoService = DES.Create(); symmCryptoService.IV = iv; symmCryptoService.Key = desKey; symmCryptoService.Padding = PaddingMode.None; symmCryptoService.Mode = CipherMode.ECB; decryptor = symmCryptoService.CreateDecryptor( desKey, symmCryptoService.IV); }
8.2.1 Description
This project creates both server and client encryption sinks, and uses these sinks to encrypt communication between the card and the PC. The card uses a configuration file to set up an encryption sink. It supports three different algorithms: DES, TripleDES, and Rijndael. The encryption sink is a formatter applied to the Remoting channel.
8.2.2 Execution
Load the AppConfig.xml into D:\Pub on the card, as well as the three files Deskey.bin, Rijndael.bin, and TripleDesKey.bin. Load and execute the ServerSink.exe. Now execute the client application. After the client has executed, you can look in the file D:\Pub\Console.log to see a log of the communication. You can modify the AppConfig.xml on the client and the server to use other algorithms than the default.
8.2.3 Discussion
This example shows an important use of the extensible .NET remoting architecture. On the server side, the EncryptionServerSink works to decrypt inbound traffic and encrypt outbound traffic. It does this by performing decryption and encryption in the ProcessMessage method. The cryptographic operations are performed directly on the inbound and outbound streams (see the EncryptionHelper class). The encryption algorithm and keys to use are passed to the constructor of EncryptionServerSink by the EncryptionServerSinkProvider, which obtains the algorithm and key when the service is set up in the Main method of Server.cs. On the client side, the EncryptionClientSink works to encrypt outbound traffic and decrypt inbound traffic. It does this by performing encryption and decryption in the ProcessMessage method. The encryption algorithm and keys to use are passed to the constructor of EncryptionClientSink by the EncryptionClientSinkProvider, which obtains the algorithm and key when the channel is set up in the Main method of Client.cs.
With the encryption sink, we create the sink and add it this way:
// Set up the encryption sink properties Hashtable properties = new Hashtable(); properties["algorithm"] = "Rijndael"
86
properties["keyfile"] = "D:\Pub\Rijndael.bin" IServerChannelSinkProvider newProvider = new EncryptionSinkProvider(properties, null); newProvider.Next = new APDUServerFormatterSinkProvider(); // Register the channel the server will be listening to ChannelServices.RegisterChannel(new APDUServerChannel(newProvider);
8.3.1 Description
SecureSession means that the data exchanged between a client and the on-card service should be encrypted using a symmetric key. The symmetric key is not shared between the on-card service and client application; rather, it is communicated by the client application securely to the service and is valid only for one session. "Session" here means the communication between a smart card and two resets. This symmetric key is called a "session key." The most interesting aspect of this sample is that it shows how to establish secure sessions using custom sinks. The encryption and decryption of exchanges between the on-card service and the client are delegated to the custom sink, instead of being handled within the application itself. This makes the code in service smaller, portable, and independent of any cryptographic algorithm being used. It is also envisioned that many client applications communicate with the on-card service at the same time using different session keys. This implies the on-card service needs to have one communication channel per client application (using the custom sink containing the session key generated by a given client). These channels should be created and registered dynamically at a port specified by the client application and should be unregistered at the end of the session. As mentioned above, the session key is not shared between the service and the client, and it is securely communicated by the client to the service. In order to ensure secure communication of the session key, the public key of the RSA key pair pertaining to the on-card service is used. The Client generates a key 16 bytes in length and encrypts it with the public key of the on-card service. The Service uses its private key to decrypt this session key. The exchange of the session key cannot occur on a secure channel, since the session key must be exchanged in order to create the secure channel itself. To accomplish the exchange, the service should have an APDUServerChannel listening at a specific port (port 46 in our sample) and should provide methods that should not be invoked over channels using the SecureSessionSink. At first, it would seem that APDUServerChannel listening on port 46 is an answer to the problem, but it actually results in a security flaw. People who understand the .NET remoting architecture should note that there is no explicit link between the transport channel and service. The system will not prevent the invocation of any service method on any channel in a given AppDomain. This shows that MyMethodOnSecureChannel() can be invoked on port 46, which does not have any security. To avoid the above-mentioned problem, APDUServerChannel at port 46 should also include a custom sink that has the sole purpose of marking when a remote method is invoked at the channel listening at port 46. This is done by setting a static Boolean variable accessible by the service. If a method such as MyMethodOnSecureChannel() is invoked over port 46, the Boolean variable is set to true and implementation of the MyMethodOnSecureChannel() method expects this flag to be false.
87
Here are the steps for establishing and communicating over a secure channel: 1. Client1 creates and registers an APDUClientChannel without a custom sink. 2. Client1 invokes the GetPublicKey() method of service at the APDUServerChannel listening on port 46. The remote method returns the public modulus and exponent. Client1 then imports the public key into an RSACryptoServiceProvider. 3. Client1 generates a random key (session key) 16 bytes in length. 4. Client1 encrypts the session key generated in step 2 and the PIN of the on-card service using the RSACryptoServiceProvider created in step 1. 5. Client1 invokes the EstablishSecureChannel() method of service at the APDUServerChannel listening on port 46. The arguments passed to this method are the port number (in this case, 7655) at which the newly created channel should listen, the encrypted pin, and the encrypted session key. 6. The EstablishSecureChannel() method in the card decrypts the PIN and session key using the private key. It validates if this PIN is correct. If it is, a new APDUServerChannel listening at the port number passed in the method call is created and registered with the custom sink called SessionSink. 7. Client1 creates and registers an APDUClientChannel with SessionSink using the session key generated in step 3. 8. Client1 invokes the MyMethodOnSecureChannel() method of service at the APDUServerChannel listening at port 7655. The data sent passes through the SecureSessionSink of the APDUClientChannel registered in step 7 and is encrypted with the session key generated in step 3. 9. The SessionSink of the APDUServerChannel listening at port 7655 receives the data and decrypts it with the session key it received in step 5. 10. The MyMethodOnSecureChannel() method is invoked, and it checks if the invocation was on a secure channel by checking the static Boolean flag. The method returns a string that passes through the SessionSink of the APDUServerChannel listening at port 7655 and is encrypted with the session key. 11. The SessionSink of the APDUClientChannel created in step 7 receives the returned data and decrypts it with the session key. These same steps will be repeated for any client that wants to communicate with the service. The APDUServerChannels with SessionSink are unregistered and destroyed on a reset (that is, the end of a smart card session).
88
ServerProcessing srvProc = _nextSink.ProcessMessage(sinkStack, requestMsg, requestHeaders, requestStream, out responseMsg, out responseHeaders, out responseStream); // returning status information return srvProc; } // EstablishSecureChannel method of Service (invoked on channel listening at port 46) public void EstablishSecureChannel(int port,byte[] pin,byte[] sessionKey) { if(!_onEstablisherChannel) throw new UnauthorizedAccessException("This method is to be called with channel having SessionEstablisherSink"); // Decrypt the pin and sessionKey first pin = _rsaProvider.Decrypt(pin,false); sessionKey = _rsaProvider.Decrypt(sessionKey,false); // Verify the PIN _myPIN.Verify(new String(cpin)); // Create and register the channel at the specified port and using SessionSink, // set up the SecureSink properties. Hashtable properties = new Hashtable(); properties["key"] = sessionKey; IServerChannelSinkProvider newProvider = new SessionSinkProvider(properties, null); newProvider.Next = new APDUServerFormatterSinkProvider(); APDUServerChannel channel = new APDUServerChannel(newProvider,port); ChannelServices.RegisterChannel(channel); } // ProcessMessage() method of SessionSink { // Decrypt the inbound message requestStream = EncryptionHelper.ProcessInboundStream(requestStream,"Rijndael",_sessionKey); // Mark that we are coming from SessionEstalisherSink MyService._onEstablisherChannel = false; ServerProcessing srvProc = _nextSink.ProcessMessage(sinkStack, requestMsg, requestHeaders, requestStream, out responseMsg, out responseHeaders, out responseStream); // Encrypt the outbound message responseStream = EncryptionHelper.ProcessOutboundStream(responseStream,"Rijndael",_sessionKey); // Return the status information return srvProc; } // MyMethodOnSecureChannel. public string MyMethodOnSecureChannel(byte[] param1) { // If we came through the channel listening at port, we throw an exception if(_onEstablisherChannel) throw new UnauthorizedAccessException("You cannot access MyMethodOnSecureChannel without SessionSink"); // Return data will be encrypted with the session key by SessionSink. return "This is fun"; } // Unregister all the channels on reset or power down private void OnReset(object sender, SessionEndedEventArgs e) { MyService._onEstablisherChannel = false; // On reset unregister the channels that were dynamically created and use SessionSink .... ... } // Client calls EstablishSecureChannel at port 46
89
{ APDUClientChannel channel = new APDUClientChannel("noprovider",null); ChannelServices.RegisterChannel(channel); // Connect to the service on the clear channel. MyService sessionEstablish = (MyService)Activator.GetObject(typeof(MyService),MYSERVICE_URI_1,"noprovider"); // This is the PIN that we share with the card byte[] pin = new byte[] {(byte)'f',(byte)'i',(byte)'r',(byte)'s',(byte)'t',(byte)'P',(byte)'i',(byte)'n'}; // Encrypt the pin and session key using the public key of the card byte [] encryptedPin = rsaProvider.Encrypt(pin, false); byte [] encryptedSessionKey = rsaProvider.Encrypt(sessionKey, false); // Now call the EstablishSecureChannel method of the card using the encrypted PIN // and session key. The card will set up an encrypted channel using the provided // session key. sessionEstablish.EstablishSecureChannel(7655, encryptedPin, encryptedSessionKey); } // Client calls MyMethodOnSecureChannel at 7655 { // Set up a Sink Provider with a SessionSink attached to it using the session key as // a parameter for creating the SessionSink. Hashtable properties = new Hashtable(); properties["key"] = sessionKey; IClientChannelSinkProvider provider = new APDUClientFormatterSinkProvider(); provider.Next = new SessionSinkProvider(properties); // Create and register a new channel using the sink provider that we've just created. channel = new APDUClientChannel("SessionSinkClient", provider); ChannelServices.RegisterChannel(channel); // Now make a call to get the service again, but this time using the new channel. // Note that we explicitly give the name of the channel as the third argument to // Activator.GetObject. MyService service = (MyService)Activator.GetObject(typeof(MyService),MYSERVICE_URI_2,"SessionSinkClient"); // The data being sent to and from the card on the secure channel is now encrypted // with the session key. Console.WriteLine(service.MyMethodOnSecureChannel(new byte[] { 1,2,3,4,5} )); }
8.4.1 Description
The remote methods of the server are decorated with the APDUAttribute, which allows the Gemalto .NET Card to support communication directly using traditional ISO 7816-4 APDUs. This is important if your application must be backwards-compatible with a terminal or device that does not support .NET remoting. The sample illustrates not only the APDUAttribute itself, but the use of the APDUException attribute, which allows you to translate .NET exceptions into ISO status words. Two clients are provided. One is a traditional .NET smart card client application that uses remoting to communicate with the card. The second is a C++ application that uses the Winscard API to send APDUs directly to the card.
90
8.4.2 Execution
Install the 'Gemalto.Samples.APDUAttribute.exe' on the card. You should try running both the CppClient and RemotingClient against the server.
8.5.1 Description
The service has two fields: field, which is an int, and tc, which is a TryCounter. It also has three methods. Each method increments both fields, and then throws an exception that is not caught on the card. The three methods illustrate the different behaviors when methods are or are not decorated with the Transaction attribute. In the methods decorated with the Transaction attribute, any changes made to the int are rolled back when the exception is thrown. The TryCounter, however, continues to increment, because the TryCounter is a special class that is not affected by Transactions. One of the methods (NestedTransaction) calls a method that is not explicitly under transaction in order to demonstrate that methods that are called by a method under transaction are also considered to be under transaction.
8.5.2 Execution
Install the Gemalto.Samples.TransactionSample.exe' on the card, and execute the client on the host. Gemalto .NET v2/v2+ User Guide 91
In the above sample, the field value will be reset to its original value when the ApplicationException is thrown, while the TryCounter will be incremented.
92
9 Client-Side Components
Some components in the .NET Smart Card Framework SDK reside on the client machine.
9.1 SmartCard_Stub
The SmartCard_Stub.dll contains stub declarations for the card's ContentManager service. You would link to the SmartCard_Stub when you want to access the ContentManager directly using remoting. The full description of the ContentManager service is provided in the .NET Card Framework API documentation.
Once you have added the SmartCard_Stub to your project, you can use remoting to connect to the ContentManager service that is preinstalled on the card. The .NET Smart Card SDK also supplies a client side wrapper for the ContentManager service called CardAccessor that creates its own remoting connection to the card.
93
9.2 SmartCard.Runtime
The SmartCard.Runtime.dll (which we'll refer to from now on as the Client runtime library) contains several items of interest to developers: It contains the client remoting framework to allow you to communicate with .NET smart card services using the standard .NET remoting architecture. It contains the CardAccessor class, which is a wrapper for the ContentManager service. It contains the definitions of the IAccessManagerClient interface, which you will need in order to build a custom access manager.
A brief overview of each of these is given here. However, the API for each of these is described in full in the .NET Smartcard Client API help file.
94
You will also need to link to Marshaller.lib and extend your Link path to:
[Install Directory]\[Install Version]\Libraries\Off Card\Marshaller
95
10 Troubleshooting
This section includes information to help solve problems encountered while developing Gemalto .NET Card applications.
96
Advanced .NET Remoting Common Language Infrastructure Annotated Standard .NET Framework Security
- END OF DOCUMENT -
97