+ All Categories
Home > Documents > Fault Attacks on Java Card - TU/ealexandria.tue.nl/extra2/afstversl/wsk-i/gadellaa2005.pdf ·...

Fault Attacks on Java Card - TU/ealexandria.tue.nl/extra2/afstversl/wsk-i/gadellaa2005.pdf ·...

Date post: 24-Mar-2018
Category:
Upload: trinhnhan
View: 214 times
Download: 1 times
Share this document with a friend
74
TECHNISCHE UNIVERSITEIT EINDHOVEN Department of Mathematics and Computing Science MASTER’S THESIS Fault Attacks on Java Card An overview of the vulnerabilities of Java Card enabled Smart Cards against fault attacks by K.O. Gadellaa Supervisors: dr. E.P. de Vink Eindhoven, August 2005
Transcript

TECHNISCHE UNIVERSITEIT EINDHOVENDepartment of Mathematics and Computing Science

MASTER’S THESIS

Fault Attacks on Java Card

An overview of the vulnerabilities of Java Card enabledSmart Cards against fault attacks

byK.O. Gadellaa

Supervisors:

dr. E.P. de Vink

Eindhoven, August 2005

Abstract

This thesis gives a wide overview of the problems of the Java Card technologyregarding fault attacks. It uses fault attacks on RSA as an example, and showshow RSA can be broken in various ways. It then gives an overview of thedifferent defense strategies against fault attacks, and how these are applicableagainst the various means of fault injection.

Preface

This document presents my master thesis for Technische Informatica at theEindhoven University of Technology. The research and work was done betweennovember 2004 and august 2005 within the Formal Methods group of the De-partment of Mathematics and Computer Science. My supervisor was Dr. Erikde Vink. Other members of the committee were Dr. Jerry den Hartog, and Dr.Rudolf Mak.

ii

Contents

1 Introduction 11.1 Goal definition . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11.2 Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2

2 Smart Cards 32.1 Smart Card technology . . . . . . . . . . . . . . . . . . . . . . . . 32.2 Writing programs which use Smart Cards . . . . . . . . . . . . . 42.3 Writing programs on Smart Cards . . . . . . . . . . . . . . . . . 5

2.3.1 Java Card . . . . . . . . . . . . . . . . . . . . . . . . . . . 52.3.2 MultOS . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9

2.4 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10

3 Weakness: Inducing Faults 113.1 Attacking the Application . . . . . . . . . . . . . . . . . . . . . . 12

3.1.1 Off-card Attacks . . . . . . . . . . . . . . . . . . . . . . . 133.1.2 Modifying the on-card code . . . . . . . . . . . . . . . . . 14

3.2 Attacking the Java Card Runtime Environment . . . . . . . . . . 143.2.1 Java Card Runtime Environment issues . . . . . . . . . . 14

3.3 Attacking the Smart Card Processor . . . . . . . . . . . . . . . . 153.3.1 Spike Attacks . . . . . . . . . . . . . . . . . . . . . . . . . 163.3.2 Glitch Attacks . . . . . . . . . . . . . . . . . . . . . . . . 163.3.3 Optical Attacks . . . . . . . . . . . . . . . . . . . . . . . . 163.3.4 Electromagnetic Perturbation Attacks . . . . . . . . . . . 16

3.4 Classification of different attacks . . . . . . . . . . . . . . . . . . 17

4 Using Faults: Fault Analysis 194.1 RSA . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194.2 Fault Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20

4.2.1 Fault Attack on RSA + CRT . . . . . . . . . . . . . . . . 204.2.2 Fault Attack on RSA with Squaring . . . . . . . . . . . . 21

4.3 Differential Fault Analysis . . . . . . . . . . . . . . . . . . . . . . 234.3.1 DFA attack on a simple signing protocol . . . . . . . . . . 234.3.2 A bit of both — A different attack . . . . . . . . . . . . . 24

4.4 How to use Fault Injection . . . . . . . . . . . . . . . . . . . . . . 244.4.1 Attacking the Application . . . . . . . . . . . . . . . . . . 254.4.2 Other methods . . . . . . . . . . . . . . . . . . . . . . . . 26

iii

5 Prevention and hardening 275.1 Hardware Measures . . . . . . . . . . . . . . . . . . . . . . . . . . 27

5.1.1 Passive protection . . . . . . . . . . . . . . . . . . . . . . 275.1.2 Active Protection . . . . . . . . . . . . . . . . . . . . . . . 28

5.2 Software Measures . . . . . . . . . . . . . . . . . . . . . . . . . . 285.2.1 Checking the outcome . . . . . . . . . . . . . . . . . . . . 285.2.2 Shamir’s countermeasure . . . . . . . . . . . . . . . . . . 29

5.3 Fault Cryptanalysis hardened algorithms . . . . . . . . . . . . . . 295.3.1 Threat Classification . . . . . . . . . . . . . . . . . . . . . 295.3.2 Infective Computation . . . . . . . . . . . . . . . . . . . . 30

5.4 Global Platform . . . . . . . . . . . . . . . . . . . . . . . . . . . 315.4.1 Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . 325.4.2 Additional Security . . . . . . . . . . . . . . . . . . . . . . 32

5.5 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 335.6 Quality of protection . . . . . . . . . . . . . . . . . . . . . . . . . 33

5.6.1 Software protection . . . . . . . . . . . . . . . . . . . . . . 345.6.2 Hardware Protection . . . . . . . . . . . . . . . . . . . . . 345.6.3 Hardened Algorithms . . . . . . . . . . . . . . . . . . . . 355.6.4 Global Platform . . . . . . . . . . . . . . . . . . . . . . . 35

6 Conclusion 366.1 Programming in Java Card . . . . . . . . . . . . . . . . . . . . . 366.2 Java Card Security . . . . . . . . . . . . . . . . . . . . . . . . . . 37

6.2.1 Open vs. closed source security . . . . . . . . . . . . . . . 376.2.2 Fault attack risk analysis . . . . . . . . . . . . . . . . . . 37

A Installing OCF and the Chipdrive 39A.1 Installing the chipdrive . . . . . . . . . . . . . . . . . . . . . . . . 39A.2 Getting OCF and using it . . . . . . . . . . . . . . . . . . . . . . 39

A.2.1 Error codes . . . . . . . . . . . . . . . . . . . . . . . . . . 40A.3 Communication between components . . . . . . . . . . . . . . . . 40

A.3.1 APDU’s . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40A.3.2 TLV’s . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41

A.4 Working with Smart Cards and OCF . . . . . . . . . . . . . . . . 42A.4.1 Communicating with the Smart Card . . . . . . . . . . . 42A.4.2 Implementation of the stock-broker example . . . . . . . . 43

B Installing Eclipse and the Java Card API 44B.1 Eclipse . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44B.2 JCOP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44B.3 Error codes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45

B.3.1 Error codes in Eclipse . . . . . . . . . . . . . . . . . . . . 45B.3.2 Debuggin JavaCard in Eclipse . . . . . . . . . . . . . . . . 45B.3.3 Error codes in the Simulation . . . . . . . . . . . . . . . . 46B.3.4 Error codes communicating with the on-card program . . 46

iv

C Java Card 47C.1 Working with Java Cards . . . . . . . . . . . . . . . . . . . . . . 47

C.1.1 On-card Applications . . . . . . . . . . . . . . . . . . . . 47C.1.2 Cash Pay . . . . . . . . . . . . . . . . . . . . . . . . . . . 48

C.2 Cash Pay Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49

D Implementation of fault attacks 50D.1 Implementation of DFA on RSA+CRT . . . . . . . . . . . . . . . 50D.2 Implementation of DFA on RSA with squaring . . . . . . . . . . 51D.3 Implementation of DFA on a simple signing protocol . . . . . . . 55D.4 Implementation of DFA on RSA by flipping bits . . . . . . . . . 56

E Java Card Bytecode Converter 58E.1 PHP code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58E.2 Sample . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62

E.2.1 Actual program . . . . . . . . . . . . . . . . . . . . . . . . 62E.2.2 output of method.cap . . . . . . . . . . . . . . . . . . . . 63

v

List of Tables

3.1 Characterization of the different forms of physical attacks . . . . 173.2 Overview of requirements and impact of attacks . . . . . . . . . . 18

5.1 Overview of different types of errors . . . . . . . . . . . . . . . . 305.2 Overview of the protection given by various defenses . . . . . . . 33

vi

List of Figures

2.1 Sample Smart Card . . . . . . . . . . . . . . . . . . . . . . . . . 42.2 Java Card Architecture . . . . . . . . . . . . . . . . . . . . . . . 72.3 MultOS Architecture . . . . . . . . . . . . . . . . . . . . . . . . . 10

3.1 layers on a Java Card enabled Smart Card . . . . . . . . . . . . . 123.2 Sample code which can circumvent the firewall . . . . . . . . . . 15

4.1 Exponentiation by squaring and multiplying . . . . . . . . . . . . 224.2 Sample simple RSA implementation . . . . . . . . . . . . . . . . 25

A.1 Schematic display of a Command APDU . . . . . . . . . . . . . . 41A.2 Schematic display of a Response APDU . . . . . . . . . . . . . . 41A.3 Sample code to get data from a smartcard . . . . . . . . . . . . . 42

C.1 Sample Java Card On-Card Application . . . . . . . . . . . . . . 48C.2 The Cash Pay protocol . . . . . . . . . . . . . . . . . . . . . . . . 49

vii

Chapter 1

Introduction

This chapter discusses the goals as were set out when starting this research, andthe structure of the document.

1.1 Goal definition

The goal of this project is to identify vulnerabilities of Java Card applicationswith respect to differential fault attacks. This concerns both the reconstructionof fault attacks reported in the literature, as well as the simulation of differentialfault attacks. The project results in a Master thesis and a demonstrator.

The planning of the project distinguishes five phases:

• Obtaining hands-on experience with the OCF Framework. Deliverable:working Internet Broker Demo (or similar).

• Getting acquainted with Java Card and the JCOP Toolset by implement-ing small Java Card programs. Deliverable: running generic purse appli-cation (or similar).

• Literature study on fault attacks, including differential fault attacks, electro-magnetic side-channels and fault injection, power glitching. Deliverable:discussion of fault attacks in general and description of fault attack vul-nerabilities of Smart Card in particular.

• Vulnerability analysis of Java Card applications regarding differential faultattacks based on the reconstruction of known fault attacks. Deliverable:report on the reconstruction and simulation of known fault attacks forJava Card.

• Identification and validation of countermeasures and robustness of JavaCard regarding differential fault attacks. Deliverable: report on possibili-ties for DFA hardening.

Apart from a discussion of the above issues the final report will include anoverview of the fault attacks that are relevant to Java Card and the implicationsthereof for the Java Card platform. Also a demonstrator or simulation will bebuilt that illustrates the fault attack vulnerabilities discussed. Java Cards, andfault analysis, and a discussion whether it is actually viable to do fault injectionon a Java Card will be presented

1

1.2 Structure

To apply to the stated goals, this document document is set up as follows:First, in chapter 2, an introduction to Smart Cards is given which flows into thegeneral principles of programming software which uses a Smart Card, and theninto programming software which can reside on a Smart Card. From there, itdiscusses the vulnerabilities Java Cards have with respect to fault injection inchapter 3, and then shows a few practical fault attacks on RSA in chapter 4.The next chapter then discusses the countermeasures and their quality, and thedocument finishes with a small chapter in which the experiences with Java Cardare discussed, and the security of Java Card.

2

Chapter 2

Smart Cards

Smart Cards are said to be used for new, advanced appliances. Everyone shouldhave one, it is said. This chapter digs into what Smart Cards essentially are,how they function, how it is possible to program applications using them, andwhat options exist for writing applications which can run on Smart Cards.

2.1 Smart Card technology

A Smart Card is a chip put on a piece of plastic. At first these were only“memory cards”, holding only data, but with the ongoing miniaturization ofelectronic devices they quickly matured into small computers. Although devel-oped and patented in 1970, even nowadays Smart Cards have limited capability.For example, some 25 years later, Smart Cards still only worked at 3 MegaHerz,and had 4 KiloBytes of memory. Around 2000, this had risen to 50 MegaHerzand 500 KiloBytes. Compare that to the personal computer which ran at 1000MegaHerz at that time and it is clear that these machines are working on adifferent scale then normal personal computers.

As a portable computer, these Smart Cards can have a multitude of appli-cations. And since they are designed to withstand tampering, they can be usedas a secure token (similar to a key, but then digital), or as a signing mechanism,similar to a (digital) seal like an autograph. They are thus used in authenti-cating a person, authorizing access to places, authorizing payments, and also astemporary means to do these things (“you only have access x times”, ticketingpurposes, etc.). Of course, Smart Cards have been around for a while and mostpeople have seen (or have) one. A large number of creditcards and bankcardshave one. European SIM cards, used in mobile cellphones, are Smart Cards. Alot of Smart Cards are used for authentication, replacing the magnetic “sweep-through” card by simply holding it in or near a digital lock. All of these areexamples of Smart Cards used in today’s society.

Typically, the computer on a Smart Card itself is very small and the chiphas a recognizable, gold-colored area which is shown in figure 2.1. This goldarea is actually the entire chip.

To (physically) connect to the chip, there is some terminal or Card HolderDevice, which is the device which actually connects to the Smart Card. Anycommunication with the Smart Card by a program thus first needs to connect

3

Figure 2.1: Sample Smart Card

to the terminal, and from there have the terminal relay the data to the SmartCard.

Important to note is that the chips themselves do not necessarily have asingle uniform command set for the on-card instructions. Different cards havedifferent commands implemented, with different names, and in different ways.It is thus in a way similar to the early years of the PC, when there were amultitude of vendors, each with different chips.

2.2 Writing programs which use Smart Cards

The usual flow of information for a program which uses a Smart Card is fromprogram, to computer, to terminal, to Smart Card, to on-card application. Allof these steps require communication. Program to computer, and Smart Card toon-card application are not a programming issue as these are already available.And as the communication between terminal and Smart Card is standardized(by ISO7816), this section describes the communication between the Smart Cardand the terminal, and the terminal and the program, which can then be usedto write programs which use a Smart Card.

Initially, when writing a program which used a Smart Card, the first hitchto overcome was the terminal: there are a multitude of terminal vendors, andeach had different standards. Thus, programming for a Smart Card requiredfirst deciding which terminals would be supported. This lasted till 1997, whenthe PC/SC workgroup [8] (a consortium of terminal vendors led by Microsoft)set up the PC/SC standard. This standard then gave a universal interface forcommunication between the off-card program and the terminal.

The second hitch which programmers faced was the Smart Card itself: eachand every vendor sold different types of Smart Cards with different possibilities,and, moreover, different standards. This was amended as well by the OpenCardconsortium, which created the Open Card Framework, or OCF. This frameworkimplemented an intermediate communication layer between on-card applicationand off-card program to which card vendors could write plugins (services) defin-

4

ing the card applications which the card implemented, and also laid down a basicfilesystem, a means to access applications, and signature systems for signing,key creation and the import/export of the keys. Similarly, it also allowed ter-minal vendors to write plugins. A PC/SC compatible Terminal Service(plugin)was available from the start. Now writing a program which used a Smart Cardwas a lot easier — only a check whether the terminal was OCF or PC/SC com-patible, and using an OpenCard compatible Smart Card would ensure that theOpenCard Framework would work as a dependable platform to program on.

