Wednesday, June 30, 2010

New version of pcsc-perl: 1.4.9

I just released a new version of pcsc-perl to fix a compilation bug.

The problem

pcsc-lite defined some error codes specific to pcsc-lite. One is SCARD_W_INSERTED_CARD.

This error code is never returned by pcsc-lite and has been removed in pcsc-lite revision 4574 included in pcsc-lite 1.6.0.


Do not reference this error code any more. The side effect is that if your Perl program uses SCARD_W_INSERTED_CARD it will fail and has to be corrected.


Thanks to Olivier Huber for reporting the problem.

See also

A previous blog entry about this Perl PCSC wrapper: PCSC sample in Perl.

Flattr this

Sunday, June 27, 2010

PyKCS11 history

This article is not part of the serie initiated by PC/SC sample in different languages. We will not use the PCSC API but the PKCS#11 API.

You can find the other articles in this serie from the first one: PyKCS11 introduction.

PKCS#11 (Cryptographic Token Interface Standard) is an API used to talk to cryptographic tokens like smart cards (but not only).

The PKCS#11 API is in C language but a wrapper for Python call pykcs11 also exists. We will use this wrapper. The project has a ohloh page.


The wrapper uses SWIG.
"SWIG is an interface compiler that connects programs written in C and C++ with scripting languages such as Perl, Python, Ruby, and Tcl. It works by taking the declarations found in C/C++ header files and using them to generate the wrapper code that scripting languages need to access the underlying C/C++ code. In addition, SWIG provides a variety of customization features that let you tailor the wrapping process to suit your application."

The wrapper is initialy written by Giuseppe Amato (started in 2004). But the API was very low level: one Python function for one PKCS#11 C function. This API was not really Python friendly. When I discovered the project, in 2006, I started writting a higher level API more Python oriented, object oriented and easier to use.

The project is still active. The latest version is 1.2.2 from June 2010.

Since I started this serie on PyKCS I added new methods and improved the wrapper to make it even easier to use.

Flattr this

PyKCS11 introduction

I will start a new serie about PyKCS11.

What is it?

PyKCS11 is a Python wrapper above the PKCS#11 API. PKCS#11 is a "Cryptographic Token Interface Standard" defined by RSA and used by smart cards (but not only).

If you are a user of PyKCS11 please add a comment. If you have requests about PyKCS11 please also add a comment.

Articles in the serie

Flattr this

Wednesday, June 23, 2010

Update on pcsc-lite security advisory CVE-2010-0407

I would like to update the status about the security issue of pcsc-lite also known as CVE-2010-0407. I presented the problem in pcsc-lite security advisory CVE-2010-0407

2 new CVE numbers

The fix in upstream revision 4208 was bogus. A fix of the fix is available in upstream revision 4334 and is included in pcsc-lite 1.5.5.

So even if pcsc-lite 1.5.4 do not have the security issue this version has a broken SCardControl() function. See Debian bug #585791 "Upgrading from pcscd_1.4.102-1_i386.deb to pcscd_1.4.102-1+lenny1_i386.deb broke my bankid application (digital signing internetbanking)".

The MSGFunctionDemarshall function in winscard_svc.c in the PC/SC Smart Card daemon (aka PCSCD) in MUSCLE PCSC-Lite before 1.5.4 might allow local users to cause a denial of service (daemon crash) via crafted SCARD_SET_ATTRIB message data, which is improperly demarshalled and triggers a buffer over-read, a related issue to CVE-2010-0407.


Buffer overflow in the MSGFunctionDemarshall function in winscard_svc.c in the PC/SC Smart Card daemon (aka PCSCD) in MUSCLE PCSC-Lite 1.5.4 and earlier might allow local users to gain privileges via crafted SCARD_CONTROL message data, which is improperly demarshalled. NOTE: this vulnerability exists because of an incorrect fix for CVE-2010-0407.


Debian should have a fixed fixed version named 1.4.102-1+lenny3 soon.

Red Hat

The Red Hat bug 596426 indicates that:


Still no news about Ubuntu, SUSE Linux and the other GNU/Linux, *BSD or Unix distributions.

Flattr this

Tuesday, June 22, 2010

PCSC sample in Java

Here is the PCSC sample in Java language I promised in PC/SC sample in different languages.


Since Java 1.6 the JRE includes the package javax.smartcardio which was defined in the JSR 268. No need to compile additional source code.

For the example I used Eclipse Galileo and the Java 1.6 provided by Apple on a Mac OS X Snow Leopard (10.6.4).

Source code

import java.util.List;
import javax.smartcardio.*;

