Important!

Blog moved to https://blog.apdu.fr/

I moved my blog from https://ludovicrousseau.blogspot.com/ to https://blog.apdu.fr/ . Why? I wanted to move away from Blogger (owne...

Friday, May 12, 2023

Blog moved to https://blog.apdu.fr/

I moved my blog from https://ludovicrousseau.blogspot.com/ to https://blog.apdu.fr/.

Why?

I wanted to move away from Blogger (owned by Google since 2003) and host the blog myself on a server I control.

Low tech

The blog is now managed by the Nikola Software. I discovered Nikola by reading a Linux Weekly News article Nikola: static-site generation in Python.

Once generated, the HTML pages are static so it is very easy and simple to host them on a web server. No need to have a database (like MySQL) on the server or run a program (like PHP) to generate the content.

Web design

I use the bootstrap4 Nikola theme with some custom changes.

I am not a web page designer. Some colors or styles may look ugly. Please send me CSS change suggestions.

Update your bookmarks

If you have links pointing to the old blog it is very easy to update them to use the new blog.

For example, you have a link to https://ludovicrousseau.blogspot.com/2021/10/what-happened-20-years-ago.html. The same article is now available at https://blog.apdu.fr/posts/2021/10/what-happened-20-years-ago/

It looks magic, but it works because I used the Nikola plugin import_blogger to import all the articles from Blogger. I then made some "manual" corrections.

Update your RSS feed

To automatically receive new articles you can register your news reader to the RSS feed at https://blog.apdu.fr/rss.xml.

Conclusion

I already updated the links I have on my other web pages to point to the new blog.

I do not plan to close the old blog at Blogger because a lot of other pages still point to it. And it is very annoying to get an HTTP 404 error when you are redirected to a web page that does not exist anymore.

Sunday, April 23, 2023

gscriptor now also in French and Russian

I modified gscriptor (included in pcsc-tools) to support internationalization (i18n). The next version of gscriptor (no release date planned yet) will be available (at least) in French and in Russian.

gscriptor

gscriptor is a graphical tool to send APDU commands to a smart card.


It is written in Perl and uses the Gtk+ graphical library.

French


Russian


Conclusion

Thanks to Pro-pra for the initial patch and the Russian localization.

If you want to add another language please copy the file pcsc-tools.pot, add your translations and send me the resulting file.

Sunday, April 16, 2023

FAQ: pcsc-lite and SCARD_E_SERVICE_STOPPED error

One of the most popular search request that bring people on my blog is about SCARD_E_SERVICE_STOPPED.

The problem

With pcsc-lite the only cause for the error SCARD_E_SERVICE_STOPPED is that the two sides, pcscd and libpcsclite, are using a different version of the communication protocol.

See for example the reported issue "SCardEstablishContext: Service was stopped.".

In the logs you have something like:

$ journalctl --unit=pcscd
[...]
févr. 11 18:55:07 debian pcscd[3715]: 00000006 winscard_svc.c:361:ContextThread() Received command: CMD_VERSION from client 8
févr. 11 18:55:07 debian pcscd[3715]: 00000004 winscard_svc.c:373:ContextThread() Client is protocol version 4:3
févr. 11 18:55:07 debian pcscd[3715]: 00000001 winscard_svc.c:382:ContextThread() Communication protocol mismatch!
févr. 11 18:55:07 debian pcscd[3715]: 00000002 winscard_svc.c:384:ContextThread() Client protocol is 4:3
févr. 11 18:55:07 debian pcscd[3715]: 00000001 winscard_svc.c:386:ContextThread() Server protocol is 4:4
févr. 11 18:55:07 debian pcscd[3715]: 00000002 winscard_svc.c:396:ContextThread() CMD_VERSION rv=0x8010001E for client 8
Here the server is using version 4.4 but the client is using version 4.3.
The error code 0x8010001E is SCARD_E_SERVICE_STOPPED.

The cause

This situation can happen if you reinstalled pcsc-lite yourself but in /usr/local/ instead of /usr/. In that case you have 2 different versions of pcsc-lite installed at the same time on your system.

You may also use an application inside a flatpak container that uses a different version of pcsc-lite. See the limitations listed in "Accessing smart cards from inside a flatpak sandbox".

The solution

