6 Apr 2011

How to develop SCWS Servlet?

I'd like to continue the subject of Smart Card Web Server (SCWS) and explain in this post how to develop servlets for SCWS. Servlet for SCWS from one point is regular JavaCard Applet but at the same it has some differences. Let me explain.

Servlet has the following properties:
  • Triggers upon HTTP request reception
  • Has to be developed using dedicated ETSI 102.588 API
  • Mapped on one or several URIs (e.g.“/operator/app”)
There are two kind of servlets:
  • Dynamic content generation
  • Interception (usage tracking)
Servlet supports the following HTTP Request methods:

GETRequests the specified resource
HEADRequests meta-information on a resource (no body)
PUTUploads (add or replace) a resource on the server
POSTSubmits data to be processed to the identified resource
DELETEDeletes the specified resource on the server
OPTIONSReturns the HTTP methods supported for the specified URI (debug purpose)
TRACEEchos back the received requests (debug purposes)

CONNECT method isn't supported by ETSI TS 102.588 standard.

SCWS API has defined in uicc.scws hence you have to import it:

import uicc.scws.*;

Class has to be declared as follows:

class ServletHelloWorld extends Applet
      implements AppletEvent, ScwsExtension
  • Class should extend Applet as it is JavaCard standard applet
  • It has to implement ScwsExtension interface to be able to trigger by SCWS
  • It has to implement AppletEvent interface to define uninstall() method
  • It could implement ToolkitInterface interface if the servlet should be triggered as STK applet
Methods which have to be implemented:
  • JavaCard mandatory methods: process(), install()
  • ScwsExtension mandatory methods: doDelete(), doGet(), doHead(), doOptions(), doPost(), doPut(), doTrace()
Ok, let's have a look to real source code:

package firstservletpackage;

/*
 * Imported packages
 */
import javacard.framework.*;
import uicc.scws.HttpRequest;
import uicc.scws.HttpResponse;
import uicc.scws.ScwsConstants;
import uicc.scws.ScwsException;
import uicc.scws.ScwsExtension;
import uicc.scws.ScwsExtensionRegistry;