public class Blog {
 public static void main(String[] args) {
  try {
   // Display the list of terminals
   TerminalFactory factory = TerminalFactory.getDefault();
   List<CardTerminal> terminals = factory.terminals().list();
   System.out.println("Terminals: " + terminals);

   // Use the first terminal
   CardTerminal terminal = terminals.get(0);

   // Connect wit hthe card
   Card card = terminal.connect("*");
   System.out.println("card: " + card);
   CardChannel channel = card.getBasicChannel();

   // Send Select Applet command
   byte[] aid = {(byte)0xA0, 0x00, 0x00, 0x00, 0x62, 0x03, 0x01, 0x0C, 0x06, 0x01};
   ResponseAPDU answer = channel.transmit(new CommandAPDU(0x00, 0xA4, 0x04, 0x00, aid));
   System.out.println("answer: " + answer.toString());

   // Send test command
   answer = channel.transmit(new CommandAPDU(0x00, 0x00, 0x00, 0x00));
   System.out.println("answer: " + answer.toString());
   byte r[] = answer.getData();
   for (int i=0; i<r.length; i++)

   // Disconnect the card
  } catch(Exception e) {
   System.out.println("Ouch: " + e.toString());


Terminals: [PC/SC terminal Gemplus GemPC Twin 00 00]
card: PC/SC card in Gemplus GemPC Twin 00 00, protocol T=1, state OK
answer: ResponseAPDU: 2 bytes, SW=9000
answer: ResponseAPDU: 14 bytes, SW=9000
Hello world!


Nothing special to add. The major advantage here is that the wrapper is included in the runtime. So you do not have to install much on a system before you can use your program, just the JRE :-)

Flattr this

Friday, June 11, 2010

pcsc-lite security advisory CVE-2010-0407

The problem

It is possible to trigger a buffer overflow in old versions of pcsc-lite, and possibly gain root access.

The bug is present in version 1.4.102 of pcsc-lite and has been corrected in revision 4208 (May 14 2009). This revision was included in pcsc-lite 1.5.4.


Debian published a DSA (Debian Security Advisory) DSA-2059-1 pcsc-lite -- buffer overflow about a vulnerability in pcsc-lite present in Debian stable.


Ubuntu has not yet published a usn (Ubuntu security notices). Maybe because pcscd is part of universe and not main. But libpcsclite is part of main. Note that Ubuntu is vulnerable even in the latest version 10.04 LTS "Lucid Lynx"

Red Hat

Red Hat has an entry for the CVE on their security web site and on their bug tracking tool as bug 596426. Maybe a new package will be available soon.

SUSE Linux

I could not find information on the site. I don't even know what versions of pcsc-lite SUSE Linux Enterprise 11 is providing.

Other distributions

There are too many Unix distributions to mention them all. If you have pointers for a Unix system just add a comment and I will update the blog.

Flattr this

Tuesday, June 8, 2010

PCSC sample in Ruby

Here is the PCSC sample in Ruby language I promised in PC/SC sample in different languages.

A PC/SC Wrapper for Ruby also exists at Smart-card communication, straight from ruby.. The latest version is 0.4.11 from 2009. I used an older version 0.3.1 when I worked with this wrapper.


You first need to install ruby and the other components needed for the compilation of smartcard for Ruby.

apt-get install ruby rake rubygems libopenssl-ruby ruby1.8-dev

Then fetch the archive smartcard-0.4.11.gem

$ sudo gem install echoe
$ unzip
$ cd smartcard
$ rake manifest
$ rake package
(in /home/rousseau/HSLM/smartcard)
  Successfully built RubyGem
  Name: smartcard
  Version: 0.3.1
  File: smartcard-0.3.1.gem
Private key not found; gem will not be signed.
Targeting "ruby" platform.
$ rake test
(in /home/rousseau/HSLM/smartcard)
/usr/bin/ruby1.8 extconf.rb
checking for main() in -lpcsclite... yes
checking for wintypes.h... yes
checking for reader.h... yes
checking for winscard.h... yes
checking for pcsclite.h... yes
creating Makefile
/usr/bin/ruby1.8 -Ilib:ext:bin:test "/var/lib/gems/1.8/gems/rake-0.8.3/lib/rake/rake_test_loader.rb" "test/test_containers.rb" "test/test_smoke.rb" 
Loaded suite /var/lib/gems/1.8/gems/rake-0.8.3/lib/rake/rake_test_loader
Finished in 0.046223 seconds.

3 tests, 14 assertions, 0 failures, 0 errors
$ rake docs

Source code

require 'smartcard'

context =
readers = context.list_readers nil

# Use the first reader
reader = readers.first

# Connect to the card
card =, reader, Smartcard::PCSC::SHARE_SHARED, Smartcard::PCSC::PROTOCOL_ANY)

# Get the protocol to use
card_status = card.status

# Select applet
aid = [0xA0, 0x00, 0x00, 0x00, 0x62, 0x03, 0x01, 0x0C, 0x06, 0x01]
select_apdu = [0x00, 0xA4, 0x04, 0x00, aid.length, aid].flatten
send_ioreq = {Smartcard::PCSC::PROTOCOL_T0 => Smartcard::PCSC::IOREQUEST_T0,
              Smartcard::PCSC::PROTOCOL_T1 => Smartcard::PCSC::IOREQUEST_T1}[card_status[:protocol]]
recv_ioreq =
response = card.transmit( {|byte| byte.chr}.join(''), send_ioreq, recv_ioreq)
response_str = (0...response.length).map { |i| ' %02x' % response[i].to_i }.join('')
puts "Answer: #{response_str}\n"

# test APDU
test_apdu = [0, 0, 0, 0]
response = card.transmit( {|byte| byte.chr}.join(''), send_ioreq, recv_ioreq)
response_str = (0...response.length).map { |i| ' %02x' % response[i].to_i }.join('')
puts "Answer: #{response_str}\n"
response_str = (0...response.length-2).map { |i| '%c' % response[i].to_i }.join('')
puts "Answer: #{response_str}\n"

# Deconnect
card.disconnect Smartcard::PCSC::DISPOSITION_LEAVE


Answer: 90 00
Answer: 48 65 6c 6c 6f 20 77 6f 72 6c 64 21 90 00
Answer: Hello world!


Nothing more to add. If you are a Ruby user you may be interested by this wrapper.

Flattr this

PCSC sample in Prolog

Here is the PCSC sample in Prolog language I promised in PC/SC sample in different languages.

Renaud Mariana wrote a PC/SC wrapper for GNU Prolog. The latest version is 1.01 dated 2003 and is available in GNU Prolog contributions PC/SC Lite interface for GNU Prolog.


You first need to install GNU Prolog:

apt-get install gprolog

Then apply some patches to the wrapper project, see my mail in the users-prolog mailing list. Then the compilation succeeds without any problem.

gplpcsc/contribs/gplpcsc$ make
gplc -c -C "-Wall -g `pkg-config --cflags libpcsclite`"  pcsc/muscle_c.c
gplc -o testapdu pcsc/muscle_c.o  -L "`pkg-config --libs libpcsclite` -lcrypto -lpthread" util_pcsc/

Source code

:- include('pcsc/muscle').

start :-