Do not mix different versions of pcsc-lite.

Conclusion

This is the second article in the FAQ "section". The first one was "FAQ: wintypes.h or winscard.h not found". I will try to provide other articles about common errors.

Friday, April 14, 2023

Verify with OpenSSL a signature computed by PyKCS11

With PyKCS11 I provide a sample code signature.py to compute a RSA+SHA256 signature. The Python sample also contains the code to check the signature using PyKCS11.

But what if you want to verify the signature using OpenSSL?

Export the public key

PYKCS11LIB environment variable is used to indicate what PKCS#11 library to use. For the tests I use SoftHSM so I set the variable using:
$ export PYKCS11LIB=/usr/local/lib/softhsm/libsofthsm2.so
#!/bin/bash

set -e

# get the 1st key object ID
ID=$(pkcs11-tool --module $PYKCS11LIB --list-objects --type pubkey \
    | grep ID \
    | cut -d: -f 2)
echo "Object id: $ID"

# export the public key
pkcs11-tool --module $PYKCS11LIB --read-object --type pubkey --id $ID -o rsa_pub.key

# convert the public key to PEM
openssl rsa -pubin -inform DER -in rsa_pub.key -outform PEM -out rsa_pub.pem

The RSA key pair has been generated by the generate.py script and is stored in the PKCS#11 token. We need to export it so that OpenSSL can use it to check the signature.

To export the key I use pkcs11-tool from the OpenSC project. We need to know the object ID of the public key. This ID is configured in generate.py script line 22. We dump the public keys and get the object ID.

$ pkcs11-tool --module $PYKCS11LIB --list-objects --type pubkey
Using slot 0 with a present token (0x27ca3aa)
Public Key Object; RSA 1024 bits
  label:      My Public Key
  ID:         22
  Usage:      encrypt, verify, wrap
  Access:     local

The script will work correctly if only one public key is present in the token. I let you handle more complex cases.

output

$ ./export_key.sh 
Using slot 0 with a present token (0x27ca3aa)
Object id:          22
Using slot 0 with a present token (0x27ca3aa)
writing RSA key

Compute signature

I modified the original signature.py script to also save the clear text message in a file cleartext.txt and the signature in a file sig_sha256.bin so these files can be used later by OpenSSL.

#!/usr/bin/env python3

from PyKCS11 import *
import binascii

pkcs11 = PyKCS11Lib()
pkcs11.load()  # define environment variable PYKCS11LIB=YourPKCS11Lib

# get 1st slot
slot = pkcs11.getSlotList(tokenPresent=True)[0]

session = pkcs11.openSession(slot, CKF_SERIAL_SESSION | CKF_RW_SESSION)
session.login("1234")

# message to sign
toSign = "Hello World!\n"
mechanism = Mechanism(CKM_SHA256_RSA_PKCS, None)

# find first private key and compute signature
privKey = session.findObjects([(CKA_CLASS, CKO_PRIVATE_KEY)])[0]
signature = session.sign(privKey, toSign, mechanism)
print("\nsignature: {}".format(binascii.hexlify(bytearray(signature))))

# save the clear text in a file
with open("cleartext.txt", "w") as f:
    f.write(toSign)

# save to a signature in a file
with open("sig_sha256.bin", "bw") as f:
    f.write(bytearray(signature))

# find first public key and verify signature
pubKey = session.findObjects([(CKA_CLASS, CKO_PUBLIC_KEY)])[0]
result = session.verify(pubKey, toSign, signature, mechanism)
print("\nVerified:", result)

# logout
session.logout()
session.closeSession()

Output

$ ./signature.py 

signature: b'322c1591cb9aba1e361264b02464a2bd9d55693bf772b4253da0862616e611dc139005742c511795c27c8f609e4ddbaafceba1c3b3ce278b8e0af564c84de54a639cff67a9a3f97dcc542cd6f0200954ef7fce4a0f87b61636272e21fc1e3ef9f0b683e360cca4231405dd90ae2c4a3638ca7a85e2b62f6ae30975ff3885ab60'

Verified: True

Verify signature

#!/bin/bash

set -e

# verify signature
openssl dgst -sha256 -verify rsa_pub.pem -signature sig_sha256.bin cleartext.txt

Output

