0% found this document useful (0 votes)
35 views

Java Card: Erik Poll Erik Poll

The document discusses the Java Card architecture, which allows for multiple applications to reside on a single smart card and be written in Java rather than a chip-specific machine code, while the Java Card runtime environment and API provide a sandbox and basic functionality on resource-constrained smart card hardware. It notes both advantages of Java Card such as vendor independence and easier programming compared to traditional smart cards, as well as disadvantages like performance overhead and complexity increasing security risks.

Uploaded by

baranovay
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views

Java Card: Erik Poll Erik Poll

The document discusses the Java Card architecture, which allows for multiple applications to reside on a single smart card and be written in Java rather than a chip-specific machine code, while the Java Card runtime environment and API provide a sandbox and basic functionality on resource-constrained smart card hardware. It notes both advantages of Java Card such as vendor independence and easier programming compared to traditional smart cards, as well as disadvantages like performance overhead and complexity increasing security risks.

Uploaded by

baranovay
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 52

Java Card

Erik Poll
Digital Security
R db d U
Radboud University
i sit Nij
Nijmegen

1
Contents
• Java Card architecture
• Java vs Java Card

• APDUs & RMI


• transient and persistent data
• transactions
• crypto

• fun with transactions

2
smartcard operating systems
• Traditional smartcard programming: native applications,
applications developed for
specific chip, using a proprietary “operating system”
• instruction set of the chip
p is confidential

• Two modern smartcard OSs (with associated programming languages)


th t b
that break
k this
thi mold:
ld
• MULTOS
• JavaCard

• NB a smartcard OS is not like Windows/Linux,


but like a pre-UNIX set of libraries providing basic functionality

3
old vs new smartcards

• one program (applet) • Applet written in high-level


• written in machine-code language (eg Java Card)
• compiled into bytecode
for a specific chip
• stored in EEPROM
• burnt into ROM or uploaded once • interpreted
i t t d on cardd
to EEPROM
• multi-application: several applets
on one card
• post-issuance: adding or deleting
applets on cards “in the field”

4
Java Card architecture

a
applet

a
applet

a
applet
t

t
Java Card Java Card API JCRE
Java
Virtual Card
Machine platform
(mini OS) (Java Card
runtime
environment)
smartcard hardware

5
Java Card vs Java architecture
Java Card applets are executed in a sandbox,
sandbox like applets in a web browser

But important differences


differences:
• no bytecode verifier on most cards (due to space required)
• downloading applets is controlled by digital signatures instead, using the
Global Platform API (formerly Visa Open Platfrom)
– plus bytecode verification, if card supports it
• sandbox more restrictive,
restrictive and includes runtime firewall to provide
protection between applets and between applets and the OS

6
Java Card firewall
RUNTIME checks to
prevent access to
• fields & methods of
other applets

ap

ap
ap

• objects
bj ts owned d by
b
pplet 2

pplet 3
pplet 1

other applets
even if these are public!

Exceptions:
• applets can access
Java Card Runtime Environment some JCRE-owned
JCRE d
JCRE = VM + API objects, eg APDU buffer
• JCRE can access anything
smartcard hardware
There is a way for applets
to expose functionality to
eachh other,
h using
i
Shareable interfaces but
you won’t be needing that
7
Advantages of JavaCard?
• vendor independence
vendor-independence
• easy to program
– higher-level
hi h l l language
l => smaller
ll programs with
ith fewer
f bugs
b
– standard functionality (eg for PINs) provided once by the API
• esp security-sensitive functionality, so people don't mess things
up by implementing this themselves
• open standard
– no reliance on security-by-obscurity
• specs can be
b studied
di d and
d criticised
i i i d
– but: all implementation tightly closed, and bug-fixes in the specs
happen secretly
Disadvantages of JavaCard?
• overhead of VM
makes cards slow and requires lots of memory => expensive
• trust?
how secure is the whole JavaCard infrastructure?
complicated platform, and complexity <-> security
• ease of programming?
may be deceptive, and invite non-experts to program cards and make silly
mistakes
• easy for attacker to experiment with card?
esp.
p if she can get
g blank JavaCard of the some brand to look for bugs
g or
weaknesses... NB security by obscurity has its merits!
The Java Card language
• A dialect of Java tailored to smartcard
– superset of a subset of Java

• subset of Java (due to hardware constraints)


– no threads, doubles, Strings, multi-dimensional arrays, and a very
restricted API
– support for int optional
– garbage collection optional
• with
ith some extras
t (d to
(due t hardware
h d peculiarities)
li iti )
– communication via APDUs or RMI
– persistent & transient data in EEPROM &RAM
– transaction mechanism

10
Don’tt create garbage !
Don
collector and very limited memory!
JavaCards usually have no garbage collector,

