woensdag 15 juni 2011

Reading smartcards with java 6

Smartcards

You've al seen them or used them, the smartcards. Best know cards are the payment cards (Visa, mastercard, Sis card, belgian eid card etc...)
At the the time, those cards worked through a magstripe (black border on the back of card) wich was read by a magnetic card reader. Today they come with a chip on it. Most chips are following the ISO7816 standard, wich makes it easier reading them out.

How does a smartcard basically work?


To keep it simple, assume that the chip on the card, is a mini computer with an operating system. It has a kind of a processor, Rom and Ram memory etc... Further it has its own file structure, comparable with the directories we know from pc's (e.g. c:\mymap\mysubmap\myfile.txt), and its own applications! So you can read out the files, or you can use an application on the chip. The files can contain data such as name, birthdate etc... The applications can be used for example for checking a PIN, calculating a hash etc...

Lets start : What do we need?


So, what we are going to do is just reading out data, nothing more or less, because even this is not the simpliest thing to do or to understand. In our example we will read the BELGIAN EID card and will retreive the name, surname etc...
Every chip card according to the ISO7816 standard can be accessed in the same way, but nevertheless, you have to read the specific manuals about the type of card you want to use. Every type of card has its own directory and file structure, own applications etc...and all this is described is manuals that comes with the chips. So, the manuals we need for the EID can be found here:

eid card specifications (very important)

eid chip structure explanation

i will refer to some pages later on in this blog.


Now, since java 6 , there is a new library, called javax.smartcardio.  It allows you to access smartcards on a more simple way than ever before. So be sure java 6 jdk is installed. Also, be sure that you have a decent card reader installed on your development system. And of course...a belgian eid card!
I assume you know how to work with eclipse/websphere...


Start coding!


Creating our class file with the necessary imports is very simple...

package com.smartcard.readers;

import java.util.Arrays;
import java.util.List;

import javax.smartcardio.Card;

import javax.smartcardio.CardChannel;
import javax.smartcardio.CardNotPresentException;
import javax.smartcardio.CardTerminal;
import javax.smartcardio.CommandAPDU;
import javax.smartcardio.ResponseAPDU;
import javax.smartcardio.TerminalFactory;


public class EidReader {

}


Now our class is created, so we can start coding the usefull things!

We need to create a command, that tells the smartcard to select the identity file on the chip. Such a command will later on be executed trough an APDU. Here the manual comes in, and there we have to look how we can build a fileselect command. It looks like this :

static byte[] IDENTITY_FILE_AID = new byte[] { 
   (byte) 0x3F,// MASTER FILE, Head directory MF "3f00"
   (byte) 0x00, 
   (byte) 0xDF,// Dedicated File, subdirectory identity DF(ID) "DF01"
   (byte) 0x01, 
   (byte) 0x40,// Elementary File, the identity file itself EF(ID#RN) "4031"
   (byte) 0x31 };


Once the file is selected and the file is read out, we have to select the fields we want. Those fields are encoded as follows:


static byte FIRST_NAME_TAG = (byte) 0x08;
 static byte LAST_NAME_TAG = (byte) 0x07;
 static byte NATIONAL_NUMBER_TAG = (byte) 0x06;
 static byte BIRTH_DATE_TAG = (byte) 0x0C;

So, now that we know the basic commands, we can start coding.
Lets create a main function in our program, where we can put our card-read-out code.
The first thing we will do is, locating all the cardterminals, and pick a card. To keep it simple, we will pick the first reader and card, and assume that its the good one to connect. (more than 1 card can be connected...). A channel will be set up to communicate with the card. This channel will be used to send the messages.


TerminalFactory factory = TerminalFactory.getDefault();
List<cardterminal> terminals = factory.terminals().list();
         
// get the first terminal
CardTerminal terminal = terminals.get(0);
         
// establish a connection with the card
Card card = terminal.connect("*");
CardChannel channel = card.getBasicChannel();

So, we are ready to send our first messages to the card.
We allready know the IDENTITY_FILE_AID, but we need to tell the system that we want to select a file, more specific, the IDENTITY_FILE_AID.
So we will build up the message and send it!!