    % print ATR data
    scard_status(_, Atr),
    print('ATR: '), print_hex_list(Atr), nl, 

    % enable trace

    Commande = [0,0xA4,4,0,0x0A,0xA0,0,0,0,0x62,3,1,0x0C,6,1],
    scard_transmit(Commande, _ApduOut1, _Sw1, _Time1),

    print_hex_list(_Sw1), nl,

    scard_transmit([0,0,0,0,0], _ApduOut2, _Sw2, _Time2),

    print_hex_list(_Sw2), nl,
    print_ASCII_list(_ApduOut2), nl.

print_ASCII_list(L) :-
    ( list(L) ->
        print('['), '$print_ASCII_list'(L,[]), print(']')
        print('print_ASCII_list error, argument is not a list')

'$print_ASCII_list' --> [], !.
'$print_ASCII_list' --> [A], { format('%c',[A]) },

:- initialization(start).


ATR: [3B FA 94 00 00 81 31 20 43 80 65 A2 01 01 01 3D 72 D6 43 21 ]
tr: 00a404000aa00000006203010c0601 - 9000, t= 15ms.
[][90 00 ]
tr: 0000000000 - 48656c6c6f20776f726c64219000, t= 23ms.
[48 65 6C 6C 6F 20 77 6F 72 6C 64 21 ][90 00 ]
[Hello world!]
GNU Prolog 1.3.0
By Daniel Diaz
Copyright (C) 1999-2007 Daniel Diaz
| ?- 


Nothing more to add. If you are a Prolog user you may be interested by this wrapper.

Flattr this

Wednesday, June 2, 2010

Comments on my blog

Some of you have tried to add comments to some posts on my blog. The comments are moderated so do not appear immediately.

The problem is that I did not know where to look for comments to moderate :-). So some very old comments (more than a month) were still not moderated and approved. Sorry for that.

On 6 comments 1 was a spam. All the 5 other have been accepted.

I also changed the configuration to be notified by mail of new comments. I should then moderate your comments within a few hours.

Lachez vos comm's.

Flattr this

Tuesday, June 1, 2010

PCSC sample in OCaml

Here is the PCSC sample in OCaml language I promised in PC/SC sample in different languages.

Manuel Preliteiro wrote a OCaml PC/SC OCaml PC/SC
Binding to the PCSC standard
started in 2003 and still active in 2007. The latest version of the project is 0.6 and is still in beta but works fine according to my tests.


You first need to install OCaml. A simple apt-get install ocaml is enough on a Debian (or derivative like Ubuntu) system. Then get the ocamlpcsc-0.6.tar.gz archive from OCaml PC/SC
Binding to the PCSC standard

ocamlpcsc-0.6$ make
cc `pkg-config libpcsclite --cflags` -c convert.c
ocamlopt -c
ocamlc -c
cc -I /usr/lib/ocaml/3.10.2 `pkg-config libpcsclite --cflags` -c pcscC.c
ocamlopt -pp camlp4o -c
ocamlc -custom -pp camlp4o -c

Source code

I am not a Caml or OCaml expert. The example is just a modification of the example from Manuel to use my applet.

open Pcscmacros;;
open Printf;;
open PcscML;;
open Str;;

let func () =
  let (rvEstablishContext, hContext) = sCardEstablishContext scard_scope_system () () in