public class FirstServlet extends javacard.framework.Applet
                          implements AppletEvent, ScwsExtension {
    /** the servlet url */
    public final static byte[] url = { '/', 'F', 'S' };
    public final static byte[] appId = { 'F', 'i', 'r', 's', 't', 'S', 'e'
                                        ,'r', 'v', 'l', 'e', 't' };
    public final static byte[] CRLF = { '\r', '\n' };
    public static final byte[] SPACE = { ' ' };
    /** error status word when install parameter are invalid */
    public final static short SW_INVALID_INSTALL_PARAMETER = (short) 0x6F06;
    /** install tag: should find the http server aid inside */
    public final static byte INSTALL_TAG = (byte) 0x71;

    public final static byte[] METHOD_GET = { 'G', 'E', 'T' };
    public final static byte[] TEXT_PLAIN = { 't', 'e', 'x', 't', '/', 'p'
                                             ,'l', 'a', 'i', 'n' };

    // Temporary operation buffer
    public byte[] temporaryBuffer;
    public final static short TEMPORARY_BUFFER_LENGTH = (short) 100;

    public final static byte[] REQUEST_BODY = { 'R', 'e', 'q', 'u', 'e', 's'
                                             ,'t', ' ', 'B', 'o', 'd', 'y', ':' };
    public final static byte[] PROTOCOL = { 'P', 'r', 'o', 't', 'o', 'c', 'o'
                                           ,'l', ':' };
    public final static byte[] CONTENT_TYPE = { 'C', 'o', 'n', 't', 'e', 'n'
                                             ,'t', ' ', 'T', 'y', 'p', 'e', ':' };
    public final static byte[] HEADER_UA = { 'H', 'e', 'a', 'd', 'e', 'r', ' '
                                            ,'U', 's', 'e', 'r', ' '
                                            , 'A', 'g', 'e', 'n', 't', ':' };
    public final static byte[] METHOD = { 'M', 'e', 't', 'h', 'o', 'd', ':' };
    public final static byte[] QUERY_STRING = { 'Q', 'u', 'e', 'r', 'y', ' '
                                             ,'S', 't', 'r', 'i', 'n', 'g', ':' };
    public final static byte[] REQUEST_URI = { 'R', 'e', 'q', 'u', 'e', 's'
                                              ,'t', ' ', 'U', 'R', 'I', ':' };
    public final static byte[] TRACE = { 'T', 'R', 'A', 'C', 'E' };
    public final static byte[] ACCEPT = { 'A', 'c', 'c', 'e', 'p', 't', ':' };
    public final static byte[] ACCEPT_LANG = { 'A', 'c', 'c', 'e', 'p', 't'
                              ,'-', 'L', 'a', 'n', 'g', 'u', 'a', 'g', 'e', ':' };
    public final static byte[] CONNECTION = { 'C', 'o', 'n', 'n', 'e', 'c'
                                             ,'t', 'i', 'o', 'n', ':' };
    public final static byte[] HOST = { 'H', 'o', 's', 't', ':' };
    public final static byte[] REFERER = { 'R', 'e', 'f', 'e', 'r', 'e', 'r', ':' };
    public final static byte[] USER_AGENT = { 'U', 's', 'e', 'r', '-', 'A'
                                             ,'g', 'e', 'n', 't', ':' };
    public final static byte[] ACCEPT_ENCODING = { 'A', 'c', 'c', 'e', 'p', 't'
                                                  , '-', 'E', 'n', 'c', 'o', 'd'
                                                  , 'i', 'n', 'g', ':' };
    public final static byte[] ALLOW = { 'A', 'l', 'l', 'o', 'w' };
    public final static byte[] ALLOW_OPTIONS = { 'G', 'E', 'T', ','
                                       , 'T', 'R', 'A', 'C', 'E'
                                       , ',', 'O', 'P', 'T', 'I', 'O', 'N', 'S' };
    public final static byte[] HTTP_10 = { 'H', 'T', 'T', 'P', ':'
                                          , '/', '1', '.', '0' };
    public final static byte[] HTTP_11 = { 'H', 'T', 'T', 'P', ':'
                                          , '/', '1', '.', '1' };

    public final static byte[] HELLO = { 'H', 'e', 'l', 'l', 'o' };

    /**
     * Constructor of servlet
     */
    public FirstServlet(byte[] buffer, short offset, byte length) {
        // First LV is instance AID
        short aid = offset;
        offset += buffer[offset] + (byte) 1;
        // Second LV is Privilege
        offset += buffer[offset] + (byte) 1;
        // Third LV is specific install parameter (extract from TAG C9)
        offset++; // skip C9 Length
        // Register the new applet instance to the JCRE
        register(buffer, (short) (aid + (short) 1), buffer[aid]);
        // Register application id,there is corresponding appId in the Run/Debug
        // configuration for URL Mapping
        // if you update this appId in current code,you may need update
        // corresponding value there for URL Mapping
        ScwsExtensionRegistry.register(this, appId, (short) 0,
                (short) appId.length);
        try {
            // Create a temporary buffer for read/write
            temporaryBuffer = JCSystem.makeTransientByteArray(
                    TEMPORARY_BUFFER_LENGTH, JCSystem.CLEAR_ON_RESET);
        } catch (SystemException se) {
            // create buffer in persistent memory as not enough transient is
            // available
            temporaryBuffer = new byte[TEMPORARY_BUFFER_LENGTH];
        }

    }

    /**
     * Method called by the JCRE at the installation of the applet
     * 
     * @param bArray
     *            the byte array containing the AID bytes
     * @param bOffset
     *            the start of AID bytes in bArray
     * @param bLength
     *            the length of the AID bytes in bArray
     */
    public static void install(byte[] bArray, short sOffset, byte bLength)
            throws ISOException {
        new FirstServlet(bArray, sOffset, bLength);
    }

    /**
     * Method called by the JCRE, uninstall the applet
     */
    public void uninstall() {
        ScwsExtensionRegistry.deregister(this);
    }

    /**
     * Method called by the JCRE, once selected
     * 
     * @param apdu
     *            the incoming APDU object
     */

    public void process(APDU apdu) throws ISOException {
        // ignore the applet select command dispached to the process
        if (selectingApplet()) {
            return;
        }
        // actually no IO methods needed for the server.
        ISOException.throwIt(ISO7816.SW_INS_NOT_SUPPORTED);
    }

    /**
     * Called by the SCWS to allow a servlet to handle a DELETE request.
     * <p>
     * If the HTTP DELETE request is incorrectly formatted, doDelete returns an
     * HTTP "Bad Request" message.
     * </p>
     * 
     * @param req
     *            - the HttpRequest object that contains the request the client
     *            made of the servlet
     * @param resp
     *            - the HttpResponse object that contains the response the
     *            servlet returns to the client
     * @throws ScwsException
     *             - if the request for the DELETE cannot be handled
     */
    public void doDelete(HttpRequest req, HttpResponse resp)
            throws ScwsException {
    }

    /**
     * Called by SCWS to allow a servlet to handle a GET request.
     * <p>
     * When using HTTP 1.1 chunked encoding (which means that the response has a
     * Transfer-Encoding header), do not set the Content-Length header.
     * </p>
     * If the HTTP POST request is incorrectly formatted, doPost returns an HTTP
     * "Bad Request" message.
     * 
     * @param req
     *            - an HttpRequest object that contains the request the client
     *            has made of the servlet
     * @param resp
     *            - an HttpResponse object that contains the response the
     *            servlet sends to the client
     * @throws ScwsException
     *             - if the request for the GET could not be handled
     */
    public void doGet(HttpRequest req, HttpResponse resp) throws ScwsException {
        // TODO Replace your doGet method below
        // ----------------------------------------------------------------------
        // return on response body:
        // status: 200 (OK)
        // Content Type: text/html
        // Protocol: HTTP/1.1
        // Method: GET
        // Header User Agent: Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0)
        // Content Type: text/html
        // ...
        try {
            short httpVersion = req.getRequestHttpVersion();

            // set header
            resp.writeStatusCode(ScwsConstants.SC_OK);
            resp.setContentType(ScwsConstants.CONTENT_TYPE_TEXT_HTML);
            resp.enableChunkMode();

            // write body
            resp.appendContent(HELLO, (short) 0, (short) HELLO.length);
            
        } catch (Exception e) {
            resp.writeStatusCode(ScwsConstants.SC_BAD_REQUEST);
        }

        resp.flush();

    }

    /**
     * Receives an HTTP HEAD request from the protected service method and
     * handles the request.
     * <p>
     * The client sends a HEAD request when it wants to see only the headers of
     * a response, such as <tt>Content-Type</tt> or <tt>Content-Length</tt>.<br>
     * <p>
     * The HTTP HEAD method counts the output bytes in the response to set the
     * Content-Length header accurately.
     * <p>
     * If the HTTP HEAD request is incorrectly formatted, doHead returns an HTTP
     * "Bad Request" message.
     * 
     * @param req
     *            - the request object that is passed to the servlet
     * @param resp
     *            - the response object that the servlet uses to return the
     *            headers to the clien
     * @throws ScwsException
     *             - if the request for the HEAD could not be handled
     */
    public void doHead(HttpRequest req, HttpResponse resp) throws ScwsException {

    }

    /**
     * The OPTIONS method represents a request for information about the
     * communication options available on the request/response chain identified
     * by the Servlet.
     * <p>
     * Called by the SCWS to allow a servlet to handle a OPTIONS request. <br>
     * The OPTIONS request determines which HTTP methods the server supports and
     * returns an appropriate header.<br>
     * For example, if a servlet overrides doGet, this method returns the
     * following header:
     * 
     * <pre>
     * Allow: <tt>GET</tt>, <tt>HEAD</tt>, <tt>OPTIONS</tt>
     * </pre>
     * 
     * </p>
     * 
     * @param req
     *            - the HttpRequest object that contains the request the client
     *            made of the servlet
     * @param resp
     *            - the HttpResponse object that contains the response the
     *            servlet returns to the client
     * @throws ScwsException
     *             - if the request for the OPTIONS cannot be handled
     */
    public void doOptions(HttpRequest req, HttpResponse resp)
            throws ScwsException {
        resp.appendHeaderVariable(ALLOW, (short) 0, (short) ALLOW.length,
                ALLOW_OPTIONS, (short) 0, (short) ALLOW_OPTIONS.length);
        resp.flush();

    }

    /**
     * Called by the SCWS to allow the servlet to handle a POST request.
     * <p>
     * When using HTTP 1.1 chunked encoding (which means that the response has a
     * Transfer-Encoding header), do not set the Content-Length header.
     * </p>
     * If the HTTP POST request is incorrectly formatted, doPost returns an HTTP
     * "Bad Request" message.
     * 
     * @param req
     *            - an HttpRequest object that contains the request the client
     *            has made of the servlet
     * @param resp
     *            - an HttpResponse object that contains the response the
     *            servlet sends to the client
     * @throws ScwsException
     *             - if the request for the POST could not be handled
     */
    public void doPost(HttpRequest req, HttpResponse resp) throws ScwsException {
    }

    /**
     * Called by the SCWS (via the service method) to allow a servlet to handle
     * a PUT request.
     * <p>
     * If the HTTP PUT request is incorrectly formatted, doPut returns an HTTP
     * "Bad Request" message.
     * 
     * @param req
     *            - the HttpRequest object that contains the request the client
     *            made of the servlet
     * @param resp
     *            - the HttpResponse object that contains the response the
     *            servlet returns to the client
     * @throws HttpCardServletException
     *             - if the request for the PUT cannot be handled
     * @throws java.lang.Exception
     */
    public void doPut(HttpRequest req, HttpResponse resp) throws ScwsException {
    }

    /**
     * Called by the server (via the service method) to allow a servlet to
     * handle a TRACE request.
     * <p>
     * The TRACE method is used to invoke a remote, application-layer loop-back
     * of the request message.
     * </p>
     * 
     * @param req
     *            - the HttpRequest object that contains the request the client
     *            made of the servlet
     * @param resp
     *            - the HttpResponse object that contains the response the
     *            servlet returns to the client
     * @throws ScwsException
     *             - if the request for the TRACE cannot be handled
     */
    public void doTrace(HttpRequest req, HttpResponse resp)
            throws ScwsException {
        // TODO Auto-generated method stub
        // --------------------------
        /*
         * A TRACE returns the headers sent with the TRACE request to the
         * client, so that they can be used in debugging.
         */
        try {

            // set header
            resp.writeStatusCode(ScwsConstants.SC_OK);
            resp.setContentType(ScwsConstants.CONTENT_TYPE_TEXT_PLAIN);
            resp.enableChunkMode();

            // TRACE /MyServlet1 HTTP/1.1
            resp.appendContent(TRACE, (short) 0, (short) TRACE.length);
            resp.appendContent(SPACE, (short) 0, (short) SPACE.length);
            getAndOutputContent(req, resp, ScwsConstants.URI_PATH_TAG);

            resp.appendContent(SPACE, (short) 0, (short) SPACE.length);
            short httpVersion = req.getRequestHttpVersion();
            if (httpVersion == ScwsConstants.HTTP_PROTOCOL_VERSION_10)
                resp.appendContent(HTTP_10, (short) 0, (short) HTTP_10.length);
            else
                resp.appendContent(HTTP_11, (short) 0, (short) HTTP_11.length);
            resp.appendContent(CRLF, (short) 0, (short) CRLF.length);

            // ex: Accept: */*
            resp.appendContent(ACCEPT, (short) 0, (short) ACCEPT.length);
            getAndOutputContent(req, resp, ScwsConstants.HEADER_ACCEPT);
            resp.appendContent(CRLF, (short) 0, (short) CRLF.length);

            // ex: Accept-Language: en-us
            resp.appendContent(ACCEPT_LANG, (short) 0,
                    (short) ACCEPT_LANG.length);
            getAndOutputContent(req, resp, ScwsConstants.HEADER_ACCEPT_LANGUAGE);
            resp.appendContent(CRLF, (short) 0, (short) CRLF.length);

            // ex: Host: localhost
            resp.appendContent(HOST, (short) 0, (short) HOST.length);
            getAndOutputContent(req, resp, ScwsConstants.HEADER_HOST);
            resp.appendContent(CRLF, (short) 0, (short) CRLF.length);

            // ex: User-Agent: Mozilla/4.0 (compatible; MSIE 5.5; Windows NT
            // 5.0)
            resp
                    .appendContent(USER_AGENT, (short) 0,
                            (short) USER_AGENT.length);
            getAndOutputContent(req, resp, ScwsConstants.HEADER_USER_AGENT);
            resp.appendContent(CRLF, (short) 0, (short) CRLF.length);

            // ex: Accept-Encoding: gzip, deflate
            resp.appendContent(ACCEPT_ENCODING, (short) 0,
                    (short) ACCEPT_ENCODING.length);
            getAndOutputContent(req, resp, ScwsConstants.HEADER_ACCEPT_ENCODING);
            resp.appendContent(CRLF, (short) 0, (short) CRLF.length);

        } catch (Exception e) {
            resp.writeStatusCode(ScwsConstants.SC_NOT_IMPLEMENTED);
        }

        resp.flush();

    }

    private void getAndOutputContent(HttpRequest req, HttpResponse resp,
            short keyword) {
        short contentLgth = req.findAndCopyKeywordValue(keyword,
                temporaryBuffer, (short) 1,
                (short) (temporaryBuffer.length - 1));
        if (contentLgth == ScwsConstants.KEYWORD_NOT_FOUND)
            contentLgth++; // Query string may not exist, so set it 0 if did
        temporaryBuffer[0] = (byte) (contentLgth);
        resp.appendContent(temporaryBuffer, (short) 1,
                (short) temporaryBuffer[0]);
        clearBuffer(); // Clear buffer for reuse
    }

    private void clearBuffer() {
        for (short i = 0; i < temporaryBuffer.length; i++) {
            temporaryBuffer[i] = 0;
        }
    }

    private short getLength(byte[] data) {
        for (short i = 0; i < data.length; i++) {
            if (data[i] == 0) {
                return i;
            }
        }
        return 0;
    }
}