// SELECT FILE COMMAND
// See BEID cardpecs v2.0 page 21
CommandAPDU selectFileApdu = new CommandAPDU( 
0x00, //CLA 
0xA4, //INS
0x08, //P1
0x0C, //P2
IDENTITY_FILE_AID);

ResponseAPDU r = channel.transmit(selectFileApdu);


Now that the identity file is selected on the card, we can start reading it out. We will read it out in pieces until there is no data anymore.

int offset = 0;
byte[] file = new byte[4096];
byte[] data;
do {
   CommandAPDU readBinaryApdu = new CommandAPDU(
        0x00, //CLA 
 0xB0, //Read binary command
 offset >> 8, //OFF_H higher byte of the offset (bit 8 = 0)
 offset & 0xFF, //OFF_L lower byte of the offset
 0xFF); //empty
   ResponseAPDU responseApdu = channel.transmit(readBinaryApdu);
   data = responseApdu.getData();
   System.arraycopy(data, 0, file, offset, data.length);
   offset += data.length;
} 
while (0xFF == data.length);
card.disconnect(false);   


Now, all the data is stored in the file byte array. It contains our data like first name, last name etc...BUT...as an extra, it is stored in the TLV (tag/type length value) format.
If you google for this you will find out how it is read.
Here, as example, we will read out our parameters...

// locate the first name field within the identity file
         int idx = 0;
         byte length = 0;
         while (idx < file.length) {
            byte tag = file[idx];
            idx++;
            length = file[idx];
            idx++;
            if (LAST_NAME_TAG == tag) {
             String name = new String(Arrays.copyOfRange(file, idx, idx + length));
               System.out.println("name: " + name);         
             }
            if (NATIONAL_NUMBER_TAG == tag) {
             String number = new String(Arrays.copyOfRange(file, idx, idx + length));
               System.out.println("national number: " + number);         
             }
            
            if (BIRTH_DATE_TAG == tag) {
             String number = new String(Arrays.copyOfRange(file, idx, idx + length));
               System.out.println("birth date: " + number);         
             }

            
            if (FIRST_NAME_TAG == tag) {
            String firstName = new String(Arrays.copyOfRange(file, idx, idx + length));
              System.out.println("first name: " + firstName);         
            }
            idx += length;
         }

vrijdag 15 april 2011

Servlet filter for user authentication

Authentication is somenthing that everyone comes across, once that you work with user profiles, individual users. Basically, a user logs in (uid && pass), and gets to the pages that are ment to have access to. But the user-check is done only once, at login-time. Actually, the user should be authenticated on every post or get etc...So you can implement authentication on every jsp page or servlet or whatever. But this is not done!
A better way is to use a filter.

What is a filter?


A filter is a kind of servlet, that is called EVERY TIME BEFORE a servlet or jsp is requested. You can choose yourself for wich jsp's or servlet's the filter is triggered, trough the web.xml. So, inside that filter you can code your authentication code, as hard or as simple it is...

Example


Lets assume you have a simple servlet, called AuthExampleServlet.java. Its a servlet, one of the hundreds that may be in your projects, that needs authentication.
So we start making a filter, lets say AuthenticationFilter.java.

The code looks like this:

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

  HttpSession session = ((HttpServletRequest)request).getSession(false);
  Boolean logon = new Boolean(false);
  if (session != null)
   logon = (Boolean) session.getAttribute("LOGON");
  
  if(!logon)
  {
   request.getRequestDispatcher("./bad_auth.jsp").forward(request, response);
   return;
  }
  
  chain.doFilter(request, response);
 }

So, every time that the filter is called, it will execute this code.
Of course, we have to put those details in the web.xml.
The we say that the AuthExampleServlet servlet must be preceded by the filter



  AuthenticationFilter
  AuthenticationFilter
  com.auth.filter.AuthenticationFilter
 
 
  AuthenticationFilter
  /AuthenticationFilter
 
 
  AuthenticationFilter
  AuthExampleServlet
  REQUEST
  FORWARD
  INCLUDE
  ERROR
 


