1
AIAC 2010/11 Ricardo Chaves
JavaCard
Departamento de Engenharia Informática
2
AIAC 2010/11 Ricardo Chaves
Java Card - old
vs
new
• Old Smart Cards:
– One program (applet) – Written in machine-code,
specific to chip – Burned into ROM
• New Smart Cards:
– Applet written in high-level language (mainly Java Card)
– Compiled into bytecode – Stored in EEPROM – Interpreted on card
– Multi-application:several applets on one card
– Post-issuance:adding or deleting applets on card
3
AIAC 2010/11 Ricardo Chaves
How Java and smart cards mix
• Java Card is a stripped down version of Java for
smart cards
– up to version 2.1 (and security is improving) – one major vendor behind Java Card is Visa
• Java Card makes multi-application cards based on
a common platform possible
– Opens smart card development
– Uses a known programming language – (re)use of standard SW development tool
– e.g. JBuilder
Departamento de Engenharia Informática
How can Java fit on a card?
Supported Java Features
• packages
• dynamic object
creation
• virtual methods
• interfaces
• exceptions
Unsupported Java Features
• dynamic class loading
• security manager
• threading
• object cloning
• garbage collection
• large data types
5
AIAC 2010/11 Ricardo Chaves
Multi-application cards
• Multi-application cards are an important goal
– getting more developers on board is essential• Multiple applets can execute on a card
– credit, debit, e-cash, loyalty programs
• Explicit and covert channels between applets must
be eliminated
– software risk management
Departamento de Engenharia Informática
6
AIAC 2010/11 Ricardo Chaves
Java Card security != Java security
Good
• no dynamic class loading
• only one active applet
• no threading
• objects include
rudimentary access
control
Bad
• native method calls
• no garbage collection
• In some smart cards
• object sharing complexity
• out of band verification
7
AIAC 2010/11 Ricardo Chaves
Security risks in Java Card 2.1
• protocol interactions
– sharing secrets between applications introduces new problems• security is hard
– linking, export, CAP files
– native methods – verification – object sharing
• multi-application risks
– applets MUST behave• the usual suspects apply
– physical attacks
– side-channel monitoring (e.g. DPA)
– the terminal problem
Departamento de Engenharia Informática
Multi-application issues
• Secure Features:
– no dynamic class loading
• reduces threat of malicious applets
– no multi-threading
• non-interference
– applet firewalls
• prevents referencing another applet’s objects
• Risks & Assumptions – trust-based applet model
• assume applets are non-malicious • security testing needed
9
AIAC 2010/11 Ricardo Chaves
Security is harder than it sounds
• Java Card is not truly
“cross platform”
– byte code àCAP – export files
• linking problems
– no strings, thus tables• code verification?
– before conversion• exception handling
• Other problems:
– native methods – INT? (32 bits) – applet testing anddebugging issues
– sharing methods among applets (difficult)
– ISO 7816 APDU problems – hostile applets
• denial of service
Departamento de Engenharia Informática
10
AIAC 2010/11 Ricardo Chaves
Java Card - Security
• What to do?
– Assume the platform is secure
• it is getting better
– Applets must be carefully designed and implemented – Testing appletsfor security is essential
11
AIAC 2010/11 Ricardo Chaves
Java Card - Development steps
Departamento de Engenharia Informática
Java Card - Programming
• Dialectof Java for programming smartcards • Subset of Java (due to hardware constraints)
– no threads, doubles, strings, garbage collection, and very restricted API
• With some extras (due to hardware peculiarities) – persistent & transient data in EEPROM & RAM – transaction mechanism
• Java Card applets are executed in a sandbox, like applets in a web browser.
(In fact, Java Card sandbox rules are more restrictive than Java’s)
13
AIAC 2010/11 Ricardo Chaves
• The Java Card language
– JC is a subset of the Java language:
• no reals, doubles, strings, multi-dim arrays • no threads
– JC uses 16 bit arithmetic, not 32.
– JC uses an optimized form of class files, called CAP-files. • The Java Card API:
– a subset of Java’s API
• no need for most standard I/O classes
– plus some extras for
• smartcard I/O with APDUs using ISO 7816 • persistent and transient data
• transactions
Java Card - Programming
Departamento de Engenharia Informática
14
AIAC 2010/11 Ricardo Chaves
• Java Card API packages: – java.lang
– Object, Exception, ...
– javacard.framework
– ISO7816, APDU, Applet, JCSystem
– javacard.security
– KeyBuilder, RSAPrivateKey, CryptoException
– javacardx.crypto
– Cipher
• More API’s: – Global Platform
– addition to the Java Card API to support downloading of (digitally signed) applets onto a card
– Open Card Framework (OCF)
– API for building terminal applications
15
AIAC 2010/11 Ricardo Chaves
• 16 bit arithmetic:
– JC code contains many(short)casts.
• In particular, all intermediate results(which are of type int) must be cast to short
Example:
short s; byte b;
s = b+s+1; // not ok, compiler complains s = (short)(b+s+1); // not ok, converter complains s = (short)(b+(short)(s+1)) // ok
Java Card - Programming
Departamento de Engenharia Informática
Java Card platform Java Card platform
Java Card - Architecture
smartcard hardware smartcard hardware appletapplet appletapplet appletapplet Java Card
18
AIAC 2010/11 Ricardo Chaves
appletappletappletapplet
Java Card - I/O with APDUs
Java Card platform Java Card platform
appletapplet appletapplet terminal terminal smartcard hardware smartcard hardware
command APDU
,
incl. applet ID
OS selects applet
and invokes its
process
method
Applet sends
response APDU
executes
applet
appletapplet
Departamento de Engenharia Informática
19
AIAC 2010/11 Ricardo Chaves
Java Card - Memory
• ROM
– program code of VM, API, and pre-installed applets
• EEPROM
– persistent storage of the data, incl. objects with their fields, and program code of downloaded applets
• is persistent, and is keptwhen power is lost
• RAM
– transient storage of data
20
AIAC 2010/11 Ricardo Chaves
• Smart Card power supply:
– the power supply of a smartcard can be interruptedat any moment, by a so-called card tear
– to cope with this, the API offers support for:
• Persistent or transient allocation of fields • Transactions
• Persistent vstransient data:
– By default, fields of Java Card objects are stored in EEPROM – The API offers methods that allow fields that are arraysto be
allocated in RAM
– This has performance advantages, and it can be useful that fields are automatically reset when power fails
Java Card - Memory
Departamento de Engenharia Informática
• Why use transient arrays ?
– “scratchpad” memory• RAM is faster & consumes less power • EEPROM has limited lifetime
– automatic clearing of transient array
• on power-down, and
• on card reset or applet selection
– can be useful!
22
AIAC 2010/11 Ricardo Chaves
• Persistent vs transient data - example:
public class MyApplet { byte[] t, p;
short balance; SomeObject o;
// persistent array p and persistent object o p = new byte[128];
o = new SomeObject(); // transient array t
t = JCSystem.makeTransientByteArray((short)128,
JCSystem.CLEAR_ON_RESET);
Java Card - Memory
Departamento de Engenharia Informática
23
AIAC 2010/11 Ricardo Chaves
• Transient array - example:
public class MyApplet {
boolean keysLoaded, blocked; // persistent state
private RSAprivateKey priv;
//@ invariant keysLoaded ==> priv != null; byte[] protocolState; // transient session state
...
protocolState =
JCSystem.makeTransientByteArray((short)1, JCSystem.CLEAR_ON_RESET); // automatically reset to 0 when card starts up ....
24
AIAC 2010/11 Ricardo Chaves
• Transactions:
– The API offers methods to join several assignments to fields into one atomic action
• ie. atomic update of the EEPROM, called a transaction.
» If the power supply stops halfway during a transaction, all assignments of that transaction are rolled back/undone.
private int balance; private int[] log;
//@ invariant (* log[n] is previous balance *); ...
// update log n++;
log[n] = balance;
balance = balance – amount; // update balance
Java Card - Memory
what if a card tear occurs here ?
Departamento de Engenharia Informática
• Transactions –example:
private int balance; private int[] log;
//@ invariant (* log[n] is previous balance *); ... JCSystem.beginTransaction(); // update log n++; log[n] = balance; // update balance
balance = balance – amount;
JCSystem.endTransaction();
26
AIAC 2010/11 Ricardo Chaves
• The Java Card Virtual Machine (JCVM):
– specification defines:• subset of the Java programming language • Java-compatible VM for smart cards include:
» binary data representations and file formats » JCVM instruction set
• JCVM familiar features include:
• Objects, Inheritance, packages, dynamic object creation, virtual methods, interfaces, and exceptions.
JavaCard - VM
Departamento de Engenharia Informática
27
AIAC 2010/11 Ricardo Chaves
Packages A package can refer to up to 128 other packages
A fully qualified package name is limited to 255 bytes. Note that the character size depends on the character encoding. A package can have up to 255 classes.
Classes A class can directly or indirectly implement up to 15 interfaces.
An interface can inherit from up to 14 interfaces.
A package can have up to 256 static methods if it contains applets (an applet package), or 255 if it doesn't (a library package).
A class can implement up to 128 public or protected instance methods, and up to 128 with package visibility.
28
AIAC 2010/11 Ricardo Chaves
Language Features
No support for: dynamic class loading, security manager (java.lang.SecurityManager), threads, object cloning, and certain aspects of package access control are not supported. Keywords No support for: native, synchronized, transient, volatile,
strictfp are not supported. Types,
Classes, and Interfaces
No support for: char, double, float, and long, or for multidimensional arrays. Support for int is optional.
Exceptions Some Exception and Error subclasses are omitted because the exceptions and errors they encapsulate cannot arise in the Java Card platform.
Java Card - Language limitations
Departamento de Engenharia Informática
• Processing APDUs
– Every time there is an incoming APDU for a selected applet:
• The JCRE invokes the applet's process() method • The incoming APDU is passed as an argument • The applet must:
– parse the command APDU – process the data
– generate a response APDU – and return control to the JCRE
30
AIAC 2010/11 Ricardo Chaves
Java Card - Message-Passing model
Departamento de Engenharia Informática
31
AIAC 2010/11 Ricardo Chaves
Java Card - Application components
Java Card application comprises:•The back-end application: • Using the card
•The host application: • Accessing the applets on the smart card
• The terminal:
• Physical interface with the card
• The Java Card:
• Java Card framework • Java Card applet
32
AIAC 2010/11 Ricardo Chaves
Inside the Java Card: • Card’s operating System • JCRE - Java Card Runtime
Environment • Java Card Virtual
Machine
• Java Card Framework and APIs
• One or more Java Applets
Java Card - Application components
Departamento de Engenharia Informática
Java Card - Applet methods
34
AIAC 2010/11 Ricardo Chaves
Java Card - Applet life-cycle
Departamento de Engenharia Informática
35
AIAC 2010/11 Ricardo Chaves
Java Card - Creating an Applet
• All Java Card applets extend the Applet base class and must implement the install() and process() methods
• JCRE calls install() when installing the applet, and process() every time there is an incoming APDU for the applet • Developing a Java Card Applet:
1. Write the Java source 2. Compile your source
3. Convert the class files into a CAP (Converted Applet) file (binary representation of classes and interfaces)
4. Verify that the CAP is valid (structure, valid bytecode subset, inter-package dependencies)
36
AIAC 2010/11 Ricardo Chaves
Java Card - Creating an Applet
Applet Structure:import javacard.framework.* ...
public class MyApplet extends Applet {
// Definitions of APDU-related instruction codes ... MyApplet() {...} // Constructor // Life-cycle methods install() {...} select() {...} process() {...} deselect() {...} // Private methods ... }
Departamento de Engenharia Informática
Java Card - Applet Methods
• install()
– called when a new applet is being installed
public static void install
( byte[] bArray, short bOffset,byte bLength){ new myApplet(null); }
• Must call register() to let JCRE know that a new applet has been installed
• select()
– when we want to use an applet
38
AIAC 2010/11 Ricardo Chaves
• process()
– when an APDU is received and applet is selected its method process is called to process the APDU – the selected applet parses the APDU and perform
whatever it needs to perform
– normally the body of process() method is a big switch with code for each INS (APDU field)value defined
• deselect()
– is called when another SELECT APDU is received
Java Card - Applet Methods
Departamento de Engenharia Informática
41
AIAC 2010/11 Ricardo Chaves
Java Card - Object Sharing
• Shareable interface enable object sharing
between applets
• Shareable Interface Object (SIO)
– An object of a class that implements a shareable interface is called a SIO
• To the owning context, an SIO is a normal object • To any other context, the SIO is an instance of the
shareable interface type
– only the methods defined in the shareable interface are accessible
42
AIAC 2010/11 Ricardo Chaves
Java Card - Applet Firewall
• The applet firewall partitions the Java Card object
system into separate protected object spaces called
context
JCRE context Group context Firewall Applet context Applet context Group context Applet contextDepartamento de Engenharia Informática
Java Card - Applet Firewall
• JCRE assigns a context to a created applet instance
• All applet instances of a single Java package share the same (group) context
• No firewall between applet instances in the same group context • Each new created object is assigned an owning context
– The JCRE maintain its own JCER context
• JCRE context has special privileges:
– the JCRE context has access to any applet’s context – There is only one active context at any given time
44
AIAC 2010/11 Ricardo Chaves
Java Card - Applet Firewall
• Sharing mechanisms are accomplished by the
following means:
– JCRE privileges
• The JCRE is able to invoke other applets methods
» i.e. select, deselect, process,... – JCRE entry point objects
• Identical to system calls
» i.e. APDU object – Global arrays
• Special type of JCRE entry point object
» i.e. APDU buffer – Shareable interfaces
» Shareable Interface Object (SIO)
Departamento de Engenharia Informática
45
AIAC 2010/11 Ricardo Chaves
Java Card - Object Sharing
• Shareable interface
• Server creates a Shareable Interface Object
– Define a shareable interface
Package com.fasttravel.airmiles; import javacard.framework.Shareable;
Public interface AirMilesInterface extends Shareable{ public void grantMiles(short amout);
46
AIAC 2010/11 Ricardo Chaves
Java Card - Object Sharing
• Create a Shareable Interface Object
– Create a service provider class, implementing the sharable interface
• creates one or more objects of the service provider class Package com.fasttravel.airmiles;
import javacard.framework.Shareable; public class AirMilesApp extends Applet
implements AirMilesInterface { private short miles;
public void grantMiles(short amout) { miles = (short)(miles + amout);} }
Departamento de Engenharia Informática
Java Card - Object Sharing
• Requesting a SIO
– Client applet lookups the server AID:
public static AID lookupAID(
byte[] buffer, short offset, byte length)
– Client applet gets the server SIO:
public static Shareable getAppletShareableInterfaceObject( AID server_aid, byte parameter)
– JCRE invokes the Server applet:
Public Shareable getShareableInterfaceObject( AID client_aid, byte parameter)
48
AIAC 2010/11 Ricardo Chaves
Java Card - Object Sharing
• Server’s Shareable Interface Object
public class AirMilesApp extends Applet
implements AirMilesInterface { short miles;
public Shareable getShareableInterfaceObject(
AID client_aid, byte parameter){ //authenticate the client
// ... explained later ...
return this; //Return the SIO }
public void grantMiles(short amout){ miles = (short)(miles + amout); }
}
Departamento de Engenharia Informática
49
AIAC 2010/11 Ricardo Chaves
Java Card - Object Sharing
• Shareable Interface Object - Usage
50
AIAC 2010/11 Ricardo Chaves
Java Card - Object Sharing
• Shareable Interface Object - InvocationPackage com.smartbank.wallet; import javacard.framework.*;
import com.fasttravel.airmiles,AirMilesInterface;
public class WalletApp extends Applet {
private byte[] air_mailes_AID = SERVER_AID_BYTES; //... Applets code ...
public void requestMiles(short amout){ AID AirMiles_aid = JCSystem.lookupAID(
air_mailes_AID, 0, air_mailes_AID.length); AirMilesInterface sio = (AirMilesInterface)
JCSystem.getAppletShareableInterfaceObject(
AirMiles_aid, SECRET); if (sio == null) ISOException.throwIt(SW_FAILED_TO_OBTAIN_SIO) sio.grantMiles(amount);
} }
Departamento de Engenharia Informática
Java Card - Object Sharing
• Authenticate a Client Applet when returning the SIO: public class AirMilesApp extends Applet
implements AirMilesInterface { public Shareable getShareableInterfaceObject(
AID client_aid, byte parameter){ if (client_aid.equals(wallet_app_aid_bytes, (short)0, (byte)wallet_app_aid_bytes.length)) == false) return null; if (parameter != SECRET) return null; return (this); }
52
AIAC 2010/11 Ricardo Chaves
Java Card - Object Sharing
• Authenticate a Client Applet when being called: – Other contexts may have obtained the SIO reference!
» Verify every time the SIO is invoked
public void grantMiles (short amount) {
AID client_aid = JCSystem.getPreviousCOntextAID();
if (client_aid.equals(wallet_app_aid_bytes, (short)0, (byte)wallet_app_aid_bytes.length)) == false)
ISOException.throwIt(SW_UNAUTHORIZED-CLIENT);
//... Performs the methods computation miles = (short)(miles + amount);
}
Departamento de Engenharia Informática
53
AIAC 2010/11 Ricardo Chaves
Java Card - Context Switch
• Context switches occur– during invocation, return, and exception exits from instance methods of an object owned by a different context
– when a sharing mechanism is applied
• the Java Card virtual machine enables access by performing a context switch
• On card reset, the JCRE context is always the active context
• During a context-switching method invocation, the current context is saved, and the new context becomes the active context
54
AIAC 2010/11 Ricardo Chaves
• Protocol interaction risks:
– Unintended protocol interactions pose risks:
• different protocols share same key material • observation of protocol Pcan be used against Q
– Shared key material is motivated by:
• digital certificates for multi-applications • small memory for public/private key pairs • crypto APIs
JavaCard - Security risks
Departamento de Engenharia Informática
• The terminal problem:
– No trusted interface for interacting with users – A common solution is to use PCs
• but PCs are easily hacked
– Windows/Linux are inherently insecure! – Some suggestions:
• smart phones/PDAs
» Are these really secure!?!
• simple dedicated devices
– Maybe in the Future:
• On the card itself !!!
56
AIAC 2010/11 Ricardo Chaves
• Physical attacks still apply:
– Physical attacks attempt to reverse engineer the card or monitor a running card to obtain card secrets
• differential power analysis (Kocher)
• no card is 100% tamper proof (Anderson & Kuhn)
– Cards often include secrets from there owners » e.g.: PayTV
– Some secrets could be used to add functionality and/or add value
• Cost of hacking the card must be greater than the return on the investment
JavaCard - Security risks
Departamento de Engenharia Informática
57
AIAC 2010/11 Ricardo Chaves
Erik Poll @ University of Nijmegen C. Enrique Ortiz @ java.sun.com/javacard/
Raman Sharykin @ University of Illinois Fu-Chiung Cheng @ Tatung University