5 Apr 2011

What is Smart Card Web Server (SCWS)?

Smart Card Web Server is web server application which works in the SIM Card. It allows HTTP/1.0 and HTTP/1.1 connection between mobile phone and SIM card. It could enrich visualizations of content by using xHTML, javascript and flash animations.
As any web server SCWS is not only performing static content but also capable to serve dynamic content using SCWS servlets. Let's have a look to generic architecture of SCWS:



All parts of SCWS at the present time have been standardized by Open Mobile Alliance (OMA) and ETSI:

Smart Card Web Server:
  • OMA-TS-Smartcard_Web_Server-V1_1-20090512-A
  • Covers the technical specificities of a HTTP server in a SIM card plus the new Remote Management architecture and protocol
  • 1.1 Approved by OMA in 2008
BIP TCP Server:
  • Standardised bearer (TS 102 223 Rel-7) for ISO (APDU) interface minor modification to BIP/TCP Client (Rel-99)
USB-IC ("IP in UICC"):
  • High speed interface (HSI) based on USB: TS 102 600
  • Direct TCP/IP connectivity, locally or remotely: TS 102 483, on top of USB
SCWS Servlet API:
  • TS 102 588 Rel-7
SCWS supports Basic Authentication by default. SCWS Servlet API allows developing any type of application. Some examples:
  • Home screen personalization based on operator design
  • Blogging application which could work even offline and upload posts when it will be online
  • Operator portal which will replace ancient STK menu application
  • etc