Hence no calls of
new ...
in your
y code except p in the installation p
phase
(which will include the applet's constructor)

More generally, JavaCard programs should not look like normal Java
programs but more like C/machine code written in Java syntax
programs,
In particular, go easy on the OO: most objects should be byte arrays

11
The Java Card language

• JavaCard uses an optimized form of class files, called cap-files

11. compiler
il translates
t l t .java
j tto .class
l
2. converter translates .class to .cap
compressing
p g code,, eg
g replacing
p g method & field names by
y offsets

• JavaCard uses 16 bit arithmetic,, not 32 bit

12
16 bit arithmetic
JavaCard code contains many(short)casts:
all intermediate results (which are of type int) must be cast to short
so that results
r su ts are
ar the
th same
sam on a 16
6 bits
ts JavaCard
Ja a ar VM
as on a normal 32 or 64 bits Java VM
short s;
; byte
y 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

Moral of the story: your JavaCard code should look really ugly,
ugly
with(short)casts all over the place.

13
(un)signed bytes
• bytes in Java and Java Card are signed
ie. for any byte b
b Є {{-128,, ..., 127}
7}

• To interpret byte as unsigned , write


b & 0x00FF Є {0, ..., 255 }

Moral of the story: your JavaCard code should look really really ugly,
with(short)casts and & 0x00FF all over the place.

14
the Java Card API
• A subset of Java
Java’ss API
– no need for most standard I/O classes
– no Strings
g
– no clone() in Object
– ...
• plus some extras for
– smartcard I/O with APDUs using ISO7816
– persistent
i and
d transient
i d
data
– transactions

15
Java Card API packages
• java
java.lang
lang
Object, Exception, ...
• javacard.framework
javacard framework
ISO7816, APDU, Applet, OwnerPIN, JCSystem
• javacard.security
KeyBuilder, RSAPrivateKey, CryptoException
• javacardx.crypto
j yp
Cipher

16
Card-terminal communication
• Communication via APDUs,
APDUs as defined in ISO7816,
ISO7816 using
javacard.framework.APDU
• JavaCard OS sends a command APDU to an applet, by invoking the
process(APDU the_apdu)
j
method of an applet. This APDU object contains a byte array buffer
the_apdu.getBuffer()
• Card sends a response APDU back, by invoking API methods on this
APDU object,
bj t eg
the_apdu.sendBytes(offset,length)

See the process methods of the *Applet.java examples on the course


webpage (sect
(section
on “smart
smart cards pract
practicalities”)
cal t es ) on how APDUs are used.

17
Java Card I/O with APDUs
1. terminal sends
command APDU,
APDU
incl. applet ID

2 OS selects applet
2.
a
applet

a
applet

a
applet
and invokes its
process method
t

t
3. applet executes

4. applet sends
response APDU
Java Card platform
terminal
smartcard hardware

18
RMI
• dealing with APDUs cumbersome
• JavaCard 2.2 introduced RMI (Remote Method Invocation)
– tterminal
rm na invokes
n o smmethods
tho s on applet
app t on the
th smartcard
smartcar
– platform translates this method invocation into APDUs
(so-called marshalling & unmarshalling)

BUT: only works if method parameters fit in the APDU buffer


So there is limit on total size on all method arguments combined.
Nobody in industry is using RMI; easier if you don't.

19
Contents
• Java Card architecture
• Java vs Java Card
• APDUs & RMI
• transient and persistent data
• transactions
• crypto

• fun with transactions

20
Recall the smartcard hardware
• ROM
– program code of VM, API, and pre-installed applets
– though
g most of that will be in EEPROM
• EEPROM
– program code of applets
– persistent storage of the data, incl. objects with their fields, and
• RAM
– transient
t si t storage
st of
f data,
d t eg call
ll stack,
st k incl.
i l method
m th d parameters
m t s and
d
local variables

JavaCard programmer only has to worry about RAM and EEPROM

21
persistent (EEPROM) vs transient (RAM)
• data stored in EEPROM is persistent,
persistent and is kept when power is lost
data stored in RAM is transient, and is lost as soon as power is lost

• By default
• fields of objects
j are stored in EEPROM
– so objects are in EEPROM
• local variables and method arguments are in RAM

Effectively: heap in EEPROM, stack in RAM

• Only exception: the API offers methods to allocate arrays in RAM


instead of EEPROM
 NB only the content of these arrays in RAM; the array header,
header incl
incl.
its lengths, are in EEPROM

22
persistent (EEPROM) vs transient (RAM)
public class MyApplet extends javacard
javacard.framework.Applet{
framework Applet{
byte[] p;
short balance;
SomeObject o;
p = new byte[128];
o = new SomeObject();
balance = 500;

public short someMethod(byte b) {


short s;
Object oo = new Someobject();
...
}

23
persistent (EEPROM) vs transient (RAM)
public class MyApplet extends javacard
javacard.framework.Applet{
framework Applet{
byte[] p; // persistent, ie in EEPROM
short balance;
SomeObject o;
p = new byte[128];
o = new SomeObject();
balance = 500;

public short someMethod(byte b) {


short s; // transient, ie in RAM
Object oo = new Someobject(); // DANGER: garbage?
...
}

24
allocating arrays in RAM
public class MyApplet extends javacard
javacard.framework.Applet{
framework Applet{
byte[] t, p;
short balance;
SomeObject o;

// persistent array p and persistent object o


p = new byte[128];
o = new SomeObject();
S Obj t()
// transient array t
t = JCSystem.makeTransientByteArray((short)128,
JCSystem.CLEAR_ON_RESET);

25
allocating arrays in RAM
public class MyApplet extends javacard
javacard.framework.Applet{
framework Applet{
byte[] t, p;
NB the field t is persistent,
short balance; t length is persistent,
t.length persistent and
SomeObject o; only the contents t[..] is transient

// persistent array p and persistent object o


p = new byte[128];
o = new SomeObject();
S Obj t()
// transient array t
t = JCSystem.makeTransientByteArray((short)128,
JCSystem.CLEAR_ON_RESET);

26
Why use transient arrays ?
For reasons of efficiency,
efficiency functionality or security:
• “scratchpad” memory
– RAM is faster & consumes less power than EEPROM
– EEPROM has limited lifetime
• automatic clearing of transient array
– on power-down,
power down and
– on card reset or applet selection
y or security
can be useful for functionality y

NB you only have very limited amount of RAM.


Use one or two global transient arrays,
arrays allocated once,
once as scratchpad.
scratchpad
Don't allocate different scratchpad arrays for different methods.

27
transient array example
public class MyApplet {
boolean keysLoaded, blocked; // persistent state
private RSAprivateKey priv;

byte[] protocolState; // transient session state


...

protocolState = JCSystem.makeTransientByteArray((short)1,
JCSystem.CLEAR_ON_RESET);
// automatically reset to 0 when card starts up
....

28
Don’tt create garbage !
Don
JavaCards usually have no garbage collector
collector, and very limited memory!

Hence NO CALLS OF
new ...
makeTransientByteArray( )
makeTransientByteArray(..)
in your code except in the installation phase
(which will include the applet's constructor)

29
Contents
• Java Card architecture
• Java vs Java Card
• ISO 7816, APDU
APDU’s,
s, RMI
• transient and persistent data
• transactions
• crypto

• fun with transactions

30
transactions example
private int balance;
private int[] log;
//@ invariant (
(* log[n]
g[ ] is p
previous balance *);
)
...

// Update log
n++;
l [ ] = b
log[n] balance;
l what if a card
// Update balance
tear occurs
here ?
balance = balance – amount;

31
transactions
• The power supply of a smartcard can be interrupted at any moment,
moment by
a so-called card tear.
• The JavaCard VM guarantees atomiticy y of bytecode
y instructions
(like a normal VM does, except for operations on doubles)
• The JavaCard API offers methods to join several instructions into one
atomic
t i action,
ti iie. atomic
t i update
d t of
f th
the EEPROM
EEPROM, called
ll d a transaction.
t ti

If the power supply stops halfway during a transaction,


transaction
all assignments of that transaction are rolled back/undone.
pp
This happens the next time the card powers
p up.
p

32
transactions example
private int balance;
private int[] log;
//@ invariant ( (* log[n]
g[ ] is p
previous balance *);
)
...
JCSystem.beginTransaction();
// Update log
n++;
l [ ] = b
log[n] balance;
l
// Update balance
balance = balance – amount;
JCSystem.commitTransaction();

33
transactions
• API methods for transactions: in class
javacard.framework.JCSYstem
g
static void beginTransaction() ()
static void endTransaction()
static void abortTransaction()

• Transactions affects all persistent data in EEPROM (ie the heap)


– exceptt some very specific
ifi EEPROM fi
fields:
ld
the try-counter fields of PIN-objects
• Transactions do not roll back changes to transient data in RAM
(ie the stack)

34
example transaction problem

[Source: AD, November 10 2006]

35
JavaCard 3.0
30
The next
next-generation
generation smart card OS
• not just arrays, but arbitrary objects can be in RAM
• garbage
b collection
ll ti
• multi-threading
security worries !
• communication with https://
the smartcard is a web-server!
But who will use it??
intended market: telco
not all card manufacturers are producing JC 3.0 cards

36
Java(Card)
( ) Crypto
yp
Crypto keys in your project code
Do not ‘hard
hard code’
code key material in source code
or
Document that you have done this in your final report,
and then document where

38
Crypto in Java and JavaCard
• Java Crypto Entension (JCE) provides classes
• SecureRandom
• MessageDigest
• Signature and Mac
• SecretKey, PublicKey
bli and
d PrivateKey
i
• Cipher – this is the object that does the crypto work
• Certificate
• Crypto in JavaCard works the same
except algorithms specified with a short instead of a String

39
SecureRandom

SecureRandom random =
SecureRandom.getInstance("SHA1PRNG");
random.setSeed(0x3141592653589793L);
d tS d(0 3141592653589793L)
...
byte[] output = new byte[8];
random.nextBytes(output);

40
MessageDigest (ie
(ie. a hash)

byte[] input1 = ...;


byte[] input2 = ...;
M
MessageDigest
Di t digest
di t = M
MessageDigest.getInstance("SHA-1");
Di t tI t ("SHA 1")
digest.update(input1);
digest.update(input2);
...
byte[] output = digest.digest(); // returns 20 byte digest

41
Signed Message Digest (ie.
(ie a MAC)

byte[] input = ...;


PrivateKey privkey = ...;
Si
Signature
t signature
i t = Si
Signature.getInstance("SHA1withRSA");
t tI t ("SHA1 ithRSA")
signature.initSign(privkey);
signature.update(input);
...
byte[] output = signature.sign(); // returns 20 byte MAC

Such a signed message digest is known as a Message Authentication Code


(MAC) andd used
d tto ensure iintegrity
t it of
f th
the message.

42
Encryption
byte[] input = ...;
PublicKey pubkey = ...;
Ci h
Cipher cipher
i h = Cipher.getInstance("RSA");
Ci h tI t ("RSA")
cipher.init(Cipher.ENCRYPT_MODE,pubkey);
cipher.update(input);
...
byte[] output = cipher.doFinal();

43
Miscellaneous issues
• You can generate keys on card and/or in the terminal
• the card can only generate RSA keys in CRT format
• To pass keys from terminal to card or vv,
vv
you need to extract the raw byte arrays from the Key-objects
• beware that the maximum size of an APDU is limited!
• If you create RSA keys in the terminal, beware that the JCE may
provide a 1024 bit (= 128 byte) key as a byte array of length 129,
because it uses a signed representation, with a leading 0x00.
• remove the leading 0x00 to use such values on the card
• Read the JavaDocs!
which eg. say that ALG_RSA_PCKS1 is only suitable for limited length message

44
That’s all !
Fun with transactions
• The JavaCard transaction mechanism fundamentally affects the
semantics of the language in a major way!
Presentingg the transaction feature
f in a f
few apparently
pp y simple
p API calls
is a bit misleading...
• The complexity
p y it introduces can cause major
j security
y headaches
Fun with transactions
Class C
{ private short i = 5;

void m(){

JCSystem.beginTransaction();
i++;
JCS t
JCSystem.abortTransaction();
b tT ti ()
// What should the value of i be?
// 5, as assignment to i is rolled back

47
Fun with transactions
Class C
{ private short i = 5;

void m(){
short j = 5;
JCSystem.beginTransaction();
i++; j++;
JCS t
JCSystem.abortTransaction();
b tT ti ()
// What should the value of i be here?
// 5, as assignment to i is rolled back
// What should the value of j be here?
// 6, as RAM-allocated j is not rolled back
}

48
Fun with transactions
Class C
{ private short[] a;

void m(){
a = null;
JCSystem.beginTransaction();
a = new short[4];
JCS t
JCSystem.abortTransaction();
b tT ti ()
// What should the value of a be here?
// a should be reset to null

49
Fun with transactions
Class C
{ private short[] a;

void m(){
short[] b;
JCSystem.beginTransaction();
a = new short[4]; b = a;
JCS t
JCSystem.abortTransaction();
b tT ti ()
// What should the value of b be?
// null, as creation of a is rolled back

// Buggy VMs have been known to mess this up...


}

50
Fun with transactions
Class C
{ private short[] a;

void m(){
short[] b;
JCSystem.beginTransaction();
a = new short[4]; b = a;
JCS t
JCSystem.abortTransaction();
b tT ti ()
// Assume buggy VM does not reset b
byte[] c = new byte[2000];
// short array b and byte array c may be aliased!
// What will b.length be?
// What happens if we read/write b[0..999]?
// What happens if we read/write b[1000..1999]?
}
51
Fun with transactions

Class Si
Cl SimpleObject
l Obj t {{public
bli short
h t llen; }
Class C
{ private short[];
void m(){
short[] b;
JCSystem.beginTransaction();
a = new short[4]; b = a;
JCSystem.abortTransaction();
// buggy VM forgets to clean up b
Object x = new SimpleObject();
x.len = (short)0x7FFF;
// What will b.length
g be?
// It might be 0x7FFF...
}
52

You might also like