<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>On the road to Bandol &#187; Tutorial</title>
	<atom:link href="http://javacard.vetilles.com/category/miscellaneous/tutorial/feed/" rel="self" type="application/rss+xml" />
	<link>http://javacard.vetilles.com</link>
	<description>A weblog on Java Card, security, and other things personal</description>
	<lastBuildDate>Mon, 18 Aug 2025 06:48:26 +0000</lastBuildDate>
	<language>en-US</language>
		<sy:updatePeriod>hourly</sy:updatePeriod>
		<sy:updateFrequency>1</sy:updateFrequency>
	<generator>https://wordpress.org/?v=4.0.32</generator>
	<item>
		<title>Q&amp;A: How to generate and protect keys in Java Card?</title>
		<link>http://javacard.vetilles.com/2011/03/06/qa-how-to-generate-and-protect-keys-in-java-card/</link>
		<comments>http://javacard.vetilles.com/2011/03/06/qa-how-to-generate-and-protect-keys-in-java-card/#comments</comments>
		<pubDate>Sun, 06 Mar 2011 20:59:50 +0000</pubDate>
		<dc:creator><![CDATA[Eric Vétillard]]></dc:creator>
				<category><![CDATA[Q&A]]></category>
		<category><![CDATA[crypto]]></category>
		<category><![CDATA[Java Card]]></category>

		<guid isPermaLink="false">http://javacard.vetilles.com/?p=703</guid>
		<description><![CDATA[Cryptographic keys are often at the heart of Java Card applications, which often rely on cryptography to protect their data in storage and/or communication. Keys therefore become the most sensitive pieces of data in such applications. All evaluators know that, as getting the values of secret/private keys is the ultimate goal of a security evaluation. [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>Cryptographic keys are often at the heart of Java Card applications, which often rely on cryptography to protect their data in storage and/or communication. Keys therefore become the most sensitive pieces of data in such applications. All evaluators know that, as getting the values of secret/private keys is the ultimate goal of a security evaluation.</p>
<p>Let&#8217;s start by secret keys, used in symmetric algorithms like AES and DES. Such keys are just random values of a given length, without any strong mathematical property((Keys must verify some properties, though, as some values will not provide an adequate protection; however, the probability to get one of these keys is quite low, and no test is usually performed on the keys that are generated on a smart card.</p>
<p>A secret key therefore starts its life as a byte array filled with random data. For a triple DES key, we need 16 bytes of data. Two origins are possible for this data: it may be imported from the outside through a personalization command, or it may be generated on the card using a random number generator. Here is an example using a RNG:</p>
<pre>
  byte[] keyBytes = JCSystem.getTransientByteArray(COD,16);
  RandomData rng = RandomData.getInstance(ALG_SECURE_RANDOM);

  rng.generateData(keyBytes,0,16);
</pre>
<p>The next step consists in creating the key object and assigning the random data to the key object:</p>
<pre>
  DESKey key = KeyBuilder.buildKey(ALG_DES, LENGTH_3DES_2KEY);
  key.setKey(keyBytes);
</pre>
<p>When that is done, the essential is done. At this point, applet developers are not responsible any more for the protection of the key. The Java Card platform is in charge of implementing the key container classes in a way that protects keys from disclosure at all times (when they are stored and when they are used). In most cases, this means that the key values will be encrypted using another key, managed by the platform.</p>
<p>Applet developers should refrain from any attempt to protect cryptographic keys when they are stored in Key objects. However, the values of keys still need to be protected, whenever they are not stored in the proper containers. For instance, the raw data used to initialize the key should be cleared after the initialization. The initialization code therefore is as follows:</p>
<pre>
  try {
    rng.generateData(keyBytes,0,16);
    key.setKey(keyBytes);
  } finally {
    Util.arrayFillNonAtomic(keyBytes,0);
  }
</pre>
<p>With private keys (used in assymetric algorithms like RSA), things are even simpler, since there is a dedicated class to generate key pairs (a public key and a private key). This means that the actual key values are kept during the entire process under the protection of the platform.</p>
<p>Basically, the two rules about keys are:</p>
<ul>
<li>Keys stored in Key container are protected by the platform, and only by the platform.</li>
<li>Plaintext key values should not be stored in byte arrays, expect for very short periods of time when absolutely needed, and the values should be cleared when then are not used any more.</li>
</ul>
<p>Following them is a good start in the proper protection of cryptographic keys.</p>
]]></content:encoded>
			<wfw:commentRss>http://javacard.vetilles.com/2011/03/06/qa-how-to-generate-and-protect-keys-in-java-card/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Q&amp;A: What do NFC NDEF Signature records bring?</title>
		<link>http://javacard.vetilles.com/2011/02/07/qa-what-do-nfc-ndef-signature-records-bring/</link>
		<comments>http://javacard.vetilles.com/2011/02/07/qa-what-do-nfc-ndef-signature-records-bring/#comments</comments>
		<pubDate>Mon, 07 Feb 2011 12:57:01 +0000</pubDate>
		<dc:creator><![CDATA[Eric Vétillard]]></dc:creator>
				<category><![CDATA[Q&A]]></category>
		<category><![CDATA[Mobile Security]]></category>
		<category><![CDATA[NFC]]></category>

		<guid isPermaLink="false">http://javacard.vetilles.com/?p=696</guid>
		<description><![CDATA[Here is another question related to NFC, this time about what I understand of NDEF signatures (could be incomplete). The NFC Forum has recently added the possibility to include a signature record in tags. Adding such a signature can be used to ensure that the content of the tag (say, a URL) has been written [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>Here is another question related to NFC, this time about what I understand of NDEF signatures (could be incomplete).</p>
<p>The NFC Forum has recently added the possibility to include a signature record in tags. Adding such a signature can be used to ensure that the content of the tag (say, a URL) has been  written by the person who sign it, and not modified afterwards. OK, so what does such a signature really bring in terms of security?</p>
<p>Well, I must admit that I am not really sure. Of course, one of the reasons is that I am yet to see a phone that verifies these signatures; I may also not have all the information. So far, I have read the NDEF spec, and the <a href="http://web.it.kth.se/~johanmon/theses/kilas.pdf" class="lipdf">thesis</a> by Markus KilÃ¥s on this topic.  So, let&#8217;s say that this entry will get modified at some point.</p>
<p>Let&#8217;s continue with the URL example, on a very simple, innocuous example: a tag in Nice that contains a URL pointing to explanations about the Ste-Reparate Cathedral. If this tag is signed, then we can expect that a mobile phone would verify the signature before to forward the URL to the browser. However, the mobile phone would also be able to read unsigned tags.</p>
<p>Let&#8217;s now consider the two main attacks on this kind of tags:</p>
<ul>
<li><strong>Cloning</strong>. The entire record can be read freely, so a signature doesn&#8217;t protect at all against cloning. A Nice supporter may be able to put a Ste-Reparate tag on a Notre-Dame de Paris  poster.</li>
<li><strong>Tag replacement</strong>. The signature does not protect against this. If a Paris supporter comes to Nice, removes the Ste-Reparate tag and replaces it with a Notre-Dame de Paris tag, this will work with a browser. Of course, the phone may display a small &#8220;Trusted&#8221; icon for a recognized signature, but unless all tags rapidly become signed, I doubt that users will notice this icon any time soon.</li>
</ul>
<p>So, my conclusion is that signatures are likely to be useless for this URL use case, at least before the industry reaches a global agreement on a way to define how signatures should be handled on phones.</p>
<p>Of course, signatures may still be very useful in proprietary applications, which may be used in the industry. In such cases, the signatures will be verified by a specific application. In that case, it would solve part of the tag replacement attacks, since it would mean that a tag from a given company could only be replaced by another tag from the same company (or a clone of it). This means that a good level of tamper-evidence will also be required.</p>
<p>Not really good looking so far, but if I have missed something, I would be really glad to update this to something more positive.</p>
]]></content:encoded>
			<wfw:commentRss>http://javacard.vetilles.com/2011/02/07/qa-what-do-nfc-ndef-signature-records-bring/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Q&amp;A: NFC attacks</title>
		<link>http://javacard.vetilles.com/2011/01/28/qa-nfc-attacks/</link>
		<comments>http://javacard.vetilles.com/2011/01/28/qa-nfc-attacks/#comments</comments>
		<pubDate>Fri, 28 Jan 2011 22:24:14 +0000</pubDate>
		<dc:creator><![CDATA[Eric Vétillard]]></dc:creator>
				<category><![CDATA[Q&A]]></category>

		<guid isPermaLink="false">http://javacard.vetilles.com/?p=690</guid>
		<description><![CDATA[Over the years, I got quite a few questions about Java Card and related technologies. As a diverging extension to the tutorial, and as a way to bring back some technical content here, I will try to write a few Q&#038;A entries on a regular basis. The first one is about NFC attacks, a topic [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>Over the years, I got quite a few questions about Java Card and related technologies. As a diverging extension to the tutorial, and as a way to bring back some technical content here, I will try to write a few Q&#038;A entries on a regular basis. The first one is about NFC attacks, a topic that currently raises some questions.</p>
<p>NFC is red hot these days, and NFC phones are starting to come out. So, what kind of attacks can we do with these phones? Are there really new things? Let&#8217;s try to look at a few things.</p>
<p>First, let me recall a few things about NFC. NFC is a <a href="http://www.nfc-forum.org/specs/" class="liexternal">complex standard</a>, with several modes of operation. To simplify things, we will only consider two:</p>
<ul>
<li><strong>Reader mode</strong>. In that case, the phone acts as a card/tag reader. This mode is activated by default, and will be used in particular to detect smart posters and other fun things of the sort.</li>
<li><strong>Card emulation mode</strong>. In that case, the phone acts as a smart card. You can use your phone as a payment card (for instance, using an EMV protocol), or as a transport card. This mode is usually not active by default. In card emulation mode, the applications typically run on a Secure Element (SE), which may be the UICC (SIM card), an Embedded Secure Element (soldered on the phone), or even a removable Secure MicroSD card (not yet widely supported, though).</li>
</ul>
<p>The first attack that most people think about is the unintended use of the smart card emulation applications. This is quite strange, because this is definitely an aspect in which the use of NFC enhances security. When you have a contactless card in your pocket, this card is always active; if it gets in a proper field, it will wake up and (maybe) start a transaction. With a NFC phone, it is possible to deactivate the listening; in that case, the phone will only listen after an explicit action from the user (for instance, starting a payment application). You don&#8217;t have to do that, and you can also leave your phone activated by default. This is a compromise between security and ease of use that is left to the end user&#8217;s decision. However, in all cases, the security is at least as good as what you get with a standard contactless card.</p>
<p>The next category of attacks comes from mobile applications, still in card emulation mode. Why mobile applications, since the card emulation applications run on a Secure Element? Well, the applications are running on a mobile phone, and mobile phone users are expecting some kind of interaction when they use their phone. For instance, when doing a payment, the user would expect some message on the screen explaining that there is an ongoing payment. And this message is quite likely to be displayed by a mobile application.</p>
<p>In most NFC phones, an event is triggered when an application is selected on a SE. This event can then be forwarded to an application. That&#8217;s when things get interesting: if this mobile application wants to display interesting information to the user, it will need to interact with the SE application. This means that it should be able to use a SE Access API. If this API is not well secured, it&#8217;s an open bar for attackers, who can select an application, send commands to any applications, etc. Of course, if the SE applications are well secured, there is not much to do, except denial-of-service attacks. But then, that already is a combination f two &#8220;if&#8221;&#8216;s: a bit much for security.</p>
<p>Securing a SE Access API is easy in principle. You can for instance take a look at JSR-177, which proposes a solution that works very well. More precisely, it works will on the UICC, because the UICC belongs to the mobile operator, and the use of JSR-177 requires a signature by the mobile operator. Now, if a bank wants to deploy an application on a MicroSD, does it want to depend on a mobile operator? Maybe not.</p>
<p>Similar problems occur everywhere. If Apple does NFC on iPhone, they are quite likely to include an embedded SE that they will tightly control, and the problem for the bank will be the same, replacing the operator by Apple. On open systems like Android, the problem is different but not easier: in a system based on self-certification, who is in charge of enseuring that secure elements are not abused? These things will be clarified, but we can expect to have some room for attacks here, at least in the beginning. Of course, this does not mean that interesting attacks are feasible, as that depends on the target applications. Since the first applications will be ports of well-known card applications, the expectations should not be too high.</p>
<p>The last potential attack that I will mention is about tag reading. It may be possible to &#8220;hijack&#8221; a tag reading through a mobile application, and replace the content of the tag with another content, for instance linking an ad to an activist site fighting the advertiser. As long as tags are used for advertising, such attacks will be just fun, but they may get more interesting if tags are used for more sensitive applications. Note that very similar attacks already exist today with QR-codes.</p>
<p>This is definitely not a complete list, and I am sure that a few unexpected things will happen with NFC, leading to vulnerabilities, attack paths, and interesting work. We&#8217;ll see.</p>
]]></content:encoded>
			<wfw:commentRss>http://javacard.vetilles.com/2011/01/28/qa-nfc-attacks/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>JC301-4: Where are the differences?</title>
		<link>http://javacard.vetilles.com/2009/04/03/jc301-4-where-are-the-differences/</link>
		<comments>http://javacard.vetilles.com/2009/04/03/jc301-4-where-are-the-differences/#comments</comments>
		<pubDate>Fri, 03 Apr 2009 20:29:46 +0000</pubDate>
		<dc:creator><![CDATA[Eric Vétillard]]></dc:creator>
				<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[Java Card 3.0]]></category>

		<guid isPermaLink="false">http://javacard.vetilles.com/?p=261</guid>
		<description><![CDATA[[Corrected April 9, 2009: more mentions of Classic, added a conclusion] You have been warned in the previous posts. The Connected Edition of Java Card 3.0 is very different from Java Card 2.x. But, how exactly are these two versions different? Well, there are differences at all levels, from the virtual machine to the application [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>[Corrected April 9, 2009: more mentions of Classic, added a conclusion]</p>
<p>You have been warned in the previous posts. The Connected Edition of Java Card 3.0 is very different from Java Card 2.x. But, how exactly are these two versions different? Well, there are differences at all levels, from the virtual machine to the application model and the deployment framework.</p>
<p>So, let&#8217;s take a close look at all these differences, going from the low-level to the high-level differences.<br />
<span id="more-261"></span></p>
<h2>At the virtual machine level</h2>
<p>At the virtual machine level, the main difference is that the Java Card virtual machine is now strongly inspired from the 32-bit CLDC virtual machine, with which it shares a lot of characteristics. Among these characteristics, we have:</p>
<ul>
<li><strong>32-bit integer by default</strong>. Yes, some of the casts are now gone for good, as Java Card 3.0 now performs 32-bit computations.</li>
<li><strong>More basic types</strong>. Java Card 3.0 now supports all standard integral types, including the (unsigned 16-bit) <code>char</code> and (signed 64-bit) <code>long</code> types.</li>
<li><strong>Mandatory bytecode verification</strong>. A serious security flaw is now gone, and reverse engineering a Java Card 3.0 card may well be a difficult task. Since the inspiration comes from CLDC, the verification uses precomputed stack maps.</li>
<li><strong>Standard distribution formats</strong>. Java Card 3.0 classes are compiled into class files, which are distribution inside JAR files, using standard encoding and compression.</li>
</ul>
<p>However, some things still didn&#8217;t come to Java Card. For instance, don&#8217;t expect any floating-point numbers, as there is little use for them, and the hardware coprocessors remain a bit too expensive.</p>
<h2>At the runtime environment level</h2>
<p>At the runtime environment level, there is one major change, memory management. Java Card 3.0 explicitly supports temporary objects, and objects are made persistent when they become reachable from a &#8220;persistence root&#8221;. The consequence is that it is now possible to allocate objects temporarily in RAM, and they will even be automatically garbage collected.</p>
<p>The transaction model has also been greatly enhanced, and it is now possible to use nested transactions, using a very flexible model. In particular, it is now possible to write libraries that use transactions in a clean way.</p>
<p>Finally, the sharing model has been enhanced. The firewall is still around, and the basic sharing mechanism remains the same. However, it has been complemented by a few mechanisms that allow two applications to exchange object instances, making the sharing framework really usable.</p>
<h2>At the API level</h2>
<p>At the API level, there are quite a few significant additions. The first one is of course the <code>String</code> class, which is quite mandatory is we are to handle HTML pages. Of course, this class does not come alone, and <code>StringBuffer</code> and a few other friends are also present.</p>
<p>In fact, a significant subset of <code>java.util</code> is present. In particular, it is now possible to manage data with other things than simple arrays, as <code>Vector</code> and <code>Hashtable</code> are available. However, these are the &#8220;old&#8221; versions of the classes, as the new container framework is too complex.</p>
<p>In addition to these basic utilities, the Generic Connection Framework (GCF) has been imported from the CLDC core library. It allows a Java Card application to open local and network connections, and to use stream-based I/O, which can be very useful, for instance to consume incoming data. </p>
<h2>At the security level</h2>
<p>The Java Card 2 security model is extremely simplified, mostly because there are very few resources to protect on a small smart card. With Java Card 3, this simplified model is not sustainable, because there are many more resources that need to be protected. Therefore, Java Card 3.0 defines a permission model that provides fine-grained access control to sensitive resources. Permissions are required for many operations, such as network accesses, local file accesses, context switching, shareable object access, and many more. </p>
<p>Naturally, the Web framework also comes with a security framework. Application-level security for Web applications is a subset of the standard servlet security framework, as used on J2EE servers. It controls how Web applications can be accessed from various kinds of clients.</p>
<p>Finally, Java Card 3.0 includes a declarative role-based security model, which separates the declaration of the security rules based on abstract roles, defined at development time, from the mapping of these abstract roles to actual users and authentication means.</p>
<h2>At the application level</h2>
<p>Naturally, the main change is the new servlet application model, which allow Web applications to be developed and deployed on a Java Card smart card. This change also comes with another related change, at a lower level; Java Card 3.0 now defines a TCP/IP-based communication model, which allows Java Card applications to serve Web requests and to establish connections with the outside using the Generic Connection Framework.</p>
<p>Another important evolution for applications is the enhanced sharing framework. A major shortcoming of the Java Card 2 sharing framework is the fact that it is very difficult to exchange data between applications, because only global arrays can be exchanged (in most cases, this means that only the APDU buffer can be used). Java Card 3.0 addresses this issue by allowing applications to transfer the ownership of some of their objects to another application. With this mechanism, it becomes possible to exchange data safely between two applications. In addition, the fine-grained permissions that control sharing provide an extra protection to applications that share objects.</p>
<h2>At the deployment level</h2>
<p>In Java Card 3.0, an application is not simply limited to a set of classes. It also includes some static content (Web pages, images, <em>etc</em>.), as well as several descriptors. One of them, the manifest, contains information that should be provided by the person/entity responsible for the deployment of the application rather than by the application developer. This separation of functions facilitates the development of portable applications.</p>
<p>To conclude, we can also recall that, even in its Connected Edition, Java Card 3.0 remains backward-compatible with Java Card 2.x. It remains possible to run all previously developed Java Card 2.x applications. The only constraint is that the binary files need to be converted in a new format.</p>
]]></content:encoded>
			<wfw:commentRss>http://javacard.vetilles.com/2009/04/03/jc301-4-where-are-the-differences/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>JC101-20C: A secure channel API</title>
		<link>http://javacard.vetilles.com/2009/03/23/jc101-20c-a-secure-channel-api/</link>
		<comments>http://javacard.vetilles.com/2009/03/23/jc101-20c-a-secure-channel-api/#comments</comments>
		<pubDate>Mon, 23 Mar 2009 20:52:16 +0000</pubDate>
		<dc:creator><![CDATA[Eric Vétillard]]></dc:creator>
				<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://javacard.vetilles.com/?p=243</guid>
		<description><![CDATA[Continuing our secure channel example, we will next define a secure channel API, and provide a small example based on this API. Beware! As mentioned before, this is only an example, not intended for real use. In addition, the code has not been actually tested so far &#8230; If our secure channel is to be [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>Continuing our secure channel example, we will next define a secure channel API, and provide a small example based on this API.</p>
<p>Beware! As mentioned before, this is only an example, not intended for real use. In addition, the code has not been actually tested so far &#8230;<br />
<span id="more-243"></span></p>
<p>If our secure channel is to be used by several applications, it should be defined in a shared library.</p>
<h2>Definition of the API</h2>
<p>The first step is here to define the API. The objective of such an API is to bring as little disruption as possible to the applications that use it. We will base our API on a pattern that is inspired from the one used in the GlobalPlatform API.</p>
<p>The main API for applications here contains four methods, as indicated below:</p>
<pre>
  public short unwrap(APDU apdu);

  public void wrapAndSend(
      APDU apdu,
      byte[] buffer,
      short outOffset,
      short outLen,
      short sw );

  public void processSecurity(APDU apdu);

  public boolean isCommandProtected();
</pre>
<p>The behavior of these methods is as follows:</p>
<ul>
<li>The <code>unwrap()</code> method removes the protection of a method, after verifying its authenticity. It also works for unprotected commands, in which case it does nothing.</li>
<li>The <code>wrapAndSend()</code> method adds the protection around the response and sends it back. It also work for unprotected commands, in which case it simply sends the response. Note that the response is complete and also includes the status word.</li>
<li>The <code>processSecurity()</code> method is used to process the commands related to the secure channel protocol. The idea is here to send to it all the commands that the application does not know, and this method will throw the appropriate exception for unknown instructions.</li>
<li>The <code>isSessionOpen()</code> is used to determine whether or not a session is currently open.</li>
<li>Finally, the is <code>CommandProtected()</code> method is used to determine whether or not the current command is protected. This method must be called during the handling of commands that require some protection.</li>
</ul>
<p>This API is quite simple to use, and it does not change significantly the way in which programs should be written. We also have defined a constructor and a few management methods, which are shown below:</p>
<pre>
  public SecureChannel();
  public void setSharedSecret(byte[] buffer, short ofs);
  public void closeSession();
  public void clear()
</pre>
<p>The explanations for these methods are:</p>
<ul>
<li>The <code>SecureChannel()</code> constructor has no arguments and simply allocates the data required.</li>
<li>The <code>setSharedSecret()</code> method is used to initialize the shared secret and make the instance ready to be used.</li>
<li>The <code>closeSession()</code> method is used to abruptly close a session, for instance as part of a security countermeasure.</li>
<li>Finally, the <code>clear()</code> method clears all information, and in particular the shared secret. It can be used as cleanup or as a countermeasure.</li>
</ul>
<p>This API is as simple as it gets, and it does not include any optional feature, such as the management of a state for the secure channel instance. The idea is here to keep it as simple as possible.</p>
<h2>Example client program</h2>
<p>Our example will be some kind of â€œHello Worldâ€ program, with two commands defined: one without security, and one with security. Both commands will do the same thing: return two concatenated copies of the input data.<br />
Let&#8217;s start our program with the simple declarations:</p>
<pre>
package com.vetilles.securehello;

import com.vetilles.security.SecureChannel;
import javacard.framework.*;

public class Hello extends Applet {
</pre>
<p>It is quite simple and classical, except of course that it imports my library class <code>SecureChannel</code>. We can continue by the definition of constants:</p>
<pre>
  // The instruction bytes
  private static final byte INS_HELLO        = 0x02 ;
  private static final byte INS_SECURE_HELLO = 0x04 ;

  // The static secret
  private static final byte[] secret =
  { 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 
    0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F } ;
</pre>
<p>We here have the two instruction bytes that we expect, as well as a static secret. We have done this in order to keep the program simple, but it definitely is not wise in terms of security, for at least two reasons:</p>
<ul>
<li>First, all instances of that class will use the same static shared secret, which makes the application&#8217;s security brittle. If the key for a single instance is leaked, then all keys are compromised.</li>
<li>Then, in a less obvious way, the value of the key is defined as a constant, and as such, it will appear in clear in the binary file for the application (the CAP file, and more specifically here, its static field component). The distribution of this file may be difficult to control, and it is unlikely to be encrypted when it is transferred to the card. In other words, the CAP file is a very bad place to put secrets in.</li>
</ul>
<p>There is a single field, which is used to hold a reference to the secure channel instance:</p>
<pre>
  private SecureChannel sc;
</pre>
<p>Then, the installation sequence (installer and constructor) is very simple:</p>
<pre>
  public static void install(
    byte[] bArray, short bOffset, byte bLength)
  {
    new Hello().register();
  }

  private Hello()
  {
    sc = new SecureChannel();
    sc.setSharedSecret(secret, (short)0);
  }
</pre>
<p>The constructor simply allocates a secure channel instance, and initializes its shared secret with the value in the CAP file. Once again, this is not the standard way to go; in a normal application, the initialization of the secret would be part of the application&#8217;s personalization process.<br />
We then get to the main command processing method. It starts in a very classical way:</p>
<pre>
  public void process(APDU apdu) {
    byte[] buffer = apdu.getBuffer();
    short len ;

    if (selectingApplet())
      return;

    switch (buffer[ISO7816.OFFSET_INS]) {
</pre>
<p>The first instruction is the standard implementation of a command without security:</p>
<pre>
    case INS_HELLO:
      len = apdu.setIncomingAndReceive();
      len = sayHello(buffer,len);
      apdu.setOutgoingAndSend(ISO7816.OFFSET_CDATA, len);
      break;
</pre>
<p>Note that the processing is performed in an external method, which is quite classical. Now, we can look at the secure version of that command:</p>
<pre>
    case INS_SECURE_HELLO:
      // Receives and unwraps the data
      apdu.setIncomingAndReceive();
      len = sc.unwrap(apdu);

      // Verifies that the command was protected
      if (!sc.isCommandProtected())
        ISOException.throwIt(
            ISO7816.SW_SECURITY_STATUS_NOT_SATISFIED);

      //Processes the command itself
      len = sayHello(buffer,len);
      
      // Wraps the response data
      sc.wrapAndSend(
          apdu, buffer,
          ISO7816.OFFSET_CDATA, len,
          (short)0x9000);
      break;
</pre>
<p>There are here four steps to be included:</p>
<ul>
<li>First, the data is received, and the command is unwrapped. If an attempt is performed to unwrap a command without first opening a secure session, or if the received command is not correct, an exception will b thrown. Otherwise, the command will be simply unwrapped, and its actual length will be returned.</li>
<li>Then, the application verifies that the command is actually protected. This is very important, since the unwrap method works perfectly on standard commands. It is therefore the application&#8217;s responsibility to verify that the command was actually protected.</li>
<li>The third part is the application processing itself, which has not been modified.</li>
<li>The fourth and final part is to wrap the response data and then send it out, to finish the processing.</li>
</ul>
<p>The last item in the switch will handle all other incoming commands:</p>
<pre>
    default:
      sc.processSecurity(apdu);
</pre>
<p>The <code>processSecurity()</code> method handles all the secure session management commands, and rejects all the other ones.</p>
<p>This example is very small, and it shows the difference between a protected command and a non-protected command. Note that there is no real need to distinguish between the two, as the â€œunwrapâ€ and â€œwrapâ€ methods are designed to work on standard commands. All we have to do is here to modify the test that verifies that the command is protected to only require encryption if a session is open:</p>
<pre>
      // Verifies that the command was protected
      if (!sc.isCommandProtected() &#038;&#038; sc.isSessionOpen())
        ISOException.throwIt(
            ISO7816.SW_SECURITY_STATUS_NOT_SATISFIED);
</pre>
<p>This small change shows how important that test about the status of the command is. Note that the very common GlobalPlatform API uses a similar architecture, in which the same kind of tests is required.</p>
]]></content:encoded>
			<wfw:commentRss>http://javacard.vetilles.com/2009/03/23/jc101-20c-a-secure-channel-api/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>JC301-3: Connected vs. Classic</title>
		<link>http://javacard.vetilles.com/2009/02/01/jc301-3-connected-vs-classic/</link>
		<comments>http://javacard.vetilles.com/2009/02/01/jc301-3-connected-vs-classic/#comments</comments>
		<pubDate>Sun, 01 Feb 2009 21:22:27 +0000</pubDate>
		<dc:creator><![CDATA[Eric Vétillard]]></dc:creator>
				<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[Java Card 3.0]]></category>

		<guid isPermaLink="false">http://javacard.vetilles.com/?p=234</guid>
		<description><![CDATA[After a month of silence, just a quick post to restart the tutorial thing, about the two editions of Java Card 3.0. Two editions As mentioned earlier, Java Card 2.x represents 5 billion cards today, and over a billion are issued each year. This represents a very significant part of the smart card business in [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>After a month of silence, just a quick post to restart the tutorial thing, about the two editions of Java Card 3.0.</p>
<h2>Two editions</h2>
<p>As mentioned earlier, Java Card 2.x represents 5 billion cards today, and over a billion are issued each year. This represents a very significant part of the smart card business in volume, and an even larger part in value, because Java Card is typically included in high-end cards.</p>
<p>Not a single salesperson would take a chance to disturb such a significant market by forcing their customers to switch from a technology to a radically different one, which also happens to be more expensive. In fact, this is exactly what the smart card industry is doing, and the reason for these two editions: one of them caters to the existing smart card market, whereas the other one targets a future market of IP-connected smart cards and related devices.<br />
<span id="more-234"></span></p>
<h3>Classic Edition</h3>
<p>The Classic Edition, as we can guess by its name, is a direct successor to the Java Card 2.2.2 specification. In practice, the changes are so small that its normal name (with the Java Card numbering rules) should have been Java Card 2.2.3. Nothing really new has been introduced.</p>
<p>The changes can be summarized in a few lines. Apart from fixing typos and small bugs, the Classic Edition only introduces support for a few new cryptographic algorithms (like RSA 4096), as well as slight improvements in which contactless transactions are handled, and improvements in the handling of the ISO7816-4/2005 specification.</p>
<p>Java Card 3.0 Classic cards therefore behave exactly like Java Card 2.x cards. They are based on the same 16-bit virtual machine, with the same restrictions (no threads, no garbage collection), the same very limited APIs, and the same single application model. They solely target APDU-based applications (contact or contactless), just like their predecessors.</p>
<p>Classic cards are also backward compatible with older cards, even at the binary level. There is no need to recompile your applications, and not even to reconvert them. Existing CAP files will run directly on Java Card 3.0 Classic cards, without modifying a single bit.</p>
<p>The objective is here to keep a product for the billion cards per year market that comes for Java Card 2, and that has a few more years of existence. Over the years, the proportion of Classic cards is expected to decrease, and eventually to become a platform for low-end cards.</p>
<h3>Connected Edition</h3>
<p>The Connected Edition is the <em>real</em> Java Card 3.0, <em>i.e.</em>, the really new specification, with a new virtual machine, a new application framework, and everything else.</p>
<p>The Connected Edition includes a 32-bit virtual machine, it can run multiple threads, it includes a much larger API, it includes real garbage collection, and many other things. As a consequence, it is much more complex than the Classic Edition, and it targets the most sophisticated chips available in 2009 (note that this situation is better than Java Card 2&#8217;s situation 10 years ago, for which no reasonable chip existed at the time).</p>
<p>In terms of applications, the Connected Edition introduces IP-based Web applications, a significant change from existing smart card applications, corresponding to the new uses of computing, in which the client often is a generic browser, which gathers information from a variety of information sources, a.k.a. servers. Connected Edition defines the way in which we can all have one (or many) personal servers that handle our personal and sensitive data.</p>
<p>Even with these major changes, Java Card 3.0 remains backward compatible with existing Java Card 2.x applications. However, this compatibility is only possible at the source code level. A Java Card 2.x application needs to be recompiled and packaged into a Connected Edition binary format (some kind of JAR file). After that, it will work correctly; the specification even allows it to interact (in a limited way) with new applications.</p>
<p>The Connected Edition does not target a well-defined market, as it includes a new application model, and includes specifications that do not correspond to any immediate market demand. For instance, Oberthur&#8217;s Gigantic Wuaow, which got a <a href="http://javacard.vetilles.com/2008/11/04/another-java-card-30-sesames-award/" class="liinternal">Sesames Award</a> last year, is a big SIM card with a USB interface. The corresponding standard for phones exists, but not a single device is available at the beginning of 2009. The Connected Edition therefore remains a forward-looking technology, who stands significant chances to become a major component of tomorrow&#8217;s cards, but still needs to prove its worth.</p>
<p>Nevertheless, this tutorial on Java Card 3.0 will focus almost exclusively on the Connected Edition, which includes all the innovation in this new spec release.</p>
]]></content:encoded>
			<wfw:commentRss>http://javacard.vetilles.com/2009/02/01/jc301-3-connected-vs-classic/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>JC101-19C: Secure channel protocol</title>
		<link>http://javacard.vetilles.com/2008/11/13/jc101-19c-secure-channel-protocol/</link>
		<comments>http://javacard.vetilles.com/2008/11/13/jc101-19c-secure-channel-protocol/#comments</comments>
		<pubDate>Thu, 13 Nov 2008 20:43:11 +0000</pubDate>
		<dc:creator><![CDATA[Eric Vétillard]]></dc:creator>
				<category><![CDATA[Java Card 2.x]]></category>
		<category><![CDATA[Security]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[APDU]]></category>
		<category><![CDATA[secure channel]]></category>

		<guid isPermaLink="false">http://javacard.vetilles.com/2008/11/13/jc101-19c-secure-channel-protocol/</guid>
		<description><![CDATA[Starting a session Protocol For our session start, we will here use a classical architecture, but with slightly different commands. First, here is a definition of the exchanges between two actors (say, Alice and Bob) to start a secure session: Alice sends a 16-byte random number to a1 &#8230; a16 to Bob. Bob replies with [&#8230;]]]></description>
				<content:encoded><![CDATA[<h2>Starting a session</h2>
<h3>Protocol</h3>
<p>For our session start, we will here use a classical architecture, but with slightly different commands. First, here is a definition of the exchanges between two actors (say, Alice and Bob) to start a secure session:</p>
<ol>
<li>Alice sends a 16-byte random number to a<sub>1</sub> &#8230; a<sub>16</sub> to Bob.</li>
<li>Bob replies with his own 16-byte random number b<sub>1</sub> &#8230; b<sub>16</sub>.</li>
<li>Alice and Bob both encrypt a<sub>1</sub> &#8230; a<sub>16</sub> with their shared secret, getting the value &alpha;<sub>1</sub> &#8230; &alpha;<sub>16</sub>.</li>
<li>Alice and Bob both encrypt b<sub>1</sub> &#8230; b<sub>16</sub> with their shared secret, getting the value &beta;<sub>1</sub> &#8230; &beta;<sub>16</sub>.</li>
<li>The session key becomes &alpha;<sub>9</sub> &#8230; &alpha;<sub>16</sub> &beta;<sub>1</sub> &#8230; &beta;<sub>8</sub>.</li>
<li>Alice sends the value &beta;<sub>9</sub> &#8230; &beta;<sub>16</sub> to Bob, encrypted with the session key, as a proof of authentication.</li>
<li>Bob verifies that the value is correct.</li>
<li>Bob then sends the value &alpha;1 &#8230; &alpha;<sub>8</sub>  to Alice, encrypted with the session key, as a proof of authentication.</li>
<li>Alice verifies that the value is correct.</li>
<li>The session has started.</li>
</ol>
<p>I will not attempt to prove that this algorithm has many interesting properties, but I will just highlight a few of its features:</p>
<ul>
<li>In stepsÂ 1 andÂ 2, both Alice and Bob generate random data that is used in the session startup process, and the session key depends on both sets of random data, as a measure against replay attacks.</li>
<li>In stepsÂ 3 andÂ 4, the simple encryption used here can be replaced by a more complex algorithm, in order to make it more difficult for an attacker to derive the shared secret from a session key.</li>
<li>The value returned by Alice to Bob on stepÂ 6 (and vice-versa on stepÂ 8) as proof of authentication shows that Alice got Bob&#8217;s random data, and that Alice knows the shared secret.</li>
<li>The value returned in stepsÂ 6 andÂ 8 are both encrypted with the session key, in order to avoid giving away precious information about the shared secret to a potential attacker.</li>
</ul>
<p><span id="more-170"></span></p>
<h3>APDU commands</h3>
<p>The next step is to transform this protocol in a sequence of APDU commands exchanged between a card terminal (as Alice), and a card (as Bob). Standard commands exist to do that (<code>INITIALIZE UPDATE</code> and <code>EXTERNAL AUTHENTICATE</code>). However, since our protocol is specific, I will define a specific command to do so, that I will call <code>START SECURE SESSION</code>.</p>
<table border cellpadding=5 cellspacing=0>
<tr>
<th align="left">CLA</th>
<td><code>00</code>, the default value</td>
</tr>
<tr>
<th align="left">INS</th>
<td><code>38</code>, our own instruction byte</td>
</tr>
<tr>
<th align="left">P1</th>
<td><code>00</code>, The current step, <code>00</code> for random data exchange, and <code>01</code> for the authentication step.</td>
</tr>
<tr>
<th align="left">P2</th>
<td><code>80</code>, <code>00</code>, and also RFU.</td>
</tr>
<tr>
<th align="left">Incoming Data</th>
<td>On step <code>00</code>, the random value a<sub>1</sub> &#8230; a<sub>16</sub>  sent by the terminal; on step <code>01</code>, the authentication value &beta;<sub>9</sub> &#8230; &beta;<sub>16</sub> encrypted with the session key.</td>
</tr>
</table>
<p>The algorithm to process a command is as follows:</p>
<ul>
<li>If P1&ne;<code>00</code> and  P1&ne;<code>01</code>, return status word <code>6A86</code>.</li>
<li>If P1=00, manage step <code>00</code>, the generation of random data.
<ol>
<li>If Lr&ne;<code>16</code>, return status word <code>6700</code>.</li>
<li>Copy received data; generate 16 bytes of new random data.</li>
<li>Compute the new session key, and the card&#8217;s authentication data.</li>
<li>Send the 16 bytes of new random data, with status word <code>9000</code>.</li>
</ol>
</li>
<li>If P1=01, manage step 01, the authentication step.
<ol>
<li>If Lr&ne;8, return status word <code>6700</code>.</li>
<li>Compute expected authentication data, and compare it to received one.</li>
<li>If the comparison fails, return <code>6982</code>.</li>
<li>Otherwise, encrypt card&#8217;s authentication data with the session key, and return it to the terminal with status word 9000.</li>
</ol>
</li>
</ul>
<table border cellpadding=5 cellspacing=0>
<tr>
<th align="left">Lr</th>
<th align="left">Out data</th>
<th align="left">SW</th>
<th align="left">Outcome</th>
</tr>
<tr>
<td><code>10</code></td>
<td>b<sub>1</sub> &#8230; b<sub>16</sub></td>
<td><code>9000</code></td>
<td>On step <code>00</code>, the outgoing data is the random value returned by the card.</td>
</tr>
<tr>
<td><code>08</code></td>
<td>&alpha;<sub>1</sub> &#8230; &alpha;<sub>8</sub></td>
<td><code>9000</code></td>
<td>On step <code>01</code>, the outgoing data is  &alpha;<sub>1</sub> &#8230; &alpha;<sub>8</sub>, encrypted with the session key.</td>
</tr>
<tr>
<td><code>00</code></td>
<td>None</td>
<td><code>6A80</code></td>
<td>Data is not as expected</td>
</tr>
<tr>
<td><code>00</code></td>
<td>None</td>
<td><code>6984</code></td>
<td>Terminal authentication failed</td>
</tr>
</table>
<h2>Exchanging messages</h2>
<h3>Protocol</h3>
<p>During a session, some security features need to be added to the messages exchanged between the card and the terminal. We will need to do two things here:</p>
<ul>
<li>Encrypt the content of the command or response in order to protect the confidentiality of its content.</li>
<li>Include a cryptographic checksum of the command or response in order to protect the integrity of its content.</li>
</ul>
<p>In order to keep our protocol simple and secure, we will consider the following simple rule for determining whether or not to apply these messages:</p>
<ul>
<li>All secure session commands will be considered as embedded in a special <code>SEND SECURE COMMAND</code> command.</li>
<li>All other commands will be considered as not covered by the secure session.</li>
</ul>
<p>There is a security rationale behind this. As we have mentioned before, attackers may analyze the commands sent to the card in order to get some information for their attacks. By always using the same command to send secure commands, we provide an elementary protection against this. We will even go a little further by doing the following:</p>
<ul>
<li>Incoming data will always be 251 bytes, regardless of the actual size of the command data (we leave five bytes for the original header).</li>
<li>Similarly, outgoing data will always be 255 bytes, regardless of the actual size of the response data.</li>
</ul>
<p>Of course, such a protocol introduces some overhead. For instance, here, the overhead will be 6 bytes for the header data plus 8 bytes for the command&#8217;s cryptographic checksum, leaving a maximum of 241 actual bytes of incoming data. For outgoing data, the overhead will be 3 bytes for the header (status word and length), and 8 bytes for the the response&#8217;s cryptographic checksum, leaving a maximum of 244 actual bytes of outgoing data.</p>
<p>Another important point is that we want to make sure that no command can be lost during a secure session. Since we are defining a specific command, we have several ways to do that, including:</p>
<ul>
<li><strong>Managing a session command counter</strong>. A counter is increased at every command, and checked on the card. The counter value must be included in the data protected by the command signature.</li>
<li><strong>Change the session key for each command</strong>. This is a very common way of dealing with this issue, which has other advantages, like the fact that the key changes for each command.</li>
</ul>
<p>In order to keep things simple, we will here use a command counter.</p>
<h3>APDU commands</h3>
<p>We can now define the handling of the <code>SEND SECURE COMMAND</code> command.</p>
<table border cellpadding=5 cellspacing=0>
<tr>
<th align="left">CLA</th>
<td><code>00</code>, the default value</td>
</tr>
<tr>
<th align="left">INS</th>
<td><code>3A</code>, our own instruction byte</td>
</tr>
<tr>
<th align="left">P1</th>
<td><code>00</code>, The MSB of the command sequence number.</td>
</tr>
<tr>
<th align="left">P2</th>
<td><code>80</code>, LSB of the command sequence number.</td>
</tr>
<tr>
<th align="left">Incoming Data</th>
<td>251 bytes, including the protected command, followed by some random padding and by a cryptographic checksum.</td>
</tr>
</table>
<p>The algorithm to process a command is as follows:</p>
<ul>
<li>If the concatenation of P1 and P2 is not equal to the expected sequence number (previous one plus one)
<ol>
<li>Close the secure channel session.</li>
<li>Return status word <code>6A86</code>.</li>
</ol>
</li>
<li>If Lr&ne;251, return status word <code>6700</code>. Otherwise, receive the data.</li>
<li>Verify the cryptogram and decrypt the command data.
<ol>
<li>Compute the signature of the 248 first bytes of the APDU buffer using the session key in CBC mode.</li>
<li>Compare this value to the 8 last bytes of the command.</li>
<li>If the values are different, close the secure channel session, and return status word <code>6982</code>.</li>
<li>Otherwise, decipher the first 240 bytes of command data into the 240 first bytes of the APDU buffer.</li>
<li>If the 5th byte of the APDU buffer (Lr of secure command) is 0, replace it with the 6th byte of the APDU buffer (Le of secure command).</li>
</ol>
</li>
<li>Process the secure command normally.</li>
<li>When the outgoing data is ready to be sent, together with the status word,
<ol>
<li>If the length of the outgoing data is greater than 237, replace it with a 0-length data and a status word of <code>6A80</code>.</li>
<li>Copy the outgoing data into the APDU buffer, starting at offset 3.</li>
<li>Copy the provided status word into the APDU buffer at offset 0.</li>
<li>Copy the length of the outgoing data into the APDU buffer as an unsigned byte at offset 2.</li>
<li>If necessary, fill with random data up to offset 240.</li>
<li>Encrypt these 240 bytes on place with the session key.</li>
<li>Compute a digital signature of these 240 bytes using the session key in CBC mode, and store it at offset 240 of the APDU buffer.</li>
<li>Send the 248 bytes of data, with a status word of <code>9000</code>.</li>
</ol>
</li>
</ul>
<p>This description deserves a few explanations about the use of the DES algorithm, which will be provided in the section about implementation.</p>
<table border cellpadding=5 cellspacing=0>
<tr>
<th align="left">Lr</th>
<th align="left">Out data</th>
<th align="left">SW</th>
<th align="left">Outcome</th>
</tr>
<tr>
<td><code>F8</code></td>
<td>Encrypted response of the other command</td>
<td><code>9000</code></td>
<td>All outcomes</td>
</tr>
</table>
<h2>Closing a session</h2>
<h3>Protocol</h3>
<p>The final step of the secure channel protocol is the closing of a session. The objective is here to get a token that proves that the entire session has taken place, and that the session can be considered as successful.</p>
<p>In order to do that, we will use a value that is a XOR of all the digital signature computed during the session, on 16 bytes (8 bytes for incoming command signatures, 8 bytes for outgoing responses signatures).</p>
<p>Upon receipt of a specific command, which will includes a signature computed by the terminal, the card will return this control value, encrypted with the session key. This value could then be used as a proof that the session actually took place, and that it contained a given set of commands.</p>
<h3>APDU commands</h3>
<p>The first thing to do is to update the handling of the <code>SEND SECURE COMMAND</code> APDU command, in order to include in it the management of the session control value, which should be updated during the handling of each command.</p>
<p>The next thing is to define the <code>CLOSE SECURE SESSION</code> command that will be used to close a session and get the session control value.</p>
<table border cellpadding=5 cellspacing=0>
<tr>
<th align="left">CLA</th>
<td><code>00</code>, the default value</td>
</tr>
<tr>
<th align="left">INS</th>
<td><code>3C</code>, our own instruction byte</td>
</tr>
<tr>
<th align="left">P1</th>
<td><code>00</code>, as RFU</td>
</tr>
<tr>
<th align="left">P2</th>
<td><code>00</code>, as RFU</td>
</tr>
<tr>
<th align="left">Incoming Data</th>
<td>8 bytes, including the sequence number, encrypted by the session key</td>
</tr>
</table>
<p>The algorithm to process a command is as follows:</p>
<ul>
<li>If Lr&ne;8, return status word <code>6700</code>. Otherwise, receive the data.</li>
<li>Decrypt the command data and verify it.
<ol>
<li>Decipher the 8 bytes of command data.</li>
<li>Compare the 2 first bytes of data to the current sequence number.</li>
<li>If they are different, close the secure channel session and return the status word <code>6984</code>.</li>
</ol>
</li>
<li>Send the control value.
<ol>
<li>Copy the control value data into the APDU buffer, starting at offset 0.</li>
<li>Encrypt these 16 bytes on place with the session key.</li>
<li>Close the secure session.</li>
<li>Send the 16 bytes of data, with a status word of <code>9000</code>.</li>
</ol>
</li>
</ul>
<p>This description deserves a few explanations about the use of the DES algorithm, which will be provided in the section about implementation.</p>
<table border cellpadding=5 cellspacing=0>
<tr>
<th align="left">Lr</th>
<th align="left">Out data</th>
<th align="left">SW</th>
<th align="left">Outcome</th>
</tr>
<tr>
<td><code>10</code></td>
<td>Encrypted session control value</td>
<td><code>9000</code></td>
<td>Success</td>
</tr>
<tr>
<td><code>00</code></td>
<td>None</td>
<td><code>6700</code></td>
<td>Received other than 8 bytes</td>
</tr>
<tr>
<td><code>00</code></td>
<td>None</td>
<td><code>6984</code></td>
<td>Wrong sequence number</td>
</tr>
</table>
<h2>Wrap-up</h2>
<p>We have provided a definition of a secure channel protocol, as an exercise to better understand the principles of smart card security. Although this protocol has been designed with security in mind, it hasn&#8217;t been subjected to any kind of peer review, and I don&#8217;t even claim to have all the skills required to design a secure channel protocol that can withstand the current stats-of-the-art of cryptographic attacks.</p>
<p>So, please, <em>don&#8217;t even think</em> about using this secure channel protocol directly in a smart card application, without first submitting to an in-depth analysis by a security professional with a strong cryptography background, as it  may include major flaws.</p>
<p>And if you can&#8217;t have this review performed, you are always better off to use a well-known, standard protocol, like those offered by GlobalPlatform, which are available on almost all cards available today, and that have been subjected to a great deal of scrutiny in the past few years.</p>
]]></content:encoded>
			<wfw:commentRss>http://javacard.vetilles.com/2008/11/13/jc101-19c-secure-channel-protocol/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>JC101-18C: Defining a secure channel from scratch</title>
		<link>http://javacard.vetilles.com/2008/10/07/jc101-18c-defining-a-secure-channel-from-scratch/</link>
		<comments>http://javacard.vetilles.com/2008/10/07/jc101-18c-defining-a-secure-channel-from-scratch/#comments</comments>
		<pubDate>Tue, 07 Oct 2008 15:54:50 +0000</pubDate>
		<dc:creator><![CDATA[Eric Vétillard]]></dc:creator>
				<category><![CDATA[Java Card 2.x]]></category>
		<category><![CDATA[Security]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[Java Card]]></category>
		<category><![CDATA[secure channel]]></category>

		<guid isPermaLink="false">http://javacard.vetilles.com/2008/10/07/jc101-18c-defining-a-secure-channel-from-scratch/</guid>
		<description><![CDATA[In the few coming posts, we will define a secure channel protocol from scratch as an example, and provide an implementation for it. This example will also be used as a way to introduce the cryptographic mechanisms that exist in Java Card. Be careful, this is not a tutorial on cryptography. I am not a [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>In the few coming posts, we will define a secure channel protocol from scratch as an example, and provide an implementation for it. This example will also be used as a way to introduce the cryptographic mechanisms that exist in Java Card.</p>
<p>Be careful, this is not a tutorial on cryptography. I am not a cryptography expert, and I will just repeat basic ideas. If you want to learn about cryptograpy, consider getting a book like this <a href="http://www.amazon.fr/gp/redirect.html?ie=UTF8&#038;location=http%3A%2F%2Fwww.amazon.fr%2FSchneiers-Cryptography-Classics-Library-Practical%2Fdp%2F0470226269%3Fie%3DUTF8%26s%3Denglish-books%26qid%3D1223394244%26sr%3D8-3&#038;tag=lesvetilles-21&#038;linkCode=ur2&#038;camp=1642&#038;creative=6746" class="liexternal">Bruce Schneier Compilation</a><img src="http://www.assoc-amazon.fr/e/ir?t=lesvetilles-21&amp;l=ur2&amp;o=8" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" /></p>
<h2>The shared secret</h2>
<p>An essential part of most secure channel protocol is the shared secret (in our case a cryptographic key), and the way in which this secret is protected from disclosure. An attacker is likely to try to get the secret in order to break the protocol. There are two very important properties of the protocol and its keys:</p>
<ul>
<li>Strength. The key strength is usually measured by the number of possible values for the key, which can be considered proportional to the time required to break a single key.</li>
<li>Resilience. The resilience of a protocol is about the consequences of a successful attack. If Charlie is able to find the encryption key for a message, will he be able to decipher all messages between Alice and Bob? Will he also be able to decipher the messages exchanged by all users of the same protocol? If a protocol is able to limit the consequences of a successful attack, it is considered as resilient.</li>
</ul>
<p><span id="more-165"></span></p>
<h3>Key strength</h3>
<p>Let&#8217;s start by the strength; by studying an example. The DES algorithm uses a 8-byte key, in which only 7 bits per byte are used (the last one is used as checksum, or parity bit). This make 56 bits, and the number of possible keys is:</p>
<p>2^56 = 72057594037927936 ~ 7.2 x 10^16</p>
<p>This looks like a large number, but today&#8217;s computers are fast. If we consider that it takes one microsecond to try a key on a message, we then need only  7.2&#215;10^10 second, or 2&#215;10^7 hours, or about 2284 years. At first, this sounds good enough, as nobody expects their application to last that long. But then, think about a hacker who controls a botnet with 100,000 computers (apparently, these are quite common). With that many computers doing the work, it will take less than 10 days to break a key. And that is way too small for any serious application.</p>
<h3>Protocol resilience</h3>
<p>That&#8217;s where resilience becomes important. Let&#8217; say that that Charlie has discovered the key used by Alice to encipher a message. If the same key is used for every communication by the protocol, he may be able to decipher all messages exchanged by anybody who uses the protocol. That would definitely be a bad protocol, and an interesting way for an attacker to keep a botnet busy. There are two classical ways to reduce these consequences and make the protocol more resilient:</p>
<ul>
<li>Session keys. The idea is here to generate a new key for every session, that will be somehow derived from the shared secret. That way, if Charlie breaks a session key, it will only apply to a single session. If measure are taken to ensure that a session only lasts a limited time (a few seconds are sufficient for most sessions), then the attacker has to be very fast (in our example, it would take a botnet of a billion computers to break a DES key in 20 seconds; and that&#8217;s not realistic today).</li>
<li>Diversified keys. The idea is here to generate a master key that is known by a centralized entity (let&#8217;s say, a bank), and to compute a diversified key for every card, for instance by using the card&#8217;s number. That way, if Charlie breaks a message sent by Alice, the secret that he will get will only be good for the messages sent by Alice, and not for those sent by anybody else.</li>
</ul>
<h3>Principles of the solution</h3>
<p>Now, let&#8217;s see what we can do in our case. We will combine a few measures:</p>
<ul>
<li>We will use a triple-DES key, <em>i.e.</em>, a 16-byte key from which 112 bits are used (you can do the computation that shows that such a key is quite difficult to break).</li>
<li>We will use diversified keys, <em>i.e.</em>, we will consider that the key used by the each card application instance is in fact computed from a master key and from an instance identification number.</li>
<li>We will use session keys, <em>i.e.</em>, we will compute a specific key for each session, in order to minimize the use of the actual card keys.</li>
</ul>
<p>Stating this is a good start, but we all have read horror stories about little details that led to the demise of some cryptographic protocol, so there are more things to consider.</p>
<h3>Key diversification</h3>
<p>The objective of key diversification is to use a single â€œbigâ€ secret to secure a large number of application instances. As mentioned previously, the typical example is a bank, or payment system, in which the master secret is known by the bank, but individual customers only get a diversified key, computed from the master secret and from their account number.</p>
<p>Of course, in a case like that, an attacker may try to guess the master secret by breaking the diversification function. Since the account number (or any number used to diversify a key) must be considered public, the complexity of breaking the master secret only depends on the size of the secret and the strength of the diversification function. Let&#8217;s consider a few functions:</p>
<ul>
<li>Triple-DES encryption. The idea is here that the diversified key is the result of the encryption of the diversification data by the master key. With today&#8217;s technology, this is not bad.</li>
<li>Triple-DES encryption, after XOR with a secret random number (or any other transformation of the diversification data). This sounds like a good idea, because it makes it impossible for an attacker to check that they have indeed found the appropriate key (since they cannot compare the result of the decrypted diversified key with the diversification data). In fact, it simply forces them to attack two diversified keys at once exercise.</li>
<li>RSA signature. The idea is the same as the first one, except that the encryption is here performed using a RSA private key. Making the public key available would allow anybody to verify the validity of a diversified key, but this is not interesting (these keys are supposed to be secret). It is therefore better not to disclose the public key.</li>
</ul>
<p>We have here seen that it is not as obvious as it seems to design such a function. Among the three solutions presented above, I would personally prefer the third one, mostly because it relies on a different technology than the rest of the protocol, which could make it more resilient: if the triple-DES technology is broken, it will have no consequences on RSA, so the diversification algorithm will still be valid.</p>
<p>Anyway, the diversification algorithm is out of the scope of our discussion here, since we are only going to implement the card side of the algorithm, where the key is just considered diversified.</p>
<h3>Session key computation</h3>
<p>Some of the security issues for session key computation algorithms are similar to those encountered for key diversification algorithms, and in particular the fact that it must be difficult to get to the instance key from a session key.</p>
<p>In addition, session keys are also used to ensure that it is not possible to â€œreplayâ€ a transaction, which means that it must not be possible to generate the same key twice. Since such a replay attack must be impossible for both parties, this means that we will need to use some random data coming from each party.</p>
<p>In addition, the computation of the session keys is normally used at the beginning of a session in order to perform the mutual authentication. Since the computation of the key requires both sides to perform computations using the shared secret, this works out fine.</p>
<p>Next time, we will try to map our protocol to APDU commands.</p>
]]></content:encoded>
			<wfw:commentRss>http://javacard.vetilles.com/2008/10/07/jc101-18c-defining-a-secure-channel-from-scratch/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>JC301-2: Why change Java Card?</title>
		<link>http://javacard.vetilles.com/2008/09/15/jc301-2-why-change-java-card/</link>
		<comments>http://javacard.vetilles.com/2008/09/15/jc301-2-why-change-java-card/#comments</comments>
		<pubDate>Mon, 15 Sep 2008 20:28:29 +0000</pubDate>
		<dc:creator><![CDATA[Eric Vétillard]]></dc:creator>
				<category><![CDATA[Java Card Bandol]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[Java Card 3.0]]></category>

		<guid isPermaLink="false">http://javacard.vetilles.com/2008/09/15/jc301-2-why-change-java-card/</guid>
		<description><![CDATA[I have recented commented on the fact that parts of the Multos specification have not evolved since August 1997. Java Card was then at its 1.0 version, and in 10 years, has known 3 major releases: 2.0 introduced the new framework, 2.1 made it mature by defining binary-level interoperability, and 2.2 added a few missing [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>I have recented commented on the fact that parts of the Multos specification have not evolved since August 1997. Java Card was then at its 1.0 version, and in 10 years, has known 3 major releases: 2.0 introduced the new framework, 2.1 made it mature by defining binary-level interoperability, and 2.2 added a few missing things. Java Card is currently dominating the smart card market, with a very large market share. In such a context, why introduce a new version of the framework, and on top of it, a major upgrade of the framework?</p>
<h2>The push factor</h2>
<p>The first reason, of course, is due to a mix of engineering push (we can do it, so let&#8217;s do it), and of commercial push (we can get more money out of it, so let&#8217;s do it).</p>
<p>The most obvious push factor, though, is <a href="http://en.wikipedia.org/wiki/Moore" s_law" rel="nofollow" class="liwikipedia">Moore&#8217;s law</a>. Smart card chips continuously become more powerful, and they pack more and more ptechnologies. Java Card 2 has been designed for 8-bit processors, and 32-bit processors are becoming quite common today. The amount of RAM available has also significantly increased, with 8k being common, and 16-32k becoming available on high-end cards. Persistent memory has also increased, with hundreds of kilobytes of ROM, and large amount of mutable persistent memory (EEPROM or flash). Another important change is the availability of high-speed I/O interfaces, such as USB (soon coming in a SIM card near you).</p>
<p>As the capacities of smart cards increase, the limits of Java Card 2 become more and more visible, in two different ways. First, some applicatione are not possible, or at least are difficult to develop using the Java Card 2 model. Then, as applications become more complex, the usability issues of Java Card 2 become obvious</p>
<p>This leads us to another push factor. 10 years ago, Java Card has been a great progress over existing development techniques for smart cards. It is well suited for small applications, but it is also quite limited, in ways that could be easily fixed on today&#8217;s chips. Encoding strings as byte arrays and performing systematic casts feels uselss and outdated, and the demand for an updated programming model grows from developers (this is a push factor, because Java Card developers rarely work for the end customers, but rather for the card manufacturers of for specialized consultants.</p>
<p>Another push factor, and also the most powerful, is the struggle for value inside the mobile phone. All actors strongly believe that mobile computing represents a major opportunity in the coming years, so everybody wants the biggest possible share of the cake. The smart card industry wants to use its long relationship with telcos (SIM cards have represented telcos on mobile phones for quite a while), combined with its experience in handling sensitive applications, to put value-added services on the SIM card, rather than putting them on the mobile phone. Of course, in order to compete with mobile phones, smart card manufacturers ned to put forward a modern programming model that integrates well in today&#8217;s Web-everywhere architecture. Hence, Java Card 3 and its servlet model.</p>
<h2>The pull factor</h2>
<p>Despite all the good reasons to push a new technology, Java Card 3 would not exist if there weren&#8217;t a few reasons to believe that there is a market for the technology, <em>i.e.</em>, a pull factor.</p>
<p>The first one comes from the mobile operators, who want to enable richer applications, and believe that at least some of them can fit on their SIM cards. They keep pushing for smart card Web servers, because it allows them to keep a provisioning model that they know well from SIM Toolkit, and because it offers a much improved user interaction.</p>
<p>Another important pull factor is NFC. SIM cards are one of the strongest options for implementing NFC, and at least some of the deployments will happen with SIM cards. NFC is also very interesting for smart cards, because it is likely to lead to the deployment of really multi-applicative platforms, possibly with multiple application providers. Once again, the interaction model offered by Java Card 3 represents a strong opportunity, as it will be very tempting to add an interface to these contactless applications. Java Card and GlobalPlatform are at the heart of all NFC deployments, and Java Card 3 is likely to emerge as a natural evolution when more sophisticated interactions will be required, or when more complex applications will be required.</p>
<p>Another factor is slowly building today, but we expect it to become a major argument. Internet security issues put a positive light on every device that provides a feeling of security. Secure tokens based on Java Card 3 are likely to be such devices, and it should be possible to build good hype on this basis, if we are able to provide a real improvement in terms of security.</p>
<h2>Targeted markets</h2>
<p>As you can guess from the comments above, the key market for Java Card 3, at least as it is perceived today, is the mobile communication market. SIM cards are a strategic asset for operators, they want to add more value to these assets, and smart card manufacturers want to help them (SIM cards represent at least two thirds of their revenues).</p>
<p>The interesting part is that, even though mobile telecom is the targeted market, all other traditional smart card markets are also involved. Mobile payment and mobile banking are two great opportunities, getting a lot of interest these days. This means that the financial sector is also involved. We can say the same thing for mobile ticketing, for mobile V (<em>i.e.</em>, mobile DRM), and some government-related applications could also be deployed. With multi-applicatoin SIM cards, it is even possible to think about new smart card applications, even though this does not happen very often, and it is likely that only few applicaionts will succeed.</p>
<p>Another market with interesting potential is IT security. With Java Card 3, a smart card is more likely to be used as a personal secure token, in particular if it is able to provide some protection of personal data. However, the demand on such devices remains unclear today.</p>
<p>We have only mentioned so far emerging or transforming markets. However, today&#8217;s Java Card market represents about 2 billion cards per year, and the first priority of the smart card industry is to secure this market for the coming years. This market has a lot of inertia, and innovations take a long time to pick up. Some markets haven&#8217;t yet picked up Java Card as mainstream technology; in most cases, these are not ready to move to Java Card 3&#8217;s servlet model.</p>
<p>The consequence is here that Java Card 3 must address all smart card markets, from the commodity markets for mass deployments to the high-end markets for early adopters of the Smart Web. We will see in the next post how this has been addressed.</p>
]]></content:encoded>
			<wfw:commentRss>http://javacard.vetilles.com/2008/09/15/jc301-2-why-change-java-card/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>JC301-1: Introducing Java Card 3.0</title>
		<link>http://javacard.vetilles.com/2008/09/04/jc201-1-introducing-java-card-30/</link>
		<comments>http://javacard.vetilles.com/2008/09/04/jc201-1-introducing-java-card-30/#comments</comments>
		<pubDate>Thu, 04 Sep 2008 21:47:33 +0000</pubDate>
		<dc:creator><![CDATA[Eric Vétillard]]></dc:creator>
				<category><![CDATA[Java Card Bandol]]></category>
		<category><![CDATA[News]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[Java Card 3.0]]></category>
		<category><![CDATA[servlet]]></category>

		<guid isPermaLink="false">http://javacard.vetilles.com/2008/09/04/jc201-1-introducing-java-card-30/</guid>
		<description><![CDATA[Foreword: The JC101 tutorial about Java Card 2 is getting closer to the end, now dealing with the subtleties of cryptography, testing, and other difficult tasks. As progress may slow to a crawl, it is time to start discussing the technology that actually started this blog, Java Card 3. &#8211; o &#8211; Your first program [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>Foreword: The JC101 tutorial about Java Card 2 is getting closer to the end, now dealing with the subtleties of cryptography, testing, and other difficult tasks. As progress may slow to a crawl, it is time to start discussing the technology that actually started this blog, Java Card 3.</p>
<p><center>&#8211; o &#8211;</center></p>
<h2>Your first program</h2>
<p>If you are going to work with Java Card 3, your first program is quite likely to look something like the following:</p>
<pre>
public class EchoServlet extends <span style="background-color: yellow">HttpServlet</span> {

  <span style="background-color: yellow">@Override</span>
  public void doGet(
          HttpServletRequest request,
          HttpServletResponse response)
              throws IOException {
    String message =
      request.getPathInfo().substring(1);
    StringBuffer echo = <span style="background-color: yellow">new</span> StringBuffer();
    echo.append(HTML[0]);
    for(<span style="background-color: yellow">int</span> i = 1; i < HTML.length; i++)
    {
      echo.append(message);
      echo.append(HTML[i]);
    }
    PrintWriter out = response.getWriter();
    out.print(echo.toString());
  }

  private static final <span style="background-color: yellow">String</span> HTML[] = {
            "&lt;html>&lt;header>&lt;title>Echo&lt;/title>&lt;/header>"
         + "&lt;body>&lt;center>
    	 + "&lt;h1>Echo&lt;/h1>&lt;br>&lt;br>&lt;br>"
         + "&lt;font color=\"#000000\">" , "&lt;/font>&lt;br>"
         + "&lt;font color=\"#444444\">" , "&lt;/font>&lt;br>"
         + "&lt;font color=\"#888888\">" , "&lt;/font>&lt;br>"
         + "&lt;font color=\"#cccccc\">" , "&lt;/font>&lt;br>"
         + "&lt;/center>&lt;br>&lt;br>"
         + "&lt;small>&lt;p align=\"center\">"
         + "Yes, this servlet runs on a Java Card.&lt;/p>&lt;/small>"
         + "&lt;/center>&lt;/body>&lt;/html>"};
}
</pre>
<p>Quite a shocker, isn&#8217;t it? This doesn&#8217; look at all like a Java Card program. There is nothing specific for card in this program; it could run on any Java EE Web server. On the program, I have outlined a few words that somehow define what Java Card 3.0 is; let&#8217;s take a look at them:</p>
<ul>
<li><code>int</code>. Everyobdy expected this one eventually, and here it is. Java Card 3.0 is a pure 32-bit virtual machine, and there is no reason to cast computation into <code>short</code> and <code>byte</code>, expect for storage. Of course, this also means that Java Card 3.0 will only work on chips that include a 32-bit processor.</li>
<li><code>String</code>. Another long-time dream of Java Card developers, in particular those working on text-intensive SIM Toolkit applets. Well, strings are supported in Java Card 3.0.</li>
<li><code>new</code>. It is nos possible to allocate objects temporarily, <em>i.e.</em>, to program in a more standard Java way. This is made possible by the availability of a real garbage collector, and by the fact that some objects are actually stored in RAM. Of course, this also means that Java Card 3.0 will only work on chips that include enough RAM (at least 16 kilobytes).</li>
<li><code>@Override</code>. This annotation is not very useful in itself, but its availability means that Java Card 3.0 is based on a recent release of Java, which supports annotations. In fact, Java Card 3.0 is based on the latest release, Java 6, and it includes supports for quite a few advanced features, including generics and others.</li>
<li><code>HttpServlet</code>. I have kept the best one for the end. Yes, this application is a servlet, and not an applet. It means that a Java Card 3.0 card is expected to be a Web server, receiving HTTP requests over a TCP/IP connection and answering appropiately with a Web page that will be displayed in your browser.</li>
</ul>
<p>Now, can we run this application? Of course, we can, and the result is shown below:</p>
<p><center><a href="http://javacard.vetilles.com/2008/09/04/jc201-1-introducing-java-card-30/execution-of-echo1/" rel='attachment wp-att-152' title='Execution of Echo1' class="liimagelink"><img src='http://javacard.vetilles.com/wp-content/uploads/2008/09/echo1.thumbnail.png' alt='Execution of Echo1' /></a></center></p>
<p>A question that often comes to mind about these applications is &#8220;<em>Is this still Java Card?</em>&#8221; The answer is unclear:</p>
<ul>
<li><strong>No, it&#8217;s not!</strong> It is a Web server, it talks to your browser. It basically supports Java, and there is no Java Card-specific stuff any more.</li>
<li><strong>Of course it is &#8230;</strong> This thing runs on a smart card, <em>i.e.</em>, on devices that keep the interesting properties of a smart card (secure, portable, cheap, manageable), as well as their drawbacks (too small, too slow). So yes, there is still plenty of Java Card-specific stuff to know about Java Card 3.0 and servlets.</li>
</ul>
<p>That&#8217;s it for today! We will get to the real stuff in a few days or weeks. For now, you have an opportunity to come visit my home turf and learn about Java Card 3.0 by attending <a href="http://www.strategiestm.com/conferences/smartuniv/08/index.htm" class="liexternal">Smart University</a> session on <a href="http://www.strategiestm.com/conferences/smartuniv/08/program_smart-card-software.htm" class="liexternal">The Art of Java Card 3.0 Programming</a> on September 16th and 17th in Sophia Antipolis. If you missed the JavaOne bash, don&#8217;t miss this opportunity to meet with the Java Card 3 community. See you there!</p>
]]></content:encoded>
			<wfw:commentRss>http://javacard.vetilles.com/2008/09/04/jc201-1-introducing-java-card-30/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