14 Mar 2011

Emacs el-get on windows

Emacs el-get allows you to install and manage elisp code for Emacs. It supports lots of differents types of sources and is able to install, update and remove them, but more importantly it will init them for you.
It allows you to keep up-to-date you elisp packages like cedet, emacs-w3m and hundred others. But if you tried to use it on windows you will figure out that a lot of them fail to install. It is related to the fact that most of packages are using UNIX command line tools which are not working on windows out-of-box.
Fortunately most of them could be installed on windows with slight modifications. Below small how-to:
1. Download and install cygwin tools and and cygwin/bin folder to your PATH. For the most of the packages you will need:
- curl (I'll explain later why it is necessary)
- ssh
- openssl
- bzr/git/subversion etc - it depends on which version control system has been used for package. It could be easily identified from recipe file. Below simple example of yasnippet recipe:
(:name yasnippet
      :type svn
      :url "http://yasnippet.googlecode.com/svn/trunk/"
      :features "yasnippet"
      :post-init (lambda ()
           (yas/initialize)
           (add-to-list 'yas/snippet-dirs (concat el-get-dir "yasnippet/snippets"))
            (yas/reload-all)))

Pay attention to type. It is specifying used version control system. In the given example it is subversion. So to be able to install this package you need svn client in your path. It is not mandatory to have it from cygwin but I prefer to use cygwin one as everything could be installed by its setup from one place.

- make utility

- autotools (autoconf, automake and co.)

- etc. (please check what exactly recipe is using.)

2. Open bash from cygwin installation (simply run cygwin.bat file) and enter the following commands:
$ cd /usr/ssl/certs
$ curl http://curl.haxx.se/ca/cacert.pem | awk 'split_after==1{n++;split_after=0} /-----END CERTIFICATE-----/ {split_after=1} {print > "cert" n ".pem"}'
$ c_rehash
If you won't do that you will have certificate error during installation of el-get from github. These commands will imports many certificates for different sites which are collected by curl developers team.

3. Follow the instruction specified on el-get site.

4. If your favourite package gives error check the following:

- If you've installed client for version control mentioned in recipe and is path specified in your PATH?

- If site is available by web browser.

- If it fails during installation check what kind of commands have been used. Try to run them from CMD prompt (not bash). If needed correct them.

I'll give you example of my patches to emacs-w3m and cedet.

emacs-w3m

Original recipe was:
(:name emacs-w3m
      :type cvs
      :module "emacs-w3m"
      :url ":pserver:anonymous@cvs.namazu.org:/storage/cvsroot"
      :build `("autoconf" ("./configure" ,(concat "--with-emacs=" el-get-emacs)) "make")
      :info "doc")

autoconf, ./configure commands are shell scripts hence they are not executable from CMD prompt and this build will fail. Fixed version of recipe:
(:name emacs-w3m
      :type cvs
      :module "emacs-w3m"
      :url ":pserver:anonymous@cvs.namazu.org:/storage/cvsroot"
      :build `("autoconf" ("./configure" ,(concat "--with-emacs=" el-get-emacs)) "make")
      :build/windows-nt ("sh /usr/bin/autoconf" "sh ./configure" "make")
      :info "doc")

CEDET

Original recipe was:
(:name cedet
      :type bzr
      :url "bzr://cedet.bzr.sourceforge.net/bzrroot/cedet/code/trunk"
      :build ("touch `find . -name Makefile`" "make")
      :load-path ("./common"))
Patch for this recipe was more difficult as “`” symbol is not valid for CMD and you cannot pass whole this command to shell as touch binary. Moreover Makefile for CEDET use UNIX version of find command. Below how I fixed it:
(:name cedet
      :type bzr
      :url "bzr://cedet.bzr.sourceforge.net/bzrroot/cedet/code/trunk"
      :build ("touch `find . -name Makefile`" "make")
      :build/windows-nt ("echo #!/bin/sh > tmp.sh & echo touch `/usr/bin/find . -name Makefile` >> tmp.sh & echo make FIND=/usr/bin/find >> tmp.sh" 
          "sed 's/^M$//' tmp.sh  > tmp2.sh"
          "sh ./tmp2.sh" "rm ./tmp.sh ./tmp2.sh")
      :load-path ("./common"))
By this way you can fix almost any recipe. If you do it, don’t forget to send patch to original author and share with us ;)

8 Mar 2011

Utility for calculation MIFARE Password

The ones who read my post about how to calculate MIFARE password found it very tough to calculate manually. Hence I've developed tool to automate it. The full source codes are available in github. If you don't care about source code, executable file is also there. You need .Net 4.0 and F# runtime to run it.

9 Feb 2011

And then there's Haskell...

> Odd that this has come up -- I was just looking at Common Lisp and
> Scheme implementations, as well as a smattering of Haskellish tools

And then there's Haskell...

Haskell is like "that girl."  You know the one...

You never really went steady, but you'd run into her from time to  
time while knocking around in disreputable joints, usually late at  
night, every several months or so.  She looked so hot, so sleek, so  
sexy, so expressive, so exotic.  You'd end up back at her place and  
the night would just...  take off.  A complete blur of hot, sweaty,  
feverish, delirious, fumbling passion.  You'd do things to each  
other...  you'd do things to her, she'd do things to you...  things  
that you're not even sure have names, that you're pretty sure are  
illegal almost anywhere.  Even her kinks have kinks --- and after one  
of these nights, you'd realize that you yourself had a lot more kinks  
than you.  And it wasn't just physical, it was --- cerebral.   
Ethereal.  Transcendent.  But it would all whiz by in a blur, and by  
morning you'd find yourself lightheaded, a bit confused, and  
stumbling homeward to your regular gal.

Over the next few days and weeks you'd find yourself occasionally  
drifting away, thinking about her.  Haskell.  You'd be there, banging  
away at your regular girl, and find yourself thinking "you know, if I  
was with Haskell, I'd be doing this completely differently."  You'd  
think "I could be doing so much bigger and better stuff with  
Haskell."  Now, your regular girl, she's not as exotic as Haskell.   
Pretty, maybe, if you're lucky.  (Perhaps your regular girlfriend's  
name is Python. ;-)  But not nearly as --- weird.  Wild.  Cool.   
Exciting.  Don't get me wrong --- your girl, she's wonderful.  You've  
got a wonderful relationship.  She's --- comfortable.  You can bang  
away at her all day and night.  She's accommodating.  Easy going.   
You work well together.  But --- confidentially --- she's, well,  
maybe just a little bit boring.  You'd catch yourself thinking these  
things, and the guilty pangs would get to you...  You'd quash the  
thoughts, buckle down, and get back to banging away.  Comfortable...   
there's a lot to be said for that, ya know?  Comfortable...  just  
keep telling yourself that.

Months would go by.  Late some night you'd find yourself out,  
disreputable places again.  Maybe that hacker bar, LtU.  Somebody'd  
slip you an URL for some renegade paper, you know, one of *those*  
papers.  You'd run into Haskell again.  And the whole thing starts over.

Eventually, you're going to get the ultimatum.  Haskell's ultimately  
just like any other girl on some level;  she needs commitment.   
Eventually, after one night of wild, feverish, kinky, abstract  
passion, she's going to say to you:  "All these times, and you don't  
understand me at all!  You know, you're going to have to get serious,  
mister!  I've got needs, too.  You're going to have to get serious  
about my monads, or that's the last time you're going to play with  
them!  Got it?"

...and then, you've got to make The Choice.

Chances are, you're going to go back to your regular gal.  Haskell's  
just too much for any one man, probably.  She leaves a trail of  
broken, brainy, embittered PhDs and former programmers behind her.   
She ruins you for the RealWorld.  You can ride a while, but you  
probably can't go the distance with her.  Go back to your regular gal  
and try not to think too much about what you've seen.  Done.  Felt.   
Thought.

Maybe you can salvage a little happiness;  but it'll be hard.  After  
all...  you've tasted Haskell.

She's not like anything else.


27 Jan 2011

How to calculate MIFARE password

In my recent post “How to access MIFARE memory” I’ve received question how to calculate MIFARE password. So in this post I would like to explain it.
The calculation of MIFARE password (MF_password) has described in Philips Application Note AN02105. It is generated based on Key A and Key B as showed below:






As you can see it is 3DES algo. The start value is 8 bytes with value 00h.
The keys DKeyA and DKeyB are derived from MIFARE Key A and Key B keys of respective MIFARE sector. But Key A and Key B are 6 bytes long. To be able to use them as 3DES keys the following conventions have defined:


Representation of the MIFARE Sector Trailer:





Representation of bits of the MIFARE Key (each consists of 6 bytes):


BYTE 5 MSB BYTE 4 BYTE 3 BYTE 2 BYTE 1 BYTE 0 LSB
K57 … K50 K47 … K40 K37 … K30 K27 … K20 K17 … K10 K07 … K00

The 6 bytes MIFARE key will be mapped to the 64 bit 3DES keys DKeyB in the following way:

DES KEY BYTE BIT 7 BIT 6 BIT 5 BIT 4 BIT 3 BIT 2 BIT 1 BIT 0
7 K56 K55 K54 K53 K52 K51 K50 P
6 K46 K45 K44 K43 K42 K41 K40 P
5 K36 K35 K34 K33 K32 K31 K30 P
4 K26 K25 K24 K23 K22 K21 K20 P
3 K16 K15 K14 K13 K12 K11 K10 P
2 K06 K05 K04 K03 K02 K01 K00 P
1 0 K57 K47 K37 K27 K17 K07 P
0 0 0 0 0 0 0 0 P

P in BIT 0 means Parity Bit (not checked).
DKeyA will be generated in the same manner according to below table:

DES KEY BYTE BIT 7 BIT 6 BIT 5 BIT 4 BIT 3 BIT 2 BIT 1 BIT 0
7 0 0 0 0 0 0 0 P
6 0 K07 K17 K27 K37 K47 K57 P
5 K56 K55 K54 K53 K52 K51 K50 P
4 K46 K45 K44 K43 K42 K41 K40 P
3 K36 K35 K34 K33 K32 K31 K30 P
2 K26 K25 K24 K23 K22 K21 K20 P
1 K16 K15 K14 K13 K12 K11 K10 P
0 K06 K05 K04 K03 K02 K01 K00 P

Some examples:
  • Initial value: 00 00 00 00 00 00 00 00
  • The DES parity bits are regarded as 0
MIFARE KEYS (LSB -> MSB) 3DES KEYS (LSB –> MSB) MF_PASSWORD (LSB –> MSB)
Key A FF FF FF FF FF FF DKeyA FE FE FE FE FE FE 7E 00 0B 54 57 07 45 FE 3A E7
Key B FF FF FF FF FF FF DKeyB 00 7E FE FE FE FE FE FE
Key A A0 A1 A2 A3 A4 A5 DKeyA 40 42 44 46 48 4A 7E 00 8C 7F 46 D7 6C E0 12 66
Key B B0 B1 B2 B3 B4 B5 DKeyB 00 7E 60 62 64 66 68 6A

14 Jan 2011

Advanced JavaCard debugging. (The story of one debug)

Sometimes ago I've written the post about JavaCard applets debugging techniques. In the current post I'd like to narrate story from real life. Actually this post is translation of post in my Russian blog.
Well, the problem which I've encountered was the SIM Toolkit (STK) applet with a couple of menu entries. On the real card when you select one of menu entry applet silently exits instead of sending SMS. Checking source code of the applet was not helped. So the only way to debug was loading applet to Software Simulator.
Ok, if no other way, I've compiled the most similar configuration of simulator to real card, created file system, loaded applet. I’ve connected Mobile Phone Simulator to OS Simulator and start browsing menu. When I’ve selected menu item which doesn’t work JCRE log has the following:
// Byte code dump, some part has skipped
CAP[1] - 0x4aac11: SAND
CAP[1] - 0x4aac12: SADD
CAP[1] - 0x4aac13: S2B
CAP[1] - 0x4aac14: BASTORE
CAP[1] - 0x4aac15: ALOAD_0
CAP[1] - 0x4aac16: SCONST_5
CAP[1] - 0x4aac17: SCONST_0
CAP[1] - 0x4aac18: INVOKESTATIC [0x1c 0x24]
LIB[7] - 0x4987eb: SCONST_5
LIB[7] - 0x4987ec: SLOAD_0
LIB[7] - 0x4987ed: INVOKESTATIC [0x1c 0x17]
Calling nativeMethod[51] - javacard/security/CryptoException/algorithmCheck(BS)V
0x498802: RETURN - returns: V0x0
LIB[7] - 0x4987f0: NEW [0x1c 0x18]
total number of effective EEPROM writing = 0xbc
total number of requested atomic update = 0x1e6
number EEPROM writing saved thanks NVL = 0x4f6
Exception: VM; SystemException; reason: 5
< INVALID exceptions java.lang for >INTP Exception jump to dispatch loop
total number of effective EEPROM writing = 0xbc
total number of requested atomic update = 0x1e6
number EEPROM writing saved thanks NVL = 0x4f6
By checking the source code of JCRE of the OS I’ve found that “reason 5” is No Resources. Checking available volatile and non volatile memory, it seems there is enough memory. From the dump I couldn’t figure out what was wrong. So no clue!
Next step to analyze applet bytecode. Fortunately Gemalto Developer Suite has utility called “Cap File Utility”. I dumped applet and searched the exact consequence of commands from dump of JCRE. After a while I found in the applet dump the following:
method_info[8] // @04b4= {
    // Some part skipped
    /*0f31*/ sand
    /*0f32*/ sadd
    /*0f33*/ s2b
    /*0f34*/ bastore
    /*0f35*/ L124: aload_0
    /*0f36*/ sconst_5
    /*0f37*/ sconst_0
    /*0f38*/ invokestatic 57
    /*0f3b*/ putfield_a 26
    /*0f3d*/ getfield_a_this 26
    /*0f3f*/ getfield_a_this 23
    /*0f41*/ sload 10
}

Pay attention to /*0f38*/ invokestatic 57. It is last call from the applet before switching to system libraries. So, it has to be something wrong with this call. But how to find what exactly it is calling. Here we have to check Component_Pool from the dump:
.Constant_Pool {
    // some part skipped
    /* 00e4, 57 */CONSTANT_StaticMethodRef : external: 0x84,0x1,0x0
    // some part skipped
}
So here it is – static method 57. It is referencing to external package. By checking ImportComponent I’ve found the right one. Here I have to mention that 0x84,0x1,0x00 means:
  • 0x84 – is 5th package in ImportComponent section due to numbering starts from 0x80
  • 0x1 – is the class number
  • 0x0 is method number
Here extract from applet dump:
.ImportComponent = {
    // some part skipped, it is 5th package due to 1st one has reference 0x80
    package_info = {
        minor_version : 2
        major_version : 1
        AID_length : 7
        AID : a0.00.00.00.62.02.01
    }
    // some part skipped }
Now we know what is AID of the imported package: a0.00.00.00.62.02.01. It is standard package javacardx.security. To figure out what is class 1 and method 0 we have to dump javacrdx.security.exp file. Below is extract from dump:
class_info { // javacardx/crypto/Cipher
    u1 token : 1 <== Class identification number
    u2 access_flags : 10000000001b
    u2 name_index : 57
    u2 export_supers_count : 1
    // some parts skipped
    export_methods {
        method_info { // getInstance
            u1 token : 0 <== Method identification number
            u2 access_flags : 11001b
            u2 name_index : 42
            u2 descriptor_index : 43
        }
    // some parts skipped
}
So now we know which method raises exception. It is getInstance() method of Cipher class. In the source code of the applet getInstance() method has called as follows:


myCipher = Cipher.getInstance( Cipher.ALG_DES_ECB_NOPAD, false );


According to specification JavaCard API:
getInstance
public static final Cipher getInstance(byte algorithm,
boolean externalAccess)
throws CryptoException
Creates a Cipher object instance of the selected algorithm.
Parameters:
algorithm - the desired Cipher algorithm. Valid codes listed in ALG_ .. constants above, for example, ALG_DES_CBC_NOPAD.
externalAccess - true indicates that the instance will be shared among multiple applet instances and that the Cipher instance will also be accessed (via a Shareable interface) when the owner of the Cipher instance is not the currently selected applet. If true the implementation must not allocate CLEAR_ON_DESELECT transient space for internal data.
Returns:
the Cipher object instance of the requested algorithm
Throws:
CryptoException - with the following reason codes:
  • CryptoException.NO_SUCH_ALGORITHM if the requested algorithm is not supported or shared access mode is not supported.

Et Voila! Issue is in externalAccess. We have to set it true, as STK applets are not explicitly selected applets by SELECT APPLICATION. They are triggered by SIM Toolkit Events.
So, changing to true externalAccess parameter has solved issue.

5 Jan 2011

LTE Basics

I’ve found the good introduction to LTE from network perspective. Enjoy.

Link to presentations

10 Dec 2010

How to access to MIFARE memory

To be able to read/write to/from MIFARE memory there is javacardx.external package specified in JavaCard 2.2.2 standard.
It specifies MemoryAccess interface and Memory class.
First we have to get object of MemoryAccess object like:

oMemAccess = Memory.getMemoryAccessInstance(Memory.MEMORY_TYPE_MIFARE
                                          , null
                                          , (short)0);


Memory.getMemoryAccessInstance() method has the following parameters:
  • memoryType - the desired external memory subsystem. Could be MEMORY_TYPE_MIFARE or MEMORY_TYPE_EXTENDED_STORE.
  • memorySize - the array containing the desired size in bytes, if applicable, in the external memory subsystem. This parameter is ignored for MIFARE memory type.
  • memorySizeOffset - the offset within the memorySize array where the 32 bit memory size number in bytes is specified. This parameter is ignored.
As you can see from above parameters list we need only specify memory type to get access MIFARE memory.
Then to write data to we can use MemoryAccess.writeData() method like:

oMemAccess.writeData(
             dataToWrite                     // the source data byte array
           , (short) 0                       // the byte offset in data buffer
           , (short) dataToWrite.length      // the length of data
           , thisCardPwdArray                // the byte array containing the 
                                             // key (password)
           , (short)0                        // the byte offset into the key 
                                             // array where the key data begins
           , (short) thisCardPwdArray.length // the length in bytes of key
           , (short) (blocknum / 4)          // sector number
           , blocknum)                       // block number

I'd like to mention one point about sector and block numbers. There are 2 type of addressing mode:

  • Absolute mode where block number accepts values 0..63 and sector number will be ignored.
  • Relative mode where block number accepts values 0..4 and sector number must be correctly set according to MIFARE memory layout.
To read data there is the method MemoryAccess.readData():


oMemAccess.readData(
               readBuf                         // destination buffer
             , (short) 0                       // offset in destination buffer
             , thisCardPwdArray                // key (password) array
             , (short)0                        // offset in key array
             , (short) thisCardPwdArray.length // key length
             , (short)secnum                   // sector number
             , (short)blocknum                 // block number
             , DATA_LEN)                       // number of bytes to read


All parameters have the same meaning as in writeData() method.


One additional remark: if the password to access MIFARE memory is incorrect there is no retry mechanism. You have to start from the beginning. The reason why it has implemented like that is absence of key counter like in PIN key.

3 Dec 2010

Usage of dynamic/diversified data during applet installation

In this post I'd like to talk a little about usage of dynamic/diversified data in install() method of JavaCard applet.

But first let me explain what is dynamic/diversified data is. It is pretty simple. If you are reading some file during applet installation and this file content is different from one card to another you are using dynamic data. As an example of such kind of data could be ICCID or IMSI of the card. The diversified data is the kind of data in the file where you have some master key and for each card you have some generation mechanism which will guarantee uniqueness of each card.

Okay, I do hope it is clear what is dynamic/diversified data is. Now back to the subject of this post. The main message of it is:

 Do not use any dynamic/diversified data during your applet installation! 


Now let me explain why. Most of the (if not all) SmartCard manufacturers are not using regular APDU commands to personalize each card as it is time consuming. Just imagine how much time it will take to produce card by creation of each file with CREATE FILE APDU and then to update its content by UPDATE BINARY/UPDATE RECORD APDU commands if your speed limited with PPS. As each command involves SmartCard Operating System to treat it, to verify all security conditions, to perform required operation. When you have to produce millions of cards per day it is unacceptable. This is why the card production process was splitted to 2 stages:
  • Master card creation 
  • Daughter card creation 
What each stage means.
Master card was created only once for each type of the SmartCard profile and for its creation regular APDU commands were used. Afterwards by special mechanism all dynamic parts which are specific for each card were determined and separated from static part and card memory dumped.

Then for daughter card creation (these is actually cards which will be produced in larges amount) this memory dump is used i.e. instead of sending each APDU command one by one and pushing OS to treat them, production writes directly to card memory. And then the small part which is unique for the each card will be  personalized by regular APDU. That is much faster.

And if you use dynamic data during applet installation it will force your applet installation command to move to dynamic part which is slowing down production process. Moreover it is quite difficult to recognize if your applet is really using dynamic data. If it is just reads it to store inside the applet, the automatic mechanism of detection may not trigger, because memory will be the same. It means if by automatic mechanism your applet is considered as static, your applet will get incorrect data as static part is located before dynamic part.

So, what is the solution if you really need to use dynamic data? Implement it other way round:
  • Post process personalization of the applet by special commands 
  • Get necessary information in runtime 
  • etc. 
Which way is right depends on your applet design and functionality.