Java Virtual Machine Advanced Features
Java Virtual Machine Advanced Features
Advanced features
• Syntax:
– public static short arrayFillNonAtomic(byte[]
bArray, short bOff, short bLen, byte bValue)
• Non-atomically fills the elements of a byte array with
specified value.
Transactions
• Atomicity guarantees atomic modifications of a single data
element
• However, an applet may need to atomically update several
different fields in several different objects
• For example: credit or debit transaction
– Increment the transaction number
– Update the purse balance
– Write a transaction log
Transactions
• Java card technology supports a similar transactional
model, with commit and rollback
• It guarantees that complex operations can be accomplished
atomically; either they successfully complete or their
partial results are not put into effect.
Commit Transactions
// begin a transaction
[Link]();
//all modifications in a set of updates of
//persistent data are temporary until
//the transaction is committed
……………
//commit a transactions
[Link]();
Abort Transaction
• Transactions can be aborted either by an applet or by the
JCRE (by calling [Link]
method)
• Aborting a transaction causes the JCRE to throw away any
changes made during the transaction and restore
conditionally update fields or array elements to their
previous value
• A transaction must be in progress when the
abortTransaction method is invoked; otherwise, the
JCRE throws a TransactionException.
Abort Transaction
• If power is lost or an error occurs during a transaction, the
JCRE invokes a JRCE internal rollback facility the next
time the card is powered on to restore the data involved in
the transaction to their pre-transaction value
Nested Transaction
• Transaction in the Java Card platform cannot be nested
(except JC3.0 co.-ed).
• There can be only one transaction in progress at a time.
(due to the limited computing resources of smart card.)
• If [Link] is called while a
transaction is already in progress, JCRE throws a
TransactionException
Commit capacity (I)
• To support the rollback of uncommitted transactions, the
JCRE maintains a commit buffer where the original
contents of the updated fields are stored until the
transaction is committed.
• The size of the commit buffer varies, depending on the
available card memory.
• Due to the size of commit buffer, putting too many things
in a transaction may not be possible
Commit capacity (II)
• Before attempting a transaction, an applet can check the
size of the available commit buffer against the size of the
data requiring an atomic update
• JCSystem provides two methods
– [Link]() return the total
number of bytes in the commit buffer.
– [Link]() returns the
number of unused bytes left in the commit buffer.
Commit capacity (III)
• In addition to storing the contents of fields modified during
a transaction, the commit buffer holds additional bytes of
overhead data (location of the fields).
• The amount of overhead data depends on the number of
fields being modified
• If the commit capacity is exceeded during a transaction,
the JCRE throws a TransactionException. Even so,
the transactions is still in progress unless it is explicitly
aborted by the applet or by the JCRE.
TransactionException
• JCRE throws a TransactionException if
– nested transaction
– commit buffer overflow
• TransactionException provides a reason code to
indicate the cause of the exception:
– IN_PROGRESS: beginTransaction was called while a transaction was
already in progress
– NOT_IN_PROGRESS: commitTransaction or abortTransaction
– BUFFER_FULL:
– INTERNAL_FAILURE
Local variables and Transient
Objects during a transaction
• Update to transient objects and local variables are never
undone regardless of whether or not they were inside a
transaction
• See the example 1 in next page
– key_buffer: transient object
– a_local: local variable
• See the example 2
– Ref_1: reference to a transient object
– Ref_2: reference to a persistent object
EXAMPLE1
Byte[] key_buffer = [Link]
(KEY_LENGTH, JCSystem.CLEAR_ON_RESET);
[Link]();
[Link] (src, src_off, key_buffer, 0,
KEY_LENGTH);
[Link] (src, src_off, key_buffer, 0,
KEY_LENGTH);
[Link] (AIDA,parameter)
[Link] (AIDB,parameter)
null
Reference on X or null SecurityException
Reference on O or null
O . M1()
result
[Link] (AIDA,parameter)
[Link] (AIDB,parameter)
Reference on O or null
Reference on O or null
Y . M2()
result
Example server side
The server must create a shareable interface that extends
[Link]
package myPackage
import [Link]
public interface loyaltyInterface extends Shareable {
public void grantPoint (short amount)
}
• The server implements the interface
package myPackage
public class loyaltyApp extends Applet implements loyaltyInterface {
private short (miles);
public void grantPoint (short amount) {
miles= (short) (miles+amount) ;
}
}
Example client side
• The client needs to know the server AID,
import myPackage;
public class clientApp extends Applet {
// request SIO from the server
loyaltyInterface sio = (loyaltyInterface)
[Link] (AIDServer,
(byte) 0)
if (sio ==null){[Link]();}
[Link](theAmount);
• The JCRE looks up the server applet and invokes the server
getShareableInterfaceObject with the client AID as parameter !!!
Example server side revisited
The server must create a shareable interface that extends
[Link]
package myPackage
import interface loyaltyInterface extends Shareable {... }
• The server implements the interface
package myPackage
public class loyaltyApp implements loyaltyInterface{ private
short (miles);
public void grantPoint (short amount) {
miles= (short) (miles+amount) ;
}
public Shareable getShareableInterfaceObject
(ClientAID, byte param){
if ([Link]( myFriend)){
return ((Shareable)this)}
else {return null}
}
Example client side revisited
• The client needs to know the server AID,
import myPackage;
public class clientApp extends Applet {
// request SIO from the server
loyaltyInterface sio = (loyaltyInterface)
[Link]
(AIDServer, (byte) 0)
if (sio == null){[Link]();}
[Link](theAmount);
Agenda
• Sharing mechanism
• Garbage collection
• Logical channel
• Byte code verification
• RMI
Java Card applet life cycle
Compilation Conversion
JCVM
Applet Applet Applet
sources class files cap file Off-card
load On-card
AID Instance
delete Applet
Loaded
Install / Register
Select Process
Deselect return
Applet Installation
• Applet installer is an optional part of the JCRE (if no post issuance)
• If the installer is included, then the deletion manager is mandatory,
• To the terminal the installer appears to be an applet (AID, select,…)
but doesn’t need to be installed as an applet,
• Installer applet privileges are the same as the RTE,
– Read and write directly in memory,
– Access object owned by other applets,
– Invoke non-entry point methods of the RTE,
– Able to invoke the install method of a new applet.
Deletion manager
• To the terminal the DM appears to be an applet,
• Same as the installer it doesn’t need to be implemented as an applet,
• Same privileges as the installer,
• An applet instance deletion may be unsuccessful :
– An object owned by the applet instance is referenced from an object
owned by another applet instance,
– An object owned by the applet instance is referenced from a static field,
– An applet instance belonging to the context is active on the card
• Applet instance deletion must be atomic,
• The resource used by the deleted instance may be recovered for future
use.
Applet deletion
• Request deletion sent in the form of an APDU,
• To be eligible for deletion, no object on the card should have
dependencies on the applet to be deleted,
• Warning static objects belong to the package not the applet…
• Call the uninstall () of the [Link]
interface
– Must implement AppletEvent interface
– Before applet deletion,
– Allow to release resources such as static objects and shared keys,
– Backup data into another applet space.
– Notify all other dependant applets,
Guidelines
• Calling uninstall method does not guarantee that the applet
will be deleted,
– Other applet are still dependent on this applet,
– A tear occurs before the deletion element are processed
• Implement the uninstall method defensively:
– The applet continues to function consistently and securely if
deletion fails,
– Applet can withstand a possible tear during the execution,
– The uninstall method can be called again if deletion is reattempted.
Requesting the uninstall
private class test extends Applet implements AppletEvent{
private boolean disableApp = false;
...
public void uninstall () {
if (!disableApp){
// to protect against tear
[Link] ();
disableApp = true; // marked uninstalled
... Remove dependency
[Link]();
}
}
public boolean select (){
if (disableApp) return false ;
return true;
}
Object deletion
• Allows to recover unreachable objects,
• Such an object can neither be pointed to by a static field nor by an
object field,
• Objects in persistent memory and potentially volatile memory,
• Needs eeprom write operations, slow and security marker.
• GC “on request”, optional,
• Initiated by the applet but activated by JCRE at the return of process
command
• The API in [Link] contains two
static methods:
– isObjectDeletionSupported,inform applet if object deletion is
supported by the platform,
– requestObjectDeletion (), invoke the mechanism.
Guidelines
• When throwing exception avoid creating exception objects
and rely on the GC to perform clean up,
• Do not create objects in method or block scope, the Object
deletion mechanism should not be considered as a GC !
• Use the deletion mechanism when a large object such as a
certificate or key must be replaced by a new one
• Use the object deletion mechanism when object resizing is
required.
Requesting the deletion
Void updateBuffer (byte requiredSize)
try {
if (buffer != null && [Link] == requiredSize)
{return}
[Link] ();
byte[] oldBuffer = buffer;
if (oldBuffer != null)
[Link]();
[Link] ()
} catch (Exception e) {
[Link](); }
}
Agenda
• Sharing mechanism
• Garbage collection
• Logical channel
• Byte code verification
• RMI
Logical Channels
• In Java Card the session-specific security data of an application is
available only when selected,
• When deselected, part of RAM is cleared (keep in mind the transient
object) and session keys for example are lost,
• In a multi application card, need to switch from an application to
another,…
• Problems :
– Java Card is currently mono threaded
– Not possible to perform a new action while the previous one is not
completed
– An application shall be selected to process an APDU command
Handling channel information on
APDU commands
A terminal can start up to 20 sessions (JC 2.2.2, 4 only with JC 2.2.1)
– Each session uses a logical channel,
– Session are associated with IO interface, one for contact and one for
contact less communication (ISO 14443),
– An applet instance can receive APDU from both IO interface, so an applet
can be connected up to 40 logical channels,
– If two APDU arrives concurrently, the contact less session has the higher
priority,
– Power loss on the contacted interface implies a card reset even a contact
less session is in progress.
Channel 0 is the default channel for both IO interface,
– Opened at card reset and cannot be closed,
– All other channels are closed at reset.
Applet selection
Multiplex command into the APDU channel, if no sharing.
If sharing is needed, use multi selectable applets…
Only specific APDU commands can contain encoded logical information
An applet can be selected on one logical channel, but also through several
channels (contact less or not),
Use of the CLA byte,
– If CLA = “0000 00cc” then the two least bits (cc) are used for the logical channels
which range from 0 to 3, i.e. :0x0X and 0x1X
– If CLA = “0100 cccc” then the four least bits (cccc) are used for the logical
channels which range from 4 to 19, i.e. 0x4Y, 0x5Y, 0x6Y and 0x7Y.
– Card compliant with 2.2.2 spec must also support proprietary class value
0x8X, 0x9X, 0xAx and 0xBX (channel 0 to 3) and 0xCY, 0xDY, 0xEY
and 0xFY (Channel 4 to 19).
Default applet
Currently selected Applet : the applet which is responding to an APDU
Normally an applet can only be selected if a command SELECT FILE is
successfully treated,
Some applet need a default applet to be selected after reset, specially for
opening a new logical channel,
Logical channels may share the same instance applet as the default applet
instance.
Card reset
After a reset the JCRE performs initialization and checks the
presence of a default applet,
– It provides the channel 0 to this applet,
– Select this applet and execute the select() method of this applet
– If an exception is thrown or returns false, the JCRE must indicate
that no active applet are available on channel 0,
– The JCRE must send an ATR.
Applet selection
Two possibilities
– Using a command APDU MANAGE CHANNEL OPEN
• Open a channel from an already opened channel and selection of a default
applet on that channel,
• If P2 equals 0, let the JRTE chose the channel in other case P2 must be in the
range 0..19.
• Call the select method or [Link] if required,
• In case of an exception or a return false, the channel is closed (status code
0x6999 ),
– With a command APDU SELECT FILE
• Select an applet on a new logical channel
In both cases, the CLA byte must specify either the channel to be open or
the open channel
– INS=0x70 for the command APDU MANAGE CHANNEL OPEN
– INS=0xA4 for the command APDU SELECT FILE
Deselecting an applet
While receiving a command APDU MANAGE CHANNEL CLOSE
(INS=0x70)
While selecting another applet using a SELECT FILE,
Or selecting the same applet on another channel specified in the CLA
byte,
The RTE call the [Link]
(appInstStillActive) method, where the
appInstStillActive parameter is set to true if the same applet
instance is still active on another logical channel,
Multi selectable applet
Multi-selectable applets shall implement the interface
[Link]
In such a case, the following methods are invoked during
selection and de-selection respectively,
– [Link] ()
– [Link]()
When a multi-selected applet instance is deselected from of
the logical channels the method
[Link] is called
When this instance is the last active, the
[Link] is called
Agenda
• Sharing mechanism
• Garbage collection
• Logical channel
• Byte code verification
• Software based attacks
JVM offensive vs. defensive
• Sun defines only a byte code format and a verification
algorithm,
• It is possible to code a defensive virtual machine,
• Until now a few cards implement BC verification or
partially
• If post issuance is allowed without any cryptographic
means to authenticate the sender, it becomes unavoidable
to implement it
• Often some of the test are implemented in a hybrid way
Exemple
Consider the following code fragment:
BO 20 xx xx 01 01 00 Processes
90 00 the request
BO 30 xx xx 00 01 Processes
09 90 00 the request
[Link]( 1 ) Processes
void / exception the request
[Link]() Processes
9 the request
Client Object
RMI paradigm
APDU
Client Object
Interface
Definition
Interface
Definition
Implementation
of the service
Card Applet
Card Applet
Prepares the
command Command APDU
process( apdu )
Decodes the command
Processes the request
Prepares the response
Processes
the request
Java Card 2.2 RMI sequence
diagram (under the hood)
Prepares the
command Command APDU process( apdu )
Decodes the
command
method( params )
Processes
Return value the request
Prepares the
Response APDU response
Decodes the
response
Return value
The complete picture
Client side Server side
RMI services
1- create
Dispatcher
myApplet applet
JCRE
The complete picture
Client side Server side
Dispatcher
myApplet applet
JCRE
The complete picture
Client side Server side
RMI services
Dispatcher
myApplet applet
4- create
RMI services
5- create
Dispatcher
JCRMI connect
myApplet applet
6- select myApplet
RMI services
Dispatcher
JCRMI connect
myApplet applet
RMI services
7- get initial reference
Dispatcher
JCRMI connect
myApplet applet
Dispatcher
JCRMI connect
myApplet applet
C-MAC
3-DES Session key
Cla’ Lc’ Data C-MAC ICV
APDU data field encryption
• If confidentiality is required, the off-card entity encrypts
the “clear text” data field of the command message being
transmitted to the card.