Of course, this is only a snippet of the whole web.xml. Do not forget to declare the AuthExampleServelt in it.
Now, With those bits and pieces, you can start a simple basic filter authentication.

Of course, filters can be used for other purposes too, like logging etc...
Also you can use multiple filters after each other

Here is a schema that explains a flow without and a flow with a filter:

maandag 11 april 2011

Web apps: Simple loading indicator with jquery and animated gif problem

The problem


It can be a real pain, if you have a web application, that has to load a lot of data, or where there is a lot of processing in the backend, and that you have to sit and wait until the page has loaded after you made a "request" (POST or GET...). I am talking about a waiting period of maximum 1.5 to 2 seconds. For example you can have a j2ee frontend and a As400 backend, and the j2ee waits for the As400 that is doing the processing.
Now, staring at the screen is not funny if the interaction is not going smooth. So, what we can do during the "wainting", is showing an indicator, that shows the well known "Please be patient, data is being loaded..." stuff with a running progress bar or turning circle. I am talking about a web app that is not or minimal ajax powered. For ajax, there are other solutions. (I know, Ajax is the cool stuff today, but still a lot of apps are not using it)

The solution

The solution is simple...When a request is made, show a popup or whatever that shows a waiting indicator...
Of course, between saying and doing something, there is a difference.
Most developers will code a waiting dialog after every single event, request, whatever...but this is not the best way, if you want it on every request. What there should be done, is calling the "waiting dialog" everytime the "i-did-a-request"-event of the browser occurs. Those events are called the "onunload" and "onbeforeunload" events.

Onunload and onbeforeunload

First of all, what is the difference between onunload and onbeforeunload. In a simple way, the onbeforeunload event is called immediately after a post of get occured. It lasts until the browser gets a response from the server. In that case, the onunload event is triggered and the page is reloading...
So the event that we have to code against, is the onbeforeunload event. Every browser has this event except the opera browser. But it is said that in future versions this little thing will be implemented.

Jquery

For keeping it simple, we will use jquery for implementing those things. First of all, we will code our waiting dialog with an animated gif in it. Initialy, it will be hidden, but this is done by jquery. You can put that dialog everywhere in your html page.

The waiting dialog:


<div id="waitdialog" title="Loading">
 <p>
  <img src="./images/pics/loader.gif" align="left">
  <br>Loading content, please wait...
 </p>
</div>


Of course, we must tell jquery that this div, is a dialog, with some properties,
like this :

$(function() {
 $( "#waitdialog" ).dialog({
  autoOpen: false,
  resizable : false,
  height: 120,
  width: 400
 });
});

It says that it must be hidden in the beginning (autoOpen false) an some props.

So the dialog is ready, but must be called on the "onbeforeunload" event of the browser.
We do it this way:

$(window).bind('beforeunload', function() {       
 $( "#waitdialog" ).html("


Loading content, please wait...

"); $( "#waitdialog" ).dialog( "open" ); });


Here, the dialog is opening on the wanted event. When you try this, every time a request is made, this code will be run trough, and the dialog will disappear on the reload of the screen.
Of course, here we use the jquery dialog...u can use whatever dialog or system you want for showing an indicator. for example "blockUI" is also a good one.
Again, do not use this for tiny or simple websites, because it is overkill.

Animated gif problem in IE

But...why is the html re-written in that functions? becaus this is a trick for using animated gifs in IE. Animated gifs stop working when the browser is doing a request or is waiting for an answer (onbeforeunload). It's a known bug (limitation) of IE. So what we do is preloading the image (html div) and changing the source of the div when the gif is needed. That does the trick.

other browsers do not have that problem...

hope this helps some people...

dinsdag 5 april 2011

Installing Ubuntu on vmware under windows 7

Ever wanted to run a linux distro without live cd or dual boot?

Sometimes its good to "simulate" operating systems, or just use them in a seperate cocoon, just to see how they work, or how they respond during some experiments, without doing any harm to existing systems like using dual boot and messing it all up.

Today there is a lot of software, that allows you to run an OS inside another OS without problems. One of them is Vmware. There are several brands in the vmware software, but the vmware player is the free one and allows you to do what we need to do. So, we will need vmware player, and you can download it here for free. The installation is easy, and after a few clicks its up and running.

Now, what we want to do, is installing and running a linux distro under vmware player.
First of all, after installing vmware, you need to download the ubuntu distro. download it here.
Look for what you choose, because there is a 32 and 64 bit version. The version i downloaded last was 10.10 64 bit. You will get an *.iso file, and store is somewhere on your hard drive. Later on, i will explain how you can run Android 2.3 and 3.0 through vmware on your pc!


Lets get started!

Now that you have installed vmware player, you can start it up. The screen looks like this:



You can see that there is a button to create a new virtual machine. We will do so, because thats what we want to to, running a virtual machine inside windows, that contains a full working ubuntu verion. After this, the next that you wil see is :

Here you have to choose where the installation package is, the image, the "disk"... Since we have no disc, but a downloaded iso file. So we choose "installer disc image (iso)", and we enter the full path of the downloaded ubuntu iso file. Then we click NEXT.



 Here we can give a name to our installation. The name does not realy matter, its just to recognize it later. What DOES matter, is the username and password that you have to enter. At this point, vmware found out that you want to install a linux distro, and as all linux distros do, it needs a userid and password. You can give it here, so you don't have to give later on in the installation, what would be the fact through boot installation. Choose wisely and click next.


Vmware asks you a name for the virtual machine. Use something easy and unique. The asked location is the location where vmware will install the image file of the OS that it will install. You can leave its defaults or just change it...click next...


Vmware asks you how much disk space your virtual linux machine needs. Default is 20 or 40 gb. If you install  ubuntu for test purposes, 20 to 40 gb will do more than enough. If you plan to use ubuntu for work, or server, or just "not for testing", think about the size it wil need.
Further on, vmware asks how it must store the installation. In one big file, or in multiple files. The difference between them is explained on the screen. Click next.

From now on, the installation of ubuntu will start up. Time to take a cup of coffee! (the next screens are the installation)







After the installation is complete, you can start up ubuntu through vmware. You can put it fullscreen, as if you pc runs on ubuntu. There we are!

a simple start for android development

Some time ago, i started learning the android development platform. Actually, its not that bad and hard at all. If you know java, and have a good understanding in software architectures, you are half way!

So a few months ago i started tha basics, following this tutorial
http://www.vogella.de/articles/Android/article.html

Its explained very well and all stuff works! the only software that you need for basic development are eclipse IDE and the android development kit. For that last one you can also use the eclipse update manager...thats sometimes easier.

Its cool if you can run your app on your own android smartphone, but its not needed! There is simulator included in the SDK.

Enjoy!

maandag 4 april 2011

Firefox 4 officially released!

Fireforx 4 is finally released!! check it out!!

check here

Move apps to sd with Android Debug Bridge (Android 2.2 - 2.3 )

Well here is my first real post!

So, what is it all about?
With most not rooted android devices, there are some limitations. Limitations like storage. The device (for example htc desire, the one i use) has 2 kind of storages. internal  (flash +- 300mb) and external (sd flash card +4Gb).
Wow! thats a lot! yes...if it is used properly...
The problem is, that a lot of apps are installed, downloaded and used on the internal flash memory. But that memory is very small, and reaches its limit very fast. Of course, you can move apps to your sd card, out of the box, but this is not allways working. So, its very hard to install a lot of apps on your android device. The app must support running from sd, it also better be no widget, and it must be movable.

Now, there are a lot of apps for moving other apps to sd (like move2sd etc...) but it uses the intern policy of the android device. So, your stuck anyway. Ok, you can root your device...but hey...thats not done in 5 minutes!

So, there is an other solution!
You can enable moving to sd, through the  Android Debug Bridge (adb).  Actually it is very simple...you connect your device to your pc, tell your pc and device that its running for development/debugging purposes, run an adb command, and there you go!

Step by step


Now, i am not going to explain every step, because i got it from another site. Its explained very well, and it works like a charm. Now i can use all the free space on my sd card that i need!

Here is the adress:

check it here


And if you want to do some more experiments with adb :

adb developer