    if (rvEstablishContext != scard_s_success) then (
      printf "SCardEstablishContext: Cannot Connect to Resource Manager %d\n" rvEstablishContext;

    let (rvListReaders, readers) = sCardListReaders () in

      printf "Readers List: \n";
      Array.iter (fun z -> print_string (z ^ " : ")) readers;
      printf "\n";

      let reader1 = readers.(0) in

      let (rvSCardConnect, hCard, dwActiveProtocol) = sCardConnect reader1 scard_share_shared scard_protocol_t1 in

        if (rvSCardConnect != scard_s_success) then (
          printf "SCardConnect: Cannot connect to card %d\n" rvSCardConnect;

        let pioSendPci = (scard_protocol_t1, 0) in
        let commande1 = [|0x00; 0xA4; 0x04; 0x00; 0x0A; 0xA0; 0x00; 0x00; 0x00; 0x62; 0x03; 0x01; 0x0C; 0x06; 0x01|] in
        let dwSendLength = Array.length commande1 in

        let (rvSCardTransmit, pioRecvPci, pcRecvBuffer) = sCardTransmit hCard pioSendPci commande1 dwSendLength in

          if (rvSCardTransmit != scard_s_success) then (
            printf "SCardTransmit: Cannot transmit to card %d\n" rvSCardTransmit;
          else (
            let (_, _) =  pioRecvPci in
              printf "Data transmited with success: ";
              Array.iter (fun z -> print_string ((string_of_int z) ^ " : ")) pcRecvBuffer;
              print_string "\n";

          let commande2 = [|0x00; 0x00; 0x00; 0x00|] in
          let dwSendLength = Array.length commande2 in

          let (rvSCardTransmit, pioRecvPci, pcRecvBuffer) = sCardTransmit hCard pioSendPci commande2 dwSendLength in
            if (rvSCardTransmit != scard_s_success) then (
              printf "SCardTransmit: Cannot transmit to card %d\n" rvSCardTransmit;
            else (
              let (_, _) =  pioRecvPci in
                printf "Data transmited with success: ";
                Array.iter (fun z -> print_string ((string_of_int z) ^ " : ")) pcRecvBuffer;
                print_string "\n";
                Array.iter (fun z -> print_char (char_of_int z)) pcRecvBuffer;
                print_string "\n";
            let rvSCardDisconnect = sCardDisconnect hCard scard_leave_card in
              if (rvSCardDisconnect != scard_s_success) then (
                printf "SCardDisconnect: Cannot disconect card %d\n" rvSCardDisconnect;


let _ = func ();;

(** ocamlopt -c **)
(** ocamlopt -pp camlp4o str.cmxa -cclib '-lpcsclite convert.o pcscC.o' -o demo pcscML.cmx pcscmacros.cmx demo.cmx **)

The last two line are the commands to execute to compile the program.


Readers List: 
Gemplus GemPC Twin 00 00 : 
Data transmited with success: 144 : 0 : 
Data transmited with success: 72 : 101 : 108 : 108 : 111 : 32 : 119 : 111 : 114 : 108 : 100 : 33 : 144 : 0 : 
Hello world!?

You can see a ? character at the end. It is the status word 0x90 0x90 badly converted in ASCII. An improvement would be to only display n-2 first characters. This is left as an exercise to the reader.


Nothing much to say. If you are a OCaml user you may be interested by this wrapper.

This blog entry is dedicated to Alexandre.

Flattr this