2.3 Writing programs on Smart Cards

Initially, Smart Cards were not “programmable”: only applications which wereadded by the card manufacturer could be used. No new application could beadded. Of course, this limitation was later overcome by having some means ofloading and executing arbitrary applications on Smart Cards, but then it meanthaving to program for a specific Smart Card. Programming for a Smart Cardwas similar to systems programming, i.e. it was processor-dependent. Thiswould mean programming for a single Smart Card Processor. It thus created adependency on the processor, which meant shutting out a host of Smart Cards,and possibly giving issues when supply of the specific Smart Card was a prob-lem. Enter two platforms: Java Card, and MultOS. Similar in architecture butdesigned by different groups, both delivered some sort of platform for whichapplications could be written. Smart Cards which were JavaCard or MultOScapable would then be a uniform platform; programming an application for JavaCard and any Java Card enabled device would suffice to execute the applicationon.

2.3.1 Java Card

Java Card is a type of Smart Card which supports a limited set of the JavaVirtual Machine. The idea is to be able to run Java bytecode on a Java Card.For an in-depth working on what a Java Card is, see [2]. Java Card brings all theadvantages of the Java runtime environment to the Smart Card, in particular:

portability The code is abstracted from any Smart Card-dependent features.

security The Java Runtime Environment ensures that the Java security modelis upheld.

development tools The on-card application can be developed in already knownenvironments for the Java language.

It is a very limited subset of the Java Runtime Environment, however. Inparticular, there are only a few features supported and quite a few which arenot, thus forcing optimization by the programmer:Supported:

• a few primitive data types: boolean, byte, short

• one dimensional arrays

• Java packages, classes, interfaces, and exceptions structure

5

• object oriented features: inheritance, virtual methods, overloading anddynamic object creation, access scope and binding rules

Optionally supported:

• the int datatype. For portability it thus depends if this is required. Dif-ferent cards may or may not support the int datatype.

• garbage collection and finalization

Unsupported:

• large primitive data types: long, double, float this means that any bigcalculation should not be done on the card, which is as it should be.

• characters and strings: as the card has no direct output it is not necessaryto work with strings, or characters. This, again, necessitates the use ofthese types to the off-card application.

• multidimensional arrays, for optimization purposes and keeping the in-struction set small,

• dynamic class loading, also for optimization purposes,

• threads, as Smart Cards are not multi-tasking,

• object serialization, as there are no threads, this is logical

• object cloning

• the security manager object, left out as the JCRE Firewall should giveadequate protection.

In particular, the above means that, if int is not supported, almost everycalculation should be cast to short’s (continually) as arithmetic calculationsare done in int’s (or 32-bit registers) . This is a bit of a fuss, as can be seenin the code example in Appendix C, where in figure C.1 on line 15, 16, and 20a typecast to short is done. Also, look at figure 4.2 where any use of numberliterals needs to be preceeded by typecasting to short.

A sample picture of the Java Card Architecture as presented by the devel-opers can be seen in figure 2.2. It shows applets being compartmentalized bythe firewall. These then use API’s added to the Smart Card by the vendor andthe Java Card Framework API. It all runs on the Java Card Virtual Machine.The Java Card Virtual machine then runs on the Java Card Open PlatformOperating System, thus creating a secure runtime environment. The Java CardRuntime Environment then runs the Smart Card. Also, it usually does not haveany filesystem, so as to ensure that data is kept inside the application only.

To have programs executed by the (embedded) Java Card Virtual Machinethe normal .class files need to be converted to .CAP (converted applet) files, sothey can be run through the bytecode interpreter. The converter optimizes thecode for the Smart Card in a number of ways:

• verifying that the load images of the classes are well-formed

• checking for Java card language violations

6

Figure 2.2: Java Card Architecture

• initializes static variables

• resolving symbolic references to classes, methods an fields to put them ina more conpact form for efficiency

• optimizing bytecode with the gained information by classloading and link-time

• allocating storage and creating data structures for classes.

After the converter is finished, it leaves a file in .cap file format for eachpackage.

.cap file format explained

The generic .cap file is actually a .jar file bundling of several .cap files (orcomponents) together. There are 12 components:

Header Component contains information of the entire package.

Directory Component contains the sizes of each of the components

Import Component describing the set of packages required for this package

Export Component contains a mapping from all public methods and fieldsto their concrete implementations

7

Method Component has the bytecode for each method in this .cap file.

Class Component has all the information for class checking.

Descriptor Component describes all variables so that they can be parsedand verified. It thus has the access flags(public, private, final, etc.)for all the variables in the package.

Static Field Component contains everything for static fields and initializa-tion procedures for classes.

Reference Location Component contains the relative offsets in theMethod.cap between calls by the Method.cap’s instructions (i.e. functioncalls) to items in the constant pool.

Constant Pool Component contains a mapping from every reference in theMethods Component to a class, method, or field (as appropriate).

Applet Component describing the applets in this package (if any)

Debug Component for helping out with debugging — normally this is notuploaded to the card.

As can be seen, the .cap file keeps different components, each with its sepa-rate function. Quite a few are interlinked with each other.

Next to creating a .cap file, the converter also creates an export file whichcontains the linking information. This is not needed for the execution of theprogram, though. It is only used as a header with linking information, to beused when linking files together. For example, when using a library from anotherpackage, the export file is necessary to complete the linking.

After the converter is finished, the .cap file can then be loaded on to theJava Card and after installation the application can be run on the JCRE.

The Java Card Runtime Environment Explained

The Java Card Runtime Environment is the environment which should ensurethat the code is executed appropriately, and any other command such as selectand deselect for the selection and deselection of applets are handled in sucha way that there is no room for malicious intent. To ensure that the context inwhich applets run are separate, it is required of the JCRE that it implementsthe isolation of applets . This means that one applet can not access the fieldsor objects of an applet in another context unless the other applet explicitlyprovides an interface for access. This is done in two steps:

The Applet Firewall ensures that all applets execute in isolation of eachother.

Object Access across Contexts Enabling is done to ensure that interop-erability between different applets is possible.

8

Applet Firewall

Every Java Card applet is run in a specific context. Its context is the package itis in. When an applet calls methods from other packets (or contexts), a contextswitch occurs and a Remote Method Invocation is done. In this way, all theapplets are “boxed in” and should not be able to interfere with each other. Asimple check for each instruction if it is within the correct context can thenensure that the firewall is upheld.

Object Sharing across Contexts

An object can only be accessed by its owning context, as the firewall preventsaccess by another applet in a different context. To have some means of passingdata from one applet to another there are three methods to have data betweencontexts. One, the JCRE Entry points, is for system communication, so eitherGlobal Arrays or Shareable Interfaces need to be used.

Global Arrays need to be defined by the vendor, and the only ones whichneed to be defined are the APDU buffer and the byte array input parameter tothe applet’s install method. Normally, no other Global Arrays are provided.

The Shareable Interface defines a set of shared interface methods. WhenApplet A wants to access a Shareable Interface Object from context B, it re-quests it from B. B then should have code to see if applet A is to be grantedpermission or not, and if so, the object is shared.

Lastly, as said, there are JCRE Entry Point Objects, and JCRE Privileges:The JCRE can invoke a method of any object on the card, and any “systemcall” is handled by a JCRE Entry Point Object which verifies if the the call tothe Object’s method is correct.

Tools

To use the Java Card platform efficiently, a number of tools are available. TheJava Card toolset provided by SUN includes the ability to convert .class filesto .cap files, and the programming API for Java Card, thus enabling simpleprograms to be created. For testing and programming, IBM has developed theJCOP toolset, which includes a terminal emulator, a Java Card emulator, andan easy way to upload applications to Java Cards. The IBM JCOP toolsetrequires the use of Eclipse (an open source development environment). For thesetup of these, see Appendix B.

2.3.2 MultOS

MultOS was the first multi-application Smart Card. Similarly to the Java Card,it has a virtual machine. However, where Java Card has as a virtual machine asubset of the Java Virtual Machine, MultOS has its own language, the MultOsEmulator Language, or MEL. MEL is similar to the Java bytecode in a sense thatboth are low-level, and are executed by a virtual machine (called the MultOSApplication Abstract Machine on a MultOS card). MultOS also has a filesystem,which is a subset of ISO7816, and keeps applications separate as well with somesort of firewall. More on MultOS can be found here [36]. However, the websiteitself seems not too well maintained from time to time as not all links workproperly.

9

The architecture for the MultOS card is similar to that of Java Card: again,applets are compartmentalized by a firewall. The applets run on a virtualmachine, which in turn runs on the Operating System which has the loadingcapabilities, and runs on the Smart Card.

Figure 2.3: MultOS Architecture

It can be seen that this architecture is very similar to the one for Java Cardpresented in figure 2.2.

Tools

Similar to the toolset for Java Card, MultOS has compilers (compiling C or Javato MEL), a MultOS simulator to simulate a MultOS Card, terminal simulatorto simulate a terminal with a MultOS card, and a loading facility to load Ap-plication Load Units, the format in which MultOS applications can be loadedon a MultOS compatible card.

2.4 Summary

We now have seen the technologies involved: what are Smart Cards, how doyou make programs using a Smart Card, and how do you program for a SmartCard. The next two chapters look at the weaknesses these Smart Cards have.

10

Chapter 3

Weakness: Inducing Faults

A Smart Card needs to protect against numerous things. Where a traditionalcomputer needs secure protocols to ensure that no data is leaked, a Smart Cardis a computer in a hostile environment. Similar to a safe, it needs to ensurethat no secret data can be learned by for example putting an ear to the safe andlistening what happens inside when you turn the lock. These so called “sidechannels” will not be discussed here.

Next to protocol attacks, Smart Cards add an extra dimension to protect:the computer needs to be physically safe from tampering. Again, comparingto a safe, it should not be possible to open the safe and look what’s insidethe safe. It has to withstand a number of techniques which directly attack theprocessor or its memory. For example, by freezing the chip so that it retainsits memory information and then reading memory somehow is something whichnormal PC’s not commonly have to protect against. Similarly, by placing avoltage meter on the memory bus, it might be possible to learn the value ofprivate keys whilst they are moved in memory. A Smart Card, however, is atthe mercy of its attacker if not properly protected.

However, it is also important that when an error occurs during the executionof the program, no program requirements are violated — i.e. no secret infor-mation is exposed, no permissions are unduly granted, etc. An attack requiringa fault to occur is called a fault attacks. Errors almost never occur naturally,as the program are usually rigorously tested and hardware is expected to be“perfect”. Because of this, programs are often not protected against errors. As-suming however that such an error exists, it needs to be controlled: when thereis a chance of one in a billion that a fault occurs, it might be infeasible for anattack to use the protocol until such an error occurs. For a Smart Card, how-ever, the computer can be in the hands of the attacker. The attacker could ofcourse try to inject a fault himself. A real-life example of this were “unloopers”,in which Smart Cards which granted access to pay-TV channels were injecteda fault so that a single branching statement was effected: instead of denyingaccess, the branch giving access was chosen [15].

Thus, this chapter looks into the means to inject a fault in a Java Cardapplet. To structure this, we model a Java Card enabled Smart Card as anumber of layers. The following figure gives a simple view of the three consideredlayers of the Java Card enabled Smart Card and are thus a bit of an abstractionof the picture in figure 2.2.

11

123

Application with protocolJava Card Runtime Environment

Smart Card Processor and architecture

Figure 3.1: layers on a Java Card enabled Smart Card

An attack on any of these layers might potentially create a malfunctioningSmart Card. We here thus discuss each of the three layers.

3.1 Attacking the Application

This section concerns the possibilities of injecting a fault through the applicationon itself. We first show how the security on the application level is handled.Any possible attacks due to interleaving should be handled by the JCRE.

A quick glance at Application code shows that code generated for Java Cardsgoes through a number of steps:

1. Conversion to .class files

2. Conversion to .cap files

3. loading onto the card

4. execution on the card

All of these depend on an amount of trust. The original files should be pro-grammed correctly, else the compilation to class files leaves untrustworthy code.Similarly, the class files should remain correct and unmodified when being con-verted to a cap file, and it should be exactly these files which are loaded ontothe card. These should then be the same files which are executed. Throughoutthis process, the files should remain trusted. To establish this are various meth-ods: signed certificates implying the trust of the one delivering the class or capfiles, conforming to GlobalPlatform standards (see also Chapter 5.4) for loadingcode onto the card securely, and lastly, hardware measures to ensure that theexecution of the code is tamperproof.

However, per the specification [19] it is not required to have any verificationon the .cap file during upload to assure it is of the proper format, as this could betoo heavy a task for a Smart Card (or any other Java Card enabled small device).It is suggested however, that at least some checking should be implemented.Assuming however that in some way a piece of (untrusted) code was uploadedto the card, the execution of the code could then only be performed on the cardwhen the card is running. When untrusted code is executed, however, it stillhas to pass the runtime checks done by the Java Card Runtime Environment.There are numerous papers describing runtime checking specifically for JavaCards [20, 21, 23, 22, 24], so it can be assumed that recent cards have suchchecking implemented even though this is not mandatory.

Even so, it is clear that there is a distinction between attacking the .classfile, the .cap file, or when it is actually ’on-card’. We assume that attackson a .class file are not very often to occur as these files are kept in a verytrusted environment. However, the .cap file needs to be uploaded in a possibly

12

hostile environment: during the upload it might be modified by modulating thecurrent, when using wireless Smart Cards the transmission might be disrupted,or, when receiving the file from an application provider or card issuer it canbe changed directly. We thus make a distinction between on-card attacks andoff-card attacks: the one modifies the installed file, the other the .cap file.Furthermore, when modifying the application to actually produce a fault, theattack is not transient: any further use of the program continues to behaveerroneously as the error persists. Yet when the ability is there to continuallyupload (correct) versions of the application, the problem can be circumventedby replacing the code. So the injected errors are not transient, but neither arethey persistent. We will thus call them semi-persistent.

3.1.1 Off-card Attacks

By manipulating (or introducing errors) into the file which contains the bytecodebefore it is uploaded to the card, a protocol can be circumvented or broken. Todo this, one needs both knowledge of the format of the file, knowledge of theprogram in question, and the ability to modify the file. The format is publiclyavailable (see also chapter 2.3.1). As can be seen from this is that the sizeof an individual component cannot change without also having to change thedictionary. Secondly, as a few components work with offsets of each other thismeans that changing one component can have side effects, meaning that largemodifications in one part can require modifications in the rest of the .cap file aswell.

Modifying the .cap file

The .cap file format does not enforce any encryption. It is thus possible tomodify the .cap file directly. This, then, can lead to incorrect code being exe-cuted on the Java Card. However, even simple checks can ensure that not a lotof modification is possible. Actually inserting code can only be done by bothinserting the code, and adjusting the rest of the .cap file so all the Componentsmatch correctly. This is thus more then a simple modification. Small modifica-tions are still possible, however. For example, a simple piece of code calculating4+5 can be easily modified to calculate 4/5, or 4+9, as long as the instructionsremain properly executable. Such small modifications have no impact on therest of the .cap file and can thus be done without any complication.