$ ./verify.sh 
Verified OK

Conclusion

Thanks to Leon Rman for the initial code and the idea.

I let you write the code to do the symmetrical operations: sign using OpenSSL and verify using PyKCS11.

Monday, April 10, 2023

New PyKCS11 1.5.12 available

I just released a new version of PyKCS11, a Python wrapper above the PKCS#11 API.
See "PyKCS11 introduction" or "PyKCS11’s documentation".

The project is registered at Pypi: https://pypi.org/project/PyKCS11/
 

Changes:

1.5.12 - April 2023, Ludovic Rousseau
  • add setAttributeValue()
  • minor improvements

 

Friday, March 31, 2023

PySCard 2.0.7 released

I just released a new version 2.0.7 of pyscard. PySCard is a python module adding smart cards support (PC/SC) to Python.

The PySCard project is available at:

 

Changes:

2.0.7 (March 2023)

  • do not include the generated HTML documentation in the archive


2.0.6 (March 2023)

  • handle SCARD_E_NO_SERVICE on Windows (on last reader removal)
  • add support of MSYS2/mingw environment on Windows
  • improve documentation
  • minor changes

Friday, March 17, 2023

FAQ: wintypes.h or winscard.h not found

One of the most popular search requests that bring people on my website https://pcsclite.apdu.fr/ is about wintypes.h not found.

Problem

For example you try to compile something and get the error:

smartcard/scard/helpers.c:28:10: fatal error: winscard.h: No such file or directory
 #include <winscard.h>
          ^~~~~~~~~~~~ 

Solution

The PC/SC header files (winscard.h, wintypes.h and some others) are provided by the development pcsclite package.

  • for Debian, Ubuntu or derivatives the package is pcsclite-dev
  • for RedHat, Fedora and derivatives the package is pcsc-lite-devel
  • for other Unixes, use your favourite search engine 😜

You install the correct package and you try again to build your software.

Conclusion

I hope this blog article will be correctly indexed by search engines to help people find the solution.

Tuesday, January 31, 2023

New version of libccid: 1.5.2

I just released version 1.5.2 of libccid the Free Software CCID class smart card reader driver. 

Changes:

1.5.2 - 31 January 2023, Ludovic Rousseau

  • Add support of
    • KAPELSE KAP-LINK
    • LDU LANDI
    • Sensyl SSC-HV Reader
    • TOKEN2 MFA NFC Reader
    • TOKEN2 Molto2
    • Thales RF Reader
  • Alcor Micro AU9560: Remove high speeds since they are not supported
  • Hack for AlcorMicro AU9560 and Acos-ID card
  • configure.ac: disable the use of --disable-usbdropdir


 

Sunday, January 22, 2023

PC/SC tools projects moved to .apdu.fr

For historical reasons some projects I maintain are still hosted at my "personal" page http://ludovic.rousseau.free.fr/ in the My computer programs page.

They are:

  • ifd-GemPC: serial GemPC 410 and USB GemPC 430 reader drivers.
  • pcsc-perl: wrapper to use PC/SC in Perl.
  • pcsc-tools: some tools to be used with smart cards and PC/SC.

Why the change?

My personal pages, hosted by my ISP (Internet Service Provider), are still not using https. I have no access to the web server so I can't change that.

The new pages will be independent from the ISP. The projects will use a DNS name I maintain myself.

According to the Internet Archive the "My computer programs" page exists since August 2001. I don't think the personal pages hosted by Free will disappear soon, but who knows. Maybe Elon Musk will buy Iliad (parent company of Free) and... anything can happen next.

I will be able to get some access statistics, in particular for the file smartcard_list.txt containing the list of ATRs used by the pcsc_scan tool.

Now hosts

The projects are now in subdomains of apdu.fr. They are at:

The old pages redirect to the new web sites.

The URL http://ludovic.rousseau.free.fr/softwares/pcsc-tools/smartcard_list.txt is used by (old) versions of ATR_analysis used by pcsc_scan. This file will be maintained up to date for the next months/years.

Conclusion

I continue my migration to self-hosting. Thanks to all the sponsors that allow me to do that.

New version of pcsc-tools: 1.6.2

I just released a new version of pcsc-tools, a suite of tools for PC/SC. 