Other uses

In [25], a method is given to pinpoint specific function calls, by having knownoutput both before and after the call. By using these it is much easier to set upthe correct timing which is might be required for fault attacks. Thus modifyingthe .cap file allows an attacker to gain better knowledge as to when a transientfault should be injected.

Feasibility

It is noteworthy that modifying the .cap file requires very precise control. Thisthus means that the attack is harder to implement although, again, if it is

13

possible to re-load the application it becomes much easier as “trial and error”should do the trick.

3.1.2 Modifying the on-card code

As it is unspecified where exactly the code on the card resides this means thatwanting to modify the code includes having to have an entire memory mappingof the card. At least knowledge of how data is stored in memory and knowingwhere the applications resides are mandatory. If this is possible then probablymuch better attacks are suitable. Yet it can be assumed that the same attackscan be mounted as were done in 3.1.1 as the capabilities are similar; only themeans are slightly different depending upon how the JCRE is implemented.

3.2 Attacking the Java Card Runtime Environ-ment

This section concerns the Java Card Runtime Environment and the possibilitiesof using it to inject a fault. For a quick overview of the Java Card RuntimeEnvironment, see chapter 2.3.1.

3.2.1 Java Card Runtime Environment issues

This subsection gives some pointers to other articles in which issues with theJCRE are discussed.

The firewall

In [28] a means is given to modify an arbitrary piece of memory. It roughly goesas follows:

Assume a class A with a reference to class B. Now let there be a faultinjected in the reference in A, so instead of pointing to B, it points to anotherinstance of A. Now the static type checking is circumvented, and there is a typeflaw. To exploit this, consider the following piece of code in figure 3.2.

Now let there be an error in the reference to b1 such that it points to the(value) of the reference to b2 in a2. a2 now no longer has an exact reference tob2. It is now possible to access and write to any value in the memory by havinga1 define the offset, and a2 write the data by doing a1->ref b = value for theoffset, and similarly, a2->ref b = value for the value it should have.

This method has been tested on some JRE’s and found working. However,to work well on a JCRE, it requires a lot of memory as the easiest way to ensurethat such an exact fault occurs is by having the memory full of such structures,ensuring that there is a high chance of actually a faulty reference pointing tothe value of the reference to another class. To be able to aquire a lot of memoryit is thus only really viable if there is garbage collection available which is notrequired for Java Cards (as said, it is optional). It can then be used to modifythe memory, thereby circumventing the firewall and writing into the memory ofanother applet.

14

01 Class A{02 B ref_b;03 }0405 Class B {06 short val;07 }0809 a1 = new A();10 a2 = new A();11 b1 = new B();12 b2 = new B();13 a1->ref_b = b1;14 a2->ref_b = b2;

Figure 3.2: Sample code which can circumvent the firewall

Object Sharing

In [27] the Object Sharing across Contexts method is examined. It shows anumber of issues:

AID impersonation It is possible to create and upload an applet which hasthe exact same AID as an existing applet, thus making a mix-up of thetwo possible where the incorrect applet is used.

Access to all Interface Methods of a Class By having knowledge of theclass, it is possible to typecast and receive access to all interface methods,even if they are not granted access to. For example, if a class implementsdifferent interfaces, access to the class through one interface can then betypecast to get access to the other implementing interfaces.

Especially AID impersonation could be used to impersonate applications,thereby possibly using a user-uploaded version of applications instead of thosealready installed. This, then can break access to other applications as these useAID checks for access control.

3.3 Attacking the Smart Card Processor

This section discusses the various means to attack a Smart Card and its archi-tecture to inject a fault. All of the attacks below are hardware attacks, and assuch have not been actually performed. It was mostly retrieved from variousresearch articles, although [12] was the primary source. Some were performedin a controlled environment in [29], so they are not theoretical at all. Moreover,Smart Cards used by PayTV were regularly broken using fault attacks [26].

To get an idea of how faults can be introduced, this section gives an overviewof the various types of attacks. Attacks are also given some measure of “invasive-ness” indicating the amount of tampering necessary. Sometimes direct accessand contact with the chip is necessary. These are considered invasive. If nocontact or direct access is necessary, the attack is considered as non-invasive.

15

Similarly important is the amount of control available. Some attacks allowcomplete control where the fault injection happens whereas others do not.

3.3.1 Spike Attacks

By varying the power fed to the chip it is possible to disrupt a computation.In some cases, this can be enough to introduce a fault [15]. A power spike canvary in some 9 different variables, including height, shape, build up and powerdown, duration, etc. As a spike works by simply connecting to the power led tothe chip, they do not need direct access to the chip and are thus non-invasive.Equipment requirements are totally dependent on the type of the spike to begenerated, but are not necessarily expensive.

3.3.2 Glitch Attacks

Similar to spikes, it is sometimes possible to disturb the clock speed. For exam-ple, by doing an update cycle at double speed some instructions will be effectedwhere others are not, so it is possible that old data is used as the new datahasn’t arrived yet [14]. The introduced “glitch” can be used to influence condi-tional jumps(by not performing them, or performing them when it is unwanted,etc. [16]), a shift register shifts twice (instead of once), or not at all, etc. Ingeneral it is a wide class which can create a change in the program, and depend-ing on that change an attack can be mounted. Similar to Spike Attacks, Glitchattacks are thus noninvasive and do not require any expensive equipment.

3.3.3 Optical Attacks

By using focused light with specific wavelengths, it is possible to change theflipflops in a memory cell. By doing this it is thus possible to change or modifythe memory by using the photoelectric effect. These attacks require light tobe able to reach the chip, and thus that any protective coating needs to beremoved. However, as no contact is needed these attacks are generally seenas semi-invasive. As for equipment, in [17] it was shown that attacks can bedone relatively cheaply with simple equipment, and also that they can be veryprecise, effecting only a single bit. However, they need not be precise at all.

3.3.4 Electromagnetic Perturbation Attacks

By creating a strong electromagnetic source near memory the ions represent-ing the states in the memory are moved around, and thereby the memory isdisturbed. It is claimed in [18] that a so called “eddy current” can be createdusing an active coil with sufficient strength. This then gives a fine control ofexactly what bit needs to be controlled. With that claim also comes the claimthat it can be done relatively cheap. As this attack only requires to be near theprocessor, it need not be opened up as it can be done from outside. It is thus anon-invasive attack.

16

3.4 Classification of different attacks

To get some feeling for what the different types of attack can accomplish, theattacks are classified in the following categories:

Control : The amount of control the attack has on where exactly the faultoccurs

Fault : The fault model which it can produce. This can be either be:

bf : for Bit Flip model, in which a specific bit can be flipped,

saf : for Stuck at Fault model, in which (a number of) connections canbe permanently disabled,

bsr : for Bit Set and Reset model, in which a specific bit can be set orreset

random : indicating that it is unknown what happens but that somethingwent wrong

depending : for the different glitch attacks

#faults : indicating the number of faults generated by a single attempt.

The attacks then lead to table 3.1.

Attack Control Fault # faults.cap modification complete saf, bsr, bf as requiredon-card modification complete saf, bsr, bf as requiredFirewall circumvention random random randomSpike Attack none random randomGlitch Attack depends depends dependsOptical Attack complete bsr, bf as requiredEddy Current Attack complete saf, bsr, bf as required

Table 3.1: Characterization of the different forms of physical attacks

Both AID impersonation and the ability to access all interface methods tonot necessarily inject a fault in the program. It might cause inconsistency whichmight lead to knowledge being learned, however.

Next to seeing what can be accomplished by each different attack, it is alsoimportant to look at what the requirements are to inject a fault. In table 3.2 isa table specifying what requirements must be met to be able to implement theattack, and the type of fault produced: semi-persistent, transient, and in thecase of Firewall circumvention this is random as it is unknown what is modified— it could be code, but it could also be a variable.

17

Attack Requirements Type.cap file modification ability to modify specific bytes semi-persistent faults

access to .cap fileon-card modification ability to modify specific bytes semi-persistent faults

access to on-card memoryFirewall circumvention JCRE with problems random error in memory,

garbage collection although possibly very precisefault in object

Spike Attack ability to manipulate power transient faultGlitch Attack ability to modify clock speed transient faultOptical Attack unprotected access to the chip transient faultEddy Current Attack physical closeness to chip transient fault

Table 3.2: Overview of requirements and impact of attacks

18

Chapter 4

Using Faults: FaultAnalysis

This chapter looks into the possibilities an attacker has to retrieve secret datafrom the Smart Card. However, as this field is broad (ranging from readingmemory during runtime to Power Analysis), this chapter (and research) willonly relate to Fault Analysis, a means to get data from chips by having a chipmalfunction in some way. Quite a few of these have actually been tested inlaboratory conditions and found working as predicted [29], which shows thatFault Attacks are real and should not be dismissed as theoretical.

The way Fault Analysis works is often protocol related. For this, the researchdone was on RSA. Thus first a short introduction into the working of RSA isgiven, and then several examples of Fault Analysis.

4.1 RSA

RSA is a protocol devised in 1977 by Ronald Rivest, Adi Shamir, and LeonardAdleman in [10]. The protocol is an asymmetric key protocol, so there is aprivate and a public key, and any message encrypted with the private key canonly be decrypted with the public key (and any key encrypted with the publickey can only be decrypted with the private key). The structure between thesekeys is as follows:

1. Take two (large and relatively equal size) primes p and q, and let n = pq

2. Choose an encryption key e and a decryption key d such thated = 1 mod ((p− 1)(q − 1))

3. To encrypt a message m, the sender can now compute c = me (mod n).To decrypt a ciphertext c, the receiver computes cd mod n. Due to themathematical structure, this is then again the original message m.

For sufficient security p and q should be something like 2048 or more bits fornow [40]. This shows that the calculations for both encryption and decryptionare very slow and can take a long time. Thus typically two optimizations areused to speed up the exponentiation. Both of them can be used to do an effectivefault attack on RSA.

19

4.2 Fault Analysis

In 1996, three researchers at Bellcore labs [9] wrote about a method to retrieveinformation from protocols which should supposedly be secure. They did thisnot by attacking the way the protocol interacts, but by attacking the calcu-lations done by the protocol. This would be possible by having the protocolwork under conditions where a fault may be injected in the calculations for theprotocol (which later was found to indeed be possible). By doing this, vari-ous information can be learned which should stay hidden. All of their attacksassume the possibility to “flip” a bit: either from zero to one, or from one tozero, possibly with conditions such as “it only flips to zero if it is one. If it isnot, then nothing happens”. Depending on the attack, various assumptions arethen made on where this flip occurs. Fault Attacks in general rely on being ableto manipulate the program, either by modifying values (bits, or bytes), or bychanging the flow of the program (by making it skip certain instructions). Mostof the time these concern a certain specific variable at certain specific positionsin the protocol. Analyzing the returned value and knowledge of the fault canthen lead to knowledge of the (hidden) parts of the protocol. By doing so thestrength of the protocol is weakened to the point that it can be broken withoutconsiderable effort.

There are a number of fault attacks on RSA using Fault Analysis. In theoriginal article [9] two were given. These work on optimizations of the RSAprotocol. These will be given here, and were implemented for this thesis workon a Java Card. We thus first give an overview of the RSA protocol.

4.2.1 Fault Attack on RSA + CRT

By using the Chinese Remainder Theorem the calculation in RSA can be dividedin smaller calculations, as follows:S = xd (mod pq) is done by using

xd = CRT (S1, S2) (mod pq) where

S1 = xd = x(d mod (p−1)) (mod p), and

S2 = xd = x(d mod (q−1)) (mod q) accordingly.

The function CRT (α, β) can be defined as aα + bβ with a = 1 − p−1q p and

b = p−1q p

p−1q here is p under a field of size q, such that p · p−1 = 1 (mod q)

This thus roughly reduces the number of multiplications necessary for the ex-ponentiation. However, as this requires knowledge of both p and q, only theowner of the secret key can use this as both values are private knowledge of thekey which is not shared.

The described attack goes as follows: Assume the attacker can disturb thevalue of S1 before it is used to calculate S. Only S1 is affected, and S2 iscalculated correctly. Let S1 be the disturbed value of S1, and S similarly theincorrect value thus calculated for S. The following then holds: as a = 1 −p−1

q p = 0 (mod q), thus S = S (mod q), but S 6= S (mod p). Thus S− S =aS1 + bS2 − aS1 − bS2 = aS1 − aS1 = a(S − S). Yet, from a = 1 − p−1

q p = 0

20

(mod q) follows that a is a multiple of q, thus a = rq, so the Greatest CommonDivisor of S − S, N becomes:

GCD(S − S, N) = GCD(a(S1 − S1), pq) = GCD(qr(S1 − S1), qp) = q

By knowing q, the attacker can then easily construct p as N = pq, andthen calculate d as well (as this is similar to the original creation of the keys).This attack was then further refined [11] by noting that Se = x, and Se = x

(mod q). Thus then the entire line can be redone to see that GCD(x− Se, N) =q. Thus, to use this attack, it requires either a correctly signed message and afaulty signed message, or the original message and the faulty signed message.

4.2.2 Fault Attack on RSA with Squaring

Another way to speed up the multiplication process is by squaring and mul-tiplying. As m(a+b) = ma · mb, it thus follows that m can be exponentiatedas mr = m2a ·m2b ·m2c

. . ., so we see that the exponentiation can be writtenas a number of multiplications and squares of the original message, such thatma = ma mod 2r · ma−(a mod 2r). Now, let z = ma mod 2r

be the the invariant,initializing z for r = 0 means that z = ma mod 20

= ma mod 1 = m0 = 1. On anincrease of r by 1 it follows that:

ma mod 2r

= {r := r + 1}ma mod 2r+1

= {a mod br+1 = a mod br + br · (a/br mod b)}ma mod 2r+2r·(a/2r mod 2)

= {split off a mod 2r}ma mod 2r ·m2r·(a/2r mod 2)