I updated ATR_analysis to use the new location of the smart card ATR list.

Changes:

1.6.2 - 22 January 2023, Ludovic ROUSSEAU
 

Tuesday, January 3, 2023

Github sponsor: 2022 status

Since January 2020 I am part of the Github sponsors program. See my previous articles: GitHub Sponsors, GitHub Sponsors: first payment and GitHub Sponsors: US$ 20 per month.

I wanted to update you about the years 2021 and 2022.

Public data

My Github sponsor page is available at Become a sponsor to Ludovic Rousseau.

You can see that I currently have 7 sponsors, and 4 past sponsors. A big thank you to all of them.

The amount of money is not public. That is why I wrote the next chapter.

Private data

In 2022 I received a total of 628 €. Compared to 394 € in 2021 that is an increase of 59%.

The amount I receive monthly is slowly growing since 2021.

To be fully transparent to my sponsors and everybody else (full disclosure?) I publish below the monthly results since the beginning of the experience:


It is far from a full time salary. But that is enough to pay for the infrastructure I use to host my different web sites.

Conclusion

Again a big thank you to my present and past sponsors.

If you want to help and become a sponsor then go to Become a sponsor to Ludovic Rousseau.

Sunday, January 1, 2023

Happy new year 2023

Dear readers,

I wish you a happy new year for 2023.

In 2022 I published 32 articles on this blog.


 

Audience in 2022


 You can notice a spike around 17th December. That is the article "AlcorMicro AU9560 reader and fast smart cards: help from crowd needed". I added the article URL in different bug reports so it gained some extra visibility.

Again, a large part of the audience comes from the United States.

 

Surprisingly, a large part of the audience uses Windows.

For a blog that talks about Free Software that is strange. I guess Windows users are interested by my projects that are also available on Windows like PySCard or PyKCS11.

Or maybe Windows developers are looking for serious information they do not find elsewhere like sample codes to use PC/SC in an application?

Most read articles


The post number one, by far, is about the AlcorMicro AU9560 (bogus) reader.

Conclusion

Thank you to you, readers.

This blog has no advertising. If you want to support me you can become a github sponsor (or send me some bitcoins but with the current electric energy crisis and bitcoin impact on the climate it may not be a good choice).

Friday, December 30, 2022

New version of pcsc-tools: 1.6.1

 I just released a new version of pcsc-tools, a suite of tools for PC/SC. 

Changes:

1.6.1 - 30 December 2022, Ludovic ROUSSEAU

  • 196 new ATRs
  • use colors on NetBSD ("wsvt25" terminal)
  • pcsc_scan: always print the version in verbose mode

Tuesday, December 27, 2022

PySCard (smartcard Python wrapper) API documentation update

The documentation for the PySCard API was not updated since 2017 (5 years ago).

epydoc → pydoctor

The tool used to generate the HTML documentation is epydoc. The latest epydoc version was released in 2008 (14 years ago). This tool is no more available in Debian so I had to move to something else.

The (new) tool to replace epydoc is pydoctor. It is actively maintained and generates nicer HTML pages.

For example, nice changes are:

Previous documentation


 

The old (epydoc) documentation is still available online at https://pyscard.sourceforge.io/epydoc/

New documentation



Conclusion

The new API documentation is available at https://pyscard.sourceforge.io/apidocs/index.html or from the project main documentation page https://pyscard.sourceforge.io/index.html

I guess I could improve the documentation. Feel free to report issues or suggest improvements.

Saturday, December 17, 2022

AlcorMicro AU9560 reader and fast smart cards: help from crowd needed

The AlcorMicro AU9560 smart card reader has problems with high speed smart cards.

The reported problem

The same problem is already reported in different places:

Example of cards in reported problems

The reader is always the same but used with different cards.

The card must have a TA1 > 0x95. To know the TA1 of your smart card you need to get and parse the card's ATR, for example using pcsc_scan program from pcsc-tools.

The problem

The reader declares it can support card/reader communication speed up to 688 172 bps.
See dwMaxDataRate field in AlcorMicro_AU9560.txt.

It is fast but I have 4.5 % of readers in my list that declare to be faster (not including contactless readers).

But speeds above ~200 000 bps are problematic with the AlcorMicro AU9560. It works fine, until an APDU exchange fails with a "Hardware error" (for example) message from the reader:

00000009 APDU: 00 A4 00 00 02 3F 00 00
00000007 ifdhandler.c:1333:IFDHTransmitToICC() usb:058f/9540:libudev:0:/dev/bus/usb/001/002 (lun: 0)
00000006 commands.c:1670:CmdXfrBlockAPDU_extended() T=0 (extended): 8 bytes
00000017 -> 000000 6F 08 00 00 00 00 0E 00 00 00 00 A4 00 00 02 3F 00 00
02734396 <- 000000 80 00 00 00 00 00 0E 41 FB 00
00000025 commands.c:1563:CCID_Receive Hardware error
00000009 APDU: 00 A4 00 00 02 3F 00 00

Where are the bogus readers?

The AlcorMicro AU9560 is not a stand alone USB reader. It must be integrated in a laptop. For example it is present in these laptop models:

  • Lenovo Thinkpad P17
  • Lenovo Thinkpad L15
  • Lenovo X1 Extreme Gen 2
  • HP Zbook
  • HP EliteBook.

I guess the same AlcorMicro AU9560 reader is present in a lot of other Lenovo or HP laptops and also laptops from other brands. 

Patch

I worked on a patch to remove the highest speeds so that the CCID driver will negotiate a lower speed that is still supported by the reader. 

Problem with the patch

My patch works fine with one card I have (NXP JCOP 4). But it generates problems with another card (Acos-ID).

The error occurs when the driver set the communication speed. The Set Parameters commands fails and the driver gets a "Card absent or mute" error.

00000004 [140396399142464] commands.c:2324:SetParameters() length: 7 bytes
00000006 [140396399142464] -> 000000 61 07 00 00 00 00 07 01 00 00 95 10 FF 46 00 FE 00
01646726 [140396415927872] ccid_usb.c:1532:InterruptRead() after (0) (2)
00621370 [140396399142464] <- 000000 82 00 00 00 00 00 07 41 FE 00
00000025 [140396399142464] commands.c:2351:SetParameters Card absent or mute
00000005 [140396399142464] prothandler.c:141:PHSetProtocol() Set PTS failed (612)

I suspect the problem to be specific to this card. But I am not sure. That is why I need your help to test with as much possible combinations as possible.

Your help is welcome

 If your have:

  1. a laptop with the AlcorMicro AU9560 smart card reader
  2. a fast enough smart card (i.e. TA1 > 0x95)

then you can help me.

The AlcorMicro AU9560 and the AlcorMicro AU9540 both use the same USB idProduct value of 0x9540 even if the two readers are a bit different. So even if you have a AU9560 the PC/SC name will be "Alcor Micro AU9540 xx yy". If you do not know what reader you have just suppose you have a AU9560.

You can check the 2 conditions above (AlcorMicro and TA1 value) using the pcsc_scan tools. See

$ pcsc_scan 
Using reader plug'n play mechanism
Scanning present readers...
0: Alcor Micro AU9540 00 00
 
Sat Dec 17 11:02:51 2022
 Reader 0: Alcor Micro AU9540 00 00
  Event number: 0
  Card state: Card inserted, Shared Mode, 
  ATR: 3B DC 96 FF 81 11 FE 80 31 C8 54 43 56 35 07 73 FF A1 C0 3C

ATR: 3B DC 96 FF 81 11 FE 80 31 C8 54 43 56 35 07 73 FF A1 C0 3C
+ TS = 3B --> Direct Convention
+ T0 = DC, Y(1): 1101, K: 12 (historical bytes)
  TA(1) = 96 --> Fi=512, Di=32, 16 cycles/ETU
    250000 bits/s at 4 MHz, fMax for Fi = 5 MHz => 312500 bits/s
  TC(1) = FF --> Extra guard time: 255 (special value)
  TD(1) = 81 --> Y(i+1) = 1000, Protocol T = 1 
-----
  TD(2) = 11 --> Y(i+1) = 0001, Protocol T = 1 
-----
  TA(3) = FE --> IFSC: 254
+ Historical bytes: 80 31 C8 54 43 56 35 07 73 FF A1 C0
[...]
+ TCK = 3C (correct checksum) Possibly identified card (using /home/rousseau/.cache/smartcard_list.txt): 3B DC 96 FF 81 11 FE 80 31 C8 54 43 56 35 07 73 FF A1 C0 3C NXP JCOP 4, J3R200P0X3U/0ZA16CP NXD6.2 (JavaCard)

Please do:

  1. download, build and install the patched version of the CCID driver from https://ccid.apdu.fr/files/ccid-1.5.1-3ac3a1a.tar.bz2
  2. test it fixes the problems you had with the previous CCID driver
  3. test it does not create new problems that were not present with the previous CCID driver
  4. if a new problem appears I would like you to report it including:
    1. the exact computer model you use
    2. the name and ATR of the smart card you use
    3. a complete pcscd trace as documented in How to get support
You can report your results using different channels:
  1. on the MUSCLE mailing list
  2. by email to me
  3. by creating a new issue on the CCID project

Conclusion

Your help will greatly improve support of this reader commonly found in laptops.

Thank you.

[Update: Jan, 20th 2023]

The patch is now included in the CCID driver and will be present in the CCID release 1.5.2 (to be released later).

[Update: Jan, 31th 2023]

The CCID driver version 1.5.2 is now available.

Support of the AlcorMicro AU9560 should be better now.

Tuesday, November 29, 2022

PC/SC sample in TypeScript (Deno)

To continue the list of PC/SC wrappers initiated in 2010 with "PC/SC sample in different languages" I now present a new sample code in Deno a modern runtime for JavaScript and TypeScript.

pcsc-deno

The wrapper is available at https://github.com/cryptographix/pcsc-deno and https://deno.land/x/pcsc

The author is Sean Michael Wykes.

The license is MIT.

I used version 0.4.
This version includes the fixes I proposed for GNU/Linux.

Deno

From Wikipedia Deno article:

Deno is a runtime for JavaScript, TypeScript, and WebAssembly that is based on the V8 JavaScript engine and the Rust programming language. Deno was co-created by Ryan Dahl, who also created Node.js.

Deno explicitly takes on the role of both runtime and package manager within a single executable, rather than requiring a separate package-management program.


Installation

Installation is very easy. First install Deno as documented in https://deno.land/#installation

The PC/SC wrapper will be downloaded and installed automatically at run time.

Source code

import {
  CommandAPDU,
  ContextProvider,
  ISO7816,
  PCSC,
} from 'https://deno.land/x/pcsc/mod.ts';

try {
  // establish a PC/SC context
  const context = ContextProvider.establishContext();

  // get all available readers
  const readers = context.listReaders();

  for (const reader of readers) {
    console.log(`Using reader: ${reader.name}`);
    if (reader.isMute) {
      console.log(`Reader ${reader.name}: MUTE`);
    } else if (reader.isPresent) {
      // connect
      const card = await reader.connect();

      // send Select Applet APDU
      const selectApplet = CommandAPDU
        .from([ISO7816.CLA.ISO, ISO7816.INS.SelectFile, 0x04, 0x00]) // ISO SELECT
        .setData([0xA0, 0x00, 0x00, 0x00, 0x62, 0x03, 0x01, 0x0C, 0x06, 0x01]);

      const resp = await card.transmitAPDU(selectApplet);

      // check for 0x90 0x00
      if (resp.SW == ISO7816.SW.SUCCESS) {
        // success ..
        console.log(`Reader ${reader.name}: applet successfully selected`);

        // send Test APDU
        const command = CommandAPDU
          .from([ISO7816.CLA.ISO, 0, 0, 0]);

        const resp = await card.transmitAPDU(command);
        if (resp.SW == ISO7816.SW.SUCCESS) {
          // success ..
          console.log(`Reader ${reader.name}: Test command successful`);

          // convert from bytes to string and display
          console.log(String.fromCharCode.apply(null, resp.data));
        } else {
          // something went wrong ..
          console.error(
            `Reader ${reader.name}: error SW=${resp.SW.toString(16)}`,
          );
        }
      } else {
        // something went wrong ..
        console.error(
          `Reader ${reader.name}: error SW=${resp.SW.toString(16)}`,
        );
      }

      // unpower and disconnect
      await card.disconnect(PCSC.Disposition.UnpowerCard);
    } else {
      console.log(`Reader ${reader.name}: NO CARD`);
    }
  }
  // release the PC/SC context
  context.shutdown();
} catch (e: PCSCException) {
  console.log(e, "error");
}