= {split off cases}{

ma mod 2r

if a/2r mod 2 = 0ma mod 2r ·m2r

if a/2r mod 2 = 1

= {z = ma mod 2r

, define additional invariant y = m2r}{

z if a/2r mod 2 = 0z · y if a/2r mod 2 = 1

= {define a/2r mod 2 = ar, or the r’th least significant bit of a}{

z if ar = 0z · y if ar = 1

The initialization of additional invariant y = m20= m1 = m, and increase r

by one:

m2r

21

= {r := r + 1}

m2r+1

= {ab+1 = ab · a}m2r·2

= {a2b = ab2}

m2r2

= {definition of y = m2r}y2

In [9], it is assumed the following algorithm is used, where dk is the k’thsignificant bit of d, so d0 is the most significant bit, and dn−1 is the least signifi-cant bit of d. Invariants are z = ma mod 2r

and y = m2r

. This algorithm ensuresthat after iteration t the value of z = mr, with r being the t least significantbits of the private key d.

inity ← m; z ← 1.mainFor k = n− 1, . . . , 0.

if dk = 1 then z ← z · y (mod N)y ← y2 (mod N)

Output z.

Figure 4.1: Exponentiation by squaring and multiplying

The article then shows the following attack: assume that the attacker can mod-ify the value z at some point t in the calculation by flipping a single bit in z fromeither zero to one, or from one to zero. Define in the iteration t where the attackhappens the (correct) value of z as zt. zt is modified to z, such that z = zt±2b forsome value of b. Define u as the most significant bits of d which haven’t been usedyet in the calculation at the time of the attack, and v the ones which have, suchthat d is the concatenation of u and v, and define w = d−v. Then instead of pro-ducing the correct signed message S, the program now produces S = zmw. ThenS = md = mv+w = mvmw = ztm

w = (z ± 2b)mw = zmw ± 2bmw = S ± 2bmw.Thus, since Se = (md)e = m, it follows that m = (S ± 2bmw)e (of course, allmodulo N).

Now let the attacker encrypt a number of messages m containing arbitrarydata, thus giving the attacker a collection of tuples V =< m, S >. The attackercan now guess the values of w and b, using variable w′ and b′, starting at themost significant bits, by trying to find a message i such that mi = (Si±2b′mw′

i )e

(mod N) for some value of b. As there are only log2(N) options for b′, this canbe done straightforward. If this holds, then two cases exist:

1. v = w and the guess is correct

22

2. v 6= w and apparently b′ is guessed incorrectly such that 2b′mw′ = ±mw2b.The chance of this occurrence happening is dependent on b, as b has log2 Npossibilities to spread out correctly in N possibilities. As there’s a ±, thischance doubles to 2 log2 N/N . For large N of over 2000 bits such a chanceis very small indeed. But, assuming such an erroneous guess occurs, thiscan be detected with good probability as follows: let I be the numberof collected messages. Assuming the errors are distributed equally overall iterations P , then the chance that a specific fault injected an error inthis iteration is 1/P , and thus a chance of P − 1/P of being in anotheriteration. For all injected faults I, the chance that there is no messagein which an error occurred in iteration t is (P − 1/P )I . The chance thatno errors occurred in r (consecutive) iterations is thus (P − 1/P )Ir

. Sowhen r becomes too big (and thus too many bits have to be found in oneprogram run), we can assume that apparently the guessed w′ is wrong aswe would have expected to find a message fitting the requirements. Forexample, with P = 1000, I = 500, setting this limit to r = 20 (i.e. up to20 bits can be found at a time) means that the chance of actually having20 consecutive iterations without a fault be at 0.000045. By assuming thischance is small enough and doesn’t occur, we can then undo the previous(erroneous) guess, and redo the process from there on. In the case that itis actually the case that so many consecutive iterations do not have a faultthe program will not terminate. Stopping it and raising r , or collectingmore messages, should then ensure that it does terminate properly.

In either case, the message which was used to find w is no longer necessary:either it produces faulty guesses, or it is of no further use, so it can be removedfrom V .

4.3 Differential Fault Analysis

Another way to have information leak out of the protocol is by using DifferentialFault Analysis, or, the knowledge between a number of separately injected faults

4.3.1 DFA attack on a simple signing protocol

In [13], the following attack is sketched: assume that there can be faults injectedin the key itself by setting bits to zero, such that either one bit is set from one tozero, or none at all. For example, imagine there being gentle pressure each timeas an attack which can possibly deplete a bit so it becomes 0. Now, continuallyfeed messages to the signing instance. This then calculates mk. Then inject afault until mk changes value. This thus implies that one bit in k has flipped.Continue this till there are no more changes and collect all intermittently signedmessages Si. After a number of steps r no more changes occur, as it follows thatk is then equal to the bitstring consisting of only 0’s, and this can be verifiedthat this state is reached by comparing against m0. Now k can be reconstructedas follows: the last signed message was encrypted with the bitstring consistingof only 0’s. Then Sk−1 was encrypted with a bitstring which had one bit atnon-zero. If the key has length n, it thus means that this bit was in one of nlocations, and thus there are n possibilities to find a key matching this message.Simply try all of these possibilities until one of them compares to Sk−1. Then,

23

consider the Sk−2 — there are now n− 1 places for a bit to be non-zero. Again,try all these possibilities. By repeating the process, the key can be found.

4.3.2 A bit of both — A different attack

This section describes a slightly different attack which is inspired by the DFAattack on a simple signing protocol and the attack on squaring. This time,assume the attacker has the ability to possibly disrupt the calculation by mod-ifying the key temporarily in a single bit. For example, disrupting the readprocess of the key, or, when calculating in a similar squaring algorithm, havinga check whether a bit equals 1 fail. In general, we assume that a single bit isflipped in the key. We now show that it is possible to find out which bit wasflipped, and what its value was.

This attack was first mentioned in [30].

Calculation

Whatever the cause, the assumed effect is that instead of calculating S = mk,instead it produces S = mk±2t

for some t. It thus follows that

S = mk±2t

=

{mk+2t

if the bit was flipped from ’0’ to ’1’mk−2t

if the bit was flipped from ’1’ to ’0’

=

{S ·m2t

if the bit was flipped from ’0’ to ’1’S/m2t

if the bit was flipped from ’1’ to ’0’

Thus it is possible when both an original and a faulty sign are available to tryall n positions and see whether S ·m2t

= S (mod N) holds for some t. If so,then st, or the t’th bit in s, must be 0. Similarly, a check S/m2t

= S (mod N)can reveal a t showing st to be 1. This then reveals the value of a single bitof the key. By having multiple faulty signs, more bits can be exposed. Byhaving enough faulty signs the entire key can be retrieved. If not enough bitsare exposed, it even then can be used as a stepping stone for a brute force attackas a number of bits are already known.

4.4 How to use Fault Injection

This section shortly describes how the methods used to injecte faults in Chapter3 can generate faults for the three given attacks.

When examining issues for attacks, we will look with respect to the RSAalgorithm. As previously seen, there are some optimizations for the RSA al-gorithm. A sample working implementation can be seen in figure 4.2. Thisimplementation only works for keys up to 8 bits as Java Card does not neces-sarily support integers. It uses CRT for speedup, and square and multiply forthe exponentiation. It is code which can be run (and was tested on) a JavaCard

To do a Fault Attack on this, we aim to accomplish such a fault whichproduces an attack described in chapter 4.

24

1 private void multiplyCRT(byte[] input, short offset, short len,

2 short d1, short d2) {

3 for (short i = offset; i < offset + len; i++) {

4 short s1, s2;

5 jctools.Util.setShort(temp, (short) 0, d1);

6 temp[2] = input[i];

7 square_mult(temp, (short) 2, (short) 1, temp, (short) 0,

8 (short) 2, p);

9 s1 = temp[2];

10 jctools.Util.setShort(temp, (short) 0, d2);

11 temp[2] = input[i];

12 square_mult(temp, (short) 2, (short) 1, temp, (short) 0,

13 (short) 2, q);

14 s2 = temp[2];

15 input[i] = (byte) ((s1+((((s2-s1)*c2)%q)*p))% super.rsamod);

16 }

17

18 protected static void square_mult(byte[]input, short offset,

19 short inlen, byte[] nr,

20 short nroffset, short nrlen,

21 short mod) {

22 for (short i = offset; i < offset + inlen; i++) {

23 short c = (short) (nrlen + nroffset - 1);

24 byte t = nr[c]; //t = lowest byte

25 short z = 1;

26 short y = input[i];

27 short j = 0;

28 while (c >= 0) {

29 if( (t & (1 << (j - ( (nr.length - 1 - c) * 8)))) != 0)

30 z = (short) ( (z * y) % mod);

31 y = (short) ( (y * y) % mod);

32 if ( (j++) % 8 == 0) {

33 c--;

34 t = nr[c];

35 }

36 }

37 input[i] = (byte) z;

38 }

39 }

Figure 4.2: Sample simple RSA implementation

4.4.1 Attacking the Application

The .cap file can be modified in several places to inject a fault which can allowan attack to happen. For example, in the code in figure 4.2 at line 9, by savingthe wrong variable to s1, or in line 12, by changing the “-” into a “+”. In the.cap file this equals to changing the instruction with hexadecimal 0x41, saddto 0x43, ssub. It is thus equal to changing a single bit. This, then, leads toan attack by using the RSA+CRT method. However, this also ensures thatany encoding or decoding operation is done incorrectly from that point onward.Of further note is that it is not viable to attack the calculation of s1 or s2

25

separately by modifying the square mult method as it would then influenceboth s1 and s1. Yet even other methods exist. Instead of calculating with d1, amodification could be made so that instead it calculates with d2, thus producingan incorrect value for S2. As the actual value of S2 is irrelevant to the equation,as long as it is not correct, it is even possible to let the calculation occur withan incorrect m.

4.4.2 Other methods

All the other methods were not actually performed. They either required phys-ical tampering with the hardware, or were not immediately feasible. Even so,it is easy to see them actually perform.

26

Chapter 5

Prevention and hardening

This chapter concerns the actions which can be taken to either prevent or atleast make fault injection harder. There are three lines which will be discussedhere. One are hardware measures, which harden the ability to modify on-cardprograms and program flows. The second regards software measures, in whichsoftware is used to check for faults. Other software measures include ensuringthat no valuable information can be learned from injecting faults. Finally, itis possible by putting down standards that any other means of injection canbe prevented. For this, the Global Platform initiative is discussed which sets astandard and deals with the security of multi-application Smart Cards.

5.1 Hardware Measures

This section includes hardware measures which can be implemented by theindustry which provides tamperproof chips. This section is based on [29].

5.1.1 Passive protection

Passive protection encompasses protections that increase the difficulty of a suc-cessful attack.

random dummy cycles are a means to ensure that any side channels areharder to use as timing is disturbed by random garbage being injected.By having these dummy cycles at random a timed attack can not easilybe well-timed.

Bus and memory encryption to prevent laser or glitch targeting against aspecific memory cell. This is done by having a temporary key created uponpower-up and encrypting and decrypting data, and saving it at differentaddresses. Instead of saving it at address a, values are now stored inh(k, a), where h is a hash function. Thus data is continually kept in adifferent position and has different values in-memory.

Passive Shield is a full metal layer that covers sensitive chip parts. To doattacks with light or electromagnetic beams this shield then needs to beremoved first.

27

Unstable internal frequency generators can help by having the frequencyat which calculations are done are inherently unstable, thereby makingattacks which require synchronized states impossible.

5.1.2 Active Protection

Active protection encompasses mechanisms that check whether tampering oc-curs and take countermeasures (possibly by locking the card). A sample ofactive protection mechanisms are:

Light detectors to detect changes in the gradient of light against optical at-tacks,

Supply voltage detectors which can react to variations in the supply voltageand can ascertain that only a tolerable voltage is used to protect againstspike attacks,

Frequency detectors to ensure the operation speed is constant to protectagainst glitch attacks,

Active shields are similar to passive shields, but these have (unrelated) datapassing through them. When this data is modified, apparently there istampering going on and protection measures can be taken. This is evenbetter protection against electromagnetic beams as it is harder to remove,and putting an electromagnetic beam through it also disrupts the datapassing through the shield.

Hardware redundancy to recalculate a number of times, by splitting the cal-culation, using checksums, or or by doing the calculation in different waysand afterwards verifying the correctness. A myriad of options exist here,depending on the allowed performance hit and transistors used. Theseprotect against injected faults by trying to ensure that only meaningfuldata is output.

5.2 Software Measures

To protect the RSA algorithm it is also possible to use different or modifiedalgorithms to ensure that any fault injected into the algorithm is detected —either by having a module which checks the calculation and decides upon itscorrectness in some way, or ensuring that any injected fault can not easily beanalyzed such that private key information can be learned. This section concernsitself only with the possibilities of ensuring the correctness of the outcome (orensuring that faults are detected).

These method protect against fault analysis in general by ensuring that aninjected fault does not allow viable information to be learned.

5.2.1 Checking the outcome

Of course, an easy solution is to simply verify that the output matches the input.By decrypting the encrypted message the input should match the decryptedoutput. Then either an error is issued when the output doesn’t match, or the

28

calculation is done again. Possibly some tamper-resistant architecture ensuresthat after a number of failures, the card locks itself as it assumes there is actualexcessive tampering going on.

Many of the hardware redundancy measures can also be implemented insoftware. However, this might give another performance hit as parallelism isharder on the software level.

This method requires that not only the RSA calculation is done, but also adecryption. Although this means that theoretically the RSA calculation takestwice as long, it should be remembered that the public key usually is of asmall order thus ensuring that the calculation goes relatively quickly. It isnot odd to have a 16-bit public key and a 2000 bit private key, ensuring thatdecryption takes roughly a tenth of the time it takes to encrypt. However, forthe generic case this cannot be assumed and such solutions thus might suffer abig performance hit.

5.2.2 Shamir’s countermeasure

Richard Shamir offered and patented a measure to check whether an RSA cal-culation done with CRT is correct. A random integer r is selected and thefollowing two numbers are computed:

sp = md mod φ(pr) (mod pr)

sq = md mod φ(qr) (mod qr)

Where φ(n) is the Euler phi function. Then, if sp = sq (mod r) the calcula-tion can be considered error free, and the actual combination part of the CRTalgorithm can be done with sp and sq.

This method has a drawback. First, the chance that sp = sq (mod r) is1/r for any two numbers, and thus this still leaves the possibility of leaking thekey.

It is an example of a mix: an extra, different calculation is done to checkthe correctness of the original calculation. However, it is also possible to tryand ensure that no valuable information can be learned from disturbing thealgorithm all together. This is explored in the next section.

5.3 Fault Cryptanalysis hardened algorithms

Instead of trying to devise methods which ensure that no fault can take place,it is also possible to consider a defense on the algorithm side: assume thatit is possible to inject faults and try to have an algorithm in which no datacan be learned from this fact. When designing such defensive algorithms, it isimportant to have some idea of the capabilities an attacker has, as this influenceswhat the algorithm needs to protect against.

5.3.1 Threat Classification

To discuss algorithmic countermeasures, it is first nice to have some sort offramework of threats which the countermeasures protect against. This classifi-cation was first made in [33], and can be seen in table 5.1.

29

1 Precise Bit Errors The attacker has precise control on both timingand location, and knows the attacked bit as wellas its operation. Thus, a single bit can be effected.

2 Precise Byte Errors The attacker has precise control on timing, butlocation is loose. By assumption this effects nomore then a single byte.

3 Unknown Byte Errors Similar to Precise Byte Errors, but now timing isloose as well, which although there is knowledgeof which variable is targeted, it is in a small timeframe in which the variable is used and it is notclear at exactly which point the variable is modi-fied — it could be before a certain set instructions,during the execution of the set, or after it.

4 Unknown Byte Errors inUnknown Variables

Similar to Unknown Byte Errors, but now it isimpossible to target a specific variable and thusit is unknown which exact variable is modified.However, only one variable is modified.

5 Random Errors The attacker has only a loose timing and has onlythe ability to inject a fault which modifies anynumber of variables

Table 5.1: Overview of different types of errors

Comparing the categories with the physical means of fault injection fromChapter 3, an unprotected card could be under attacks of category one andtwo if Optical or Eddy Current attacks are used, where a spike attack wouldprobably be in category three, four, or five.

Furthermore, when having created a defensive algorithm, it is possible toconsider the computation and see what knowledge might be learned when acombination of faults under the assumed model are injected, thus leading to atleast a step-wise methodology to expose flaws.

5.3.2 Infective Computation

The primary reason the computation of RSA with CRT is vulnerable to theattack is because of the break-up in separate calculations. However, it is possibleto ensure that any injected fault propagates through the calculation in such away that no information is leaked. This is called infective computation and wasfirst described in [32]. Furthermore, infective computation tries to avoid anydecision making points as decisions can be manipulated as well by an attacker— the attacker could then attack the algorithm, and any checking of the validityof the outcome could be modified as well, ensuring that improper information isreleased. Attacks on branches are not uncommon and therefore are somethingwhich should be avoided.

The following algorithm from [32] depends on the equivalence which can beset up between variables in which one is expressed in the other.

1. Compute bkp = m/pc and bkq = m/qc2. Let there also be another key pair (er, dr) such that dr = d − r with r

30

relatively prime to n and er = d−1r (mod φ(n)).

3. Compute:sp = mdr mod φ(p) (mod p)

m1 = serp mod p + kp · p (mod q)

sq = mdr mod φ(q)1 (mod q)

4. And finally, compute:

m2 = serq mod q + kq·

s = CRT (sp, sq) ·mr2 mod n

Where CRT is the combinational algorithm for the Chinese RemainderTheorem.

This algorithm ensures that any modification to sp propagates through the entirecalculation, thereby making it impossible to use the attack described in chapter4.2.1. It works by splitting the calculation of md to mdr ·mr; md

r is calculatedthrough the usual CRT speedup, and m2 = m when no errors occur:

m2 = mder

r1 mod q + m/q =

m11 mod q + m/q = {similar for m1 to m}m

However, this algorithm puts an additional requirement on public/privatekey pairs, which can leave the keys vulnerable to simple “guessing” in an intel-ligent way, viz. small secret exponent attacks [31].

Other Algorithms

Other Algorithms have been proposed [33] and subsequently broken [35]. How-ever, the direction taken seems sound: ensure that the CRT Speedup is safe totampering by using a different number system. Although there is a performancehit compared to the speedup delivered by straight CRT, it is still quicker thena straightforward square-and-multiply algorithm.

5.4 Global Platform

As a final means to establish protection, the entire process of loading applica-tions on a Smart Card needs to be addressed. Next to that there are additionalsecurity issues which a multi-application Smart Card such as a Java Card hasto deal with. This section discusses the standardization of multi-applicationSmart Cards, as done in the Global Platform standard. By no means does itencompass the entire standard or delves into it too deeply as the standard itselfis somewhat complex.

31

5.4.1 Structure

The Global Platform, much like the Open Platform, is a consortium of cardvendors which aims to solve the issues with multi-application Smart Cards.This is done by formalizing the behavior of multi-application Smart Cards andby defining additional security constraints.

In Global Platform terms, there is a clear distinction in the different roles:there is a Card Holder — the actual user who has the card, a Card Issuer —the authority which issues the card and is essentially responsible for its security,and one or more Application Producers — which deliver the applications whichare used on the Smart Card.

To ensure security, the on-card representative of the Card Issuer is the CardManager, an application which provides an API to other applications, appli-cation selection and execution, and card content management. Furthermore, itcan provide services for Card Holder Verification, and is also a Security Domain.

Security Domains are on-card representatives of the application provider(or Controlling Authority). Security Domains support security services (keyhandling, encryption, decryption, signature, verification) for their owners appli-cations, and can authorize the loading of applications. It also governs the accessto applications — much like the Shareable interface from Chapter 2.3.1. EachSecurity Domain implements its own Secure Channel which can be used whenany off-card application wants to use an application managed by this SecurityDomain.

A Secure Channel can be anything from an encrypted communication witha specific key or no encryption at all — it is dependent upon the security theapplication requires. Both a Security Domain and an application can implementa Secure Channel: either the application has its own keyset, or it uses its SecurityDomain and let all communication go through there.

To check whether applications, security domains, and the actual card itselfshould be accessible, there is the notion of a Lifetime Cycle. Roughly it meansthat they can be in different states and when once a new state has been reached itis impossible to go to the previous state. The states themselves concern aroundinitialization, execution, and eventually, termination. If this is for the Card,then the card is no longer usable. If this is for an Application, it could meanthat the application is actually removed, or, if in ROM, is simply “disabled”.

Lifetime Cycles thus provide a quick and clear way to check for accessibility,and allow for a clear distinction between the different states.

5.4.2 Additional Security

To ensure data integrity, not only Secure Channels are available, but also theloading of applications is secured by also sending a hash of the data to checkintegrity. Installing an application thus starts with opening a secure channel,then transmitting the data and hashes, and finally, when the Security Domainconsiders the data valid and the hashes are correct, the data will be committedto (persistent) memory.

In short, the Global Platform ensures that applications remain separate andcannot interfere with each other’s execution (unless the Security Domain grantsaccess). Furthermore, it handles the loading and deletion of applications afterthe card is issued, and ensures that during this data integrity is kept. When

32

using Global Platform, it is thus not easy to modify the .cap file during trans-mission as described in Chapter 3.1.1.

5.5 Overview

We have now seen a selection of measures which can make fault attacks harder.For ease, table 5.2 gives a quick overview which defense mechanism works againstwhich attack.

Defense mechanism .cap

mod

ifica

tion

on-c

ard

mod

ifica

tion

Fir

ewal

lci

rcum

vent

ion

Spik

eA

ttac

k

Glit

chA

ttac

k

Opt

ical

Att

ack

Edd

yC

urre

ntA

ttac

k

RSA

wit

hfa

ult

Dummy cycles ± ± ± ±bus-memory encryption +passive shield + +unstable frequency generators ±light detectors +supply voltage detectors +frequency detectors +active shields + +recalculation related +Global Platform + + ±infective computing ± ± +

Table 5.2: Overview of the protection given by various defenses

“Recalculation related” encompasses both the hard- and software abilitiesto recalculate the computation and check for errors, as well as the solutionpresented by Shamir.

5.6 Quality of protection

This section gives a few points of thought on the quality of the protection. Toview the quality of protection however, we first have to put it into a frame-work. IBM made a general classification [37] often cited, as it gives a genericclassification of capabilities attackers can expect to have.

The attackers were classified in three groups depending upon their expectedcapabilities and attack strengths:

Class 1 (Clever outsiders): In this class are considered intelligent attackerswithout sufficient knowledge of the system who only use moderately so-phisticated equipment. These attackers usually try to take advantage ofthe weaknesses in a system rather then actually creating one.

33

Class 2 (Knowledgeble insiders): In this class are attackers who have hada substantially specialized technical education and/or experience. Theycan have quite sophisticated tools available for analysis.

Class 3 (Funded organizations): These are attackers which are able to ac-tually assemble teams of specialists (possibly themselves Class 2 attackers) with varying skills and are backed by great funding resources. These canthus design sophisticated attacks, and use the most sophisticated analysistools.

5.6.1 Software protection

Both the “software measures” and the “hardware redundancy” protection meth-ods have at some point to decide whether a computation is faulty or not. How-ever, these decision points are natural points of attack in the first place forattackers. A little bit of sophistication would first give an attack against thealgorithm, and then bypassing the decision point which should decide the (in-fected) computation was flawed. It is thus a defense which in itself is flawed.Class 2 attackers should be able to do this, and possibly Class 1 attackers aswell if the how becomes available to them.

5.6.2 Hardware Protection

Three things can be said about the quality of the Hardware Protection:

Shields

Both the Active and Passive shield can be removed with sufficient expertise andtime. Especially passive shields can be removed with some chemical processes.Of course, this does mean that it is clear that tampering has been going onwith the chip, and it might take quite some time. Thus Class 1 attackers mighthave problems with this if done properly. Class 2 attackers will have sufficientknowledge to at least be moderately successful in circumventing these.

Voltage Detectors

The problem with voltage detectors is that the spike can be modified in a largenumber of ways. Especially short and strong spikes might be over before it isdetected, whilst it could have done damage. For Class 2 and Class 3 attackers,it need not be adequate protection.

Dummy cycles and unstable frequency generators

It should be noted that these not so much disable attacks, but make them harderas the timing which some attacks require might be harder to do. Even so, whenthe gap is sufficiently wide (for example, when trying to attack RSA+CRT thereit is roughly half the calculation which is susceptible to even a single fault) itmight not give adequate protection.

34

5.6.3 Hardened Algorithms

Currently, the known algorithms have weaknesses themselves. Type 1 and 2errors are very hard if not impossible to defend against. If an attacker canmodify a single bit or byte then it is possible to do oracle attacks by simplysetting a bit to a fixed value and seeing if the result is modified. If not, thenapparently the guessed value of the bit or byte is correct (such an attack wasproposed in [34]; the attack given in 4.3.2 is also an example of this).

Furthermore, it is very hard to see all possibilities when examining a hard-ened algorithm. So even with the 5 classes of errors, it is still very hard todecide whether the algorithm actually protects against a certain class of errors.

But for sufficiently hardened algorithms, it means that considerable expertiseis required. It thus ranks in class 2 if not class 3 attackers.

5.6.4 Global Platform

No issues could be found within the Global Platform. It is something for furtherresearch — moreover as the standard itself seems to lack documents giving agood overview of the structure (as they instead dive into the technical require-ments).

35

Chapter 6

Conclusion

This chapter concludes the thesis and answers the remaining questions:

1. What are the experiences with programming in Java Card?

2. What is the security of the Java Card enabled Smart Card?

6.1 Programming in Java Card

Programming in Java Card is, simply said, horrible. If there is no garbagecollector available then Java Card is about the worst choice one can have froma language-feature point of view. However, considering that Java, and JavaCard, has as one of its strong points the inherent security it is not hard to seewhy Java Card is available. As is, Java Card is a subset of Java, but with someadditions in the the API. However, the pure subset is so limited that most Javaprograms will not work properly in Java Card without some (serious) rewriting.

Further more, it might be the case that because no garbage collection isavailable it would ensure that every object be well-considered to ensure that nobig calculations are done on data which is kept in EEPROM — reading andwriting permanently degrades EEPROM.

Overall, this causes a learning curve which is easily underestimated: it isproclaimed to be easy, yet there are quite a lot of hurdles — most importantlythe lack of garbage collection (it might be optional on the card, but having toprogram card-independent would mean working without), and the difficulty ofwriting applications which work both on- and off-card (for example, one mightwant to have one cryptographic module written which works on Java Card, andthen, as it works, also use it in the off-card program which connects to the JavaCard enabled Smart Card). Because of the differences in architecture (JCRE vsJRE), cross-architecture programming requires some thought and tricks. With-out garbage collection, the use of objects means that all objects must be static,which is not the (common) practice in Object-Oriented Programming.

36

6.2 Java Card Security

6.2.1 Open vs. closed source security

Normally, in security, everything but the key is out in the open. Kerckhoff’slaw (or Shannon’s Maxim) is the starting point in cryptosystems. However, inSmart Cards, the security of the Smart Card is not in the open. Anderson [38]claims that until as recently as 1995 (so 25 years after the first Smart Cards wereintroduced!) security of Smart Cards relied upon the small size, the obscurityof its design and the (relative) unavailability of tools with which chips could betested and probed. Even now often no indication is given with respect to theactual security measures incorporated into Smart Cards to prevent the host ofattacks an a Smart Card has to defend itself to function securely. It is surprisingthat the Smart Card industry has not developed some sort of standard similar toa safe [39], displaying the amount of time a Smart Card is resistant to tampering.Although this might be something when Smart Cards mature and the populacein general considers them to be similar to safes.

The consequence of the closedness of Smart Cards is that it is very hard totest Smart Card security and has thus been a mostly theoretical exercise thusfar.

6.2.2 Fault attack risk analysis

The major risk presented by Fault Analysis is the fact that even a single faultybit can expose the secret key. It is thus vital for Smart Cards that there is bothprotection against fault injection, and awareness in the community that thisprotection might be inadequate. As said before, under laboratory conditionsthese could be reproduced [29], and other fault attacks have been seen and usedby actual attackers [15], so it is not so much the question if fault attacks arepossible, but whether there is adequate protection to make them inviable.

To ensure that security is adequate, the following things are important:

1. Smart Card vendors should ensure that the cards have tamper evidenceto make it clear that tampering has been going on. This is especially truefor multi-application Smart Cards such as those with Java Card, as theseSmart Cards might not carry hardened algorithms.

2. Those employing Java Card enabled Smart Cards should be aware of theissues with Java Card, and should make use of Global Platform for theadditional security.

3. Java Card enabled Smart Cards should only be employed under the as-sumption that they can be compromised within sufficient time. Therethus should be a security policy in place to make clear that the SmartCard is simply a link: loss of Smart Card should be seen as possible lossof the key and thus loss of the Smart Card should not be disastrous forthe overall security of the system.

4. GlobalPlatform cards should be used as these are step forward for security

5. Protocols and applets should not be written assuming that nothing cango wrong. Infective computation is nice, but even using decision points

37

as extra checks is better then no check. As it is, the more security, thebetter.

38

Appendix A

Installing OCF and theChipdrive

In this appendix I show how to install OCF in windows environments, and touse the Towitoko chipdrive micro 130. The first thing to do is to install thechipdrive, then work on OCF.

A.1 Installing the chipdrive

The towitoko chipdrive needs drivers from the towitoko site.Go to http://www.towitoko.de, pick “download”, then “drivers”, and installthe towitoko chipdrive. Check if the diagnosis tools work, they should beinstalled under windows in “Start”, “Programs”, “SCM Microsystems CHIP-DRIVE tools”, “PCSCDiag”

A.2 Getting OCF and using it

Getting OCF is easy.

1. Go to http://www.opencard.org

2. Choose “download”

3. Download ”OpenCard Framework All-in-One”, which will download thefile installOCF.class

4. Run Java -classpath <saveddir> installOCF, where saveddir is thedirectory where it is saved. follow the instructions, and if using Windows2000 or XP, do not choose to setup an opencard.properties file as thischecks for the Microsoft Smart Card Base Components, something whichis automatically installed using Windows 2000 and XP. Installing thiswhen they are already available will give issues using the software.

5. (optionally) if not using Windows 2000 or XP, then you need to installthe Microsoft Smart Card Base Components. I found them at [5], but asearch on “Microsoft Smart Card Base” should lead you to the right pageas well.

39

6. Set up the opencard.properties file. For a sample PC/SC terminal (whichthe Towitoko driver conforms to) the following should suffice:

OpenCard.services = com.ibm.opencard.factory\MFCCardServiceFactory.opencard.opt.util.PassThruCardServiceFactory

OpenCard.terminals = com.ibm.opencard.terminal\pcsc10.Pcsc10CardTerminalFactory

OpenCard.trace = opencard:5"

7. (optionally) Check whether the demo examples work properly. Theseshould work without a hitch.

To use it, the appropriate classes need to be in your path. In JBuilder, this isaccomplished by adding the OCF directory as a required library for the project.

A.2.1 Error codes

There are multiple errors which can occur, both with installing OCF and usingOCF. A few common errors include:

properties file not found The properties file is not in the required direc-tories. It should be in the JAVA HOME directory, usually something like..Java/jre/lib

Exception, error code 8000xxxxx This is an exception raised during theruntime of the program. Most of the time these are from the PCSCenvironment. To know what the exception means, look inOCF DIR/OCF1.2/components/pcscwrapper/src/src/com.../ibm/opencard/terminal/pcsc10/natives/MSWin32/scarderr.hThis contains a listing of error codes and their meaning.

A.3 Communication between components

This section describes the communication between the Smart Card and theterminal, and the means commonly used for data transfer. Although physicalcommunication is done using electric pulses, this section will only detail in whichformat the data units need to be delivered.

A.3.1 APDU’s

Communication between the terminal and the Smart Card is done according toISO7816 with Application Package Data Units, or APDU’s. Command APDU’sare send to the card, which responds with Response APDU’s. Both have a fixedstructure. The Command APDU consists of a Header, which contains 4 bytes,in order:

1. CLA or Class byte, specifying the class of instruction of this command.

2. INS or Instruction byte, specifying the specific command.

3. P1 or Parameter 1, a byte for specific parameters to the command.

40

4. P2 or Parameter 2, also a byte for specific parameters to the command.

It then has a Body, constructed of:

1. LC or Length Byte, specifying the length(in bytes) of the optional datawhich is following.

2. Optional Data – anything that needs to be sent to the card.

3. LE or Length Expected, a byte specifying the length of the data to bereturned by the return command. If this is 0, then all data available tothe command is returned.

In total, a Command APDU thus looks like the following:

CLA INS P1 P2 LC Optional Data LE

Figure A.1: Schematic display of a Command APDU

The smart card can then decode the Command APDU, execute the com-mand, and return a Response APDU which consists of the following:

1. Optional Data: the data returned by the execution of the command. Thisshould be equal to the length specified in the LE byte.

2. SW1 or Status Word 1: A byte containing the status of the executionaccording to ISO7816-4

3. SW2 or Status Word 2: similar to Status Word 1.

Or, as a schematic:

Optional Data SW1 SW2

Figure A.2: Schematic display of a Response APDU

In case any errors occur during execution, the smart card is expected toanswer properly in the Status Words. For example, if an error occurred, thetype of error (if specified in ISO7816-4) should be specified in the returnedStatus Words, thus indicating that something went wrong.

A.3.2 TLV’s

To be able to send data, Tag-Length-Value structures are recommended. Theseconsist of a field which denotes the type (or Tag), the length of the value, andthe value itself. It is possible to have the value be constructed of multiple values,which themselves then should be TLV’s again to disable any ambiguity. Thus, asample TLV would be a triple (T,4,HELLO), where “T” is the indicator of thetype that follows is TEXT, “4” is the length of the type TEXT, and “HELLO”is the actual data, a 4-byte array of type TEXT.

41

A.4 Working with Smart Cards and OCF

This section describes on how to work with Smart Cards and OCF. First, ithas a subsection regarding how the communication with a Smart Card works.Second, it describes using this to implement the Stock-Broker example from [1,Chapter 12]

A.4.1 Communicating with the Smart Card

In Appendix A.2 the installation of OCF is discussed. Following this shouldlead to a trouble-free installation. Not following this can give a multitude ofproblems. Problems the writer encountered were OS issues (requiring a reinstallof the OS) and Java version collisions (leading to non operating installations).

Then, following [1] gives a nice introduction on how OCF works with SmartCards. The sample code can also be downloaded [6], but a short version is givenhere for reference as well in figure A.3.

1 try{

2 SmartCard.start();

3 CardRequest cr = new CardRequest(CardRequest.ANYCARD, null,

4 FileAccessCardService.class);

5 cr.setTimeout(10);

6 SmartCard sc = SmartCard.waitForCard(cr);

7 if(sc == null)

8 return; // no smartcard in time with required properties.

9 FileAccessCardService facs = (FileAccessCardService)

10 sc.getCardService( FileAccessCardService.class, true);

11 CardFile root = new CardFile(facs);

12 CardFile file = new CardFile(root,":c009");

13 try{

14 String entry=new String(facs.read(file.getPath(),0,

16 file.getLength() ));

17 System.out.println(entry.trim()); //trim the end.

18 } //end try

19 catch (CardServiceInvalidCredentialException cse){

20 //handle invalid password.

21 }// end of catch invalidpassword

22 } //end try main init

23 catch (Exception ex)

24 {//multitude of exceptions possible here }

Figure A.3: Sample code to get data from a smartcard

As can be seen, the actual program performs numerous steps. First, on line 2,it initializes OCF with the static call to Smartcard.start(). This initializationalso checks and tries to load software for communicating with a Terminal. Ifanything fails, it will throw appropriate exceptions. Then, a CardRequest iscreated, resembling the fact that we would like to have a card in the readerwhich has the FileAccessService implemented, and it is given a timeout of 10seconds. Following that, a concrete SmartCard object is created if the card wasinserted (or already in place) when we actually wait for a card which fullfillsthe request with the command Smartcard.waitForCard(cr). It is here that

42

the terminal is actually communicated with, and thus if it has any problems,the program will halt here (by throwing an exception). If the returned value isnot null (and thus an acceptable SmartCard was found), we continue to line9. From the SmartCard Object we try and get the FileAccessService which weknow it should have, and ask for its rootfile. Since the filesystem is hexadecimal,we ask for the file with name C0:09 which is located in the root directory. Wethen try to access the file, and since the file might be protected by password,this is done in a separate try...catch block. Finally, on line 16 after the fileis read, we then output it but first we remove any trailing spaces (as the filemight have been bigger, it is normal to pad the text with spaces at the end).

A.4.2 Implementation of the stock-broker example

The stock broker example is an application which signs stock orders whichcan then be sent over the internet without being (unrecognizably) tamperedwith. Sadly, with the given Smart Card (an IBM MFC) which was used thestockbroker example cannot be executed [1, page 214], as it misses the requiredcryptographic libraries. Since this functionality was not shipped with the card,it would mean that to be able to execute a similar example it would requireimplementing the missing functionality and “uploading” it to the card. As thiswould require knowledge of both the card itself and knowing how to uploadto this specific card, it was decided not to try to implement this functionality.Especially since the research should revolve around Java Card, and not an MFCcard. It was thus decided to not implement this example at all.

43

Appendix B

Installing Eclipse and theJava Card API

This chapter concerns the Eclipse programming environment, and how to set itup for use of the JCOP toolset. Actually programming with Java Card is shownin appendix C.

B.1 Eclipse

Eclipse is a freely distributable programming environment. It also has an exten-sion which allows the JCOP toolset be added for easy development of on-cardapplications. Eclipse can be downloaded from:http://www.eclipse.org but JCOP currently does not support eclipse 3.01 yet.It only works for Eclipse 2.1. So:

1. go to http://www.eclipse.org

2. choose “downloads”

3. choose a site regionally close for quick downloads (pick a http site!)

4. choose the 2.1.3 release

5. download the file “eclipse-SDK-2.1.3-win32.zip”, and unzip it to the di-rectory where you want eclipse to be

Eclipse should now work. For working in eclipse, please consult the variousdocuments online; [3, 4] are definitely worth looking into. Both can be found athttp://www.eclipse.org/eclipse/index.html

B.2 JCOP

JCOP toolset is the Java Card Open Platform Operating System Toolset, atoolset for creating on-card applications. It can be found at:http://www.zurich.ibm.com/Java Card.

The toolset is not free, though. Most useful is the JCOP Shell, which allowsboth easy communication, uploading, deleting etc. with Java Cards, as well as

44

allows testing on a virtual card. Other applications can then connect to theshell as if it were a terminal with a card inserted. To install the JCOP toolset:

1. Open eclipse

2. select the “Update Manager” from the “Help” menu

3. Create a new bookmark, with URLhttp://www.zurich.ibm.com/jcop/download/eclipse/

4. Expand the newly created bookmark to expose the JCOP Tools feature.

5. In the “Preview” view, click on Install. It will then install JCOP tools forEclipse

To be able to use the JCOP toolset, you need to register. Either put a CDin which registers (which, in my case, didn’t work), or point to an installeddirectory (which did work in my case. So then first install the “old” JCOPsoftware from the CD)

When all is installed, consult the help onhttp://www.zurich.ibm.com/jcop/download/eclipse/doc/index.html; Check the“Quick Start”, “Concepts” and “JCOP Shell”.

To let a program communicate with the JCOP simulation, ensure that thesimulation is running, and the shell is not connected. The connecting programshould use the RemoteJC terminal, or simply useTerminal.getInstance("Remote",null).

To connect to the card, use the PCSCJCTerminal or, again,Terminal.getInstance("PCSC",null) should work fine as well.

B.3 Error codes

B.3.1 Error codes in Eclipse

First, there are all sorts of error codes which can be thrown in Eclipse. Keep inmind that the Java Card subset of Java has different base classes and thus allsorts of methods may not work (for example, the Exception.getMessage().

Next to all the error codes created by the Java compiler (which should beknown to any Java programmer), an additional disadvantage of the way thingswork is if an error is caught by the converter. No real error message is given,only an error message of “” (i.e., nothing) can occur. Another error which Iencountered was “invalid local variable” which happened when an integer wasused and the program was being converted (although this is not always apparentthat the error lies in the converting). To solve other issues, I turned to the JavaCard forum [7] as a source of information as well as a forum to ask any questions.

B.3.2 Debuggin JavaCard in Eclipse

When running a simulation, the debugger will halt several times on “bad data”issues. Simply stepping over these should lead to a successful installation of theapplication on the simulator. From there on “normal” debugging ensues withbreakpoints and watches, etc.

45

B.3.3 Error codes in the Simulation

When running a simulation, the program is loaded automatically on the (sim-ulated) card. This may give errors as well. If the program did not compileproperly (and thus no .cap file was properly made) there should be errors inloading it. Another problem which can occur is after loading the applet, it willautomatically initialize the applet (and thus run the install method. Thiscreates an object of the chosen type and any errors with this will give 6a20 BadData as error.

B.3.4 Error codes communicating with the on-card pro-gram

Another error occurring frequently is “6F00”, which indicates that a runtimeerror occurred while executing the on-card program. This means that an ex-ception was thrown and was not caught. Debugging can be done by throwingexceptions with the ISOException.throwIt(<code>) which will return <code>as an error code so it is known where the error occurs, or by using the debuggerof Eclipse.

46

Appendix C

Java Card

This appendix has a small introduction on how to program an on-card appli-cation for a Java Card. For more information about Java Card, see Chapter2.3.1

C.1 Working with Java Cards

Java Card programs can be most easily created with the JCOP toolset andEclipse, a free, open source programming environment. For installation instruc-tions, see Appendix B. As said, to use programs the Java Card needs .cap files.The eclipse environment creates those automatically and allows easy testingwith the JCOP shell, thereby eliminating the need to do all the “converting” bycalling the commands manually, or uploading it to the card. Instead, it is putin the JCOP shell, which emulates Java Cards. This speeds up development,and also development can be done without any Java Card (or terminal) beingavailable.

C.1.1 On-card Applications

As the JCOP Toolset and the Java Card technology are mainly to allow easyaccess to programming on-card applications, we here give a quick rundown of asample applet for an on-card applet.

As can be seen in figure C.1, the program has two methods, both of which aremandatory. The first is an install method, which is called when the applet isinstalled on the Java Card. This method then initializes the object. The othermethod is the process method, which is called when this applet is selectedand when any APDU is sent to this applet. The process method thus handlesany data sent to the applet, which can be seen as it gets the buffer from thereceived APDU in line 8, and checks its instruction byte (which should be thereaccording to the ISO7816 specification of CAPDU’s from Appendix A.3.1). Incase it is the select statement self (0xb1) it doesn’t need to do anything. Inthe case that it matches our self-defined byte 0xff we get the length of thecommand, the expected return data, check if they are appropriate and if thecommand matches, and, if so, copy the array into the APDU and send it backout again. If anything goes wrong, we throw an exception with id 42.

47

1 private byte[] arr = {(byte)72, (byte) 105, (byte) 33};// Hi!

2

3 public static void install(byte[] bArray,short bOffset,byte bLength){

4 (new AppletName()).register(bArray,(short)(bOffset + 1), bArray[bOffset]);

5 }

6

7 public void process(APDU APDU){

8 byte[] buf = APDU.getBuffer();

9 switch(buf[ISO7816.OFFSET_INS]){

10 case (byte)0xb1: break;

11 case (byte)0xff:

12 short lc = APDU.setIncomingAndReceive();//receive data & get LC

13 short le = APDU.setOutgoing();//set direction to outgoing and get LE

14 if(lc == 1 && buf[5] == 0xff && le ==3) {//5 == OFFSET_CDATA for APDU

15 Util.arrayCopy(arr, (short)0, buf, (short)0, (short)2);

16 APDU.setOutgoingLength((short)2);

17 APDU.sendBytes((short)0, (short)2);

18 return;

19 }//end if

20 default:

21 ISOException.throwIt((short)42);

22 }//end switch

23 }//end void process()

Figure C.1: Sample Java Card On-Card Application

Noteworthy are the arrayCopy, which copies one array to the other. Sincethere is no garbage collection, any new statement would allocate memory per-manently. Thus, copying arrays around by using new temporary arrays is un-acceptable. This is also seen in the fact that the APDU buffer is reused. Also,in lines 15 and 16, there is continuous typecasting to shorts, as in Java, onlytyping “0” is always an int instead of a short

C.1.2 Cash Pay

To get an indication of the programming required for programs on a Java Card,a simple application was built which models a digital purse application. Wewill call this “Cash Pay”. Cash Pay is a program which signs bills: the sellersubmits an amount, which is then signed and returned by the buyer. Theseller can then ‘cash’ this amount by connecting to a bank where the amountcan be transferred between the two agents. This simple protocol was used todemonstrate a working example on and with Java Card.

A sample run would be as follows:

1. Buyer B wants to buy an item from Seller S.

2. S signs the amount with his private key from RSA and sends both hispublic key and the signed amount towards the card of B.

3. B’s card decrypts the amount, verifies that the amount is correct, and thensigns the original message and some counter (to ensure that duplication

48

Buyer Seller Bank

Q1

Q2

Q3

msc Cash Pay

Q1: (Amount, T ime)SK(S), PK(S)

Q2: ((Counter,Amount, T ime, PK(S))SK(B), PK(B))

Q3: ((Counter,Amount, T ime, PK(S))SK(B), PK(B))

Figure C.2: The Cash Pay protocol

is impossible) with its own private key. He then sends the message backto Seller S.

4. S can now contact the bank, which can verify that both parties agree onthe amount, and that both parties are known. Thus the transfer betweenthe accounts of S and B can be accomplished.

Every data object is packed nicely into TLV’s (see Appendix A.3.1) as it shouldbe to ensure no typing errors occur. The implementation both on the SmartCard and the server side are relatively straightforward. To get some idea onhow things work, the encryption is done using RSA (for the workings of RSA,see Chapter 4.1), with very small blocksizes. This limits the application: aseverything is calculated modulus the RSA’s modulus, it means that there canonly be a limited size of numbers, which should be smaller then the modulusof both the Smart Card and the Seller. In appendix C.2 all the code can befound of this implementation. Again, the on-card application suffers from thearchitecture as typecasts to short are commonplace.

C.2 Cash Pay Code

The code for Cash Pay, both on and off-card, can be found in the directory onthe CD, under /cashpay/oncard and /cashpay/offcard respectively.

49

Appendix D

Implementation of faultattacks

This chapter contains the code which was used to implement the fault attacksin Chapter 4. To get insight into the protocol of RSA and how the givenfour attacks work, the four were implemented. This section describes the fourseparately. To simulate the attack, all implementations of RSA were given adisturb boolean, describing whether or not its execution should be disturbed. Ifit is disturbed, this is done ’appropriately’, i.e. no disturbance in the calculationis made at the wrong spot.

For implementation of the RSA protocols on Java Card, see the CD, under/code/jctools.

D.1 Implementation of DFA on RSA+CRT

This subsection discusses the implementation of the attack described in sec-tion 4.2.1. Sample code is thus as follows:

01 short origval = 7;

02 byte tosend[] = {(byte)origval};

03 crypto.encrypt(tosend,(short)1,(short)0);//array, size, offset

04 short scorrect = tosend[0];

05 if(s<0) scorrect += crypto.getMod();

06 tosend[0] = (byte)origval;

07 crypto.disturb();

08 crypto.encrypt(tosend,(short)1,(short)0);

09 short serr = tosend[0];

10 if(serr<0) serr+= crypto.getMod();

11 long sdiff = s-serr;

12 if(se<0) sdiff+= crypto.getMod();

13 long xse = (origval-serr)%crypto.getMod();

14 int val1 = (int)EGCD.GCD(se, crypto.getMod())[EGCD.GCD_VAL];

15 //returns Extended GCD: (xmult, ymult, gcdval) such that

16 // xmult*arg1 + ymult*arg2 = gcdval

17 int val2 = crypto.getMod() / val1;

50

D.2 Implementation of DFA on RSA with squar-ing

This subsection discusses the implementation of the attack described in sec-tion 4.2.2.

001 BigInteger crackRSA()

002 {

003 Vector v = new Vector();

004 BigInteger mod = new BigInteger((new Short(crypto.getMod())).toString());

005 for(int i = 5; i < 5*40; i=i+5)

006 {

007 byte[] b = {new Integer(i).byteValue()};

008 byte[] orig = {new Integer(i).byteValue()};

009 crypto.disturb();

010 crypto.encrypt(b, (short)1, (short)0);

011 crypto.encrypt(orig, (short)1,(short)0);

012 BigInteger b1 = new BigInteger(b);

013 BigInteger benc = new BigInteger(orig);

014 MsgData m = new MsgData(new BigInteger((new Integer(i)).toString()), b1);

015 v.add(m);

016 }

017 //now we have a vector with stuff :)

018 byte[] key = {0};

019 int len = 0;

020 SearchData dt = new SearchData(key, mod.bitLength(),0, v);

021 while(dt.getKnownLen()!= dt.getKeyLen())

022 {

023 dt = findbits(dt);

024 if(dt==null)

025 return null;

026 }

027 return new BigInteger(dt.getKey());

028 }

029

030

031 /**

032 *

033 * <p>Title: Searchdata data holder</p>

034 * <p>Description: holds data for searching through faulty signed messages</p>

035 * <p>Copyright: Copyright (c) 2005</p>

036 * <p>Company: </p>

037 * @author Koos Gadellaa

038 * @version 1.0

039 */

040 class SearchData

041 {

042 byte[] key; //the key which is known.

043 int foundlen;//the number of bits which are known in the key

044 int keylen;//the length of the key in bits???

045 Vector messages;

046 public SearchData(byte[] k, int keylength, int fndlen, Vector msg)

047 {

048 if(k.length<2)

51

049 {

050 key = new byte[2];

051 key[1] = k[0];

052 }

053 else

054 key = k;

055 keylen = keylength;

056 foundlen = fndlen;

057 messages = msg;

058 }

059 public void setMessages(Vector v)

060 {

061 messages = v;

062 }

063 public void setKey(byte[]k, int l)

064 {

065 key = k;

066 keylen = l;

067 }

068 public byte[] getKey()

069 {

070 return key;

071 }

072 public int getKeyLen()

073 {

074 return keylen;

075 }

076 public int getKnownLen()

077 {

078 return foundlen;

079 }

080 public Vector getMsgs()

081 {

082 return messages;

083 }

084 }

085

086 class MsgData

087 {

088 BigInteger original;

089 BigInteger encoded;

090 public MsgData(BigInteger orig, BigInteger coded)

091 {

092 original = orig;

093 encoded = coded;

094 }

095 public BigInteger getOrig()

096 {

097 return original;

098 }

099 public BigInteger getCoded()

100 {

101 return encoded;

102 }

52

103

104

105 }

106

107 /**

108 * find bits from d where maximum keysize is given.

109 * @param d the data to use for searching

110 * @param keysize the maximum size of the key to be found from the data.

111 * @return

112 */

113 SearchData findbits(SearchData d)

114 {

115 int keysize = d.getKeyLen()-d.getKnownLen();

116 BigInteger mod = new BigInteger(new Short(crypto.getMod()).toString());

117 BigInteger pub = new BigInteger(new Short(crypto.getPub()).toString());

118 for(int r=1; r<keysize+1; r++)

119 {

120 byte[][] w = generate_append(d.getKey(), keysize, r);

121 for(int i = 0; i < w.length; i++)

122 {

123 Object[] v = d.getMsgs().toArray();

124 BigInteger wi = new BigInteger(w[i]);

125 BigInteger two = new BigInteger("2");

126 for(int p = 0; p<v.length; p++)

127 {

128 MsgData dt = (MsgData)(v[p]);

129 BigInteger c = dt.getOrig().modPow(wi, mod);

130 BigInteger origmsg = dt.getOrig();

131 BigInteger sgnmsg = dt.getCoded();

132 for(int t = 0; t < d.getKeyLen(); t++)

133 {

134 // 2 vars: one for S_j + 2^t M_j^w, and one for S_j - 2^t M_j^w

135 // we then ’encrypt’ these and check if they’re equal to the original

136 // so var-orig == 0 <==> var == orig

137 BigInteger added = c.add(sgnmsg);

138 BigInteger subst = c.subtract(sgnmsg);

139 subst = subst.modPow(pub, mod);

140 added = added.modPow(pub, mod);

141 subst = subst.subtract(dt.getOrig());

142 added = added.subtract(dt.getOrig());

143 subst = subst.mod(mod);

144 added = added.mod(mod);

145 //either subst or added needs to be 0 now to go have success

146 if (added.compareTo(BigInteger.ZERO)==0||

147 subst.compareTo(BigInteger.ZERO)==0) {

148 //success!

149 Vector m = d.getMsgs();

150 m.remove(v[p]); //this was a success so no need to use it anymore

151 return new SearchData(w[i],d.getKeyLen(), d.getKnownLen() + r, m);

152 }

153 //else

154 c = c.multiply(two);

155 c = c.mod(mod);

156 }//end for loop for t.

53

157 }

158 }

159 //nothing found with this r...

160 if(r > 3 )//arbitrary size here...

161 {

162 // we assume we’ve made a mistake and backtrack!

163 System.out.println("backtracking...");

164 byte[] k = d.getKey();

165 BigInteger b = new BigInteger(k);

166 // we now need to remove the previous key, so

167 int ln = d.getKnownLen();

168 b=b.clearBit(d.getKeyLen() - ln);

169 ln--;

170 return findbits(new SearchData(b.toByteArray(), d.getKeyLen(),

ln, d.getMsgs()));

171 }

172 }

173 System.out.println("r was too small so we couldn’t continue");

174 System.out.println("backtracking...");

175 byte[] k = d.getKey();

176 BigInteger b = new BigInteger(k);

177 // we now need to remove the previous key, so

178 int ln = d.getKnownLen(); // this is thus one too much

179 b=b.clearBit(d.getKeyLen() - ln);

180 ln--;

181 //this works since the actual key isn’t modified

182 // it’s not the nicest code, but it works.

183 //we thus might want to revise this...

184 return findbits(new SearchData(b.toByteArray(), d.getKeyLen(),

ln, d.getMsgs()));

185 }

186

187 /**

188 * generates bitstrings of w (so possible new keys).

189 * @param key the original key to which the strings are appended to

190 * @param ln the length of the original key

191 * @param r the length of the bitstrings appended

192 * @return an array of possible keys.

193 */

194 byte[][] generate_append(byte[]key, int ln, int r)

195 {

196 int i = 1<<r;

197 byte w[][] = new byte[i][];

198 int off = ln -r;

199 BigInteger bkey = new BigInteger(key);

200 //off is the place where the various bits need to be inserted

201 // as bitstring is 1,2, 3, ... which is 01,10, 11, ... in binary we can

202 // then simply append this starting at position off, such that LSB = off.

203 for(int j = 0; j < i; j++)

204 {

205 BigInteger b = BigInteger.valueOf(j);

206 b = b.shiftLeft(off);

207 b = b.add(bkey);

208 if(b.toByteArray().length <2) //since it can be smaller then one...

54

209 {

210 byte[] b2 = new byte[2];

211 b2[1] = b.toByteArray()[0];

212 w[j] = b2;

213 }

214 else

215 w[j] = b.toByteArray();

216 }

217 return w;

218 }

D.3 Implementation of DFA on a simple signingprotocol

This subsection discusses the implementation of the attack described in sec-tion 4.3.1.

01 /**

02 * Attack on an asymmetric cryptosystem according to Biham and Shamir

03 * from Advances in Cryptology, 1997

04 * Works by disturbing until the key is 0,

05 * thus having m^0=m, and then work backwards.

06 */

07 int maxsize = 256;

08 byte[][] mem = new byte[maxsize][]; //arbitrary size here.

09 int i;

10 for(i =2; i < maxsize; i++)

11 {

12 //we here calculate the crypto of i, and save i,signed(i)

13 byte[] b = new byte[2];

14 b[0] = (byte)i;

15 b[1] = b[0];

16 crypto.encrypt(b,(short)1,(short)1);

17 if(b[1]==1 || b[1] == b[0])

18 break;

19 //b0 !/ b1 so encryption is with non-null key.

20 crypto.disturb();

21 mem[i-2] = b;

22 }

23 if(mem[253] != null)

24 return; // it took too many tries decrypting

25 //we’re not at maxsize so fault attack succeeded

26 // so now we need to start decrypting.

27 int key = 0;

28 //we need to find a t such that key|2^t = M^i-1

29 for(i=i-3; i>=0; i--)

30 {

31 int q=1;

32 for(int t=0; t<15; t++)

33 {

34 int t2 = 1<<t;

35 t2 |= key;

36 if(check_message(mem[i],t2))

55

37 {

38 key = t2;

39 break;

40 }

41 }

42 }

D.4 Implementation of DFA on RSA by flippingbits

This section describes the attack from chapter 4.3.2.

01 short thekey = 0;

02 for(i=0; i < maxsize; i++)

03 {

04 //for each item b in mem[]

05 //b[0] is the input, b[1] is the output.

06 byte[] b = mem[i];

07 // now we need to check if something was changed at all,

08 //so we try to sign the original and see if it matches

09 //but first we save the origanal value...

10 int base = b[0];

11 int err = b[1];

12 crypto.sign(b, (short)0, (short)1);

13 int signed = b[0];

14 if(b[0] == b[1])

15 continue;

16 // now we calculate:

17 // err == base^FS

18 // FS == S - 2^t

19 // S == FS + 2^t

20 // base^S == base^(FS+2^t)

21 // base^S == base^FS * base^2^t

22 // so we can find a correct value which is base^2^t such that

23 // the equation holds. This t then is probably the bit where it

24 // went wrong.

25 int basesq = (base * base) % crypto.getMod();

26 if(signed < 0) signed += 256; // different since it’s an issue

27 // due to char manipulation...

28 int tocheck = err * base % crypto.getMod(); // case where t = 0...

29 if(tocheck < 0) tocheck += crypto.getMod();

30 if( signed == tocheck)

31 {

32 //correct value found with i = 0 so i_0 = 1 in key...

33 thekey |= 1;

34 continue;

35 }

36 int j;

37 for( j=1; j < 16; j++)

38 {

39 tocheck = err * basesq % crypto.getMod();

40 if(tocheck < 0) tocheck += crypto.getMod();

41 if(signed == tocheck)

56

42 {

43 thekey |= (1<<j);

44 break;

45 }

46 basesq = (basesq * basesq) % crypto.getMod();

47 if (basesq < 0) basesq += crypto.getMod();

48 }

49 }

57

Appendix E

Java Card BytecodeConverter

This concerns a small program which was used to convert Java Card Bytecodeto the more readable instruction set. It is something which I did not find onthe internet, and thus have written myself to get insight into the Java CardBytecode, and the structure of the .cap file. It was written in PHP and simplyoutputs three columns: the HEX value, the value in decimals, and the possibleinstruction code it might represent. Whether this actually is an instruction isdependent upon the structure of the .cap file and the instructions themselves assome of them take arguments.

E.1 PHP code

001 <HTML>

002 <head>Java Bytecode Converter</head>

003 <br>

004 <form enctype="multipart/form-data"

005 action="index.php"

006 method="post"><br>

007 Type (or select) Filename:

008 <input type="file"

009 name="thefile">

010 <input type="submit"

011 value="Upload File">

012 <br>

013 <?

014

015 if($_FILES[’thefile’][’error’] == 0)

016 {

017 echo "file uploaded is:";

018 echo $_FILES[’thefile’][’name’];

019 echo "<br>\n" ;

020 }

021 else

022 {

023 echo "No file uploaded or file upload had an issue!!<br>\n";

58

024 return;

025 }

026

027 if(!move_uploaded_file($_FILES[’thefile’][’tmp_name’], "temp.cap"))

028 {

029 echo "error processing file!<br>\n";

030 return;

031 }

032

033 echo "Now displaying file with stuff moved around...<br>\n";

034

035 function key_in_array($needle, $haystack) {

036 $haystack = array_flip($haystack);

037 if (in_array($needle, $haystack))

038 {

039 return true;

040 } else {

041 return false;

042 }

043 }

044

045 $toparse = "

046 0 00 nop 47 2F sstore_0

047 1 01 aconst_null 48 30 sstore_1

048 2 02 sconst_m1 49 31 sstore_2

049 3 03 sconst_0 50 32 sstore_3

050 4 04 sconst_1 51 33 istore_0

051 5 05 sconst_2 52 34 istore_1

052 6 06 sconst_3 53 35 istore_2

053 7 07 sconst_4 54 36 istore_3

054 8 08 sconst_5 55 37 aastore

055 9 09 iconst_m1 56 38 bastore

056 10 0A iconst_0 57 39 sastore

057 11 0B iconst_1 58 3A iastore

058 12 0C iconst_2 59 3B pop

059 13 0D iconst_3 60 3C pop2

060 14 0E iconst_4 61 3D dup

061 15 0F iconst_5 62 3E dup2

062 16 10 bspush 63 3F dup_x

063 17 11 sspush 64 40 swap_x

064 18 12 bipush 65 41 sadd

065 19 13 sipush 66 42 iadd

066 20 14 iipush 67 43 ssub

067 21 15 aload 68 44 isub

068 22 16 sload 69 45 smul

069 23 17 iload 70 46 imul

070 24 18 aload_0 71 47 sdiv

071 25 19 aload_1 72 48 idiv

072 26 1A aload_2 73 49 srem

073 27 1B aload_3 74 4A irem

074 28 1C sload_0 75 4B sneg

075 29 1D sload_1 76 4C ineg

076 30 1E sload_2 77 4D sshl

077 31 1F sload_3 78 4E ishl

59

078 32 20 iload_0 79 4F sshr

079 33 21 iload_1 80 50 ishr

080 34 22 iload_2 81 51 sushr

081 35 23 iload_3 82 52 iushr

082 36 24 aaload 83 53 sand

083 37 25 baload 84 54 iand

084 38 26 saload 85 55 sor

085 39 27 iaload 86 56 ior

086 40 28 astore 87 57 sxor

087 41 29 sstore 88 58 ixor

088 42 2A istore 89 59 sinc

089 43 2B astore_0 90 5A iinc

090 44 2C astore_1 91 5B s2b

091 45 2D astore_2 92 5C s2i

092 46 2E astore_3 93 5D i2b

093 94 5E i2s 141 8D invokestatic

094 95 5F icmp 142 8E invokeinterface

095 96 60 ifeq 143 8F new

096 97 61 ifne 144 90 newarray

097 98 62 iflt 145 91 anewarray

098 99 63 ifge 146 92 arraylength

099 100 64 ifgt 147 93 athrow

100 101 65 ifle 148 94 checkcast

101 102 66 ifnull 149 95 instanceof

102 103 67 ifnonnull 150 96 sinc_w

103 104 68 if_acmpeq 151 97 iinc_w

104 105 69 if_acmpne 152 98 ifeq_w

105 106 6A if_scmpeq 153 99 ifne_w

106 107 6B if_scmpne 154 9A iflt_w

107 108 6C if_scmplt 155 9B ifge_w

108 109 6D if_scmpge 156 9C ifgt_w

109 110 6E if_scmpgt 157 9D ifle_w

110 111 6F if_scmple 158 9E ifnull_w

111 112 70 goto 159 9F ifnonnull_w

112 113 71 jsr 160 A0 if_acmpeq_w

113 114 72 ret 161 A1 if_acmpne_w

114 115 73 stableswitch 162 A2 if_scmpeq_w

115 116 74 itableswitch 163 A3 if_scmpne_w

116 117 75 slookupswitch 164 A4 if_scmplt_w

117 118 76 ilookupswitch 165 A5 if_scmpge_w

118 119 77 areturn 166 A6 if_scmpgt_w

119 120 78 sreturn 167 A7 if_scmple_w

120 121 79 ireturn 168 A8 goto_w

121 122 7A return 169 A9 getfield_a_w

122 123 7B getstatic_a 170 AA getfield_b_w

123 124 7C getstatic_b 171 AB getfield_s_w

124 125 7D getstatic_s 172 AC getfield_i_w

125 126 7E getstatic_i 173 AD getfield_a_this

126 127 7F putstatic_a 174 AE getfield_b_this

127 128 80 putstatic_b 175 AF getfield_s_this

128 129 81 putstatic_s 176 B0 getfield_i_this

129 130 82 putstatic_i 177 B1 putfield_a_w

130 131 83 getfield_a 178 B2 putfield_b_w

131 132 84 getfield_b 179 B3 putfield_s_w

60

132 133 85 getfield_s 180 B4 putfield_i_w

133 134 86 getfield_i 181 B5 putfield_a_this

134 135 87 putfield_a 182 B6 putfield_b_this

135 136 88 putfield_b 183 B7 putfield_s_this

136 137 89 putfield_s 184 B8 putfield_i_this

137 138 8A putfield_i

138 139 8B invokevirtual 254 FE impdep1

139 140 8C invokespecial 255 FF impdep2 ";

140

141

142

143 $vals = explode(" ", $toparse);

144 $i=0;

145 $temp = "";

146 $trans = array();

147 foreach($vals as $var)

148 {

149 if($var != "")

150 {

151 // echo $var."\t ".$i."<br>";

152 if($i==0)

153 $temp = $var;

154 if($i == 2)

155 {

156 $mnem = trim($var);

157 $trans[chr($temp)] = ("<pre>".($temp<128?$temp:$temp-255).

158 "\t".dechex($temp)."\t".$mnem."</pre>") ;

159 }

160 $i++;

161 $i %= 3;

162 }

163 }

164

165 //now fill all the nonexistant values with ’correct’ ones so it’s

166 // entirely 255 values are filled...

167

168 for($i=0; $i<255; $i++)

169 if( $trans[chr($i)] == "" )

170 {

171 $trans[chr($i)] = ("<pre>".$i."\t".dechex($i).

172 "\tNONEXISTANT:".($i - 256)."</pre>");

173 }

174

175 if(($data = file_get_contents("temp.cap")))

176 {

177 $outp = strtr($data, $trans);

178 echo $outp;

179 }

180 else

181 echo "File get contents FAILED!<br>\n";

182

183 ?>

184 </body>

185 </HTML>

61

E.2 Sample

In this section is shown a small program, and the bytecode it gives after con-version.

E.2.1 Actual program

/*

* Created on May 19, 2005

* Created by Koos Gadellaa

* Copyright 2005

*

*/

package miniapp;

import javacard.framework.APDU;

import javacard.framework.Applet;

import javacard.framework.ISO7816;

import javacard.framework.ISOException;

/**

* @author Koos Gadellaa

*

* Copyright 2005

*/

public class MiniApplet extends Applet {

public static void install(byte[] bArray, short bOffset, byte bLength) {

// OP-compliant JavaCard applet registration

new MiniApplet().register(

bArray,

(short) (bOffset + 1),

bArray[bOffset]);

}

public void process(APDU apdu) {

// Good practice: Return 9000 on SELECT

if (selectingApplet()) {

return;

}

byte[] buf = apdu.getBuffer();

switch (buf[ISO7816.OFFSET_INS]) {

case (byte) 0xb1 :

short q = apdu.setIncomingAndReceive();

short exp_len = apdu.setOutgoing();

apdu.setOutgoingLength((short) 2);

if (exp_len != 2)

ISOException.throwIt((short) 8);

buf[0] = 0x4f; //O

62

buf[1] = 0x4b; //K

apdu.sendBytes((short) 0, (short) 2);

return;

default :

ISOException.throwIt((short) 7);

// good practice: If you don’t know the INStruction, say so:

ISOException.throwIt(ISO7816.SW_INS_NOT_SUPPORTED);

}

}

}

E.2.2 output of method.cap

Below is the output of the program. As it is quite large already for even a smallprogram. It reads top to bottom, left to right.

7 7 sconst 40 0 nop109 6d if scmpge0 0 nop1 1 aconst null16 10 bspush24 18 aload 0-115 8c invokespecial0 0 nop2 2 sconst m1122 7a return5 5 sconst 248 30 sstore 1-112 8f new0 0 nop3 3 sconst 061 3d dup-115 8c invokespecial0 0 nop9 9 iconst m124 18 aload 029 1d sload 14 4 sconst 165 41 sadd24 18 aload 029 1d sload 137 25 baload-116 8b invokevirtual0 0 nop0 0 nop122 7a return3 3 sconst 035 23 iload 324 18 aload 0-116 8b invokevirtual0 0 nop4 4 sconst 1

96 60 ifeq3 3 sconst 0122 7a return25 19 aload 1-116 8b invokevirtual0 0 nop6 6 sconst 345 2d astore 226 1a aload 24 4 sconst 137 25 baload115 73 stableswitch0 0 nop52 34 istore 10 ff impdep2-78 b1 putfield a w0 ff impdep2-78 b1 putfield a w0 0 nop9 9 iconst m125 19 aload 1-116 8b invokevirtual0 0 nop8 8 sconst 550 32 sstore 325 19 aload 1-116 8b invokevirtual0 0 nop10 a iconst 041 29 sstore4 4 sconst 125 19 aload 15 5 sconst 2-116 8b invokevirtual0 0 nop7 7 sconst 422 16 sload

4 4 sconst 15 5 sconst 2106 6a if scmpeq7 7 sconst 416 10 bspush8 8 sconst 5-114 8d invokestatic0 0 nop1 1 aconst null26 1a aload 23 3 sconst 016 10 bspush79 4f sshr56 38 bastore26 1a aload 24 4 sconst 116 10 bspush75 4b sneg56 38 bastore25 19 aload 13 3 sconst 05 5 sconst 2-116 8b invokevirtual0 0 nop5 5 sconst 2122 7a return16 10 bspush7 7 sconst 4-114 8d invokestatic0 0 nop1 1 aconst null17 11 sspush109 6d if scmpge0 0 nop-114 8d invokestatic0 0 nop1 1 aconst null122 7a return

63

Bibliography

[1] Uwe Hansmann, Martin S. Nickous, Thomas Schack, Achim Schneider,Frank Seliger. Smart Card Application Development Using Java.Springer-Verlag.

[2] Zhiqun Chen. Java Card Technology for Smart Cards.Addison-Wesley

[3] Eclipse Basic Tutorial.http://www.eclipse.org/documentation/pdf/org.eclipse.platform.doc.user 2.1.3.pdf

[4] Java Development User Guide.http://www.eclipse.org/documentation/pdf/org.eclipse.jdt.doc.user 2.1.3.pdf

[5] Microsoft. Smart Card Base Componentshttp://www.microsoft.com/downloads/release.asp?releaseid=36755

[6] Uwe Hansmann, Martin S. Nickous, Thomas Schack, Achim Schneider,Frank Seliger. Readfile Sample.http://www.opencard.org/SCJavaBook/SCJavaBook.zip ReadFile.Java

[7] Java Forum - Java Cardhttp://forum.Java.sun.com/forum.jspa?forumID=23

[8] PC/SC Workgrouphttp://www.pcscworkgroup.com/

[9] Dan Boneh, Richard A. DeMillo, Richard J. Lipton. On the Importance ofEliminating Errors in Cryptographic Computations.Journal of Cryptology 2001, Volume 14, pages 37-51. Springer-Verlag.

[10] Ronald Rivest, Adi Shamir, Leonard Adleman. A Method for ObtainingDigital Signatures and Public-Key Cryptosystems.Communications of the ACM, 21:120–126, February 1978, Page 223

[11] A.K. Lenstra. Memo on RSA signature generation in the presence of faultsmanuscript, Sept. 28, 1996. Available from the author, [email protected]

[12] Johannes Blomer, Jean-Pierre Seifert. Fault Based Cryptanalysis of the Ad-vanced Encryption Standard (AES)Financial Cryptography 2003, LNCS 2742, Springer-Verlag.

64

[13] Eli Biham, Adi Shamir. Differential Fault Analysis of Secret Key Cryp-tosystemsAdvances in Cryptlogy - CRYPTO ’97, LNCS 1294, Springer-Verlag.

[14] Oliver Kommerling, Markus G. Kuhn. Design Principles for Tamper-Resistant HardwareUSENIX workshop on Smartcard Technology 1999

[15] C. Aumuller, P. Bier, W. Fischer, P. Hofreiter, J.-P. Seifert Fault Attackson RSA with CRT: Concrete Results and Practical CountermeasuresProceedings of CHES ’02, LNCS 2523, Springer-Verlag

[16] Ross Anderson, Markus Kuhn Low Cost Attacks on Tamper Resistant Hard-wareSecurity Protocols, 5th international Workshop 1997, LNCS 1361, Springer-Verlag

[17] Sergi P. Skorobogogatov, Ross J.Anderson Optical Fault Induction AttacksProceedings of CHES ’02, LNCS 2523, Springer-Verlag

[18] J.-J. Quisquater, D. Samyde Eddy Current for Magnetic Analysis with Ac-tive SensorE-Smart 2002, NOVAMEDIA

[19] Virtual Machine Specification, Java Card Platform, Version 2.2.1 Sun Mi-crosystems

[20] Pierre Bieber, Jacques Cazin, Abdellah Al-Marouani, Pierre Girard, Jean-Louis Lanet, Virginie Wels, Guy Zanon The PACAP Prototype: a Tool forDetecting Java Card Illegal FlowProgramming and Security, LNCS 2041, Springer-Verlag.

[21] Xavier Leroy On-Card Bytecode Verification for Java CardE-Smart 2001, LNCS 2140, Springer-Verlag

[22] Xavier Leroy Bytecode verification on Java Smart CardsSoftware — Practice & Experience volume 32

[23] R.M. Cohen Defensive Java Virtual Machine version 0.5 alpha1997, http://www.computationallogic.com/software/djvm/

[24] Eva Rose Lightweight bytecode verificationKluwer Academic Papers, 2003

[25] Serge Chaumete, Damien Sauveron New security problems raised by openmultiapplication smart cards2004

[26] John McCormac, Knut Vikor, Martyn Williams, Rene Vreeman, LinusSugoy, Brian McIlwrath Hacking Pay TVhttp://www.iol.ie/ kooltek/faq.html, chapter 2

[27] Michael Montgomery, Ksheerabdhi Krishna Secure Object Sharing in JavaCardUSENIX Workshop on Smartcard Technology 1999

65

[28] Sudhakar Govindavajhala, Andrew W. Appel Using Memory Errors to At-tack a Virtual Machine2003 IEEE Symposium on Security and Privacy, May 11–14, 2003

[29] Hagai Bar-El, Hamid Choukri, David Naccache, Michael Tunstall, ClaireWhelan The Sorcerer’s Apprentice Guide to Fault AttacksWorkshop on Fault Detection and Tolerance in Cryptography, June 2004.

[30] F.bao, R.H.Deng, Y. Han, A.Jeng, A.D.Narasimhalu, T.Ngair BreakingPublic Key Cryptosystems on Tamper Resistant Devices in the Presence ofTransient FaultsProceedings of the 5th Workshop on Secure Protocols, LNCS 1361,Springer-Verlag.

[31] Alexander May, Cryptanalysis of Unbalanced RSA with Small CRT-Exponent,CRYPTO 2002, LNCS 2442, Springer-Verlag.

[32] Sung-Ming Yen, Seungjoo Kim, Seongam Lim, Sang-Jae Moon, RSASpeedup with Chinese Remainder Theorem Immune against Hardware FaultCryptanalysis,ICICS 2001, LNCS 2288, Springer-Verlag

[33] Johannes Blomer, Martin Otto, Jean-Pierre Seifert, A New CRT-RSA Al-gorithm Secure Against Bellcore Attacks,ACM CCS 2003, ACM Press

[34] Sung-Ming Yen, Marc Joye, Checking before output may not be enoughagainst fault-based cryptanalysis,IEEE Transactions on Computers, September 2000.

[35] David Wagner, Cryptanalysis of a Provably Secure CRT-RSA Algorithm,ACM conference on Computer and communications security 2004

[36] MultOS website,http://www.multos.com/

[37] DG Abraham, GM Donal, GP Double, JV Stevens, Transaction SecuritySystem,IBM Systems Journal volume 30 no. 2 (1991)

[38] Ross Anderson, Security EngineeringWiley Publishing, 2001

[39] Underwriters Laboratories, Inchttp://www.ul.com

[40] Arjen K. Lenstra, Eric R. Verheul, Selecting Cryptographic Key Sizes,Journal of Cryptology 14, Springer-Verlag, 2001

66


Recommended