Output

$ deno run --unstable --allow-ffi blog.ts
Using reader: Gemalto PC Twin Reader (F8345B4A) 00 00
Reader Gemalto PC Twin Reader (F8345B4A) 00 00: applet successfully selected
Reader Gemalto PC Twin Reader (F8345B4A) 00 00: command successful
Hello world!


Conclusion

Nothing special to say. Thanks Sean for the wrapper.

If you work on a Free Software PC/SC wrapper that is not yet in my list please let me know.

Wednesday, November 16, 2022

Share a smart card reader between a host and its guest VM(s)

As I wrote in "One smart card reader accessible from many computers" it is possible to share a smart card reader between 2 or more systems.

 

Problem

I recently received a bug report about a problem between pcsc-lite and VirtualBox. When the smart card reader is connected to the VM guest then the kernel on the host reports errors like:

2022-11-11T14:25:01.186983-08:00 track pcscd[2474]: 00000001 eventhandler.c:336:EHStatusHandlerThread() Error communicating to: SCM Microsystems Inc. SCR 3310 [CCID Interface] (53311514247933) 00 00 
2022-11-11T14:25:01.186993-08:00 track pcscd[2474]: 00000005 ccid_usb.c:1356:InterruptRead() libusb_submit_transfer failed: LIBUSB_ERROR_IO 
2022-11-11T14:25:01.188050-08:00 track kernel: [ 1247.705353][ T2521] usb 1-2: usbfs: process 2521 (pcscd) did not claim interface 0 before use 
2022-11-11T14:25:01.188053-08:00 track kernel: [ 1247.705386][ T2521] usb 1-2: usbfs: process 2521 (pcscd) did not claim interface 0 before use 
2022-11-11T14:25:01.587034-08:00 track pcscd[2474]: 00400173 ccid_usb.c:865:WriteUSB() write failed (1/2): -1 LIBUSB_ERROR_IO 
2022-11-11T14:25:01.587076-08:00 track pcscd[2474]: 00000008 ifdwrapper.c:364:IFDStatusICC() Card not transacted: 612

And after some times (in days) the host kernel crashes.

A Linux kernel crash is never a good thing. pcsc-lite may be very powerful but it can't crash the Linux kernel. Only a bug in the kernel itself can generate a crash. Here I suspect the VirtualBox Linux kernel module to do something bad.

Solution

Instead of connecting the USB smart card reader in the guest VM (and disconnecting it from the host) it is possible to share the smart card reader(s) between the host and guest with some help from pcsc-lite.

Setup

My demo setup:

I use 2 very different operating systems, GNU/Linux and NetBSD, on purpose. It is to show it is possible to mix systems. 

Host

In the host, no change to the configuration. But we will redirect (inject) /run/pcscd/pcscd.comm in the virtual machine. 

On the Debian host I run:

$ ssh -N -R/tmp/pcscd.comm:/run/pcscd/pcscd.comm VMNetBSD

Guest

On the NetBSD VM I use:

$ export PCSCLITE_CSOCK_NAME=/tmp/pcscd.comm

Then I can run any application using pcsc-lite and get access to the smart card(s) and reader(s) from the host. For example: 

$ pcsc_scan -c
Wed Nov 16 17:26:55 2022 Reader 0: Alcor Micro AU9540 00 00 Event number: 0 Card state: Card inserted, ATR: 3B A7 00 40 18 80 65 A2 08 01 01 52

With a screenshot:


Limitations

pcsc-lite to pcsc-lite

As I demonstrated the solution is not limited to GNU/Linux. Any Unix system using pcsc-lite can be used. But you must use the same pcsc-lite protocol on both sides.

For example the current protocol version used by pcsc-lite 1.9.9 (current version) is 4.4. It is the same protocol version since pcsc-lite 1.8.24 released in Oct 2018.

macOS or Windows host

It should be technically possible to use Windows or macOS as the host OS. That would involve a new development. Contact me if you need something like that.

Conclusion

No need to disconnect/reconnect the USB reader in the VM. Just share it with the host.

You will be able to use the same smart card at the same time on the two sides. Isn't it nice?