Skip to contentSkip to conversation

usb-ccid (v15)

PATCH In review Alon Levy 2 participants 23 messages Jan 11, 2011 – Jan 31, 2011 Kbuild

lore
Share & tools
lore

Alon Levy

author
#0 lore raw

cover usb-ccid (v15)

This patchset adds three new devices, usb-ccid, ccid-card-passthru and ccid-card-emulated, providing a CCID bus, a simple passthru protocol implementing card requiring a client, and a standalone emulated card.

It also introduces a new directory libcaccard with CAC card emulation, CAC is a type of ISO 7816 smart card.

Tree for pull: git://anongit.freedesktop.org/~alon/qemu usb_ccid.v15

v14-v15 changes:
* add patch with --enable-smartcard and --disable-smartcard and only disable ccid-card-emulated if nss not found.
* add patch with description strings
* s/libcaccard/libcacard/ in docs/ccid.txt

v13-v14 changes:
- support device_del/device_add on ccid-card-* and usb-ccid
* usb-ccid:
* lose card reference when card device deleted
* check slot number and deny adding a slot if one is already added.
* ccid-card-*: use qdev_simple_unplug_cb in both emulated and passthru ccid cards, the exitfn already takes care of triggering card removal in the usb dev.
* libcacard:
* remove double include of config-host.mak
* add replay of card events to libcacard to support second and more emulation
* don't initialize more then once (doesn't support it right now, so one thread, NSS thread, is left when device_del is done)
* add VCARD_EMUL_INIT_ALREADY_INITED
* ccid-card-emulated:
* take correct mutexes on signaling to fix deadlocks on device_del
* allow card insertion/removal event without proper reader insertion event

v12-v13 changes:
* libcacard:
* fix Makefile clean to remove vscclient
* fix double include of config-host in Makefile
* usb-ccid: remove attach/detach logic, usb is always attached. Guest doesn't care if there is a reader attached with no card anyway.
* ccid-card-passthru: don't close chr_dev on removal, makes it possible to use device_del/device_add to create remove/insertion for debugging.

v11-v12 changes:
* fix out of tree build

v10-v11 changes:
* fix last patch that removed one of the doc files.
* updated flow table in docs/ccid.txt

v8-v10 changes:
* usb-ccid:
* add slot for future use (Gerd)
* ifdef ENABLE_MIGRATION for migration support on account of usb migration not being ready in general. (Gerd)
* verbosified commit messages. (Gerd)
* put libcacard docs in libcacard commit. (Gerd)

v8-v9 changes:
* Blue Swirl comments:
* white space fixes
* enabled by default, disabled only if missing nss
* forgotten fix from v8 (don't build libcacard.so)
* added a note about device being little endian
* library renamed from libcaccard to libcacard
* squashed both of libcacard patches, they touched different files anyway.

v7-v8 changes:
* Blue Swirl comments:
* usb-ccid: deannonymize some structs
* usb-ccid: coding style change - answer_t and bulk_in_t fixed
* usb-ccid: handle endianess conversion between guest and host
* usb-ccid: s/ccid_bulk_in_copy_out/ccid_bulk_in_copy_to_guest/
* ccid-card-emulated: fix segfault if backend not specified
* ccid-card-emulated: let last reader inserted win
* libcaccard: remove double vscard_common.h

v6->v7 changes:
* external libcaccard became internal directory libcaccard
* statically link object files into qemu
* produce libcaccard.so for usage by external projects
* applied coding style to new code (please check me)
- did not use the qemu options parsing for libcaccard, since it seems to draw large amounts of qemu code (monitor for instance).

v5->v6 changes:
* really remove static debug (I apologize for claiming to have done so before)

v4->v5 changes:
* rebased to latest
* remove static debug in card devices
* fix --enable-smartcard to link
* stall instead of assert when exceeding BULK_OUT_DATA_SIZE
* make ccid_reserve_recv_buf for too large len discard message, not exit
* make ccid_reserve_recv_buf return void*
* fix typo
* remove commented code in VMState

v3->v4:
* remove ccid field in CCIDBus
* remove static debug in bus
* add back docs

v2->v3:
* split into bus (usb-ccid.c, uses ccid.h) and card (ccid-card-passthru.c).
* removed documentation (being revised).

v1->v2:
* all QSIMPLEQ turned into fixed sized rings
* all allocated buffers turned into fixed size buffers
* added migration support
* added a message to tell client qemu has migrated to ip:port
* for lack of monitor commands ip:port are 0:0, which causes the updated vscclient to connect to one port higher on the same host. will add monitor commands in a separate patch. tested with current setup.

Alon Levy (6):
usb-ccid: add CCID bus
ccid: add passthru card device
ccid: add ccid-card-emulated device (v2)
ccid: add docs
ccid: configure: add --enable/disable and nss only disable
ccid: add qdev description strings

Robert Relyea (1):
libcacard: initial commit after coding style fixes

 Makefile                    |    6 +-
 Makefile.objs               |    7 +
 Makefile.target             |    2 +
 configure                   |   48 ++
 docs/ccid.txt               |  135 +++++
 docs/libcacard.txt          |  483 +++++++++++++++
 hw/ccid-card-emulated.c     |  535 +++++++++++++++++
 hw/ccid-card-passthru.c     |  273 +++++++++
 hw/ccid.h                   |   35 ++
 hw/usb-ccid.c               | 1356 +++++++++++++++++++++++++++++++++++++++++++
 libcacard/Makefile          |   14 +
 libcacard/cac.c             |  411 +++++++++++++
 libcacard/cac.h             |   20 +
 libcacard/card_7816.c       |  780 +++++++++++++++++++++++++
 libcacard/card_7816.h       |   60 ++
 libcacard/card_7816t.h      |  163 ++++++
 libcacard/config.h          |   81 +++
 libcacard/event.c           |  112 ++++
 libcacard/eventt.h          |   28 +
 libcacard/link_test.c       |   20 +
 libcacard/mutex.h           |   59 ++
 libcacard/passthru.c        |  612 +++++++++++++++++++
 libcacard/passthru.h        |   50 ++
 libcacard/vcard.c           |  350 +++++++++++
 libcacard/vcard.h           |   85 +++
 libcacard/vcard_emul.h      |   62 ++
 libcacard/vcard_emul_nss.c  | 1171 +++++++++++++++++++++++++++++++++++++
 libcacard/vcard_emul_type.c |   60 ++
 libcacard/vcard_emul_type.h |   29 +
 libcacard/vcardt.h          |   66 +++
 libcacard/vevent.h          |   26 +
 libcacard/vreader.c         |  526 +++++++++++++++++
 libcacard/vreader.h         |   54 ++
 libcacard/vreadert.h        |   23 +
 libcacard/vscard_common.h   |  130 ++++
 libcacard/vscclient.c       |  710 ++++++++++++++++++++++
 36 files changed, 8580 insertions(+), 2 deletions(-)
 create mode 100644 docs/ccid.txt
 create mode 100644 docs/libcacard.txt
 create mode 100644 hw/ccid-card-emulated.c
 create mode 100644 hw/ccid-card-passthru.c
 create mode 100644 hw/ccid.h
 create mode 100644 hw/usb-ccid.c
 create mode 100644 libcacard/Makefile
 create mode 100644 libcacard/cac.c
 create mode 100644 libcacard/cac.h
 create mode 100644 libcacard/card_7816.c
 create mode 100644 libcacard/card_7816.h
 create mode 100644 libcacard/card_7816t.h
 create mode 100644 libcacard/config.h
 create mode 100644 libcacard/event.c
 create mode 100644 libcacard/eventt.h
 create mode 100644 libcacard/link_test.c
 create mode 100644 libcacard/mutex.h
 create mode 100644 libcacard/passthru.c
 create mode 100644 libcacard/passthru.h
 create mode 100644 libcacard/vcard.c
 create mode 100644 libcacard/vcard.h
 create mode 100644 libcacard/vcard_emul.h
 create mode 100644 libcacard/vcard_emul_nss.c
 create mode 100644 libcacard/vcard_emul_type.c
 create mode 100644 libcacard/vcard_emul_type.h
 create mode 100644 libcacard/vcardt.h
 create mode 100644 libcacard/vevent.h
 create mode 100644 libcacard/vreader.c
 create mode 100644 libcacard/vreader.h
 create mode 100644 libcacard/vreadert.h
 create mode 100644 libcacard/vscard_common.h
 create mode 100644 libcacard/vscclient.c
Signature · 1 line
1.7.3.4
author
#14 lore raw

PATCH 4/7 ccid: add ccid-card-emulated device (v2)

This devices uses libcacard (internal) to emulate a smartcard conforming to the CAC standard. It attaches to the usb-ccid bus. Usage instructions (example command lines) are in the following patch in docs/ccid.txt. It uses libcacard which uses nss, so it can work with both hw cards and certificates (files).

changes from v1:
remove stale comments, use only c-style comments bugfix, forgot to set recv_len
change reader name to 'Virtual Reader'

---
 Makefile.objs           |    2 +-
 hw/ccid-card-emulated.c |  534 +++++++++++++++++++++++++++++++++++++++++++++++
 hw/ccid-card-passthru.c |    1 -
 3 files changed, 535 insertions(+), 2 deletions(-)
 create mode 100644 hw/ccid-card-emulated.c
Makefile.objs +1 -1
index 6a0030b..303b642 100644
@@ -197,7 +197,7 @@ hw-obj-$(CONFIG_FDC) += fdc.o
 hw-obj-$(CONFIG_ACPI) += acpi.o acpi_piix4.o
 hw-obj-$(CONFIG_APM) += pm_smbus.o apm.o
 hw-obj-$(CONFIG_DMA) += dma.o
-hw-obj-$(CONFIG_SMARTCARD) += usb-ccid.o ccid-card-passthru.o
+hw-obj-$(CONFIG_SMARTCARD) += usb-ccid.o ccid-card-passthru.o ccid-card-emulated.o
 
 # PPC devices
 hw-obj-$(CONFIG_OPENPIC) += openpic.o
hw/ccid-card-emulated.c new file +534 -0

534 lines not on this page · raw message

hw/ccid-card-passthru.c +0 -1
index 6ec4f21..f9fb82c 100644
@@ -253,7 +253,6 @@ static CCIDCardInfo passthru_card_info = {
     .exitfn = passthru_exitfn,
     .get_atr = passthru_get_atr,
     .apdu_from_guest = passthru_apdu_from_guest,
-    .qdev.unplug    = qdev_simple_unplug_cb,
     .qdev.props     = (Property[]) {
         DEFINE_PROP_CHR("chardev", PassthruState, cs),
         DEFINE_PROP_UINT8("debug", PassthruState, debug, 0),
Signature · 1 line
1.7.3.4
author
#19 lore raw

PATCH 5/7 ccid: add docs

In reply to Alon Levy

Add documentation for the usb-ccid device and accompanying two card devices, ccid-card-emulated and ccid-card-passthru.

---
 docs/ccid.txt |  135 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 1 files changed, 135 insertions(+), 0 deletions(-)
 create mode 100644 docs/ccid.txt
docs/ccid.txt new file +135 -0
new file mode 100644
index 0000000..b8e504a
@@ -0,0 +1,135 @@
+Qemu CCID Device Documentation.
+
+Contents
+1. USB CCID device
+2. Building
+3. Using ccid-card-emulated with hardware
+4. Using ccid-card-emulated with certificates
+5. Using ccid-card-passthru with client side hardware
+6. Using ccid-card-passthru with client side certificates
+7. Passthrough protocol scenario
+8. libcacard
+
+1. USB CCID device
+
+The USB CCID device is a USB device implementing the CCID specification, which
+lets one connect smart card readers that implement the same spec. For more
+information see the specification:
+
+ Universal Serial Bus
+ Device Class: Smart Card
+ CCID
+ Specification for
+ Integrated Circuit(s) Cards Interface Devices
+ Revision 1.1
+ April 22rd, 2005
+
+Smartcard are used for authentication, single sign on, decryption in
+public/private schemes and digital signatures. A smartcard reader on the client
+cannot be used on a guest with simple usb passthrough since it will then not be
+available on the client, possibly locking the computer when it is "removed". On
+the other hand this device can let you use the smartcard on both the client and
+the guest machine. It is also possible to have a completely virtual smart card
+reader and smart card (i.e. not backed by a physical device) using this device.
+
+2. Building
+
+The cryptographic functions and access to the physical card is done via NSS.
+
+Installing NSS:
+
+In redhat/fedora:
+    yum install nss-devel
+In ubuntu/debian:
+    apt-get install libnss3-dev
+    (not tested on ubuntu)
+
+Configuring and building:
+    ./configure --enable-smartcard && make
+
+3. Using ccid-card-emulated with hardware
+
+Assuming you have a working smartcard on the host with the current
+user, using NSS, qemu acts as another NSS client using ccid-card-emulated:
+
+    qemu -usb -device usb-ccid -device ccid-card-emualated
+
+4. Using ccid-card-emulated with certificates
+
+You must create the certificates. This is a one time process. We use NSS
+certificates:
+
+    certutil -d /etc/pki/nssdb -x -t "CT,CT,CT" -S -s "CN=cert1" -n cert1
+
+Note: you must have exactly three certificates.
+
+Assuming the current user can access the certificates (use certutil -L to
+verify), you can use the emulated card type with the certificates backend:
+
+    qemu -usb -device usb-ccid -device ccid-card-emulated,backend=certificates,cert1=cert1,cert2=cert2,cert3=cert3
+
+5. Using ccid-card-passthru with client side hardware
+
+on the host specify the ccid-card-passthru device with a suitable chardev:
+
+    qemu -chardev socket,server,host=0.0.0.0,port=2001,id=ccid,nowait -usb -device usb-ccid -device ccid-card-passthru,chardev=ccid
+
+on the client run vscclient, built when you built the libcacard library:
+    libcacard/vscclient <qemu-host> 2001
+
+6. Using ccid-card-passthru with client side certificates
+
+Run qemu as per #5, and run vscclient as follows:
+(Note: vscclient command line interface is in a state of change)
+
+    libcacard/vscclient -e "db=\"/etc/pki/nssdb\" use_hw=no soft=(,Test,CAC,,cert1,cert2,cert3)" <qemu-host> 2001
+
+7. Passthrough protocol scenario
+
+This is a typical interchange of messages when using the passthru card device.
+usb-ccid is a usb device. It defaults to an unattached usb device on startup.
+usb-ccid expects a chardev and expects the protocol defined in
+cac_card/vscard_common.h to be passed over that.
+The usb-ccid device can be in one of three modes:
+ * detached
+ * attached with no card
+ * attached with card
+
+A typical interchange is: (the arrow shows who started each exchange, it can be client
+originated or guest originated)
+
+client event      |      vscclient           |    passthru    |     usb-ccid  |  guest event
+----------------------------------------------------------------------------------------------
+                  |      VSC_Init            |                |               |
+                  |      VSC_ReaderAdd       |                |     attach    |
+                  |                          |                |               |  sees new usb device.
+card inserted ->  |                          |                |               |
+                  |      VSC_ATR             |   insert       |     insert    |  see new card
+                  |                          |                |               |
+                  |      VSC_APDU            |   VSC_APDU     |               | <- guest sends APDU
+client<->physical |                          |                |               |
+card APDU exchange|                          |                |               |
+client response ->|      VSC_APDU            |   VSC_APDU     |               |  receive APDU response
+                                                    ...
+                                    [APDU<->APDU repeats several times]
+                                                    ...
+card removed  ->  |                          |                |               |
+                  |      VSC_CardRemove      |   remove       |    remove     |   card removed
+                                                    ...
+                                    [(card insert, apdu's, card remove) repeat]
+                                                    ...
+kill/quit         |                          |                |               |
+  vscclient       |                          |                |               |
+                  |      VSC_ReaderRemove    |                |    detach     |
+                  |                          |                |               |   usb device removed.
+
+
+8. libcacard
+
+ccid-card-passthru and vscclient use libcacard as the card emulator.
+libcacard implements a completely virtual CAC (DoD standard for smart cards)
+compliant card and uses NSS to actually retrive certificates and do any
+encryption using the backend (real reader + card or file backed certificates).
+
+For documentation of cac_card see README in libcacard subdirectory.
+
Signature · 1 line
1.7.3.4
author
#10 lore raw

PATCH 6/6 ccid: configure: add --enable-smartcard and --disable-smartcard

In reply to Alon Levy
---
 configure |   28 ++++++++++++++++++----------
 1 files changed, 18 insertions(+), 10 deletions(-)
configure +18 -10
index 4567057..ebc8250 100755
@@ -748,6 +748,10 @@ for opt do
   ;;
   --enable-rbd) rbd="yes"
   ;;
+  --disable-smartcard) smartcard="no"
+  ;;
+  --enable-smartcard) smartcard="yes"
+  ;;
   *) echo "ERROR: unknown option $opt"; show_help="yes"
   ;;
   esac
@@ -942,6 +946,8 @@ echo "                           Default:trace-<pid>"
 echo "  --disable-spice          disable spice"
 echo "  --enable-spice           enable spice"
 echo "  --enable-rbd             enable building the rados block device (rbd)"
+echo "  --disable-smartcard      disable smartcard support"
+echo "  --enable-smartcard       enable smartcard support"
 echo ""
 echo "NOTE: The object files are built at the place where configure is launched"
 exit 1
@@ -2210,16 +2216,18 @@ EOF
 fi
 
 # check for libcacard for smartcard support
-smartcard_cflags="-I\$(SRC_PATH)/libcacard"
-libcacard_libs=$($pkgconfig --libs nss 2>/dev/null)
-libcacard_cflags=$($pkgconfig --cflags nss)
-# TODO - what's the minimal nss version we support?
-if $pkgconfig --atleast-version=3.12.8 nss; then
-    smartcard="yes"
-    QEMU_CFLAGS="$QEMU_CFLAGS $smartcard_cflags $libcacard_cflags"
-    LIBS="$libcacard_libs $LIBS"
-else
-    smartcard="no"
+if test "$smartcard" != "no" ; then
+    smartcard_cflags="-I\$(SRC_PATH)/libcacard"
+    libcacard_libs=$($pkgconfig --libs nss 2>/dev/null)
+    libcacard_cflags=$($pkgconfig --cflags nss)
+    # TODO - what's the minimal nss version we support?
+    if $pkgconfig --atleast-version=3.12.8 nss; then
+        smartcard="yes"
+        QEMU_CFLAGS="$QEMU_CFLAGS $smartcard_cflags $libcacard_cflags"
+        LIBS="$libcacard_libs $LIBS"
+    else
+        smartcard="no"
+    fi
 fi
 
 ##########################################
Signature · 1 line
1.7.3.4
author
#2 lore raw

PATCH 2/7 ccid: add passthru card device

In reply to Alon Levy

The passthru ccid card is a device sitting on the usb-ccid bus and using a chardevice to communicate with a remote device using the VSCard protocol defined in libcacard/vscard_common.h

Usage docs available in following patch in docs/ccid.txt

---
 Makefile.objs             |    2 +-
 hw/ccid-card-passthru.c   |  273 +++++++++++++++++++++++++++++++++++++++++++++
 libcacard/vscard_common.h |  130 +++++++++++++++++++++
 3 files changed, 404 insertions(+), 1 deletions(-)
 create mode 100644 hw/ccid-card-passthru.c
 create mode 100644 libcacard/vscard_common.h
Makefile.objs +1 -1
index 7da4771..274db5e 100644
@@ -197,7 +197,7 @@ hw-obj-$(CONFIG_FDC) += fdc.o
 hw-obj-$(CONFIG_ACPI) += acpi.o acpi_piix4.o
 hw-obj-$(CONFIG_APM) += pm_smbus.o apm.o
 hw-obj-$(CONFIG_DMA) += dma.o
-hw-obj-$(CONFIG_SMARTCARD) += usb-ccid.o
+hw-obj-$(CONFIG_SMARTCARD) += usb-ccid.o ccid-card-passthru.o
 
 # PPC devices
 hw-obj-$(CONFIG_OPENPIC) += openpic.o
hw/ccid-card-passthru.c new file +273 -0

273 lines not on this page · raw message

libcacard/vscard_common.h new file +130 -0

130 lines not on this page · raw message

Signature · 1 line
1.7.3.4
author
#21 lore raw

PATCH 7/7 ccid: add qdev description strings

In reply to Alon Levy
---
 hw/ccid-card-emulated.c |    1 +
 hw/ccid-card-passthru.c |    1 +
 hw/usb-ccid.c           |    1 +
 3 files changed, 3 insertions(+), 0 deletions(-)
hw/ccid-card-emulated.c +1 -0
index 5531ce1..5e85e8e 100644
@@ -509,6 +509,7 @@ static int emulated_exitfn(CCIDCardState *base)
 
 static CCIDCardInfo emulated_card_info = {
     .qdev.name = EMULATED_DEV_NAME,
+    .qdev.desc = "emulated smartcard",
     .qdev.size = sizeof(EmulatedState),
     .initfn = emulated_initfn,
     .exitfn = emulated_exitfn,
hw/ccid-card-passthru.c +1 -0
index f9fb82c..351651c 100644
@@ -247,6 +247,7 @@ static VMStateDescription passthru_vmstate = {
 
 static CCIDCardInfo passthru_card_info = {
     .qdev.name = PASSTHRU_DEV_NAME,
+    .qdev.desc = "passthrough smartcard",
     .qdev.size = sizeof(PassthruState),
     .qdev.vmsd = &passthru_vmstate,
     .initfn = passthru_initfn,
hw/usb-ccid.c +1 -0
index 58f69a6..7b2ea2a 100644
@@ -1330,6 +1330,7 @@ static VMStateDescription ccid_vmstate = {
 static struct USBDeviceInfo ccid_info = {
     .product_desc   = "QEMU USB CCID",
     .qdev.name      = CCID_DEV_NAME,
+    .qdev.desc      = "CCID Rev 1.1 smartcard reader",
     .qdev.size      = sizeof(USBCCIDState),
     .init           = ccid_initfn,
     .handle_packet  = usb_generic_handle_packet,
Signature · 1 line
1.7.3.4
author
#20 lore raw

PATCH 6/7 ccid: configure: add --enable/disable and nss only disable

In reply to Alon Levy

add --enable-smartcard and --disable-smartcard flags, and let the nss check only disable building the ccid-card-emulated device, since both the usb-ccid and ccid-card-passthru don't depend on it.

---
 Makefile.objs   |    3 ++-
 Makefile.target |    2 +-
 configure       |   39 ++++++++++++++++++++++++++++-----------
 3 files changed, 31 insertions(+), 13 deletions(-)
Makefile.objs +2 -1
index 303b642..03cc91e 100644
@@ -197,7 +197,8 @@ hw-obj-$(CONFIG_FDC) += fdc.o
 hw-obj-$(CONFIG_ACPI) += acpi.o acpi_piix4.o
 hw-obj-$(CONFIG_APM) += pm_smbus.o apm.o
 hw-obj-$(CONFIG_DMA) += dma.o
-hw-obj-$(CONFIG_SMARTCARD) += usb-ccid.o ccid-card-passthru.o ccid-card-emulated.o
+hw-obj-$(CONFIG_SMARTCARD) += usb-ccid.o ccid-card-passthru.o
+hw-obj-$(CONFIG_SMARTCARD_NSS) += ccid-card-emulated.o
 
 # PPC devices
 hw-obj-$(CONFIG_OPENPIC) += openpic.o
Makefile.target +1 -1
index 419a530..0222c6b 100644
@@ -335,7 +335,7 @@ obj-y += $(addprefix $(HWDIR)/, $(hw-obj-y))
 
 endif # CONFIG_SOFTMMU
 
-obj-y += $(addprefix ../libcacard/, $(libcacard-$(CONFIG_SMARTCARD)))
+obj-y += $(addprefix ../libcacard/, $(libcacard-$(CONFIG_SMARTCARD_NSS)))
 
 obj-y += $(addprefix ../, $(trace-obj-y))
 obj-$(CONFIG_GDBSTUB_XML) += gdbstub-xml.o
configure +28 -11
index 4567057..de2e498 100755
@@ -335,6 +335,7 @@ trace_file="trace"
 spice=""
 rbd=""
 smartcard="yes"
+smartcard_nss="yes"
 
 # OS specific
 if check_define __linux__ ; then
@@ -748,6 +749,10 @@ for opt do
   ;;
   --enable-rbd) rbd="yes"
   ;;
+  --disable-smartcard) smartcard="no"
+  ;;
+  --enable-smartcard) smartcard="yes"
+  ;;
   *) echo "ERROR: unknown option $opt"; show_help="yes"
   ;;
   esac
@@ -942,6 +947,8 @@ echo "                           Default:trace-<pid>"
 echo "  --disable-spice          disable spice"
 echo "  --enable-spice           enable spice"
 echo "  --enable-rbd             enable building the rados block device (rbd)"
+echo "  --disable-smartcard      disable smartcard support"
+echo "  --enable-smartcard       enable smartcard support"
 echo ""
 echo "NOTE: The object files are built at the place where configure is launched"
 exit 1
@@ -2210,16 +2217,21 @@ EOF
 fi
 
 # check for libcacard for smartcard support
-smartcard_cflags="-I\$(SRC_PATH)/libcacard"
-libcacard_libs=$($pkgconfig --libs nss 2>/dev/null)
-libcacard_cflags=$($pkgconfig --cflags nss)
-# TODO - what's the minimal nss version we support?
-if $pkgconfig --atleast-version=3.12.8 nss; then
-    smartcard="yes"
-    QEMU_CFLAGS="$QEMU_CFLAGS $smartcard_cflags $libcacard_cflags"
-    LIBS="$libcacard_libs $LIBS"
-else
-    smartcard="no"
+if test "$smartcard" != "no" ; then
+    smartcard_cflags="-I\$(SRC_PATH)/libcacard"
+    libcacard_libs=$($pkgconfig --libs nss 2>/dev/null)
+    libcacard_cflags=$($pkgconfig --cflags nss 2>/dev/null)
+    # TODO - what's the minimal nss version we support?
+    if $pkgconfig --atleast-version=3.12.8 nss >/dev/null 2>&1 ; then
+        smartcard_nss="yes"
+        QEMU_CFLAGS="$QEMU_CFLAGS $smartcard_cflags $libcacard_cflags"
+        LIBS="$libcacard_libs $LIBS"
+    else
+        smartcard_nss="no"
+    fi
+fi
+if test "$smartcard" == "no" ; then
+    smartcard_nss="no"
 fi
 
 ##########################################
@@ -2456,6 +2468,7 @@ echo "spice support     $spice"
 echo "rbd support       $rbd"
 echo "xfsctl support    $xfs"
 echo "smartcard support $smartcard"
+echo "   \_ nss support $smartcard_nss"
 
 if test $sdl_too_old = "yes"; then
 echo "-> Your SDL version is too old - please upgrade to have SDL support"
@@ -2729,6 +2742,10 @@ if test "$smartcard" = "yes" ; then
   echo "CONFIG_SMARTCARD=y" >> $config_host_mak
 fi
 
+if test "$smartcard_nss" = "yes" ; then
+  echo "CONFIG_SMARTCARD_NSS=y" >> $config_host_mak
+fi
+
 # XXX: suppress that
 if [ "$bsd" = "yes" ] ; then
   echo "CONFIG_BSD=y" >> $config_host_mak
@@ -3059,7 +3076,7 @@ fi
 if test "$target_darwin_user" = "yes" ; then
   echo "CONFIG_DARWIN_USER=y" >> $config_target_mak
 fi
-if test "$smartcard" = "yes" ; then
+if test "$smartcard_nss" = "yes" ; then
   echo "subdir-$target: subdir-libcacard" >> $config_host_mak
   echo "libcacard_libs=$libcacard_libs" >> $config_host_mak
   echo "libcacard_cflags=$libcacard_cflags" >> $config_host_mak
Signature · 1 line
1.7.3.4
author
#12 lore raw

PATCH 3/7 libcacard: initial commit after coding style fixes

In reply to Alon Levy

From: Robert Relyea <[email protected]>

libcacard emulates a Common Access Card (CAC) which is a standard for smartcards. It is used by the emulated ccid card introduced in a following patch. Docs are available in docs/libcacard.txt

---
 Makefile                    |    6 +-
 Makefile.objs               |    5 +
 Makefile.target             |    2 +
 configure                   |   25 +
 docs/libcacard.txt          |  483 ++++++++++++++++++
 libcacard/Makefile          |   14 +
 libcacard/cac.c             |  411 +++++++++++++++
 libcacard/cac.h             |   20 +
 libcacard/card_7816.c       |  780 ++++++++++++++++++++++++++++
 libcacard/card_7816.h       |   60 +++
 libcacard/card_7816t.h      |  163 ++++++
 libcacard/config.h          |   81 +++
 libcacard/event.c           |  112 ++++
 libcacard/eventt.h          |   28 +
 libcacard/link_test.c       |   20 +
 libcacard/mutex.h           |   59 +++
 libcacard/passthru.c        |  612 ++++++++++++++++++++++
 libcacard/passthru.h        |   50 ++
 libcacard/vcard.c           |  350 +++++++++++++
 libcacard/vcard.h           |   85 ++++
 libcacard/vcard_emul.h      |   62 +++
 libcacard/vcard_emul_nss.c  | 1171 +++++++++++++++++++++++++++++++++++++++++++
 libcacard/vcard_emul_type.c |   60 +++
 libcacard/vcard_emul_type.h |   29 ++
 libcacard/vcardt.h          |   66 +++
 libcacard/vevent.h          |   26 +
 libcacard/vreader.c         |  526 +++++++++++++++++++
 libcacard/vreader.h         |   54 ++
 libcacard/vreadert.h        |   23 +
 libcacard/vscclient.c       |  710 ++++++++++++++++++++++++++
 30 files changed, 6091 insertions(+), 2 deletions(-)
 create mode 100644 docs/libcacard.txt
 create mode 100644 libcacard/Makefile
 create mode 100644 libcacard/cac.c
 create mode 100644 libcacard/cac.h
 create mode 100644 libcacard/card_7816.c
 create mode 100644 libcacard/card_7816.h
 create mode 100644 libcacard/card_7816t.h
 create mode 100644 libcacard/config.h
 create mode 100644 libcacard/event.c
 create mode 100644 libcacard/eventt.h
 create mode 100644 libcacard/link_test.c
 create mode 100644 libcacard/mutex.h
 create mode 100644 libcacard/passthru.c
 create mode 100644 libcacard/passthru.h
 create mode 100644 libcacard/vcard.c
 create mode 100644 libcacard/vcard.h
 create mode 100644 libcacard/vcard_emul.h
 create mode 100644 libcacard/vcard_emul_nss.c
 create mode 100644 libcacard/vcard_emul_type.c
 create mode 100644 libcacard/vcard_emul_type.h
 create mode 100644 libcacard/vcardt.h
 create mode 100644 libcacard/vevent.h
 create mode 100644 libcacard/vreader.c
 create mode 100644 libcacard/vreader.h
 create mode 100644 libcacard/vreadert.h
 create mode 100644 libcacard/vscclient.c
Makefile +4 -2
index 6d601ee..b522d0a 100644
@@ -173,6 +173,8 @@ check-qlist: check-qlist.o qlist.o qint.o $(CHECK_PROG_DEPS)
 check-qfloat: check-qfloat.o qfloat.o $(CHECK_PROG_DEPS)
 check-qjson: check-qjson.o qfloat.o qint.o qdict.o qstring.o qlist.o qbool.o qjson.o json-streamer.o json-lexer.o json-parser.o $(CHECK_PROG_DEPS)
 
+QEMULIBS=libhw32 libhw64 libuser libdis libdis-user libcacard
+
 clean:
 # avoid old build problems by removing potentially incorrect old files
 	rm -f config.mak op-i386.h opc-i386.h gen-op-i386.h op-arm.h opc-arm.h gen-op-arm.h
@@ -184,7 +186,7 @@ clean:
 	rm -f trace-dtrace.dtrace trace-dtrace.dtrace-timestamp
 	rm -f trace-dtrace.h trace-dtrace.h-timestamp
 	$(MAKE) -C tests clean
-	for d in $(ALL_SUBDIRS) libhw32 libhw64 libuser libdis libdis-user; do \
+	for d in $(ALL_SUBDIRS) $(QEMULIBS); do \
 	if test -d $$d; then $(MAKE) -C $$d $@ || exit 1; fi; \
 	rm -f $$d/qemu-options.def; \
         done
@@ -195,7 +197,7 @@ distclean: clean
 	rm -f roms/seabios/config.mak roms/vgabios/config.mak
 	rm -f qemu-doc.info qemu-doc.aux qemu-doc.cp qemu-doc.dvi qemu-doc.fn qemu-doc.info qemu-doc.ky qemu-doc.log qemu-doc.pdf qemu-doc.pg qemu-doc.toc qemu-doc.tp qemu-doc.vr
 	rm -f qemu-tech.info qemu-tech.aux qemu-tech.cp qemu-tech.dvi qemu-tech.fn qemu-tech.info qemu-tech.ky qemu-tech.log qemu-tech.pdf qemu-tech.pg qemu-tech.toc qemu-tech.tp qemu-tech.vr
-	for d in $(TARGET_DIRS) libhw32 libhw64 libuser libdis libdis-user; do \
+	for d in $(TARGET_DIRS) $(QEMULIBS); do \
 	rm -rf $$d || exit 1 ; \
         done
 
Makefile.objs +5 -0
index 274db5e..6a0030b 100644
@@ -315,6 +315,11 @@ user-obj-y += qemu-timer-common.o
 endif
 endif
 
+######################################################################
+# smartcard
+
+libcacard-y = cac.o event.o passthru.o vcard.o vreader.o vcard_emul_nss.o vcard_emul_type.o card_7816.o
+
 vl.o: QEMU_CFLAGS+=$(GPROF_CFLAGS)
 
 vl.o: QEMU_CFLAGS+=$(SDL_CFLAGS)
Makefile.target +2 -0
index a5e217e..419a530 100644
@@ -335,6 +335,8 @@ obj-y += $(addprefix $(HWDIR)/, $(hw-obj-y))
 
 endif # CONFIG_SOFTMMU
 
+obj-y += $(addprefix ../libcacard/, $(libcacard-$(CONFIG_SMARTCARD)))
+
 obj-y += $(addprefix ../, $(trace-obj-y))
 obj-$(CONFIG_GDBSTUB_XML) += gdbstub-xml.o
 
configure +25 -0
index 839980c..4567057 100755
@@ -2209,6 +2209,19 @@ EOF
   fi
 fi
 
+# check for libcacard for smartcard support
+smartcard_cflags="-I\$(SRC_PATH)/libcacard"
+libcacard_libs=$($pkgconfig --libs nss 2>/dev/null)
+libcacard_cflags=$($pkgconfig --cflags nss)
+# TODO - what's the minimal nss version we support?
+if $pkgconfig --atleast-version=3.12.8 nss; then
+    smartcard="yes"
+    QEMU_CFLAGS="$QEMU_CFLAGS $smartcard_cflags $libcacard_cflags"
+    LIBS="$libcacard_libs $LIBS"
+else
+    smartcard="no"
+fi
+
 ##########################################
 
 ##########################################
@@ -3046,6 +3059,11 @@ fi
 if test "$target_darwin_user" = "yes" ; then
   echo "CONFIG_DARWIN_USER=y" >> $config_target_mak
 fi
+if test "$smartcard" = "yes" ; then
+  echo "subdir-$target: subdir-libcacard" >> $config_host_mak
+  echo "libcacard_libs=$libcacard_libs" >> $config_host_mak
+  echo "libcacard_cflags=$libcacard_cflags" >> $config_host_mak
+fi
 list=""
 if test ! -z "$gdb_xml_files" ; then
   for x in $gdb_xml_files; do
@@ -3266,6 +3284,13 @@ for hwlib in 32 64; do
   echo "QEMU_CFLAGS+=-DTARGET_PHYS_ADDR_BITS=$hwlib" > $d/config.mak
 done
 
+if [ $source_path != $workdir ]; then
+    # out of tree build
+    mkdir -p libcacard
+    rm -f libcacard/Makefile
+    ln -s $source_path/libcacard/Makefile libcacard/Makefile
+fi
+
 d=libuser
 mkdir -p $d
 rm -f $d/Makefile
docs/libcacard.txt new file +483 -0

483 lines not on this page · raw message

libcacard/Makefile new file +14 -0
new file mode 100644
index 0000000..b146779
@@ -0,0 +1,14 @@
+include ../config-host.mak
+include $(SRC_PATH)/Makefile.objs
+include $(SRC_PATH)/rules.mak
+
+$(call set-vpath, $(SRC_PATH):$(SRC_PATH)/libcacard)
+
+vscclient: $(libcacard-y) vscclient.o
+	gcc $(libcacard_libs) -o $@ $^
+
+all: vscclient
+
+clean:
+	rm -f *.o */*.o *.d */*.d *.a */*.a *~ */*~ vscclient
+
libcacard/cac.c new file +411 -0

411 lines not on this page · raw message

libcacard/cac.h new file +20 -0
new file mode 100644
index 0000000..bb2a9f0
@@ -0,0 +1,20 @@
+/*
+ * defines the entry point for the cac card. Only used by cac.c anc
+ * vcard_emul_type.c
+ */
+#ifndef CAC_H
+#define CAC_H 1
+#include "vcard.h"
+#include "vreader.h"
+/*
+ * Initialize the cac card. This is the only public function in this file. All
+ * the rest are connected through function pointers.
+ */
+VCardStatus cac_card_init(VReader *reader, VCard *card, const char *params,
+              unsigned char * const *cert, int cert_len[],
+              VCardKey *key[] /* adopt the keys*/,
+              int cert_count);
+
+/* not yet implemented */
+VCardStatus cac_is_cac_card(VReader *reader);
+#endif
libcacard/card_7816.c new file +780 -0

780 lines not on this page · raw message

libcacard/card_7816.h new file +60 -0

60 lines not on this page · raw message

libcacard/card_7816t.h new file +163 -0

163 lines not on this page · raw message

libcacard/config.h new file +81 -0

81 lines not on this page · raw message

libcacard/event.c new file +112 -0

112 lines not on this page · raw message

libcacard/eventt.h new file +28 -0
new file mode 100644
index 0000000..4c3df4f
@@ -0,0 +1,28 @@
+/*
+ *
+ */
+
+#ifndef EVENTT_H
+#define EVENTT_H 1
+#include "vreadert.h"
+#include "vcardt.h"
+
+typedef struct VEventStruct VEvent;
+
+typedef enum {
+    VEVENT_READER_INSERT,
+    VEVENT_READER_REMOVE,
+    VEVENT_CARD_INSERT,
+    VEVENT_CARD_REMOVE,
+    VEVENT_LAST,
+} VEventType;
+
+struct VEventStruct {
+    VEvent *next;
+    VEventType type;
+    VReader *reader;
+    VCard *card;
+};
+#endif
+
+
libcacard/link_test.c new file +20 -0
new file mode 100644
index 0000000..40d2c6d
@@ -0,0 +1,20 @@
+/*
+ *
+ */
+#include <stdio.h>
+#include "vcard.h"
+
+VCardStatus cac_card_init(const char *flags, VCard *card,
+                const unsigned char *cert[],
+                int cert_len[], VCardKey *key[] /* adopt the keys*/,
+                int cert_count);
+/*
+ * this will crash... just test the linkage right now
+ */
+
+main(int argc, char **argv)
+{
+    VCard *card; /* no constructor yet */
+    cac_card_init("", card, NULL, 0, NULL, 0);
+}
+
libcacard/mutex.h new file +59 -0

59 lines not on this page · raw message

libcacard/passthru.c new file +612 -0

612 lines not on this page · raw message

libcacard/passthru.h new file +50 -0

50 lines not on this page · raw message

libcacard/vcard.c new file +350 -0

21 lines not on this page · raw message

libcacard/vcard.h new file +85 -0

85 lines not on this page · raw message

libcacard/vcard_emul.h new file +62 -0

62 lines not on this page · raw message

libcacard/vcard_emul_nss.c new file +1171 -0

1,171 lines not on this page · raw message

libcacard/vcard_emul_type.c new file +60 -0

60 lines not on this page · raw message

libcacard/vcard_emul_type.h new file +29 -0
new file mode 100644
index 0000000..da15528

Lines of this file are not shown. View the raw message.

libcacard/vcardt.h new file +66 -0

66 lines not on this page · raw message

libcacard/vevent.h new file +26 -0
new file mode 100644
index 0000000..f202ea8

Lines of this file are not shown. View the raw message.

libcacard/vreader.c new file +526 -0

526 lines not on this page · raw message

libcacard/vreader.h new file +54 -0

54 lines not on this page · raw message

libcacard/vreadert.h new file +23 -0
new file mode 100644
index 0000000..4c01259

Lines of this file are not shown. View the raw message.

libcacard/vscclient.c new file +710 -0

710 lines not on this page · raw message

The rest of this diff is not shown. View the raw message.

Signature · 1 line
1.7.3.4

Part of the diff is not shown here. View the raw message.

author
#1 lore raw

PATCH 1/7 usb-ccid: add CCID bus

In reply to Alon Levy

A CCID device is a smart card reader. It is a USB device, defined at [1]. This patch introduces the usb-ccid device that is a ccid bus. Next patches will introduce two card types to use it, a passthru card and an emulated card.

[1] http://www.usb.org/developers/devclass_docs/DWG_Smart-Card_CCID_Rev110.

---
 Makefile.objs |    1 +
 configure     |    6 +
 hw/ccid.h     |   35 ++
 hw/usb-ccid.c | 1355 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 4 files changed, 1397 insertions(+), 0 deletions(-)
 create mode 100644 hw/ccid.h
 create mode 100644 hw/usb-ccid.c
Makefile.objs +1 -0
index d6b3d60..7da4771 100644
@@ -197,6 +197,7 @@ hw-obj-$(CONFIG_FDC) += fdc.o
 hw-obj-$(CONFIG_ACPI) += acpi.o acpi_piix4.o
 hw-obj-$(CONFIG_APM) += pm_smbus.o apm.o
 hw-obj-$(CONFIG_DMA) += dma.o
+hw-obj-$(CONFIG_SMARTCARD) += usb-ccid.o
 
 # PPC devices
 hw-obj-$(CONFIG_OPENPIC) += openpic.o
configure +6 -0
index 831a741..839980c 100755
@@ -334,6 +334,7 @@ trace_backend="nop"
 trace_file="trace"
 spice=""
 rbd=""
+smartcard="yes"
 
 # OS specific
 if check_define __linux__ ; then
@@ -2441,6 +2442,7 @@ echo "Trace output file $trace_file-<pid>"
 echo "spice support     $spice"
 echo "rbd support       $rbd"
 echo "xfsctl support    $xfs"
+echo "smartcard support $smartcard"
 
 if test $sdl_too_old = "yes"; then
 echo "-> Your SDL version is too old - please upgrade to have SDL support"
@@ -2710,6 +2712,10 @@ if test "$spice" = "yes" ; then
   echo "CONFIG_SPICE=y" >> $config_host_mak
 fi
 
+if test "$smartcard" = "yes" ; then
+  echo "CONFIG_SMARTCARD=y" >> $config_host_mak
+fi
+
 # XXX: suppress that
 if [ "$bsd" = "yes" ] ; then
   echo "CONFIG_BSD=y" >> $config_host_mak
hw/ccid.h new file +35 -0
new file mode 100644
index 0000000..af59070
@@ -0,0 +1,35 @@
+#ifndef __CCID_H__
+#define __CCID_H__
+
+#include "qdev.h"
+
+typedef struct CCIDCardState CCIDCardState;
+typedef struct CCIDCardInfo CCIDCardInfo;
+
+struct CCIDCardState {
+    DeviceState qdev;
+    uint32_t    slot; // For future use with multiple slot reader.
+};
+
+struct CCIDCardInfo {
+    DeviceInfo qdev;
+    void (*print)(Monitor *mon, CCIDCardState *card, int indent);
+    const uint8_t *(*get_atr)(CCIDCardState *card, uint32_t *len);
+    void (*apdu_from_guest)(CCIDCardState *card, const uint8_t *apdu, uint32_t len);
+    int (*exitfn)(CCIDCardState *card);
+    int (*initfn)(CCIDCardState *card);
+};
+
+void ccid_card_send_apdu_to_guest(CCIDCardState *card, uint8_t* apdu, uint32_t len);
+void ccid_card_card_removed(CCIDCardState *card);
+void ccid_card_card_inserted(CCIDCardState *card);
+void ccid_card_card_error(CCIDCardState *card, uint64_t error);
+void ccid_card_qdev_register(CCIDCardInfo *card);
+
+/* support guest visible insertion/removal of ccid devices based on actual
+ * devices connected/removed. Called by card implementation (passthru, local) */
+int ccid_card_ccid_attach(CCIDCardState *card);
+void ccid_card_ccid_detach(CCIDCardState *card);
+
+#endif // __CCID_H__
+
hw/usb-ccid.c new file +1355 -0

1,355 lines not on this page · raw message

Signature · 1 line
1.7.3.4
author
#11 lore raw

Re: [Qemu-devel] [PATCH 6/6] ccid: configure: add --enable-smartcard and --disable-smartcard

In reply to Alon Levy
Quoted 4 lines · Alon Levy
---
 configure |   28 ++++++++++++++++++----------
 1 files changed, 18 insertions(+), 10 deletions(-)

[snip]

Another oops, not a good morning. Ignore this patch, the real 6/7 will be arriving momentarily. (forgot to clear the patches.usb_ccid.v15 directory).

Alon

author
#22 lore raw
In reply to Alon Levy

Ping

Quoted 199 lines · Alon Levy

This patchset adds three new devices, usb-ccid, ccid-card-passthru and ccid-card-emulated, providing a CCID bus, a simple passthru protocol implementing card requiring a client, and a standalone emulated card.

It also introduces a new directory libcaccard with CAC card emulation, CAC is a type of ISO 7816 smart card.

Tree for pull: git://anongit.freedesktop.org/~alon/qemu usb_ccid.v15

v14-v15 changes:
* add patch with --enable-smartcard and --disable-smartcard and only disable ccid-card-emulated if nss not found.
* add patch with description strings
* s/libcaccard/libcacard/ in docs/ccid.txt

v13-v14 changes:
- support device_del/device_add on ccid-card-* and usb-ccid
* usb-ccid:
* lose card reference when card device deleted
* check slot number and deny adding a slot if one is already added.
* ccid-card-*: use qdev_simple_unplug_cb in both emulated and passthru ccid cards, the exitfn already takes care of triggering card removal in the usb dev.
* libcacard:
* remove double include of config-host.mak
* add replay of card events to libcacard to support second and more emulation
* don't initialize more then once (doesn't support it right now, so one thread, NSS thread, is left when device_del is done)
* add VCARD_EMUL_INIT_ALREADY_INITED
* ccid-card-emulated:
* take correct mutexes on signaling to fix deadlocks on device_del
* allow card insertion/removal event without proper reader insertion event

v12-v13 changes:
* libcacard:
* fix Makefile clean to remove vscclient
* fix double include of config-host in Makefile
* usb-ccid: remove attach/detach logic, usb is always attached. Guest doesn't care if there is a reader attached with no card anyway.
* ccid-card-passthru: don't close chr_dev on removal, makes it possible to use device_del/device_add to create remove/insertion for debugging.

v11-v12 changes:
* fix out of tree build

v10-v11 changes:
* fix last patch that removed one of the doc files.
* updated flow table in docs/ccid.txt

v8-v10 changes:
* usb-ccid:
* add slot for future use (Gerd)
* ifdef ENABLE_MIGRATION for migration support on account of usb migration not being ready in general. (Gerd)
* verbosified commit messages. (Gerd)
* put libcacard docs in libcacard commit. (Gerd)

v8-v9 changes:
* Blue Swirl comments:
* white space fixes
* enabled by default, disabled only if missing nss
* forgotten fix from v8 (don't build libcacard.so)
* added a note about device being little endian
* library renamed from libcaccard to libcacard
* squashed both of libcacard patches, they touched different files anyway.

v7-v8 changes:
* Blue Swirl comments:
* usb-ccid: deannonymize some structs
* usb-ccid: coding style change - answer_t and bulk_in_t fixed
* usb-ccid: handle endianess conversion between guest and host
* usb-ccid: s/ccid_bulk_in_copy_out/ccid_bulk_in_copy_to_guest/
* ccid-card-emulated: fix segfault if backend not specified
* ccid-card-emulated: let last reader inserted win
* libcaccard: remove double vscard_common.h

v6->v7 changes:
* external libcaccard became internal directory libcaccard
* statically link object files into qemu
* produce libcaccard.so for usage by external projects
* applied coding style to new code (please check me)
- did not use the qemu options parsing for libcaccard, since it seems to draw large amounts of qemu code (monitor for instance).

v5->v6 changes:
* really remove static debug (I apologize for claiming to have done so before)

v4->v5 changes:
* rebased to latest
* remove static debug in card devices
* fix --enable-smartcard to link
* stall instead of assert when exceeding BULK_OUT_DATA_SIZE
* make ccid_reserve_recv_buf for too large len discard message, not exit
* make ccid_reserve_recv_buf return void*
* fix typo
* remove commented code in VMState

v3->v4:
* remove ccid field in CCIDBus
* remove static debug in bus
* add back docs

v2->v3:
* split into bus (usb-ccid.c, uses ccid.h) and card (ccid-card-passthru.c).
* removed documentation (being revised).

v1->v2:
* all QSIMPLEQ turned into fixed sized rings
* all allocated buffers turned into fixed size buffers
* added migration support
* added a message to tell client qemu has migrated to ip:port
* for lack of monitor commands ip:port are 0:0, which causes the updated vscclient to connect to one port higher on the same host. will add monitor commands in a separate patch. tested with current setup.

Alon Levy (6):
usb-ccid: add CCID bus
ccid: add passthru card device
ccid: add ccid-card-emulated device (v2)
ccid: add docs
ccid: configure: add --enable/disable and nss only disable
ccid: add qdev description strings

Robert Relyea (1):
libcacard: initial commit after coding style fixes

 Makefile                    |    6 +-
 Makefile.objs               |    7 +
 Makefile.target             |    2 +
 configure                   |   48 ++
 docs/ccid.txt               |  135 +++++
 docs/libcacard.txt          |  483 +++++++++++++++
 hw/ccid-card-emulated.c     |  535 +++++++++++++++++
 hw/ccid-card-passthru.c     |  273 +++++++++
 hw/ccid.h                   |   35 ++
 hw/usb-ccid.c               | 1356 +++++++++++++++++++++++++++++++++++++++++++
 libcacard/Makefile          |   14 +
 libcacard/cac.c             |  411 +++++++++++++
 libcacard/cac.h             |   20 +
 libcacard/card_7816.c       |  780 +++++++++++++++++++++++++
 libcacard/card_7816.h       |   60 ++
 libcacard/card_7816t.h      |  163 ++++++
 libcacard/config.h          |   81 +++
 libcacard/event.c           |  112 ++++
 libcacard/eventt.h          |   28 +
 libcacard/link_test.c       |   20 +
 libcacard/mutex.h           |   59 ++
 libcacard/passthru.c        |  612 +++++++++++++++++++
 libcacard/passthru.h        |   50 ++
 libcacard/vcard.c           |  350 +++++++++++
 libcacard/vcard.h           |   85 +++
 libcacard/vcard_emul.h      |   62 ++
 libcacard/vcard_emul_nss.c  | 1171 +++++++++++++++++++++++++++++++++++++
 libcacard/vcard_emul_type.c |   60 ++
 libcacard/vcard_emul_type.h |   29 +
 libcacard/vcardt.h          |   66 +++
 libcacard/vevent.h          |   26 +
 libcacard/vreader.c         |  526 +++++++++++++++++
 libcacard/vreader.h         |   54 ++
 libcacard/vreadert.h        |   23 +
 libcacard/vscard_common.h   |  130 ++++
 libcacard/vscclient.c       |  710 ++++++++++++++++++++++
 36 files changed, 8580 insertions(+), 2 deletions(-)
 create mode 100644 docs/ccid.txt
 create mode 100644 docs/libcacard.txt
 create mode 100644 hw/ccid-card-emulated.c
 create mode 100644 hw/ccid-card-passthru.c
 create mode 100644 hw/ccid.h
 create mode 100644 hw/usb-ccid.c
 create mode 100644 libcacard/Makefile
 create mode 100644 libcacard/cac.c
 create mode 100644 libcacard/cac.h
 create mode 100644 libcacard/card_7816.c
 create mode 100644 libcacard/card_7816.h
 create mode 100644 libcacard/card_7816t.h
 create mode 100644 libcacard/config.h
 create mode 100644 libcacard/event.c
 create mode 100644 libcacard/eventt.h
 create mode 100644 libcacard/link_test.c
 create mode 100644 libcacard/mutex.h
 create mode 100644 libcacard/passthru.c
 create mode 100644 libcacard/passthru.h
 create mode 100644 libcacard/vcard.c
 create mode 100644 libcacard/vcard.h
 create mode 100644 libcacard/vcard_emul.h
 create mode 100644 libcacard/vcard_emul_nss.c
 create mode 100644 libcacard/vcard_emul_type.c
 create mode 100644 libcacard/vcard_emul_type.h
 create mode 100644 libcacard/vcardt.h
 create mode 100644 libcacard/vevent.h
 create mode 100644 libcacard/vreader.c
 create mode 100644 libcacard/vreader.h
 create mode 100644 libcacard/vreadert.h
 create mode 100644 libcacard/vscard_common.h
 create mode 100644 libcacard/vscclient.c
Signature · 1 line
1.7.3.4
#3 lore raw

Re: [Qemu-devel] [PATCH 2/7] ccid: add passthru card device

In reply to Alon Levy

libcacard/vscard_common.h

Quoted 6 lines · Alon Levy
libcacard/vscard_common.h new file +0 -0
new file mode 100644
index 0000000..9ff1295

This file (and the .c file) need a coding style pass to fixup comments and the use of _ as a prefix but I want to focus on the protocol itself.

First, let's get a written spec into the wiki. I think it's important that all of our compatibility protocols are documented in a more formal way such that can be reviewed by a wider audience.

Quoted 15 lines
libcacard/vscard_common.h new file +13 -0
@@ -0,0 +1,130 @@
+/* Virtual Smart Card protocol definition
+ *
+ * This protocol is between a host implementing a group of virtual smart card
+ * reader, and a client implementing a virtual smart card, or passthrough to
+ * a real card.
+ *
+ * The current implementation passes the raw APDU's from 7816 and additionally
+ * contains messages to setup and teardown readers, handle insertion and
+ * removal of cards, negotiate the protocol and provide for error responses.
+ *
+ * Copyright (c) 2010 Red Hat.
+ *
+ * This code is licensed under the LGPL.

libcacard/vscard_common.h line 23

Quoted 10 lines
libcacard/vscard_common.h new file +10 -0
+ */
+
+#ifndef _VSCARD_COMMON_H
+#define _VSCARD_COMMON_H
+
+#include<stdint.h>
+
+#define VERSION_MAJOR_BITS 11
+#define VERSION_MIDDLE_BITS 11
+#define VERSION_MINOR_BITS 10

Distros make versioning not enough. Inevitably, someone wants to back port a bug fix or a feature for some RHEL7.2 release or something like that.

Feature negotiation has worked pretty well for us and I'd suggest using it within the protocol.

Quoted 22 lines
libcacard/vscard_common.h new file +21 -0
+#define MAKE_VERSION(major, middle, minor) \
+     (  (major<<  (VERSION_MINOR_BITS + VERSION_MIDDLE_BITS)) \
+      | (middle<<   VERSION_MINOR_BITS) \
+      | (minor)  )
+
+/** IMPORTANT NOTE on VERSION
+ *
+ * The version below MUST be changed whenever a change in this file is made.
+ *
+ * The last digit, the minor, is for bug fix changes only.
+ *
+ * The middle digit is for backward / forward compatible changes, updates
+ * to the existing messages, addition of fields.
+ *
+ * The major digit is for a breaking change of protocol, presumably
+ * something that cannot be accomodated with the existing protocol.
+ */
+
+#define VSCARD_VERSION MAKE_VERSION(0,0,1)
+
+typedef enum {

libcacard/vscard_common.h line 55

Quoted 10 lines
libcacard/vscard_common.h new file +10 -0
+    VSC_Init,
+    VSC_Error,
+    VSC_ReaderAdd,
+    VSC_ReaderAddResponse,
+    VSC_ReaderRemove,
+    VSC_ATR,
+    VSC_CardRemove,
+    VSC_APDU,
+    VSC_Reconnect
+} VSCMsgType;

Should number the enum to be specific at least.

libcacard/vscard_common.h line 62

Quoted 8 lines
libcacard/vscard_common.h new file +7 -0
+
+typedef enum {
+    VSC_GENERAL_ERROR=1,
+    VSC_CANNOT_ADD_MORE_READERS,
+} VSCErrorCode;
+
+typedef uint32_t reader_id_t;

This namespace is reserved by C.

libcacard/vscard_common.h line 69

Quoted 8 lines
libcacard/vscard_common.h new file +7 -0
+#define VSCARD_UNDEFINED_READER_ID 0xffffffff
+#define VSCARD_MINIMAL_READER_ID    0
+
+typedef struct VSCMsgHeader {
+    VSCMsgType type;
+    reader_id_t   reader_id;
+    uint32_t   length;

Is length just the data length or the whole message length?

Quoted 13 lines
libcacard/vscard_common.h new file +12 -0
+    uint8_t    data[0];
+} VSCMsgHeader;
+
+/* VSCMsgInit               Client<->  Host
+ * Host replies with allocated reader id in ReaderAddResponse
+ * */
+typedef struct VSCMsgInit {
+    uint32_t   version;
+} VSCMsgInit;
+
+/* VSCMsgError              Client<->  Host
+ * */

libcacard/vscard_common.h line 91

Quoted 10 lines
libcacard/vscard_common.h new file +10 -0
+typedef struct VSCMsgError {
+    uint32_t   code;
+} VSCMsgError;
+
+/* VSCMsgReaderAdd          Client ->  Host
+ * Host replies with allocated reader id in ReaderAddResponse
+ * name - name of the reader on client side.
+ * */
+typedef struct VSCMsgReaderAdd {
+    uint8_t    name[0];

Is this a string?

Quoted 26 lines
libcacard/vscard_common.h new file +25 -0
+} VSCMsgReaderAdd;
+
+/* VSCMsgReaderAddResponse  Host ->  Client
+ * Reply to ReaderAdd
+ * */
+typedef struct VSCMsgReaderAddResponse {
+} VSCMsgReaderAddResponse;
+
+/* VSCMsgReaderRemove       Client ->  Host
+ * */
+typedef struct VSCMsgReaderRemove {
+} VSCMsgReaderRemove;
+
+/* VSCMsgATR                Client ->  Host
+ * Answer to reset. Sent for card insertion or card reset.
+ * */
+typedef struct VSCMsgATR {
+    uint8_t     atr[0];
+} VSCMsgATR;
+
+/* VSCMsgCardRemove         Client ->  Host
+ * */
+typedef struct VSCMsgCardRemove {
+} VSCMsgCardRemove;
+

libcacard/vscard_common.h line 126

Quoted 10 lines
libcacard/vscard_common.h new file +10 -0
+/* VSCMsgAPDU               Client<->  Host
+ * */
+typedef struct VSCMsgAPDU {
+    uint8_t    data[0];
+} VSCMsgAPDU;
+
+/* VSCMsgReconnect          Host ->  Client
+ * */
+typedef struct VSCMsgReconnect {
+    uint32_t   ip;

This is not ipv6 friendly. Two strings would be a better choice.

Regards,

Anthony Liguori

Quoted 5 lines
libcacard/vscard_common.h new file +4 -0
+    uint16_t   port;
+} VSCMsgReconnect;
+
+#endif
#13 lore raw

Re: [Qemu-devel] [PATCH 3/7] libcacard: initial commit after coding style fixes

In reply to Alon Levy
Quoted 8 lines · Alon Levy

From: Robert Relyea<[email protected]>

libcacard emulates a Common Access Card (CAC) which is a standard for smartcards. It is used by the emulated ccid card introduced in a following patch. Docs are available in docs/libcacard.txt

I think importing the code like this is a reasonable place to start.

Regards,

Anthony Liguori

#15 lore raw

Re: [Qemu-devel] [PATCH 4/7] ccid: add ccid-card-emulated device (v2)

In reply to Alon Levy
Quoted 510 lines · Alon Levy

This devices uses libcacard (internal) to emulate a smartcard conforming to the CAC standard. It attaches to the usb-ccid bus. Usage instructions (example command lines) are in the following patch in docs/ccid.txt. It uses libcacard which uses nss, so it can work with both hw cards and certificates (files).

changes from v1:
remove stale comments, use only c-style comments bugfix, forgot to set recv_len
change reader name to 'Virtual Reader'

---
  Makefile.objs           |    2 +-
  hw/ccid-card-emulated.c |  534 +++++++++++++++++++++++++++++++++++++++++++++++
  hw/ccid-card-passthru.c |    1 -
  3 files changed, 535 insertions(+), 2 deletions(-)

create mode 100644 hw/ccid-card-emulated.c

Makefile.objs +1 -1
index 6a0030b..303b642 100644
@@ -197,7 +197,7 @@ hw-obj-$(CONFIG_FDC) += fdc.o
  hw-obj-$(CONFIG_ACPI) += acpi.o acpi_piix4.o
  hw-obj-$(CONFIG_APM) += pm_smbus.o apm.o
  hw-obj-$(CONFIG_DMA) += dma.o
-hw-obj-$(CONFIG_SMARTCARD) += usb-ccid.o ccid-card-passthru.o
+hw-obj-$(CONFIG_SMARTCARD) += usb-ccid.o ccid-card-passthru.o ccid-card-emulated.o
 
  # PPC devices
  hw-obj-$(CONFIG_OPENPIC) += openpic.o
hw/ccid-card-emulated.c new file +471 -0
new file mode 100644
index 0000000..5531ce1
@@ -0,0 +1,534 @@
+/*
+ * CCID Card Device. Emulated card.
+ *
+ * It can be used to provide access to the local hardware in a non exclusive
+ * way, or it can use certificates. It requires the usb-ccid bus.
+ *
+ * Usage 1: standard, mirror hardware reader+card:
+ * qemu .. -usb -device usb-ccid -device ccid-card-emulated
+ *
+ * Usage 2: use certificates, no hardware required
+ * one time: create the certificates:
+ *  for i in 1 2 3; do certutil -d /etc/pki/nssdb -x -t "CT,CT,CT" -S -s "CN=user$i" -n user$i; done
+ * qemu .. -usb -device usb-ccid -device ccid-card-emulated,cert1=user1,cert2=user2,cert3=user3
+ *
+ * If you use a non default db for the certificates you can specify it using the db parameter.
+ *
+ *
+ * Copyright (c) 2010 Red Hat.
+ * Written by Alon Levy.
+ *
+ * This code is licenced under the LGPL.
+ */
+
+#include<pthread.h>
+#include<eventt.h>
+#include<vevent.h>
+#include<vreader.h>
+#include<vcard_emul.h>
+#include "qemu-char.h"
+#include "monitor.h"
+#include "hw/ccid.h"
+
+#define DPRINTF(card, lvl, fmt, ...) \
+do { if (lvl<= card->debug) { printf("ccid-card-emul: %s: " fmt , __func__, ## __VA_ARGS__); } } while (0)
+
+#define EMULATED_DEV_NAME "ccid-card-emulated"
+
+#define BACKEND_NSS_EMULATED "nss-emulated" /* the default */
+#define BACKEND_CERTIFICATES "certificates"
+
+typedef struct EmulatedState EmulatedState;
+
+enum {
+    EMUL_READER_INSERT = 0,
+    EMUL_READER_REMOVE,
+    EMUL_CARD_INSERT,
+    EMUL_CARD_REMOVE,
+    EMUL_GUEST_APDU,
+    EMUL_RESPONSE_APDU,
+    EMUL_ERROR,
+};
+
+static const char* emul_event_to_string(uint32_t emul_event)
+{
+    switch (emul_event) {
+        case EMUL_READER_INSERT: return "EMUL_READER_INSERT";
+        case EMUL_READER_REMOVE: return "EMUL_READER_REMOVE";
+        case EMUL_CARD_INSERT: return "EMUL_CARD_INSERT";
+        case EMUL_CARD_REMOVE: return "EMUL_CARD_REMOVE";
+        case EMUL_GUEST_APDU: return "EMUL_GUEST_APDU";
+        case EMUL_RESPONSE_APDU: return "EMUL_RESPONSE_APDU";
+        case EMUL_ERROR: return "EMUL_ERROR";
+        default:
+            break;
+    }
+    return "UNKNOWN";
+}
+
+typedef struct EmulEvent {
+    QSIMPLEQ_ENTRY(EmulEvent) entry;
+    union {
+        struct {
+            uint32_t type;
+        } gen;
+        struct {
+            uint32_t type;
+            uint64_t code;
+        } error;
+        struct {
+            uint32_t type;
+            uint32_t len;
+            uint8_t data[];
+        } data;
+    } p;
+} EmulEvent;
+
+#define MAX_ATR_SIZE 40
+struct EmulatedState {
+    CCIDCardState base;
+    uint8_t  debug;
+    char*    backend;
+    char*    cert1;
+    char*    cert2;
+    char*    cert3;
+    char*    db;
+    uint8_t  atr[MAX_ATR_SIZE];
+    uint8_t  atr_length;
+    QSIMPLEQ_HEAD(event_list, EmulEvent) event_list;
+    pthread_mutex_t event_list_mutex;
+    VReader *reader;
+    QSIMPLEQ_HEAD(guest_apdu_list, EmulEvent) guest_apdu_list;
+    pthread_mutex_t vreader_mutex; /* and guest_apdu_list mutex */
+    pthread_mutex_t handle_apdu_mutex;
+    pthread_cond_t handle_apdu_cond;
+    int      pipe[2];
+    int      quit_apdu_thread;
+    pthread_mutex_t apdu_thread_quit_mutex;
+    pthread_cond_t apdu_thread_quit_cond;
+};
+
+static void emulated_apdu_from_guest(CCIDCardState *base, const uint8_t *apdu, uint32_t len)
+{
+    EmulatedState *card = DO_UPCAST(EmulatedState, base, base);
+    EmulEvent *event = (EmulEvent*)malloc(sizeof(EmulEvent) + len);
+
+    assert(event);
+    event->p.data.type = EMUL_GUEST_APDU;
+    event->p.data.len = len;
+    memcpy(event->p.data.data, apdu, len);
+    pthread_mutex_lock(&card->vreader_mutex);
+    QSIMPLEQ_INSERT_TAIL(&card->guest_apdu_list, event, entry);
+    pthread_mutex_unlock(&card->vreader_mutex);
+    pthread_mutex_lock(&card->handle_apdu_mutex);
+    pthread_cond_signal(&card->handle_apdu_cond);
+    pthread_mutex_unlock(&card->handle_apdu_mutex);
+}
+
+static const uint8_t* emulated_get_atr(CCIDCardState *base, uint32_t *len)
+{
+    EmulatedState *card = DO_UPCAST(EmulatedState, base, base);
+
+    *len = card->atr_length;
+    return card->atr;
+}
+
+static void emulated_push_event(EmulatedState *card, EmulEvent *event)
+{
+    pthread_mutex_lock(&card->event_list_mutex);
+    QSIMPLEQ_INSERT_TAIL(&(card->event_list), event, entry);
+    pthread_mutex_unlock(&card->event_list_mutex);
+    if (write(card->pipe[1], card, 1) != 1) {
+        DPRINTF(card, 1, "write to pipe failed\n");
+    }
+}
+
+static void emulated_push_type(EmulatedState *card, uint32_t type)
+{
+    EmulEvent *event = (EmulEvent*)malloc(sizeof(EmulEvent));
+
+    assert(event);
+    event->p.gen.type = type;
+    emulated_push_event(card, event);
+}
+
+static void emulated_push_error(EmulatedState *card, uint64_t code)
+{
+    EmulEvent *event = (EmulEvent*)malloc(sizeof(EmulEvent));
+
+    assert(event);
+    event->p.error.type = EMUL_ERROR;
+    event->p.error.code = code;
+    emulated_push_event(card, event);
+}
+
+static void emulated_push_data_type(EmulatedState *card, uint32_t type,
+    const uint8_t *data, uint32_t len)
+{
+    EmulEvent *event = (EmulEvent*)malloc(sizeof(EmulEvent) + len);
+
+    assert(event);
+    event->p.data.type = type;
+    event->p.data.len = len;
+    memcpy(event->p.data.data, data, len);
+    emulated_push_event(card, event);
+}
+
+static void emulated_push_reader_insert(EmulatedState *card)
+{
+    emulated_push_type(card, EMUL_READER_INSERT);
+}
+
+static void emulated_push_reader_remove(EmulatedState *card)
+{
+    emulated_push_type(card, EMUL_READER_REMOVE);
+}
+
+static void emulated_push_card_insert(EmulatedState *card,
+    const uint8_t *atr, uint32_t len)
+{
+    emulated_push_data_type(card, EMUL_CARD_INSERT, atr, len);
+}
+
+static void emulated_push_card_remove(EmulatedState *card)
+{
+    emulated_push_type(card, EMUL_CARD_REMOVE);
+}
+
+static void emulated_push_response_apdu(EmulatedState *card,
+    const uint8_t* apdu, uint32_t len)
+{
+    emulated_push_data_type(card, EMUL_RESPONSE_APDU, apdu, len);
+}
+
+#define APDU_BUF_SIZE 270
+static void *handle_apdu_thread(void* arg)
+{
+    EmulatedState *card = arg;
+    uint8_t recv_data[APDU_BUF_SIZE];
+    int recv_len;
+    VReaderStatus reader_status;
+    EmulEvent *event;
+
+    while (1) {
+        pthread_mutex_lock(&card->handle_apdu_mutex);
+        pthread_cond_wait(&card->handle_apdu_cond,&card->handle_apdu_mutex);
+        pthread_mutex_unlock(&card->handle_apdu_mutex);
+        if (card->quit_apdu_thread) {
+            card->quit_apdu_thread = 0; // debugging
+            break;
+        }
+        pthread_mutex_lock(&card->vreader_mutex);
+        while (!QSIMPLEQ_EMPTY(&card->guest_apdu_list)) {
+            event = QSIMPLEQ_FIRST(&card->guest_apdu_list);
+            assert((unsigned long)event>  1000);
+            QSIMPLEQ_REMOVE_HEAD(&card->guest_apdu_list, entry);
+            if (event->p.data.type != EMUL_GUEST_APDU) {
+                DPRINTF(card, 1, "unexpected message in handle_apdu_thread\n");
+                free(event);
+                continue;
+            }
+            if (card->reader == NULL) {
+                DPRINTF(card, 1, "reader is NULL\n");
+                free(event);
+                continue;
+            }
+            recv_len = sizeof(recv_data);
+            reader_status = vreader_xfr_bytes(card->reader,
+                    event->p.data.data, event->p.data.len,
+                    recv_data,&recv_len);
+            DPRINTF(card, 2, "got back apdu of length %d\n", recv_len);
+            if (reader_status == VREADER_OK) {
+                emulated_push_response_apdu(card, recv_data, recv_len);
+            } else {
+                emulated_push_error(card, reader_status);
+            }
+            free(event);
+        }
+        pthread_mutex_unlock(&card->vreader_mutex);
+    }
+    pthread_mutex_lock(&card->apdu_thread_quit_mutex);
+    pthread_cond_signal(&card->apdu_thread_quit_cond);
+    pthread_mutex_unlock(&card->apdu_thread_quit_mutex);
+    return NULL;
+}
+
+static void *event_thread(void *arg)
+{
+    int atr_len = MAX_ATR_SIZE;
+    uint8_t atr[MAX_ATR_SIZE];
+    VEvent *event = NULL;
+    EmulatedState *card = arg;
+
+    while (1) {
+        const char *reader_name;
+
+        event = vevent_wait_next_vevent();
+        if (event == NULL || event->type == VEVENT_LAST) {
+            break;
+        }
+        if (event->type != VEVENT_READER_INSERT) {
+            if (card->reader == NULL&&  event->reader != NULL) {
+                // Happens after device_add followed by card remove or insert.
+                // XXX: create synthetic add_reader events if vcard_emul_init
+                // already called, which happens if device_del and device_add are
+                // called
+                card->reader = vreader_reference(event->reader);
+            } else {
+                if (event->reader != card->reader) {
+                    fprintf(stderr, "ERROR: wrong reader: quiting event_thread\n");
+                    break;
+                }
+            }
+        }
+        switch (event->type) {
+        case VEVENT_READER_INSERT:
+            /* TODO: take a specific reader. i.e. track which reader
+             * we are seeing here, check it is the one we want (the first,
+             * or by a particular name), and ignore if we don't want it.
+             */
+            reader_name = vreader_get_name(event->reader);
+            if (card->reader != NULL) {
+                DPRINTF(card, 2, "READER INSERT - replacing %s with %s\n",
+                    vreader_get_name(card->reader), reader_name);
+                pthread_mutex_lock(&card->vreader_mutex);
+                vreader_free(card->reader);
+                pthread_mutex_unlock(&card->vreader_mutex);
+                emulated_push_reader_remove(card);
+            }
+            pthread_mutex_lock(&card->vreader_mutex);
+            DPRINTF(card, 2, "READER INSERT %s\n", reader_name);
+            card->reader = vreader_reference(event->reader);
+            pthread_mutex_unlock(&card->vreader_mutex);
+            emulated_push_reader_insert(card);
+            break;
+        case VEVENT_READER_REMOVE:
+            DPRINTF(card, 2, " READER REMOVE: %s \n",
+                    vreader_get_name(event->reader));
+            pthread_mutex_lock(&card->vreader_mutex);
+            vreader_free(card->reader);
+            card->reader = NULL;
+            pthread_mutex_unlock(&card->vreader_mutex);
+            emulated_push_reader_remove(card);
+            break;
+        case VEVENT_CARD_INSERT:
+            /* get the ATR (intended as a response to a power on from the
+             * reader */
+            atr_len = MAX_ATR_SIZE;
+            vreader_power_on(event->reader, atr,&atr_len);
+            card->atr_length = (uint8_t)atr_len;
+            DPRINTF(card, 2, " CARD INSERT\n");
+            emulated_push_card_insert(card, atr, atr_len);
+            break;
+        case VEVENT_CARD_REMOVE:
+            DPRINTF(card, 2, " CARD REMOVE\n");
+            emulated_push_card_remove(card);
+            break;
+        case VEVENT_LAST: /* quit */
+            vevent_delete(event);
+            return NULL;
+            break;
+        default:
+            break;
+        }
+        vevent_delete(event);
+    }
+    return NULL;
+}
+
+static void pipe_read(void *opaque)
+{
+    EmulatedState *card = opaque;
+    EmulEvent *event, *next;
+    char dummy;
+    int len;
+
+    do {
+        len = read(card->pipe[0],&dummy, sizeof(dummy));
+    } while (len == sizeof(dummy));
+    pthread_mutex_lock(&card->event_list_mutex);
+    QSIMPLEQ_FOREACH_SAFE(event,&card->event_list, entry, next) {
+        DPRINTF(card, 2, "event %s\n", emul_event_to_string(event->p.gen.type));
+        switch (event->p.gen.type) {
+            case EMUL_RESPONSE_APDU:
+                ccid_card_send_apdu_to_guest(&card->base, event->p.data.data,
+                    event->p.data.len);
+                break;
+            case EMUL_READER_INSERT:
+                ccid_card_ccid_attach(&card->base);
+                break;
+            case EMUL_READER_REMOVE:
+                ccid_card_ccid_detach(&card->base);
+                break;
+            case EMUL_CARD_INSERT:
+                assert(event->p.data.len<= MAX_ATR_SIZE);
+                card->atr_length = event->p.data.len;
+                memcpy(card->atr, event->p.data.data, card->atr_length);
+                ccid_card_card_inserted(&card->base);
+                break;
+            case EMUL_CARD_REMOVE:
+                ccid_card_card_removed(&card->base);
+                break;
+            case EMUL_ERROR:
+                ccid_card_card_error(&card->base, event->p.error.code);
+                break;
+            default:
+                DPRINTF(card, 2, "unexpected event\n");
+                break;
+        }
+        free(event);
+    }
+    QSIMPLEQ_INIT(&card->event_list);
+    pthread_mutex_unlock(&card->event_list_mutex);
+}
+
+static int init_pipe_signaling(EmulatedState *card)
+{
+   if (pipe(card->pipe)<  0) {
+       DPRINTF(card, 2, "pipe creation failed\n");
+       return -1;
+   }
+   fcntl(card->pipe[0], F_SETFL, O_NONBLOCK);
+   fcntl(card->pipe[1], F_SETFL, O_NONBLOCK);
+   fcntl(card->pipe[0], F_SETOWN, getpid());
+   qemu_set_fd_handler(card->pipe[0], pipe_read, NULL, card);
+   return 0;
+}
+
+#define CERTIFICATES_DEFAULT_DB "/etc/pki/nssdb"
+#define CERTIFICATES_ARGS_TEMPLATE "db=\"%s\" use_hw=no soft=(,Virtual Reader,CAC,,%s,%s,%s)"
+
+static int wrap_vcard_emul_init(VCardEmulOptions *options)
+{
+    static int called = 0;
+    static int options_was_null = 0;
+
+    if (called) {
+        if ((options == NULL) != options_was_null) {
+            printf("%s: warning: running emulated with certificates and emulated side by side is not supported\n", __FUNCTION__);
+            return VCARD_EMUL_FAIL;
+        }
+        vcard_emul_replay_insertion_events();
+        return VCARD_EMUL_OK;
+    }
+    options_was_null = (options == NULL);
+    called = 1;
+    return vcard_emul_init(options);
+}
+
+static int emulated_initialize_vcard_from_certificates(EmulatedState *card)
+{
+    char emul_args[200];
+    VCardEmulOptions *options = NULL;
+
+    snprintf(emul_args, sizeof(emul_args) - 1, CERTIFICATES_ARGS_TEMPLATE,
+        card->db ? card->db : CERTIFICATES_DEFAULT_DB,
+        card->cert1, card->cert2, card->cert3);
+    options = vcard_emul_options(emul_args);
+    if (options == NULL) {
+        printf("%s: warning: not using certificates due to initialization error\n", __func__);
+    }
+    return wrap_vcard_emul_init(options);
+}
+
+static int emulated_initfn(CCIDCardState *base)
+{
+    EmulatedState *card = DO_UPCAST(EmulatedState, base, base);
+    int rv;
+    pthread_t thread_id;
+    VCardEmulError ret;
+
+    QSIMPLEQ_INIT(&card->event_list);
+    QSIMPLEQ_INIT(&card->guest_apdu_list);
+    pthread_mutex_init(&card->event_list_mutex, NULL);
+    pthread_mutex_init(&card->vreader_mutex, NULL);
+    pthread_mutex_init(&card->handle_apdu_mutex, NULL);
+    pthread_cond_init(&card->handle_apdu_cond, NULL);
+    card->reader = NULL;
+    card->quit_apdu_thread = 0;
+    if (init_pipe_signaling(card)<  0) {
+        return -1;
+    }
+    if (!card->backend) {
+        card->backend = strdup((char*)BACKEND_NSS_EMULATED);
+    }
+    /* TODO: a passthru backened that works on local machine. third card type? */
+    if (strcmp(BACKEND_CERTIFICATES, card->backend) == 0
+&&  card->cert1 != NULL&&  card->cert2 != NULL&&  card->cert3 != NULL) {
+        ret = emulated_initialize_vcard_from_certificates(card);
+    } else {
+        if (strcmp(BACKEND_CERTIFICATES, card->backend) == 0) {
+            printf("%s: you must provide all three certs for certificates backend\n",
+                EMULATED_DEV_NAME);
+            return -1;
+        }
+        if (card->backend&&  strcmp(BACKEND_NSS_EMULATED, card->backend) != 0) {
+            printf("%s: bad backend specified. The options are:\n%s (default), %s.\n",
+                EMULATED_DEV_NAME, BACKEND_NSS_EMULATED, BACKEND_CERTIFICATES);
+            return -1;
+        }
+        /* default to mirroring the local hardware readers */
+        ret = wrap_vcard_emul_init(NULL);

hw/ccid-card-emulated.c line 481

Quoted 10 lines
hw/ccid-card-emulated.c new file +10 -0
+    }
+    if (ret != VCARD_EMUL_OK) {
+        printf("%s: failed to initialize vcard\n", EMULATED_DEV_NAME);
+        return -1;
+    }
+    rv = pthread_create(&thread_id, NULL, event_thread, card);
+    if (rv<  0) {
+        printf("%s: error creating event thread\n", EMULATED_DEV_NAME);
+        return -1;
+    }

Why can't this be implemented with qemu_set_fd_handler? The event thread si just spinning on read.

Regards,

Anthony Liguori

Quoted 66 lines
hw/ccid-card-emulated.c new file +53 -0
+    rv = pthread_create(&thread_id, NULL, handle_apdu_thread, card);
+    if (rv<  0) {
+        printf("%s: error creating handle_apdu thread\n", EMULATED_DEV_NAME);
+        return -1;
+    }
+    return 0;
+}
+
+static int emulated_exitfn(CCIDCardState *base)
+{
+    EmulatedState *card = DO_UPCAST(EmulatedState, base, base);
+    VEvent *vevent = vevent_new(VEVENT_LAST, NULL, NULL);
+
+    vevent_queue_vevent(vevent); /* stop vevent thread */
+    pthread_mutex_lock(&card->apdu_thread_quit_mutex);
+    card->quit_apdu_thread = 1; /* stop handle_apdu thread */
+    pthread_cond_signal(&card->handle_apdu_cond);
+    pthread_cond_wait(&card->apdu_thread_quit_cond,&card->apdu_thread_quit_mutex);
+    /* handle_apdu thread stopped, can destroy all of it's mutexes */
+    pthread_cond_destroy(&card->handle_apdu_cond);
+    pthread_cond_destroy(&card->apdu_thread_quit_cond);
+    pthread_mutex_destroy(&card->apdu_thread_quit_mutex);
+    pthread_mutex_destroy(&card->handle_apdu_mutex);
+    pthread_mutex_destroy(&card->vreader_mutex);
+    pthread_mutex_destroy(&card->event_list_mutex);
+    return 0;
+}
+
+static CCIDCardInfo emulated_card_info = {
+    .qdev.name = EMULATED_DEV_NAME,
+    .qdev.size = sizeof(EmulatedState),
+    .initfn = emulated_initfn,
+    .exitfn = emulated_exitfn,
+    .get_atr = emulated_get_atr,
+    .apdu_from_guest = emulated_apdu_from_guest,
+    .qdev.unplug    = qdev_simple_unplug_cb,
+    .qdev.props     = (Property[]) {
+        DEFINE_PROP_STRING("backend", EmulatedState, backend),
+        DEFINE_PROP_STRING("cert1", EmulatedState, cert1),
+        DEFINE_PROP_STRING("cert2", EmulatedState, cert2),
+        DEFINE_PROP_STRING("cert3", EmulatedState, cert3),
+        DEFINE_PROP_STRING("db", EmulatedState, db),
+        DEFINE_PROP_UINT8("debug", EmulatedState, debug, 0),
+        DEFINE_PROP_END_OF_LIST(),
+    },
+};
+
+static void ccid_card_emulated_register_devices(void)
+{
+    ccid_card_qdev_register(&emulated_card_info);
+}
+
+device_init(ccid_card_emulated_register_devices)
hw/ccid-card-passthru.c +0 -1
index 6ec4f21..f9fb82c 100644
@@ -253,7 +253,6 @@ static CCIDCardInfo passthru_card_info = {
      .exitfn = passthru_exitfn,
      .get_atr = passthru_get_atr,
      .apdu_from_guest = passthru_apdu_from_guest,
-    .qdev.unplug    = qdev_simple_unplug_cb,
      .qdev.props     = (Property[]) {
          DEFINE_PROP_CHR("chardev", PassthruState, cs),
          DEFINE_PROP_UINT8("debug", PassthruState, debug, 0),
author
#4 lore raw

Re: [Qemu-devel] [PATCH 2/7] ccid: add passthru card device

In reply to Anthony Liguori
Quoted 11 lines · Anthony Liguori

libcacard/vscard_common.h

Quoted 5 lines · Alon Levy
libcacard/vscard_common.h new file +0 -0
new file mode 100644
index 0000000..9ff1295

This file (and the .c file) need a coding style pass to fixup comments and the use of _ as a prefix but I want to focus on the protocol itself.

Quoted 3 lines

First, let's get a written spec into the wiki. I think it's important that all of our compatibility protocols are documented in a more formal way such that can be reviewed by a wider audience.

ok, I'll create Features/Smartcard/Protocol

Quoted 30 lines
Quoted 15 lines
libcacard/vscard_common.h new file +13 -0
@@ -0,0 +1,130 @@
+/* Virtual Smart Card protocol definition
+ *
+ * This protocol is between a host implementing a group of virtual smart card
+ * reader, and a client implementing a virtual smart card, or passthrough to
+ * a real card.
+ *
+ * The current implementation passes the raw APDU's from 7816 and additionally
+ * contains messages to setup and teardown readers, handle insertion and
+ * removal of cards, negotiate the protocol and provide for error responses.
+ *
+ * Copyright (c) 2010 Red Hat.
+ *
+ * This code is licensed under the LGPL.

libcacard/vscard_common.h line 23

Quoted 10 lines
libcacard/vscard_common.h new file +10 -0
+ */
+
+#ifndef _VSCARD_COMMON_H
+#define _VSCARD_COMMON_H
+
+#include<stdint.h>
+
+#define VERSION_MAJOR_BITS 11
+#define VERSION_MIDDLE_BITS 11
+#define VERSION_MINOR_BITS 10

Distros make versioning not enough. Inevitably, someone wants to back port a bug fix or a feature for some RHEL7.2 release or something like that.

Quoted 3 lines

Feature negotiation has worked pretty well for us and I'd suggest using it within the protocol.

Suggestion accepted.

Quoted 25 lines
Quoted 25 lines
libcacard/vscard_common.h new file +25 -0
+#define MAKE_VERSION(major, middle, minor) \
+     (  (major<<  (VERSION_MINOR_BITS + VERSION_MIDDLE_BITS)) \
+      | (middle<<   VERSION_MINOR_BITS) \
+      | (minor)  )
+
+/** IMPORTANT NOTE on VERSION
+ *
+ * The version below MUST be changed whenever a change in this file is made.
+ *
+ * The last digit, the minor, is for bug fix changes only.
+ *
+ * The middle digit is for backward / forward compatible changes, updates
+ * to the existing messages, addition of fields.
+ *
+ * The major digit is for a breaking change of protocol, presumably
+ * something that cannot be accomodated with the existing protocol.
+ */
+
+#define VSCARD_VERSION MAKE_VERSION(0,0,1)
+
+typedef enum {
+    VSC_Init,
+    VSC_Error,
+    VSC_ReaderAdd,
+    VSC_ReaderAddResponse,
Quoted 8 lines

libcacard/vscard_common.h line 55

Quoted 6 lines
libcacard/vscard_common.h new file +6 -0
+    VSC_ReaderRemove,
+    VSC_ATR,
+    VSC_CardRemove,
+    VSC_APDU,
+    VSC_Reconnect
+} VSCMsgType;

Should number the enum to be specific at least.

will fix.

Quoted 10 lines

libcacard/vscard_common.h line 62

Quoted 8 lines
libcacard/vscard_common.h new file +7 -0
+
+typedef enum {
+    VSC_GENERAL_ERROR=1,
+    VSC_CANNOT_ADD_MORE_READERS,
+} VSCErrorCode;
+
+typedef uint32_t reader_id_t;

This namespace is reserved by C.

reader_id_t is reserved?

Quoted 11 lines

libcacard/vscard_common.h line 69

Quoted 8 lines
libcacard/vscard_common.h new file +7 -0
+#define VSCARD_UNDEFINED_READER_ID 0xffffffff
+#define VSCARD_MINIMAL_READER_ID    0
+
+typedef struct VSCMsgHeader {
+    VSCMsgType type;
+    reader_id_t   reader_id;
+    uint32_t   length;

Is length just the data length or the whole message length?

data length, I'll add a comment.

Quoted 16 lines
Quoted 16 lines
libcacard/vscard_common.h new file +16 -0
+    uint8_t    data[0];
+} VSCMsgHeader;
+
+/* VSCMsgInit               Client<->  Host
+ * Host replies with allocated reader id in ReaderAddResponse
+ * */
+typedef struct VSCMsgInit {
+    uint32_t   version;
+} VSCMsgInit;
+
+/* VSCMsgError              Client<->  Host
+ * */
+typedef struct VSCMsgError {
+    uint32_t   code;
+} VSCMsgError;
+
Quoted 9 lines

libcacard/vscard_common.h line 91

Quoted 6 lines
libcacard/vscard_common.h new file +6 -0
+/* VSCMsgReaderAdd          Client ->  Host
+ * Host replies with allocated reader id in ReaderAddResponse
+ * name - name of the reader on client side.
+ * */
+typedef struct VSCMsgReaderAdd {
+    uint8_t    name[0];

Is this a string?

Yes. You expect char?

Quoted 29 lines
Quoted 29 lines
libcacard/vscard_common.h new file +29 -0
+} VSCMsgReaderAdd;
+
+/* VSCMsgReaderAddResponse  Host ->  Client
+ * Reply to ReaderAdd
+ * */
+typedef struct VSCMsgReaderAddResponse {
+} VSCMsgReaderAddResponse;
+
+/* VSCMsgReaderRemove       Client ->  Host
+ * */
+typedef struct VSCMsgReaderRemove {
+} VSCMsgReaderRemove;
+
+/* VSCMsgATR                Client ->  Host
+ * Answer to reset. Sent for card insertion or card reset.
+ * */
+typedef struct VSCMsgATR {
+    uint8_t     atr[0];
+} VSCMsgATR;
+
+/* VSCMsgCardRemove         Client ->  Host
+ * */
+typedef struct VSCMsgCardRemove {
+} VSCMsgCardRemove;
+
+/* VSCMsgAPDU               Client<->  Host
+ * */
+typedef struct VSCMsgAPDU {
+    uint8_t    data[0];
Quoted 9 lines

libcacard/vscard_common.h line 126

Quoted 6 lines
libcacard/vscard_common.h new file +6 -0
+} VSCMsgAPDU;
+
+/* VSCMsgReconnect          Host ->  Client
+ * */
+typedef struct VSCMsgReconnect {
+    uint32_t   ip;

This is not ipv6 friendly. Two strings would be a better choice.

Will fix.

Quoted 9 lines

Regards,

Anthony Liguori

Quoted 4 lines
libcacard/vscard_common.h new file +4 -0
+    uint16_t   port;
+} VSCMsgReconnect;
+
+#endif
author
#16 lore raw

Re: [Qemu-devel] [PATCH 4/7] ccid: add ccid-card-emulated device (v2)

In reply to Anthony Liguori
Quoted 515 lines · Anthony Liguori
Quoted 514 lines · Alon Levy

This devices uses libcacard (internal) to emulate a smartcard conforming to the CAC standard. It attaches to the usb-ccid bus. Usage instructions (example command lines) are in the following patch in docs/ccid.txt. It uses libcacard which uses nss, so it can work with both hw cards and certificates (files).

changes from v1:
remove stale comments, use only c-style comments bugfix, forgot to set recv_len
change reader name to 'Virtual Reader'

---
 Makefile.objs           |    2 +-
 hw/ccid-card-emulated.c |  534 +++++++++++++++++++++++++++++++++++++++++++++++
 hw/ccid-card-passthru.c |    1 -
 3 files changed, 535 insertions(+), 2 deletions(-)
 create mode 100644 hw/ccid-card-emulated.c
Makefile.objs +1 -1
index 6a0030b..303b642 100644
@@ -197,7 +197,7 @@ hw-obj-$(CONFIG_FDC) += fdc.o
 hw-obj-$(CONFIG_ACPI) += acpi.o acpi_piix4.o
 hw-obj-$(CONFIG_APM) += pm_smbus.o apm.o
 hw-obj-$(CONFIG_DMA) += dma.o
-hw-obj-$(CONFIG_SMARTCARD) += usb-ccid.o ccid-card-passthru.o
+hw-obj-$(CONFIG_SMARTCARD) += usb-ccid.o ccid-card-passthru.o ccid-card-emulated.o
 
 # PPC devices
 hw-obj-$(CONFIG_OPENPIC) += openpic.o
hw/ccid-card-emulated.c new file +476 -0
new file mode 100644
index 0000000..5531ce1
@@ -0,0 +1,534 @@
+/*
+ * CCID Card Device. Emulated card.
+ *
+ * It can be used to provide access to the local hardware in a non exclusive
+ * way, or it can use certificates. It requires the usb-ccid bus.
+ *
+ * Usage 1: standard, mirror hardware reader+card:
+ * qemu .. -usb -device usb-ccid -device ccid-card-emulated
+ *
+ * Usage 2: use certificates, no hardware required
+ * one time: create the certificates:
+ *  for i in 1 2 3; do certutil -d /etc/pki/nssdb -x -t "CT,CT,CT" -S -s "CN=user$i" -n user$i; done
+ * qemu .. -usb -device usb-ccid -device ccid-card-emulated,cert1=user1,cert2=user2,cert3=user3
+ *
+ * If you use a non default db for the certificates you can specify it using the db parameter.
+ *
+ *
+ * Copyright (c) 2010 Red Hat.
+ * Written by Alon Levy.
+ *
+ * This code is licenced under the LGPL.
+ */
+
+#include<pthread.h>
+#include<eventt.h>
+#include<vevent.h>
+#include<vreader.h>
+#include<vcard_emul.h>
+#include "qemu-char.h"
+#include "monitor.h"
+#include "hw/ccid.h"
+
+#define DPRINTF(card, lvl, fmt, ...) \
+do { if (lvl<= card->debug) { printf("ccid-card-emul: %s: " fmt , __func__, ## __VA_ARGS__); } } while (0)
+
+#define EMULATED_DEV_NAME "ccid-card-emulated"
+
+#define BACKEND_NSS_EMULATED "nss-emulated" /* the default */
+#define BACKEND_CERTIFICATES "certificates"
+
+typedef struct EmulatedState EmulatedState;
+
+enum {
+    EMUL_READER_INSERT = 0,
+    EMUL_READER_REMOVE,
+    EMUL_CARD_INSERT,
+    EMUL_CARD_REMOVE,
+    EMUL_GUEST_APDU,
+    EMUL_RESPONSE_APDU,
+    EMUL_ERROR,
+};
+
+static const char* emul_event_to_string(uint32_t emul_event)
+{
+    switch (emul_event) {
+        case EMUL_READER_INSERT: return "EMUL_READER_INSERT";
+        case EMUL_READER_REMOVE: return "EMUL_READER_REMOVE";
+        case EMUL_CARD_INSERT: return "EMUL_CARD_INSERT";
+        case EMUL_CARD_REMOVE: return "EMUL_CARD_REMOVE";
+        case EMUL_GUEST_APDU: return "EMUL_GUEST_APDU";
+        case EMUL_RESPONSE_APDU: return "EMUL_RESPONSE_APDU";
+        case EMUL_ERROR: return "EMUL_ERROR";
+        default:
+            break;
+    }
+    return "UNKNOWN";
+}
+
+typedef struct EmulEvent {
+    QSIMPLEQ_ENTRY(EmulEvent) entry;
+    union {
+        struct {
+            uint32_t type;
+        } gen;
+        struct {
+            uint32_t type;
+            uint64_t code;
+        } error;
+        struct {
+            uint32_t type;
+            uint32_t len;
+            uint8_t data[];
+        } data;
+    } p;
+} EmulEvent;
+
+#define MAX_ATR_SIZE 40
+struct EmulatedState {
+    CCIDCardState base;
+    uint8_t  debug;
+    char*    backend;
+    char*    cert1;
+    char*    cert2;
+    char*    cert3;
+    char*    db;
+    uint8_t  atr[MAX_ATR_SIZE];
+    uint8_t  atr_length;
+    QSIMPLEQ_HEAD(event_list, EmulEvent) event_list;
+    pthread_mutex_t event_list_mutex;
+    VReader *reader;
+    QSIMPLEQ_HEAD(guest_apdu_list, EmulEvent) guest_apdu_list;
+    pthread_mutex_t vreader_mutex; /* and guest_apdu_list mutex */
+    pthread_mutex_t handle_apdu_mutex;
+    pthread_cond_t handle_apdu_cond;
+    int      pipe[2];
+    int      quit_apdu_thread;
+    pthread_mutex_t apdu_thread_quit_mutex;
+    pthread_cond_t apdu_thread_quit_cond;
+};
+
+static void emulated_apdu_from_guest(CCIDCardState *base, const uint8_t *apdu, uint32_t len)
+{
+    EmulatedState *card = DO_UPCAST(EmulatedState, base, base);
+    EmulEvent *event = (EmulEvent*)malloc(sizeof(EmulEvent) + len);
+
+    assert(event);
+    event->p.data.type = EMUL_GUEST_APDU;
+    event->p.data.len = len;
+    memcpy(event->p.data.data, apdu, len);
+    pthread_mutex_lock(&card->vreader_mutex);
+    QSIMPLEQ_INSERT_TAIL(&card->guest_apdu_list, event, entry);
+    pthread_mutex_unlock(&card->vreader_mutex);
+    pthread_mutex_lock(&card->handle_apdu_mutex);
+    pthread_cond_signal(&card->handle_apdu_cond);
+    pthread_mutex_unlock(&card->handle_apdu_mutex);
+}
+
+static const uint8_t* emulated_get_atr(CCIDCardState *base, uint32_t *len)
+{
+    EmulatedState *card = DO_UPCAST(EmulatedState, base, base);
+
+    *len = card->atr_length;
+    return card->atr;
+}
+
+static void emulated_push_event(EmulatedState *card, EmulEvent *event)
+{
+    pthread_mutex_lock(&card->event_list_mutex);
+    QSIMPLEQ_INSERT_TAIL(&(card->event_list), event, entry);
+    pthread_mutex_unlock(&card->event_list_mutex);
+    if (write(card->pipe[1], card, 1) != 1) {
+        DPRINTF(card, 1, "write to pipe failed\n");
+    }
+}
+
+static void emulated_push_type(EmulatedState *card, uint32_t type)
+{
+    EmulEvent *event = (EmulEvent*)malloc(sizeof(EmulEvent));
+
+    assert(event);
+    event->p.gen.type = type;
+    emulated_push_event(card, event);
+}
+
+static void emulated_push_error(EmulatedState *card, uint64_t code)
+{
+    EmulEvent *event = (EmulEvent*)malloc(sizeof(EmulEvent));
+
+    assert(event);
+    event->p.error.type = EMUL_ERROR;
+    event->p.error.code = code;
+    emulated_push_event(card, event);
+}
+
+static void emulated_push_data_type(EmulatedState *card, uint32_t type,
+    const uint8_t *data, uint32_t len)
+{
+    EmulEvent *event = (EmulEvent*)malloc(sizeof(EmulEvent) + len);
+
+    assert(event);
+    event->p.data.type = type;
+    event->p.data.len = len;
+    memcpy(event->p.data.data, data, len);
+    emulated_push_event(card, event);
+}
+
+static void emulated_push_reader_insert(EmulatedState *card)
+{
+    emulated_push_type(card, EMUL_READER_INSERT);
+}
+
+static void emulated_push_reader_remove(EmulatedState *card)
+{
+    emulated_push_type(card, EMUL_READER_REMOVE);
+}
+
+static void emulated_push_card_insert(EmulatedState *card,
+    const uint8_t *atr, uint32_t len)
+{
+    emulated_push_data_type(card, EMUL_CARD_INSERT, atr, len);
+}
+
+static void emulated_push_card_remove(EmulatedState *card)
+{
+    emulated_push_type(card, EMUL_CARD_REMOVE);
+}
+
+static void emulated_push_response_apdu(EmulatedState *card,
+    const uint8_t* apdu, uint32_t len)
+{
+    emulated_push_data_type(card, EMUL_RESPONSE_APDU, apdu, len);
+}
+
+#define APDU_BUF_SIZE 270
+static void *handle_apdu_thread(void* arg)
+{
+    EmulatedState *card = arg;
+    uint8_t recv_data[APDU_BUF_SIZE];
+    int recv_len;
+    VReaderStatus reader_status;
+    EmulEvent *event;
+
+    while (1) {
+        pthread_mutex_lock(&card->handle_apdu_mutex);
+        pthread_cond_wait(&card->handle_apdu_cond,&card->handle_apdu_mutex);
+        pthread_mutex_unlock(&card->handle_apdu_mutex);
+        if (card->quit_apdu_thread) {
+            card->quit_apdu_thread = 0; // debugging
+            break;
+        }
+        pthread_mutex_lock(&card->vreader_mutex);
+        while (!QSIMPLEQ_EMPTY(&card->guest_apdu_list)) {
+            event = QSIMPLEQ_FIRST(&card->guest_apdu_list);
+            assert((unsigned long)event>  1000);
+            QSIMPLEQ_REMOVE_HEAD(&card->guest_apdu_list, entry);
+            if (event->p.data.type != EMUL_GUEST_APDU) {
+                DPRINTF(card, 1, "unexpected message in handle_apdu_thread\n");
+                free(event);
+                continue;
+            }
+            if (card->reader == NULL) {
+                DPRINTF(card, 1, "reader is NULL\n");
+                free(event);
+                continue;
+            }
+            recv_len = sizeof(recv_data);
+            reader_status = vreader_xfr_bytes(card->reader,
+                    event->p.data.data, event->p.data.len,
+                    recv_data,&recv_len);
+            DPRINTF(card, 2, "got back apdu of length %d\n", recv_len);
+            if (reader_status == VREADER_OK) {
+                emulated_push_response_apdu(card, recv_data, recv_len);
+            } else {
+                emulated_push_error(card, reader_status);
+            }
+            free(event);
+        }
+        pthread_mutex_unlock(&card->vreader_mutex);
+    }
+    pthread_mutex_lock(&card->apdu_thread_quit_mutex);
+    pthread_cond_signal(&card->apdu_thread_quit_cond);
+    pthread_mutex_unlock(&card->apdu_thread_quit_mutex);
+    return NULL;
+}
+
+static void *event_thread(void *arg)
+{
+    int atr_len = MAX_ATR_SIZE;
+    uint8_t atr[MAX_ATR_SIZE];
+    VEvent *event = NULL;
+    EmulatedState *card = arg;
+
+    while (1) {
+        const char *reader_name;
+
+        event = vevent_wait_next_vevent();
+        if (event == NULL || event->type == VEVENT_LAST) {
+            break;
+        }
+        if (event->type != VEVENT_READER_INSERT) {
+            if (card->reader == NULL&&  event->reader != NULL) {
+                // Happens after device_add followed by card remove or insert.
+                // XXX: create synthetic add_reader events if vcard_emul_init
+                // already called, which happens if device_del and device_add are
+                // called
+                card->reader = vreader_reference(event->reader);
+            } else {
+                if (event->reader != card->reader) {
+                    fprintf(stderr, "ERROR: wrong reader: quiting event_thread\n");
+                    break;
+                }
+            }
+        }
+        switch (event->type) {
+        case VEVENT_READER_INSERT:
+            /* TODO: take a specific reader. i.e. track which reader
+             * we are seeing here, check it is the one we want (the first,
+             * or by a particular name), and ignore if we don't want it.
+             */
+            reader_name = vreader_get_name(event->reader);
+            if (card->reader != NULL) {
+                DPRINTF(card, 2, "READER INSERT - replacing %s with %s\n",
+                    vreader_get_name(card->reader), reader_name);
+                pthread_mutex_lock(&card->vreader_mutex);
+                vreader_free(card->reader);
+                pthread_mutex_unlock(&card->vreader_mutex);
+                emulated_push_reader_remove(card);
+            }
+            pthread_mutex_lock(&card->vreader_mutex);
+            DPRINTF(card, 2, "READER INSERT %s\n", reader_name);
+            card->reader = vreader_reference(event->reader);
+            pthread_mutex_unlock(&card->vreader_mutex);
+            emulated_push_reader_insert(card);
+            break;
+        case VEVENT_READER_REMOVE:
+            DPRINTF(card, 2, " READER REMOVE: %s \n",
+                    vreader_get_name(event->reader));
+            pthread_mutex_lock(&card->vreader_mutex);
+            vreader_free(card->reader);
+            card->reader = NULL;
+            pthread_mutex_unlock(&card->vreader_mutex);
+            emulated_push_reader_remove(card);
+            break;
+        case VEVENT_CARD_INSERT:
+            /* get the ATR (intended as a response to a power on from the
+             * reader */
+            atr_len = MAX_ATR_SIZE;
+            vreader_power_on(event->reader, atr,&atr_len);
+            card->atr_length = (uint8_t)atr_len;
+            DPRINTF(card, 2, " CARD INSERT\n");
+            emulated_push_card_insert(card, atr, atr_len);
+            break;
+        case VEVENT_CARD_REMOVE:
+            DPRINTF(card, 2, " CARD REMOVE\n");
+            emulated_push_card_remove(card);
+            break;
+        case VEVENT_LAST: /* quit */
+            vevent_delete(event);
+            return NULL;
+            break;
+        default:
+            break;
+        }
+        vevent_delete(event);
+    }
+    return NULL;
+}
+
+static void pipe_read(void *opaque)
+{
+    EmulatedState *card = opaque;
+    EmulEvent *event, *next;
+    char dummy;
+    int len;
+
+    do {
+        len = read(card->pipe[0],&dummy, sizeof(dummy));
+    } while (len == sizeof(dummy));
+    pthread_mutex_lock(&card->event_list_mutex);
+    QSIMPLEQ_FOREACH_SAFE(event,&card->event_list, entry, next) {
+        DPRINTF(card, 2, "event %s\n", emul_event_to_string(event->p.gen.type));
+        switch (event->p.gen.type) {
+            case EMUL_RESPONSE_APDU:
+                ccid_card_send_apdu_to_guest(&card->base, event->p.data.data,
+                    event->p.data.len);
+                break;
+            case EMUL_READER_INSERT:
+                ccid_card_ccid_attach(&card->base);
+                break;
+            case EMUL_READER_REMOVE:
+                ccid_card_ccid_detach(&card->base);
+                break;
+            case EMUL_CARD_INSERT:
+                assert(event->p.data.len<= MAX_ATR_SIZE);
+                card->atr_length = event->p.data.len;
+                memcpy(card->atr, event->p.data.data, card->atr_length);
+                ccid_card_card_inserted(&card->base);
+                break;
+            case EMUL_CARD_REMOVE:
+                ccid_card_card_removed(&card->base);
+                break;
+            case EMUL_ERROR:
+                ccid_card_card_error(&card->base, event->p.error.code);
+                break;
+            default:
+                DPRINTF(card, 2, "unexpected event\n");
+                break;
+        }
+        free(event);
+    }
+    QSIMPLEQ_INIT(&card->event_list);
+    pthread_mutex_unlock(&card->event_list_mutex);
+}
+
+static int init_pipe_signaling(EmulatedState *card)
+{
+   if (pipe(card->pipe)<  0) {
+       DPRINTF(card, 2, "pipe creation failed\n");
+       return -1;
+   }
+   fcntl(card->pipe[0], F_SETFL, O_NONBLOCK);
+   fcntl(card->pipe[1], F_SETFL, O_NONBLOCK);
+   fcntl(card->pipe[0], F_SETOWN, getpid());
+   qemu_set_fd_handler(card->pipe[0], pipe_read, NULL, card);
+   return 0;
+}
+
+#define CERTIFICATES_DEFAULT_DB "/etc/pki/nssdb"
+#define CERTIFICATES_ARGS_TEMPLATE "db=\"%s\" use_hw=no soft=(,Virtual Reader,CAC,,%s,%s,%s)"
+
+static int wrap_vcard_emul_init(VCardEmulOptions *options)
+{
+    static int called = 0;
+    static int options_was_null = 0;
+
+    if (called) {
+        if ((options == NULL) != options_was_null) {
+            printf("%s: warning: running emulated with certificates and emulated side by side is not supported\n", __FUNCTION__);
+            return VCARD_EMUL_FAIL;
+        }
+        vcard_emul_replay_insertion_events();
+        return VCARD_EMUL_OK;
+    }
+    options_was_null = (options == NULL);
+    called = 1;
+    return vcard_emul_init(options);
+}
+
+static int emulated_initialize_vcard_from_certificates(EmulatedState *card)
+{
+    char emul_args[200];
+    VCardEmulOptions *options = NULL;
+
+    snprintf(emul_args, sizeof(emul_args) - 1, CERTIFICATES_ARGS_TEMPLATE,
+        card->db ? card->db : CERTIFICATES_DEFAULT_DB,
+        card->cert1, card->cert2, card->cert3);
+    options = vcard_emul_options(emul_args);
+    if (options == NULL) {
+        printf("%s: warning: not using certificates due to initialization error\n", __func__);
+    }
+    return wrap_vcard_emul_init(options);
+}
+
+static int emulated_initfn(CCIDCardState *base)
+{
+    EmulatedState *card = DO_UPCAST(EmulatedState, base, base);
+    int rv;
+    pthread_t thread_id;
+    VCardEmulError ret;
+
+    QSIMPLEQ_INIT(&card->event_list);
+    QSIMPLEQ_INIT(&card->guest_apdu_list);
+    pthread_mutex_init(&card->event_list_mutex, NULL);
+    pthread_mutex_init(&card->vreader_mutex, NULL);
+    pthread_mutex_init(&card->handle_apdu_mutex, NULL);
+    pthread_cond_init(&card->handle_apdu_cond, NULL);
+    card->reader = NULL;
+    card->quit_apdu_thread = 0;
+    if (init_pipe_signaling(card)<  0) {
+        return -1;
+    }
+    if (!card->backend) {
+        card->backend = strdup((char*)BACKEND_NSS_EMULATED);
+    }
+    /* TODO: a passthru backened that works on local machine. third card type? */
+    if (strcmp(BACKEND_CERTIFICATES, card->backend) == 0
+&&  card->cert1 != NULL&&  card->cert2 != NULL&&  card->cert3 != NULL) {
+        ret = emulated_initialize_vcard_from_certificates(card);
+    } else {
+        if (strcmp(BACKEND_CERTIFICATES, card->backend) == 0) {
+            printf("%s: you must provide all three certs for certificates backend\n",
+                EMULATED_DEV_NAME);
+            return -1;
+        }
+        if (card->backend&&  strcmp(BACKEND_NSS_EMULATED, card->backend) != 0) {
+            printf("%s: bad backend specified. The options are:\n%s (default), %s.\n",
+                EMULATED_DEV_NAME, BACKEND_NSS_EMULATED, BACKEND_CERTIFICATES);
+            return -1;
+        }
+        /* default to mirroring the local hardware readers */
+        ret = wrap_vcard_emul_init(NULL);
+    }
+    if (ret != VCARD_EMUL_OK) {
+        printf("%s: failed to initialize vcard\n", EMULATED_DEV_NAME);
+        return -1;
+    }
Quoted 9 lines

hw/ccid-card-emulated.c line 481

Quoted 5 lines
hw/ccid-card-emulated.c new file +5 -0
+    rv = pthread_create(&thread_id, NULL, event_thread, card);
+    if (rv<  0) {
+        printf("%s: error creating event thread\n", EMULATED_DEV_NAME);
+        return -1;
+    }

Why can't this be implemented with qemu_set_fd_handler? The event thread si just spinning on read.

The issue is not letting NSS block any of qemu's threads.

Quoted 70 lines

Regards,

Anthony Liguori

Quoted 65 lines
hw/ccid-card-emulated.c new file +53 -0
+    rv = pthread_create(&thread_id, NULL, handle_apdu_thread, card);
+    if (rv<  0) {
+        printf("%s: error creating handle_apdu thread\n", EMULATED_DEV_NAME);
+        return -1;
+    }
+    return 0;
+}
+
+static int emulated_exitfn(CCIDCardState *base)
+{
+    EmulatedState *card = DO_UPCAST(EmulatedState, base, base);
+    VEvent *vevent = vevent_new(VEVENT_LAST, NULL, NULL);
+
+    vevent_queue_vevent(vevent); /* stop vevent thread */
+    pthread_mutex_lock(&card->apdu_thread_quit_mutex);
+    card->quit_apdu_thread = 1; /* stop handle_apdu thread */
+    pthread_cond_signal(&card->handle_apdu_cond);
+    pthread_cond_wait(&card->apdu_thread_quit_cond,&card->apdu_thread_quit_mutex);
+    /* handle_apdu thread stopped, can destroy all of it's mutexes */
+    pthread_cond_destroy(&card->handle_apdu_cond);
+    pthread_cond_destroy(&card->apdu_thread_quit_cond);
+    pthread_mutex_destroy(&card->apdu_thread_quit_mutex);
+    pthread_mutex_destroy(&card->handle_apdu_mutex);
+    pthread_mutex_destroy(&card->vreader_mutex);
+    pthread_mutex_destroy(&card->event_list_mutex);
+    return 0;
+}
+
+static CCIDCardInfo emulated_card_info = {
+    .qdev.name = EMULATED_DEV_NAME,
+    .qdev.size = sizeof(EmulatedState),
+    .initfn = emulated_initfn,
+    .exitfn = emulated_exitfn,
+    .get_atr = emulated_get_atr,
+    .apdu_from_guest = emulated_apdu_from_guest,
+    .qdev.unplug    = qdev_simple_unplug_cb,
+    .qdev.props     = (Property[]) {
+        DEFINE_PROP_STRING("backend", EmulatedState, backend),
+        DEFINE_PROP_STRING("cert1", EmulatedState, cert1),
+        DEFINE_PROP_STRING("cert2", EmulatedState, cert2),
+        DEFINE_PROP_STRING("cert3", EmulatedState, cert3),
+        DEFINE_PROP_STRING("db", EmulatedState, db),
+        DEFINE_PROP_UINT8("debug", EmulatedState, debug, 0),
+        DEFINE_PROP_END_OF_LIST(),
+    },
+};
+
+static void ccid_card_emulated_register_devices(void)
+{
+    ccid_card_qdev_register(&emulated_card_info);
+}
+
+device_init(ccid_card_emulated_register_devices)
hw/ccid-card-passthru.c +0 -1
index 6ec4f21..f9fb82c 100644
@@ -253,7 +253,6 @@ static CCIDCardInfo passthru_card_info = {
     .exitfn = passthru_exitfn,
     .get_atr = passthru_get_atr,
     .apdu_from_guest = passthru_apdu_from_guest,
-    .qdev.unplug    = qdev_simple_unplug_cb,
     .qdev.props     = (Property[]) {
         DEFINE_PROP_CHR("chardev", PassthruState, cs),
         DEFINE_PROP_UINT8("debug", PassthruState, debug, 0),
#5 lore raw

Re: [Qemu-devel] [PATCH 2/7] ccid: add passthru card device

In reply to Alon Levy
Quoted 106 lines · Alon Levy
Quoted 12 lines · Anthony Liguori

libcacard/vscard_common.h

Quoted 6 lines · Alon Levy
libcacard/vscard_common.h new file +0 -0
new file mode 100644
index 0000000..9ff1295

This file (and the .c file) need a coding style pass to fixup comments and the use of _ as a prefix but I want to focus on the protocol itself.

Quoted 4 lines

First, let's get a written spec into the wiki. I think it's important that all of our compatibility protocols are documented in a more formal way such that can be reviewed by a wider audience.

ok, I'll create Features/Smartcard/Protocol

Quoted 30 lines
Quoted 16 lines
libcacard/vscard_common.h new file +13 -0
@@ -0,0 +1,130 @@
+/* Virtual Smart Card protocol definition
+ *
+ * This protocol is between a host implementing a group of virtual smart card
+ * reader, and a client implementing a virtual smart card, or passthrough to
+ * a real card.
+ *
+ * The current implementation passes the raw APDU's from 7816 and additionally
+ * contains messages to setup and teardown readers, handle insertion and
+ * removal of cards, negotiate the protocol and provide for error responses.
+ *
+ * Copyright (c) 2010 Red Hat.
+ *
+ * This code is licensed under the LGPL.

libcacard/vscard_common.h line 23

Quoted 10 lines
libcacard/vscard_common.h new file +10 -0
+ */
+
+#ifndef _VSCARD_COMMON_H
+#define _VSCARD_COMMON_H
+
+#include<stdint.h>
+
+#define VERSION_MAJOR_BITS 11
+#define VERSION_MIDDLE_BITS 11
+#define VERSION_MINOR_BITS 10

Distros make versioning not enough. Inevitably, someone wants to back port a bug fix or a feature for some RHEL7.2 release or something like that.

Quoted 4 lines

Feature negotiation has worked pretty well for us and I'd suggest using it within the protocol.

Suggestion accepted.

Quoted 25 lines
Quoted 25 lines
libcacard/vscard_common.h new file +25 -0
+#define MAKE_VERSION(major, middle, minor) \
+     (  (major<<   (VERSION_MINOR_BITS + VERSION_MIDDLE_BITS)) \
+      | (middle<<    VERSION_MINOR_BITS) \
+      | (minor)  )
+
+/** IMPORTANT NOTE on VERSION
+ *
+ * The version below MUST be changed whenever a change in this file is made.
+ *
+ * The last digit, the minor, is for bug fix changes only.
+ *
+ * The middle digit is for backward / forward compatible changes, updates
+ * to the existing messages, addition of fields.
+ *
+ * The major digit is for a breaking change of protocol, presumably
+ * something that cannot be accomodated with the existing protocol.
+ */
+
+#define VSCARD_VERSION MAKE_VERSION(0,0,1)
+
+typedef enum {
+    VSC_Init,
+    VSC_Error,
+    VSC_ReaderAdd,
+    VSC_ReaderAddResponse,
Quoted 9 lines

libcacard/vscard_common.h line 55

Quoted 7 lines
libcacard/vscard_common.h new file +6 -0
+    VSC_ReaderRemove,
+    VSC_ATR,
+    VSC_CardRemove,
+    VSC_APDU,
+    VSC_Reconnect
+} VSCMsgType;

Should number the enum to be specific at least.

will fix.

Quoted 11 lines

libcacard/vscard_common.h line 62

Quoted 9 lines
libcacard/vscard_common.h new file +7 -0
+
+typedef enum {
+    VSC_GENERAL_ERROR=1,
+    VSC_CANNOT_ADD_MORE_READERS,
+} VSCErrorCode;
+
+typedef uint32_t reader_id_t;

This namespace is reserved by C.

Quoted 2 lines

reader_id_t is reserved?

Anything with the suffix '_t' is reserved by the standard library.

It's a widely violated rule, but we have run into problems from not obeying it.

Quoted 10 lines
Quoted 10 lines

libcacard/vscard_common.h line 91

Quoted 7 lines
libcacard/vscard_common.h new file +6 -0
+/* VSCMsgReaderAdd          Client ->   Host
+ * Host replies with allocated reader id in ReaderAddResponse
+ * name - name of the reader on client side.
+ * */
+typedef struct VSCMsgReaderAdd {
+    uint8_t    name[0];

Is this a string?

Quoted 2 lines

Yes. You expect char?

Yes, also, what's the encoding (UTF-8)?

Regards,

Anthony Liguori

#17 lore raw

Re: [Qemu-devel] [PATCH 4/7] ccid: add ccid-card-emulated device (v2)

In reply to Alon Levy
Quoted 528 lines · Alon Levy
Quoted 516 lines · Anthony Liguori
Quoted 514 lines · Alon Levy

This devices uses libcacard (internal) to emulate a smartcard conforming to the CAC standard. It attaches to the usb-ccid bus. Usage instructions (example command lines) are in the following patch in docs/ccid.txt. It uses libcacard which uses nss, so it can work with both hw cards and certificates (files).

changes from v1:
remove stale comments, use only c-style comments bugfix, forgot to set recv_len
change reader name to 'Virtual Reader'

---
  Makefile.objs           |    2 +-
  hw/ccid-card-emulated.c |  534 +++++++++++++++++++++++++++++++++++++++++++++++
  hw/ccid-card-passthru.c |    1 -
  3 files changed, 535 insertions(+), 2 deletions(-)

create mode 100644 hw/ccid-card-emulated.c

Makefile.objs +1 -1
index 6a0030b..303b642 100644
@@ -197,7 +197,7 @@ hw-obj-$(CONFIG_FDC) += fdc.o
  hw-obj-$(CONFIG_ACPI) += acpi.o acpi_piix4.o
  hw-obj-$(CONFIG_APM) += pm_smbus.o apm.o
  hw-obj-$(CONFIG_DMA) += dma.o
-hw-obj-$(CONFIG_SMARTCARD) += usb-ccid.o ccid-card-passthru.o
+hw-obj-$(CONFIG_SMARTCARD) += usb-ccid.o ccid-card-passthru.o ccid-card-emulated.o
 
  # PPC devices
  hw-obj-$(CONFIG_OPENPIC) += openpic.o
hw/ccid-card-emulated.c new file +476 -0
new file mode 100644
index 0000000..5531ce1
@@ -0,0 +1,534 @@
+/*
+ * CCID Card Device. Emulated card.
+ *
+ * It can be used to provide access to the local hardware in a non exclusive
+ * way, or it can use certificates. It requires the usb-ccid bus.
+ *
+ * Usage 1: standard, mirror hardware reader+card:
+ * qemu .. -usb -device usb-ccid -device ccid-card-emulated
+ *
+ * Usage 2: use certificates, no hardware required
+ * one time: create the certificates:
+ *  for i in 1 2 3; do certutil -d /etc/pki/nssdb -x -t "CT,CT,CT" -S -s "CN=user$i" -n user$i; done
+ * qemu .. -usb -device usb-ccid -device ccid-card-emulated,cert1=user1,cert2=user2,cert3=user3
+ *
+ * If you use a non default db for the certificates you can specify it using the db parameter.
+ *
+ *
+ * Copyright (c) 2010 Red Hat.
+ * Written by Alon Levy.
+ *
+ * This code is licenced under the LGPL.
+ */
+
+#include<pthread.h>
+#include<eventt.h>
+#include<vevent.h>
+#include<vreader.h>
+#include<vcard_emul.h>
+#include "qemu-char.h"
+#include "monitor.h"
+#include "hw/ccid.h"
+
+#define DPRINTF(card, lvl, fmt, ...) \
+do { if (lvl<= card->debug) { printf("ccid-card-emul: %s: " fmt , __func__, ## __VA_ARGS__); } } while (0)
+
+#define EMULATED_DEV_NAME "ccid-card-emulated"
+
+#define BACKEND_NSS_EMULATED "nss-emulated" /* the default */
+#define BACKEND_CERTIFICATES "certificates"
+
+typedef struct EmulatedState EmulatedState;
+
+enum {
+    EMUL_READER_INSERT = 0,
+    EMUL_READER_REMOVE,
+    EMUL_CARD_INSERT,
+    EMUL_CARD_REMOVE,
+    EMUL_GUEST_APDU,
+    EMUL_RESPONSE_APDU,
+    EMUL_ERROR,
+};
+
+static const char* emul_event_to_string(uint32_t emul_event)
+{
+    switch (emul_event) {
+        case EMUL_READER_INSERT: return "EMUL_READER_INSERT";
+        case EMUL_READER_REMOVE: return "EMUL_READER_REMOVE";
+        case EMUL_CARD_INSERT: return "EMUL_CARD_INSERT";
+        case EMUL_CARD_REMOVE: return "EMUL_CARD_REMOVE";
+        case EMUL_GUEST_APDU: return "EMUL_GUEST_APDU";
+        case EMUL_RESPONSE_APDU: return "EMUL_RESPONSE_APDU";
+        case EMUL_ERROR: return "EMUL_ERROR";
+        default:
+            break;
+    }
+    return "UNKNOWN";
+}
+
+typedef struct EmulEvent {
+    QSIMPLEQ_ENTRY(EmulEvent) entry;
+    union {
+        struct {
+            uint32_t type;
+        } gen;
+        struct {
+            uint32_t type;
+            uint64_t code;
+        } error;
+        struct {
+            uint32_t type;
+            uint32_t len;
+            uint8_t data[];
+        } data;
+    } p;
+} EmulEvent;
+
+#define MAX_ATR_SIZE 40
+struct EmulatedState {
+    CCIDCardState base;
+    uint8_t  debug;
+    char*    backend;
+    char*    cert1;
+    char*    cert2;
+    char*    cert3;
+    char*    db;
+    uint8_t  atr[MAX_ATR_SIZE];
+    uint8_t  atr_length;
+    QSIMPLEQ_HEAD(event_list, EmulEvent) event_list;
+    pthread_mutex_t event_list_mutex;
+    VReader *reader;
+    QSIMPLEQ_HEAD(guest_apdu_list, EmulEvent) guest_apdu_list;
+    pthread_mutex_t vreader_mutex; /* and guest_apdu_list mutex */
+    pthread_mutex_t handle_apdu_mutex;
+    pthread_cond_t handle_apdu_cond;
+    int      pipe[2];
+    int      quit_apdu_thread;
+    pthread_mutex_t apdu_thread_quit_mutex;
+    pthread_cond_t apdu_thread_quit_cond;
+};
+
+static void emulated_apdu_from_guest(CCIDCardState *base, const uint8_t *apdu, uint32_t len)
+{
+    EmulatedState *card = DO_UPCAST(EmulatedState, base, base);
+    EmulEvent *event = (EmulEvent*)malloc(sizeof(EmulEvent) + len);
+
+    assert(event);
+    event->p.data.type = EMUL_GUEST_APDU;
+    event->p.data.len = len;
+    memcpy(event->p.data.data, apdu, len);
+    pthread_mutex_lock(&card->vreader_mutex);
+    QSIMPLEQ_INSERT_TAIL(&card->guest_apdu_list, event, entry);
+    pthread_mutex_unlock(&card->vreader_mutex);
+    pthread_mutex_lock(&card->handle_apdu_mutex);
+    pthread_cond_signal(&card->handle_apdu_cond);
+    pthread_mutex_unlock(&card->handle_apdu_mutex);
+}
+
+static const uint8_t* emulated_get_atr(CCIDCardState *base, uint32_t *len)
+{
+    EmulatedState *card = DO_UPCAST(EmulatedState, base, base);
+
+    *len = card->atr_length;
+    return card->atr;
+}
+
+static void emulated_push_event(EmulatedState *card, EmulEvent *event)
+{
+    pthread_mutex_lock(&card->event_list_mutex);
+    QSIMPLEQ_INSERT_TAIL(&(card->event_list), event, entry);
+    pthread_mutex_unlock(&card->event_list_mutex);
+    if (write(card->pipe[1], card, 1) != 1) {
+        DPRINTF(card, 1, "write to pipe failed\n");
+    }
+}
+
+static void emulated_push_type(EmulatedState *card, uint32_t type)
+{
+    EmulEvent *event = (EmulEvent*)malloc(sizeof(EmulEvent));
+
+    assert(event);
+    event->p.gen.type = type;
+    emulated_push_event(card, event);
+}
+
+static void emulated_push_error(EmulatedState *card, uint64_t code)
+{
+    EmulEvent *event = (EmulEvent*)malloc(sizeof(EmulEvent));
+
+    assert(event);
+    event->p.error.type = EMUL_ERROR;
+    event->p.error.code = code;
+    emulated_push_event(card, event);
+}
+
+static void emulated_push_data_type(EmulatedState *card, uint32_t type,
+    const uint8_t *data, uint32_t len)
+{
+    EmulEvent *event = (EmulEvent*)malloc(sizeof(EmulEvent) + len);
+
+    assert(event);
+    event->p.data.type = type;
+    event->p.data.len = len;
+    memcpy(event->p.data.data, data, len);
+    emulated_push_event(card, event);
+}
+
+static void emulated_push_reader_insert(EmulatedState *card)
+{
+    emulated_push_type(card, EMUL_READER_INSERT);
+}
+
+static void emulated_push_reader_remove(EmulatedState *card)
+{
+    emulated_push_type(card, EMUL_READER_REMOVE);
+}
+
+static void emulated_push_card_insert(EmulatedState *card,
+    const uint8_t *atr, uint32_t len)
+{
+    emulated_push_data_type(card, EMUL_CARD_INSERT, atr, len);
+}
+
+static void emulated_push_card_remove(EmulatedState *card)
+{
+    emulated_push_type(card, EMUL_CARD_REMOVE);
+}
+
+static void emulated_push_response_apdu(EmulatedState *card,
+    const uint8_t* apdu, uint32_t len)
+{
+    emulated_push_data_type(card, EMUL_RESPONSE_APDU, apdu, len);
+}
+
+#define APDU_BUF_SIZE 270
+static void *handle_apdu_thread(void* arg)
+{
+    EmulatedState *card = arg;
+    uint8_t recv_data[APDU_BUF_SIZE];
+    int recv_len;
+    VReaderStatus reader_status;
+    EmulEvent *event;
+
+    while (1) {
+        pthread_mutex_lock(&card->handle_apdu_mutex);
+        pthread_cond_wait(&card->handle_apdu_cond,&card->handle_apdu_mutex);
+        pthread_mutex_unlock(&card->handle_apdu_mutex);
+        if (card->quit_apdu_thread) {
+            card->quit_apdu_thread = 0; // debugging
+            break;
+        }
+        pthread_mutex_lock(&card->vreader_mutex);
+        while (!QSIMPLEQ_EMPTY(&card->guest_apdu_list)) {
+            event = QSIMPLEQ_FIRST(&card->guest_apdu_list);
+            assert((unsigned long)event>   1000);
+            QSIMPLEQ_REMOVE_HEAD(&card->guest_apdu_list, entry);
+            if (event->p.data.type != EMUL_GUEST_APDU) {
+                DPRINTF(card, 1, "unexpected message in handle_apdu_thread\n");
+                free(event);
+                continue;
+            }
+            if (card->reader == NULL) {
+                DPRINTF(card, 1, "reader is NULL\n");
+                free(event);
+                continue;
+            }
+            recv_len = sizeof(recv_data);
+            reader_status = vreader_xfr_bytes(card->reader,
+                    event->p.data.data, event->p.data.len,
+                    recv_data,&recv_len);
+            DPRINTF(card, 2, "got back apdu of length %d\n", recv_len);
+            if (reader_status == VREADER_OK) {
+                emulated_push_response_apdu(card, recv_data, recv_len);
+            } else {
+                emulated_push_error(card, reader_status);
+            }
+            free(event);
+        }
+        pthread_mutex_unlock(&card->vreader_mutex);
+    }
+    pthread_mutex_lock(&card->apdu_thread_quit_mutex);
+    pthread_cond_signal(&card->apdu_thread_quit_cond);
+    pthread_mutex_unlock(&card->apdu_thread_quit_mutex);
+    return NULL;
+}
+
+static void *event_thread(void *arg)
+{
+    int atr_len = MAX_ATR_SIZE;
+    uint8_t atr[MAX_ATR_SIZE];
+    VEvent *event = NULL;
+    EmulatedState *card = arg;
+
+    while (1) {
+        const char *reader_name;
+
+        event = vevent_wait_next_vevent();
+        if (event == NULL || event->type == VEVENT_LAST) {
+            break;
+        }
+        if (event->type != VEVENT_READER_INSERT) {
+            if (card->reader == NULL&&   event->reader != NULL) {
+                // Happens after device_add followed by card remove or insert.
+                // XXX: create synthetic add_reader events if vcard_emul_init
+                // already called, which happens if device_del and device_add are
+                // called
+                card->reader = vreader_reference(event->reader);
+            } else {
+                if (event->reader != card->reader) {
+                    fprintf(stderr, "ERROR: wrong reader: quiting event_thread\n");
+                    break;
+                }
+            }
+        }
+        switch (event->type) {
+        case VEVENT_READER_INSERT:
+            /* TODO: take a specific reader. i.e. track which reader
+             * we are seeing here, check it is the one we want (the first,
+             * or by a particular name), and ignore if we don't want it.
+             */
+            reader_name = vreader_get_name(event->reader);
+            if (card->reader != NULL) {
+                DPRINTF(card, 2, "READER INSERT - replacing %s with %s\n",
+                    vreader_get_name(card->reader), reader_name);
+                pthread_mutex_lock(&card->vreader_mutex);
+                vreader_free(card->reader);
+                pthread_mutex_unlock(&card->vreader_mutex);
+                emulated_push_reader_remove(card);
+            }
+            pthread_mutex_lock(&card->vreader_mutex);
+            DPRINTF(card, 2, "READER INSERT %s\n", reader_name);
+            card->reader = vreader_reference(event->reader);
+            pthread_mutex_unlock(&card->vreader_mutex);
+            emulated_push_reader_insert(card);
+            break;
+        case VEVENT_READER_REMOVE:
+            DPRINTF(card, 2, " READER REMOVE: %s \n",
+                    vreader_get_name(event->reader));
+            pthread_mutex_lock(&card->vreader_mutex);
+            vreader_free(card->reader);
+            card->reader = NULL;
+            pthread_mutex_unlock(&card->vreader_mutex);
+            emulated_push_reader_remove(card);
+            break;
+        case VEVENT_CARD_INSERT:
+            /* get the ATR (intended as a response to a power on from the
+             * reader */
+            atr_len = MAX_ATR_SIZE;
+            vreader_power_on(event->reader, atr,&atr_len);
+            card->atr_length = (uint8_t)atr_len;
+            DPRINTF(card, 2, " CARD INSERT\n");
+            emulated_push_card_insert(card, atr, atr_len);
+            break;
+        case VEVENT_CARD_REMOVE:
+            DPRINTF(card, 2, " CARD REMOVE\n");
+            emulated_push_card_remove(card);
+            break;
+        case VEVENT_LAST: /* quit */
+            vevent_delete(event);
+            return NULL;
+            break;
+        default:
+            break;
+        }
+        vevent_delete(event);
+    }
+    return NULL;
+}
+
+static void pipe_read(void *opaque)
+{
+    EmulatedState *card = opaque;
+    EmulEvent *event, *next;
+    char dummy;
+    int len;
+
+    do {
+        len = read(card->pipe[0],&dummy, sizeof(dummy));
+    } while (len == sizeof(dummy));
+    pthread_mutex_lock(&card->event_list_mutex);
+    QSIMPLEQ_FOREACH_SAFE(event,&card->event_list, entry, next) {
+        DPRINTF(card, 2, "event %s\n", emul_event_to_string(event->p.gen.type));
+        switch (event->p.gen.type) {
+            case EMUL_RESPONSE_APDU:
+                ccid_card_send_apdu_to_guest(&card->base, event->p.data.data,
+                    event->p.data.len);
+                break;
+            case EMUL_READER_INSERT:
+                ccid_card_ccid_attach(&card->base);
+                break;
+            case EMUL_READER_REMOVE:
+                ccid_card_ccid_detach(&card->base);
+                break;
+            case EMUL_CARD_INSERT:
+                assert(event->p.data.len<= MAX_ATR_SIZE);
+                card->atr_length = event->p.data.len;
+                memcpy(card->atr, event->p.data.data, card->atr_length);
+                ccid_card_card_inserted(&card->base);
+                break;
+            case EMUL_CARD_REMOVE:
+                ccid_card_card_removed(&card->base);
+                break;
+            case EMUL_ERROR:
+                ccid_card_card_error(&card->base, event->p.error.code);
+                break;
+            default:
+                DPRINTF(card, 2, "unexpected event\n");
+                break;
+        }
+        free(event);
+    }
+    QSIMPLEQ_INIT(&card->event_list);
+    pthread_mutex_unlock(&card->event_list_mutex);
+}
+
+static int init_pipe_signaling(EmulatedState *card)
+{
+   if (pipe(card->pipe)<   0) {
+       DPRINTF(card, 2, "pipe creation failed\n");
+       return -1;
+   }
+   fcntl(card->pipe[0], F_SETFL, O_NONBLOCK);
+   fcntl(card->pipe[1], F_SETFL, O_NONBLOCK);
+   fcntl(card->pipe[0], F_SETOWN, getpid());
+   qemu_set_fd_handler(card->pipe[0], pipe_read, NULL, card);
+   return 0;
+}
+
+#define CERTIFICATES_DEFAULT_DB "/etc/pki/nssdb"
+#define CERTIFICATES_ARGS_TEMPLATE "db=\"%s\" use_hw=no soft=(,Virtual Reader,CAC,,%s,%s,%s)"
+
+static int wrap_vcard_emul_init(VCardEmulOptions *options)
+{
+    static int called = 0;
+    static int options_was_null = 0;
+
+    if (called) {
+        if ((options == NULL) != options_was_null) {
+            printf("%s: warning: running emulated with certificates and emulated side by side is not supported\n", __FUNCTION__);
+            return VCARD_EMUL_FAIL;
+        }
+        vcard_emul_replay_insertion_events();
+        return VCARD_EMUL_OK;
+    }
+    options_was_null = (options == NULL);
+    called = 1;
+    return vcard_emul_init(options);
+}
+
+static int emulated_initialize_vcard_from_certificates(EmulatedState *card)
+{
+    char emul_args[200];
+    VCardEmulOptions *options = NULL;
+
+    snprintf(emul_args, sizeof(emul_args) - 1, CERTIFICATES_ARGS_TEMPLATE,
+        card->db ? card->db : CERTIFICATES_DEFAULT_DB,
+        card->cert1, card->cert2, card->cert3);
+    options = vcard_emul_options(emul_args);
+    if (options == NULL) {
+        printf("%s: warning: not using certificates due to initialization error\n", __func__);
+    }
+    return wrap_vcard_emul_init(options);
+}
+
+static int emulated_initfn(CCIDCardState *base)
+{
+    EmulatedState *card = DO_UPCAST(EmulatedState, base, base);
+    int rv;
+    pthread_t thread_id;
+    VCardEmulError ret;
+
+    QSIMPLEQ_INIT(&card->event_list);
+    QSIMPLEQ_INIT(&card->guest_apdu_list);
+    pthread_mutex_init(&card->event_list_mutex, NULL);
+    pthread_mutex_init(&card->vreader_mutex, NULL);
+    pthread_mutex_init(&card->handle_apdu_mutex, NULL);
+    pthread_cond_init(&card->handle_apdu_cond, NULL);
+    card->reader = NULL;
+    card->quit_apdu_thread = 0;
+    if (init_pipe_signaling(card)<   0) {
+        return -1;
+    }
+    if (!card->backend) {
+        card->backend = strdup((char*)BACKEND_NSS_EMULATED);
+    }
+    /* TODO: a passthru backened that works on local machine. third card type? */
+    if (strcmp(BACKEND_CERTIFICATES, card->backend) == 0
+&&   card->cert1 != NULL&&   card->cert2 != NULL&&   card->cert3 != NULL) {
+        ret = emulated_initialize_vcard_from_certificates(card);
+    } else {
+        if (strcmp(BACKEND_CERTIFICATES, card->backend) == 0) {
+            printf("%s: you must provide all three certs for certificates backend\n",
+                EMULATED_DEV_NAME);
+            return -1;
+        }
+        if (card->backend&&   strcmp(BACKEND_NSS_EMULATED, card->backend) != 0) {
+            printf("%s: bad backend specified. The options are:\n%s (default), %s.\n",
+                EMULATED_DEV_NAME, BACKEND_NSS_EMULATED, BACKEND_CERTIFICATES);
+            return -1;
+        }
+        /* default to mirroring the local hardware readers */
+        ret = wrap_vcard_emul_init(NULL);
+    }
+    if (ret != VCARD_EMUL_OK) {
+        printf("%s: failed to initialize vcard\n", EMULATED_DEV_NAME);
+        return -1;
+    }
Quoted 10 lines

hw/ccid-card-emulated.c line 481

Quoted 6 lines
hw/ccid-card-emulated.c new file +5 -0
+    rv = pthread_create(&thread_id, NULL, event_thread, card);
+    if (rv<   0) {
+        printf("%s: error creating event thread\n", EMULATED_DEV_NAME);
+        return -1;
+    }

Why can't this be implemented with qemu_set_fd_handler? The event thread si just spinning on read.

Quoted 2 lines

The issue is not letting NSS block any of qemu's threads.

I'd rather use a thread pool to execute NSS calls asynchronously. None of QEMU is really thread safe which means you'll have to be really careful about what goes into these threads. I think this leads to code that is very subtle and easy to break.

Regards,

Anthony Liguori

Quoted 73 lines
Quoted 73 lines

Regards,

Anthony Liguori

Quoted 66 lines
hw/ccid-card-emulated.c new file +53 -0
+    rv = pthread_create(&thread_id, NULL, handle_apdu_thread, card);
+    if (rv<   0) {
+        printf("%s: error creating handle_apdu thread\n", EMULATED_DEV_NAME);
+        return -1;
+    }
+    return 0;
+}
+
+static int emulated_exitfn(CCIDCardState *base)
+{
+    EmulatedState *card = DO_UPCAST(EmulatedState, base, base);
+    VEvent *vevent = vevent_new(VEVENT_LAST, NULL, NULL);
+
+    vevent_queue_vevent(vevent); /* stop vevent thread */
+    pthread_mutex_lock(&card->apdu_thread_quit_mutex);
+    card->quit_apdu_thread = 1; /* stop handle_apdu thread */
+    pthread_cond_signal(&card->handle_apdu_cond);
+    pthread_cond_wait(&card->apdu_thread_quit_cond,&card->apdu_thread_quit_mutex);
+    /* handle_apdu thread stopped, can destroy all of it's mutexes */
+    pthread_cond_destroy(&card->handle_apdu_cond);
+    pthread_cond_destroy(&card->apdu_thread_quit_cond);
+    pthread_mutex_destroy(&card->apdu_thread_quit_mutex);
+    pthread_mutex_destroy(&card->handle_apdu_mutex);
+    pthread_mutex_destroy(&card->vreader_mutex);
+    pthread_mutex_destroy(&card->event_list_mutex);
+    return 0;
+}
+
+static CCIDCardInfo emulated_card_info = {
+    .qdev.name = EMULATED_DEV_NAME,
+    .qdev.size = sizeof(EmulatedState),
+    .initfn = emulated_initfn,
+    .exitfn = emulated_exitfn,
+    .get_atr = emulated_get_atr,
+    .apdu_from_guest = emulated_apdu_from_guest,
+    .qdev.unplug    = qdev_simple_unplug_cb,
+    .qdev.props     = (Property[]) {
+        DEFINE_PROP_STRING("backend", EmulatedState, backend),
+        DEFINE_PROP_STRING("cert1", EmulatedState, cert1),
+        DEFINE_PROP_STRING("cert2", EmulatedState, cert2),
+        DEFINE_PROP_STRING("cert3", EmulatedState, cert3),
+        DEFINE_PROP_STRING("db", EmulatedState, db),
+        DEFINE_PROP_UINT8("debug", EmulatedState, debug, 0),
+        DEFINE_PROP_END_OF_LIST(),
+    },
+};
+
+static void ccid_card_emulated_register_devices(void)
+{
+    ccid_card_qdev_register(&emulated_card_info);
+}
+
+device_init(ccid_card_emulated_register_devices)
hw/ccid-card-passthru.c +0 -1
index 6ec4f21..f9fb82c 100644
@@ -253,7 +253,6 @@ static CCIDCardInfo passthru_card_info = {
      .exitfn = passthru_exitfn,
      .get_atr = passthru_get_atr,
      .apdu_from_guest = passthru_apdu_from_guest,
-    .qdev.unplug    = qdev_simple_unplug_cb,
      .qdev.props     = (Property[]) {
          DEFINE_PROP_CHR("chardev", PassthruState, cs),
          DEFINE_PROP_UINT8("debug", PassthruState, debug, 0),
author
#6 lore raw

Re: [Qemu-devel] [PATCH 2/7] ccid: add passthru card device

In reply to Anthony Liguori
Quoted 92 lines · Anthony Liguori
Quoted 91 lines · Alon Levy
Quoted 10 lines · Anthony Liguori

libcacard/vscard_common.h

Quoted 5 lines · Alon Levy
libcacard/vscard_common.h new file +0 -0
new file mode 100644
index 0000000..9ff1295

This file (and the .c file) need a coding style pass to fixup comments and the use of _ as a prefix but I want to focus on the protocol itself.

Quoted 3 lines

First, let's get a written spec into the wiki. I think it's important that all of our compatibility protocols are documented in a more formal way such that can be reviewed by a wider audience.

ok, I'll create Features/Smartcard/Protocol

Quoted 28 lines
Quoted 14 lines
libcacard/vscard_common.h new file +13 -0
@@ -0,0 +1,130 @@
+/* Virtual Smart Card protocol definition
+ *
+ * This protocol is between a host implementing a group of virtual smart card
+ * reader, and a client implementing a virtual smart card, or passthrough to
+ * a real card.
+ *
+ * The current implementation passes the raw APDU's from 7816 and additionally
+ * contains messages to setup and teardown readers, handle insertion and
+ * removal of cards, negotiate the protocol and provide for error responses.
+ *
+ * Copyright (c) 2010 Red Hat.
+ *
+ * This code is licensed under the LGPL.

libcacard/vscard_common.h line 23

Quoted 10 lines
libcacard/vscard_common.h new file +10 -0
+ */
+
+#ifndef _VSCARD_COMMON_H
+#define _VSCARD_COMMON_H
+
+#include<stdint.h>
+
+#define VERSION_MAJOR_BITS 11
+#define VERSION_MIDDLE_BITS 11
+#define VERSION_MINOR_BITS 10

Distros make versioning not enough. Inevitably, someone wants to back port a bug fix or a feature for some RHEL7.2 release or something like that.

Quoted 3 lines

Feature negotiation has worked pretty well for us and I'd suggest using it within the protocol.

Suggestion accepted.

Quoted 24 lines
Quoted 24 lines
libcacard/vscard_common.h new file +24 -0
+#define MAKE_VERSION(major, middle, minor) \
+     (  (major<<   (VERSION_MINOR_BITS + VERSION_MIDDLE_BITS)) \
+      | (middle<<    VERSION_MINOR_BITS) \
+      | (minor)  )
+
+/** IMPORTANT NOTE on VERSION
+ *
+ * The version below MUST be changed whenever a change in this file is made.
+ *
+ * The last digit, the minor, is for bug fix changes only.
+ *
+ * The middle digit is for backward / forward compatible changes, updates
+ * to the existing messages, addition of fields.
+ *
+ * The major digit is for a breaking change of protocol, presumably
+ * something that cannot be accomodated with the existing protocol.
+ */
+
+#define VSCARD_VERSION MAKE_VERSION(0,0,1)
+
+typedef enum {
+    VSC_Init,
+    VSC_Error,
+    VSC_ReaderAdd,
Quoted 8 lines

libcacard/vscard_common.h line 55

Quoted 7 lines
libcacard/vscard_common.h new file +7 -0
+    VSC_ReaderAddResponse,
+    VSC_ReaderRemove,
+    VSC_ATR,
+    VSC_CardRemove,
+    VSC_APDU,
+    VSC_Reconnect
+} VSCMsgType;

Should number the enum to be specific at least.

will fix.

Quoted 8 lines

libcacard/vscard_common.h line 62

Quoted 7 lines
libcacard/vscard_common.h new file +7 -0
+
+typedef enum {
+    VSC_GENERAL_ERROR=1,
+    VSC_CANNOT_ADD_MORE_READERS,
+} VSCErrorCode;
+
+typedef uint32_t reader_id_t;

This namespace is reserved by C.

Quoted 6 lines
Quoted 1 line

reader_id_t is reserved?

Anything with the suffix '_t' is reserved by the standard library.

It's a widely violated rule, but we have run into problems from not obeying it.

I thought qemu coding style said something explicitly about using _t for types that alias basic types - this is actually a change I did to comply..

Quoted 9 lines
Quoted 9 lines
Quoted 9 lines

libcacard/vscard_common.h line 91

Quoted 7 lines
libcacard/vscard_common.h new file +6 -0
+/* VSCMsgReaderAdd          Client ->   Host
+ * Host replies with allocated reader id in ReaderAddResponse
+ * name - name of the reader on client side.
+ * */
+typedef struct VSCMsgReaderAdd {
+    uint8_t    name[0];

Is this a string?

Quoted 3 lines
Quoted 1 line

Yes. You expect char?

Yes, also, what's the encoding (UTF-8)?

It's not actually printed anywhere right now, so I'd say unspecififed. I'll document UTF-8.

Quoted 5 lines

Regards,

Anthony Liguori

author
#7 lore raw

Re: [Qemu-devel] [PATCH 2/7] ccid: add passthru card device

In reply to Anthony Liguori
Quoted 91 lines · Anthony Liguori

libcacard/vscard_common.h

Quoted 5 lines · Alon Levy
libcacard/vscard_common.h new file +0 -0
new file mode 100644
index 0000000..9ff1295

This file (and the .c file) need a coding style pass to fixup comments and the use of _ as a prefix but I want to focus on the protocol itself.

First, let's get a written spec into the wiki. I think it's important that all of our compatibility protocols are documented in a more formal way such that can be reviewed by a wider audience.

Quoted 14 lines
libcacard/vscard_common.h new file +13 -0
@@ -0,0 +1,130 @@
+/* Virtual Smart Card protocol definition
+ *
+ * This protocol is between a host implementing a group of virtual smart card
+ * reader, and a client implementing a virtual smart card, or passthrough to
+ * a real card.
+ *
+ * The current implementation passes the raw APDU's from 7816 and additionally
+ * contains messages to setup and teardown readers, handle insertion and
+ * removal of cards, negotiate the protocol and provide for error responses.
+ *
+ * Copyright (c) 2010 Red Hat.
+ *
+ * This code is licensed under the LGPL.

libcacard/vscard_common.h line 23

Quoted 10 lines
libcacard/vscard_common.h new file +10 -0
+ */
+
+#ifndef _VSCARD_COMMON_H
+#define _VSCARD_COMMON_H
+
+#include<stdint.h>
+
+#define VERSION_MAJOR_BITS 11
+#define VERSION_MIDDLE_BITS 11
+#define VERSION_MINOR_BITS 10

Distros make versioning not enough. Inevitably, someone wants to back port a bug fix or a feature for some RHEL7.2 release or something like that.

Feature negotiation has worked pretty well for us and I'd suggest using it within the protocol.

Quoted 21 lines
libcacard/vscard_common.h new file +21 -0
+#define MAKE_VERSION(major, middle, minor) \
+     (  (major<<  (VERSION_MINOR_BITS + VERSION_MIDDLE_BITS)) \
+      | (middle<<   VERSION_MINOR_BITS) \
+      | (minor)  )
+
+/** IMPORTANT NOTE on VERSION
+ *
+ * The version below MUST be changed whenever a change in this file is made.
+ *
+ * The last digit, the minor, is for bug fix changes only.
+ *
+ * The middle digit is for backward / forward compatible changes, updates
+ * to the existing messages, addition of fields.
+ *
+ * The major digit is for a breaking change of protocol, presumably
+ * something that cannot be accomodated with the existing protocol.
+ */
+
+#define VSCARD_VERSION MAKE_VERSION(0,0,1)
+
+typedef enum {

libcacard/vscard_common.h line 55

Quoted 10 lines
libcacard/vscard_common.h new file +10 -0
+    VSC_Init,
+    VSC_Error,
+    VSC_ReaderAdd,
+    VSC_ReaderAddResponse,
+    VSC_ReaderRemove,
+    VSC_ATR,
+    VSC_CardRemove,
+    VSC_APDU,
+    VSC_Reconnect
+} VSCMsgType;

Should number the enum to be specific at least.

libcacard/vscard_common.h line 62

Quoted 7 lines
libcacard/vscard_common.h new file +7 -0
+
+typedef enum {
+    VSC_GENERAL_ERROR=1,
+    VSC_CANNOT_ADD_MORE_READERS,
+} VSCErrorCode;
+
+typedef uint32_t reader_id_t;

This namespace is reserved by C.

Quoted 10 lines

libcacard/vscard_common.h line 69

Quoted 7 lines
libcacard/vscard_common.h new file +7 -0
+#define VSCARD_UNDEFINED_READER_ID 0xffffffff
+#define VSCARD_MINIMAL_READER_ID    0
+
+typedef struct VSCMsgHeader {
+    VSCMsgType type;
+    reader_id_t   reader_id;
+    uint32_t   length;

Is length just the data length or the whole message length?

The data length. Is this enough to document?

Quoted 54 lines
Quoted 12 lines
libcacard/vscard_common.h new file +12 -0
+    uint8_t    data[0];
+} VSCMsgHeader;
+
+/* VSCMsgInit               Client<->  Host
+ * Host replies with allocated reader id in ReaderAddResponse
+ * */
+typedef struct VSCMsgInit {
+    uint32_t   version;
+} VSCMsgInit;
+
+/* VSCMsgError              Client<->  Host
+ * */

libcacard/vscard_common.h line 91

Quoted 10 lines
libcacard/vscard_common.h new file +10 -0
+typedef struct VSCMsgError {
+    uint32_t   code;
+} VSCMsgError;
+
+/* VSCMsgReaderAdd          Client ->  Host
+ * Host replies with allocated reader id in ReaderAddResponse
+ * name - name of the reader on client side.
+ * */
+typedef struct VSCMsgReaderAdd {
+    uint8_t    name[0];

Is this a string?

Quoted 29 lines
libcacard/vscard_common.h new file +29 -0
+} VSCMsgReaderAdd;
+
+/* VSCMsgReaderAddResponse  Host ->  Client
+ * Reply to ReaderAdd
+ * */
+typedef struct VSCMsgReaderAddResponse {
+} VSCMsgReaderAddResponse;
+
+/* VSCMsgReaderRemove       Client ->  Host
+ * */
+typedef struct VSCMsgReaderRemove {
+} VSCMsgReaderRemove;
+
+/* VSCMsgATR                Client ->  Host
+ * Answer to reset. Sent for card insertion or card reset.
+ * */
+typedef struct VSCMsgATR {
+    uint8_t     atr[0];
+} VSCMsgATR;
+
+/* VSCMsgCardRemove         Client ->  Host
+ * */
+typedef struct VSCMsgCardRemove {
+} VSCMsgCardRemove;
+
+/* VSCMsgAPDU               Client<->  Host
+ * */
+typedef struct VSCMsgAPDU {
+    uint8_t    data[0];
Quoted 8 lines

libcacard/vscard_common.h line 126

Quoted 6 lines
libcacard/vscard_common.h new file +6 -0
+} VSCMsgAPDU;
+
+/* VSCMsgReconnect          Host ->  Client
+ * */
+typedef struct VSCMsgReconnect {
+    uint32_t   ip;

This is not ipv6 friendly. Two strings would be a better choice.

A string for host makes sense, why for port? isn't a 32 bit port enough?

Quoted 10 lines

Regards,

Anthony Liguori

Quoted 4 lines
libcacard/vscard_common.h new file +4 -0
+    uint16_t   port;
+} VSCMsgReconnect;
+
+#endif
#8 lore raw

Re: [Qemu-devel] [PATCH 2/7] ccid: add passthru card device

Quoted 4 lines · Alon Levy
Quoted 2 lines

This is not ipv6 friendly. Two strings would be a better choice.

A string for host makes sense, why for port? isn't a 32 bit port enough?

For an protocol, an integer is probably fine. For an API, a string is nice to allow service names too.

Regards,

Anthony Liguori

Quoted 11 lines
Quoted 11 lines

Regards,

Anthony Liguori

Quoted 5 lines
libcacard/vscard_common.h new file +4 -0
+    uint16_t   port;
+} VSCMsgReconnect;
+
+#endif
author
#9 lore raw

Re: [Qemu-devel] [PATCH 2/7] ccid: add passthru card device

In reply to Anthony Liguori
Quoted 11 lines · Anthony Liguori

libcacard/vscard_common.h

Quoted 5 lines · Alon Levy
libcacard/vscard_common.h new file +0 -0
new file mode 100644
index 0000000..9ff1295

This file (and the .c file) need a coding style pass to fixup comments and the use of _ as a prefix but I want to focus on the protocol itself.

Quoted 3 lines

First, let's get a written spec into the wiki. I think it's important that all of our compatibility protocols are documented in a more formal way such that can be reviewed by a wider audience.

http://wiki.qeum.org/Features/Smartcard

I'm still working on the rest, but you can review and comment on it. I've done a number of changes from the submitted here. I guess the idea is that iterations on the wiki can be faster? The changes done to the protocol:

Removed Reconnect - doesn't scale easily, the same work should be done
by whomever is initiating the migration, or via other mechanisms (i.e. spice)
Added Flush/FlushComplete - still need to be able to tell client to wrap
up the outstanding operations in any way. I'm planning on implementing this using register_savevm_live.
Fixes suggested by you - set the enum, removed _ from surrounding #ifdef
(btw - why does no one use #pragma once? IIUC it's supported by gcc?)

The major issue I haven't tackled yet is the thread removal in ccid-card-emulated.c is that a blocker for integration? Can it be tackled later?

Alon

[snip]

author
#18 lore raw

Re: [Qemu-devel] [PATCH 4/7] ccid: add ccid-card-emulated device (v2)

In reply to Anthony Liguori
Quoted 515 lines · Anthony Liguori
Quoted 514 lines · Alon Levy

This devices uses libcacard (internal) to emulate a smartcard conforming to the CAC standard. It attaches to the usb-ccid bus. Usage instructions (example command lines) are in the following patch in docs/ccid.txt. It uses libcacard which uses nss, so it can work with both hw cards and certificates (files).

changes from v1:
remove stale comments, use only c-style comments bugfix, forgot to set recv_len
change reader name to 'Virtual Reader'

---
 Makefile.objs           |    2 +-
 hw/ccid-card-emulated.c |  534 +++++++++++++++++++++++++++++++++++++++++++++++
 hw/ccid-card-passthru.c |    1 -
 3 files changed, 535 insertions(+), 2 deletions(-)
 create mode 100644 hw/ccid-card-emulated.c
Makefile.objs +1 -1
index 6a0030b..303b642 100644
@@ -197,7 +197,7 @@ hw-obj-$(CONFIG_FDC) += fdc.o
 hw-obj-$(CONFIG_ACPI) += acpi.o acpi_piix4.o
 hw-obj-$(CONFIG_APM) += pm_smbus.o apm.o
 hw-obj-$(CONFIG_DMA) += dma.o
-hw-obj-$(CONFIG_SMARTCARD) += usb-ccid.o ccid-card-passthru.o
+hw-obj-$(CONFIG_SMARTCARD) += usb-ccid.o ccid-card-passthru.o ccid-card-emulated.o
 
 # PPC devices
 hw-obj-$(CONFIG_OPENPIC) += openpic.o
hw/ccid-card-emulated.c new file +476 -0
new file mode 100644
index 0000000..5531ce1
@@ -0,0 +1,534 @@
+/*
+ * CCID Card Device. Emulated card.
+ *
+ * It can be used to provide access to the local hardware in a non exclusive
+ * way, or it can use certificates. It requires the usb-ccid bus.
+ *
+ * Usage 1: standard, mirror hardware reader+card:
+ * qemu .. -usb -device usb-ccid -device ccid-card-emulated
+ *
+ * Usage 2: use certificates, no hardware required
+ * one time: create the certificates:
+ *  for i in 1 2 3; do certutil -d /etc/pki/nssdb -x -t "CT,CT,CT" -S -s "CN=user$i" -n user$i; done
+ * qemu .. -usb -device usb-ccid -device ccid-card-emulated,cert1=user1,cert2=user2,cert3=user3
+ *
+ * If you use a non default db for the certificates you can specify it using the db parameter.
+ *
+ *
+ * Copyright (c) 2010 Red Hat.
+ * Written by Alon Levy.
+ *
+ * This code is licenced under the LGPL.
+ */
+
+#include<pthread.h>
+#include<eventt.h>
+#include<vevent.h>
+#include<vreader.h>
+#include<vcard_emul.h>
+#include "qemu-char.h"
+#include "monitor.h"
+#include "hw/ccid.h"
+
+#define DPRINTF(card, lvl, fmt, ...) \
+do { if (lvl<= card->debug) { printf("ccid-card-emul: %s: " fmt , __func__, ## __VA_ARGS__); } } while (0)
+
+#define EMULATED_DEV_NAME "ccid-card-emulated"
+
+#define BACKEND_NSS_EMULATED "nss-emulated" /* the default */
+#define BACKEND_CERTIFICATES "certificates"
+
+typedef struct EmulatedState EmulatedState;
+
+enum {
+    EMUL_READER_INSERT = 0,
+    EMUL_READER_REMOVE,
+    EMUL_CARD_INSERT,
+    EMUL_CARD_REMOVE,
+    EMUL_GUEST_APDU,
+    EMUL_RESPONSE_APDU,
+    EMUL_ERROR,
+};
+
+static const char* emul_event_to_string(uint32_t emul_event)
+{
+    switch (emul_event) {
+        case EMUL_READER_INSERT: return "EMUL_READER_INSERT";
+        case EMUL_READER_REMOVE: return "EMUL_READER_REMOVE";
+        case EMUL_CARD_INSERT: return "EMUL_CARD_INSERT";
+        case EMUL_CARD_REMOVE: return "EMUL_CARD_REMOVE";
+        case EMUL_GUEST_APDU: return "EMUL_GUEST_APDU";
+        case EMUL_RESPONSE_APDU: return "EMUL_RESPONSE_APDU";
+        case EMUL_ERROR: return "EMUL_ERROR";
+        default:
+            break;
+    }
+    return "UNKNOWN";
+}
+
+typedef struct EmulEvent {
+    QSIMPLEQ_ENTRY(EmulEvent) entry;
+    union {
+        struct {
+            uint32_t type;
+        } gen;
+        struct {
+            uint32_t type;
+            uint64_t code;
+        } error;
+        struct {
+            uint32_t type;
+            uint32_t len;
+            uint8_t data[];
+        } data;
+    } p;
+} EmulEvent;
+
+#define MAX_ATR_SIZE 40
+struct EmulatedState {
+    CCIDCardState base;
+    uint8_t  debug;
+    char*    backend;
+    char*    cert1;
+    char*    cert2;
+    char*    cert3;
+    char*    db;
+    uint8_t  atr[MAX_ATR_SIZE];
+    uint8_t  atr_length;
+    QSIMPLEQ_HEAD(event_list, EmulEvent) event_list;
+    pthread_mutex_t event_list_mutex;
+    VReader *reader;
+    QSIMPLEQ_HEAD(guest_apdu_list, EmulEvent) guest_apdu_list;
+    pthread_mutex_t vreader_mutex; /* and guest_apdu_list mutex */
+    pthread_mutex_t handle_apdu_mutex;
+    pthread_cond_t handle_apdu_cond;
+    int      pipe[2];
+    int      quit_apdu_thread;
+    pthread_mutex_t apdu_thread_quit_mutex;
+    pthread_cond_t apdu_thread_quit_cond;
+};
+
+static void emulated_apdu_from_guest(CCIDCardState *base, const uint8_t *apdu, uint32_t len)
+{
+    EmulatedState *card = DO_UPCAST(EmulatedState, base, base);
+    EmulEvent *event = (EmulEvent*)malloc(sizeof(EmulEvent) + len);
+
+    assert(event);
+    event->p.data.type = EMUL_GUEST_APDU;
+    event->p.data.len = len;
+    memcpy(event->p.data.data, apdu, len);
+    pthread_mutex_lock(&card->vreader_mutex);
+    QSIMPLEQ_INSERT_TAIL(&card->guest_apdu_list, event, entry);
+    pthread_mutex_unlock(&card->vreader_mutex);
+    pthread_mutex_lock(&card->handle_apdu_mutex);
+    pthread_cond_signal(&card->handle_apdu_cond);
+    pthread_mutex_unlock(&card->handle_apdu_mutex);
+}
+
+static const uint8_t* emulated_get_atr(CCIDCardState *base, uint32_t *len)
+{
+    EmulatedState *card = DO_UPCAST(EmulatedState, base, base);
+
+    *len = card->atr_length;
+    return card->atr;
+}
+
+static void emulated_push_event(EmulatedState *card, EmulEvent *event)
+{
+    pthread_mutex_lock(&card->event_list_mutex);
+    QSIMPLEQ_INSERT_TAIL(&(card->event_list), event, entry);
+    pthread_mutex_unlock(&card->event_list_mutex);
+    if (write(card->pipe[1], card, 1) != 1) {
+        DPRINTF(card, 1, "write to pipe failed\n");
+    }
+}
+
+static void emulated_push_type(EmulatedState *card, uint32_t type)
+{
+    EmulEvent *event = (EmulEvent*)malloc(sizeof(EmulEvent));
+
+    assert(event);
+    event->p.gen.type = type;
+    emulated_push_event(card, event);
+}
+
+static void emulated_push_error(EmulatedState *card, uint64_t code)
+{
+    EmulEvent *event = (EmulEvent*)malloc(sizeof(EmulEvent));
+
+    assert(event);
+    event->p.error.type = EMUL_ERROR;
+    event->p.error.code = code;
+    emulated_push_event(card, event);
+}
+
+static void emulated_push_data_type(EmulatedState *card, uint32_t type,
+    const uint8_t *data, uint32_t len)
+{
+    EmulEvent *event = (EmulEvent*)malloc(sizeof(EmulEvent) + len);
+
+    assert(event);
+    event->p.data.type = type;
+    event->p.data.len = len;
+    memcpy(event->p.data.data, data, len);
+    emulated_push_event(card, event);
+}
+
+static void emulated_push_reader_insert(EmulatedState *card)
+{
+    emulated_push_type(card, EMUL_READER_INSERT);
+}
+
+static void emulated_push_reader_remove(EmulatedState *card)
+{
+    emulated_push_type(card, EMUL_READER_REMOVE);
+}
+
+static void emulated_push_card_insert(EmulatedState *card,
+    const uint8_t *atr, uint32_t len)
+{
+    emulated_push_data_type(card, EMUL_CARD_INSERT, atr, len);
+}
+
+static void emulated_push_card_remove(EmulatedState *card)
+{
+    emulated_push_type(card, EMUL_CARD_REMOVE);
+}
+
+static void emulated_push_response_apdu(EmulatedState *card,
+    const uint8_t* apdu, uint32_t len)
+{
+    emulated_push_data_type(card, EMUL_RESPONSE_APDU, apdu, len);
+}
+
+#define APDU_BUF_SIZE 270
+static void *handle_apdu_thread(void* arg)
+{
+    EmulatedState *card = arg;
+    uint8_t recv_data[APDU_BUF_SIZE];
+    int recv_len;
+    VReaderStatus reader_status;
+    EmulEvent *event;
+
+    while (1) {
+        pthread_mutex_lock(&card->handle_apdu_mutex);
+        pthread_cond_wait(&card->handle_apdu_cond,&card->handle_apdu_mutex);
+        pthread_mutex_unlock(&card->handle_apdu_mutex);
+        if (card->quit_apdu_thread) {
+            card->quit_apdu_thread = 0; // debugging
+            break;
+        }
+        pthread_mutex_lock(&card->vreader_mutex);
+        while (!QSIMPLEQ_EMPTY(&card->guest_apdu_list)) {
+            event = QSIMPLEQ_FIRST(&card->guest_apdu_list);
+            assert((unsigned long)event>  1000);
+            QSIMPLEQ_REMOVE_HEAD(&card->guest_apdu_list, entry);
+            if (event->p.data.type != EMUL_GUEST_APDU) {
+                DPRINTF(card, 1, "unexpected message in handle_apdu_thread\n");
+                free(event);
+                continue;
+            }
+            if (card->reader == NULL) {
+                DPRINTF(card, 1, "reader is NULL\n");
+                free(event);
+                continue;
+            }
+            recv_len = sizeof(recv_data);
+            reader_status = vreader_xfr_bytes(card->reader,
+                    event->p.data.data, event->p.data.len,
+                    recv_data,&recv_len);
+            DPRINTF(card, 2, "got back apdu of length %d\n", recv_len);
+            if (reader_status == VREADER_OK) {
+                emulated_push_response_apdu(card, recv_data, recv_len);
+            } else {
+                emulated_push_error(card, reader_status);
+            }
+            free(event);
+        }
+        pthread_mutex_unlock(&card->vreader_mutex);
+    }
+    pthread_mutex_lock(&card->apdu_thread_quit_mutex);
+    pthread_cond_signal(&card->apdu_thread_quit_cond);
+    pthread_mutex_unlock(&card->apdu_thread_quit_mutex);
+    return NULL;
+}
+
+static void *event_thread(void *arg)
+{
+    int atr_len = MAX_ATR_SIZE;
+    uint8_t atr[MAX_ATR_SIZE];
+    VEvent *event = NULL;
+    EmulatedState *card = arg;
+
+    while (1) {
+        const char *reader_name;
+
+        event = vevent_wait_next_vevent();
+        if (event == NULL || event->type == VEVENT_LAST) {
+            break;
+        }
+        if (event->type != VEVENT_READER_INSERT) {
+            if (card->reader == NULL&&  event->reader != NULL) {
+                // Happens after device_add followed by card remove or insert.
+                // XXX: create synthetic add_reader events if vcard_emul_init
+                // already called, which happens if device_del and device_add are
+                // called
+                card->reader = vreader_reference(event->reader);
+            } else {
+                if (event->reader != card->reader) {
+                    fprintf(stderr, "ERROR: wrong reader: quiting event_thread\n");
+                    break;
+                }
+            }
+        }
+        switch (event->type) {
+        case VEVENT_READER_INSERT:
+            /* TODO: take a specific reader. i.e. track which reader
+             * we are seeing here, check it is the one we want (the first,
+             * or by a particular name), and ignore if we don't want it.
+             */
+            reader_name = vreader_get_name(event->reader);
+            if (card->reader != NULL) {
+                DPRINTF(card, 2, "READER INSERT - replacing %s with %s\n",
+                    vreader_get_name(card->reader), reader_name);
+                pthread_mutex_lock(&card->vreader_mutex);
+                vreader_free(card->reader);
+                pthread_mutex_unlock(&card->vreader_mutex);
+                emulated_push_reader_remove(card);
+            }
+            pthread_mutex_lock(&card->vreader_mutex);
+            DPRINTF(card, 2, "READER INSERT %s\n", reader_name);
+            card->reader = vreader_reference(event->reader);
+            pthread_mutex_unlock(&card->vreader_mutex);
+            emulated_push_reader_insert(card);
+            break;
+        case VEVENT_READER_REMOVE:
+            DPRINTF(card, 2, " READER REMOVE: %s \n",
+                    vreader_get_name(event->reader));
+            pthread_mutex_lock(&card->vreader_mutex);
+            vreader_free(card->reader);
+            card->reader = NULL;
+            pthread_mutex_unlock(&card->vreader_mutex);
+            emulated_push_reader_remove(card);
+            break;
+        case VEVENT_CARD_INSERT:
+            /* get the ATR (intended as a response to a power on from the
+             * reader */
+            atr_len = MAX_ATR_SIZE;
+            vreader_power_on(event->reader, atr,&atr_len);
+            card->atr_length = (uint8_t)atr_len;
+            DPRINTF(card, 2, " CARD INSERT\n");
+            emulated_push_card_insert(card, atr, atr_len);
+            break;
+        case VEVENT_CARD_REMOVE:
+            DPRINTF(card, 2, " CARD REMOVE\n");
+            emulated_push_card_remove(card);
+            break;
+        case VEVENT_LAST: /* quit */
+            vevent_delete(event);
+            return NULL;
+            break;
+        default:
+            break;
+        }
+        vevent_delete(event);
+    }
+    return NULL;
+}
+
+static void pipe_read(void *opaque)
+{
+    EmulatedState *card = opaque;
+    EmulEvent *event, *next;
+    char dummy;
+    int len;
+
+    do {
+        len = read(card->pipe[0],&dummy, sizeof(dummy));
+    } while (len == sizeof(dummy));
+    pthread_mutex_lock(&card->event_list_mutex);
+    QSIMPLEQ_FOREACH_SAFE(event,&card->event_list, entry, next) {
+        DPRINTF(card, 2, "event %s\n", emul_event_to_string(event->p.gen.type));
+        switch (event->p.gen.type) {
+            case EMUL_RESPONSE_APDU:
+                ccid_card_send_apdu_to_guest(&card->base, event->p.data.data,
+                    event->p.data.len);
+                break;
+            case EMUL_READER_INSERT:
+                ccid_card_ccid_attach(&card->base);
+                break;
+            case EMUL_READER_REMOVE:
+                ccid_card_ccid_detach(&card->base);
+                break;
+            case EMUL_CARD_INSERT:
+                assert(event->p.data.len<= MAX_ATR_SIZE);
+                card->atr_length = event->p.data.len;
+                memcpy(card->atr, event->p.data.data, card->atr_length);
+                ccid_card_card_inserted(&card->base);
+                break;
+            case EMUL_CARD_REMOVE:
+                ccid_card_card_removed(&card->base);
+                break;
+            case EMUL_ERROR:
+                ccid_card_card_error(&card->base, event->p.error.code);
+                break;
+            default:
+                DPRINTF(card, 2, "unexpected event\n");
+                break;
+        }
+        free(event);
+    }
+    QSIMPLEQ_INIT(&card->event_list);
+    pthread_mutex_unlock(&card->event_list_mutex);
+}
+
+static int init_pipe_signaling(EmulatedState *card)
+{
+   if (pipe(card->pipe)<  0) {
+       DPRINTF(card, 2, "pipe creation failed\n");
+       return -1;
+   }
+   fcntl(card->pipe[0], F_SETFL, O_NONBLOCK);
+   fcntl(card->pipe[1], F_SETFL, O_NONBLOCK);
+   fcntl(card->pipe[0], F_SETOWN, getpid());
+   qemu_set_fd_handler(card->pipe[0], pipe_read, NULL, card);
+   return 0;
+}
+
+#define CERTIFICATES_DEFAULT_DB "/etc/pki/nssdb"
+#define CERTIFICATES_ARGS_TEMPLATE "db=\"%s\" use_hw=no soft=(,Virtual Reader,CAC,,%s,%s,%s)"
+
+static int wrap_vcard_emul_init(VCardEmulOptions *options)
+{
+    static int called = 0;
+    static int options_was_null = 0;
+
+    if (called) {
+        if ((options == NULL) != options_was_null) {
+            printf("%s: warning: running emulated with certificates and emulated side by side is not supported\n", __FUNCTION__);
+            return VCARD_EMUL_FAIL;
+        }
+        vcard_emul_replay_insertion_events();
+        return VCARD_EMUL_OK;
+    }
+    options_was_null = (options == NULL);
+    called = 1;
+    return vcard_emul_init(options);
+}
+
+static int emulated_initialize_vcard_from_certificates(EmulatedState *card)
+{
+    char emul_args[200];
+    VCardEmulOptions *options = NULL;
+
+    snprintf(emul_args, sizeof(emul_args) - 1, CERTIFICATES_ARGS_TEMPLATE,
+        card->db ? card->db : CERTIFICATES_DEFAULT_DB,
+        card->cert1, card->cert2, card->cert3);
+    options = vcard_emul_options(emul_args);
+    if (options == NULL) {
+        printf("%s: warning: not using certificates due to initialization error\n", __func__);
+    }
+    return wrap_vcard_emul_init(options);
+}
+
+static int emulated_initfn(CCIDCardState *base)
+{
+    EmulatedState *card = DO_UPCAST(EmulatedState, base, base);
+    int rv;
+    pthread_t thread_id;
+    VCardEmulError ret;
+
+    QSIMPLEQ_INIT(&card->event_list);
+    QSIMPLEQ_INIT(&card->guest_apdu_list);
+    pthread_mutex_init(&card->event_list_mutex, NULL);
+    pthread_mutex_init(&card->vreader_mutex, NULL);
+    pthread_mutex_init(&card->handle_apdu_mutex, NULL);
+    pthread_cond_init(&card->handle_apdu_cond, NULL);
+    card->reader = NULL;
+    card->quit_apdu_thread = 0;
+    if (init_pipe_signaling(card)<  0) {
+        return -1;
+    }
+    if (!card->backend) {
+        card->backend = strdup((char*)BACKEND_NSS_EMULATED);
+    }
+    /* TODO: a passthru backened that works on local machine. third card type? */
+    if (strcmp(BACKEND_CERTIFICATES, card->backend) == 0
+&&  card->cert1 != NULL&&  card->cert2 != NULL&&  card->cert3 != NULL) {
+        ret = emulated_initialize_vcard_from_certificates(card);
+    } else {
+        if (strcmp(BACKEND_CERTIFICATES, card->backend) == 0) {
+            printf("%s: you must provide all three certs for certificates backend\n",
+                EMULATED_DEV_NAME);
+            return -1;
+        }
+        if (card->backend&&  strcmp(BACKEND_NSS_EMULATED, card->backend) != 0) {
+            printf("%s: bad backend specified. The options are:\n%s (default), %s.\n",
+                EMULATED_DEV_NAME, BACKEND_NSS_EMULATED, BACKEND_CERTIFICATES);
+            return -1;
+        }
+        /* default to mirroring the local hardware readers */
+        ret = wrap_vcard_emul_init(NULL);
+    }
+    if (ret != VCARD_EMUL_OK) {
+        printf("%s: failed to initialize vcard\n", EMULATED_DEV_NAME);
+        return -1;
+    }
Quoted 9 lines

hw/ccid-card-emulated.c line 481

Quoted 5 lines
hw/ccid-card-emulated.c new file +5 -0
+    rv = pthread_create(&thread_id, NULL, event_thread, card);
+    if (rv<  0) {
+        printf("%s: error creating event thread\n", EMULATED_DEV_NAME);
+        return -1;
+    }

Why can't this be implemented with qemu_set_fd_handler? The event thread si just spinning on read.

I've looked a little more closely at why I did it exactly this way.

The short answer is that both threads are not spinning, they are waiting on conditions, the event_thread on the libcacard vevent_queue condition, and the apdu_thread on the ccid-card-emulated internal guest_apdu queue condition, triggered by the main thread.

This is the ccid-card-emulated threads and flow (hope it's understandable):

libcacard details:

vcard_emul_event_thread for each reader
blocking on SECMOD_WaitForAnyTokenEvent
pushes events to vevent queue

ccid-card-emulated details:

event_thread
read vevent queue -> {reader,card}x{insert,remove} -> write to apdu_pipe

(writes to apdu_pipe are mutex protected)

handle_apdu_thread
pop guest_apdu_list -> vreader_xfr_bytes -> write result to apdu_pipe

main_thread
usb event
apdu from guest -> push to guest_apdu_list
apdu_pipe read
apdu to guest
ccid attach
ccid detach
ccid card removed
ccid card inserted

If I had a mechanism to let the qemu main loop wait on a mutex or condition variable I could remove both event_thread and handle_apdu_thread. (reading a little more about this let me to believe the solution I came up with, i.e. a queue and a condition variable, is commonly used for this in POSIX).

But right now:
I need a separate thread to block on the vevent queue condition (pthread_cond_t/CONDITION_VARIABLE in linux/windows). I need a separate thread to call vreader_xfr_bytes (it may block on the NSS thread).

Alternatives:
launch a thread for each apdu from guest:
since the apdu's are linear any way (i.e. each one would wait for the next) this seems wasteful.
Since we need to wait on a condition signaled by NSS, there is no alternative then having a separate thread for that.

Alon

Quoted 70 lines

Regards,

Anthony Liguori

Quoted 65 lines
hw/ccid-card-emulated.c new file +53 -0
+    rv = pthread_create(&thread_id, NULL, handle_apdu_thread, card);
+    if (rv<  0) {
+        printf("%s: error creating handle_apdu thread\n", EMULATED_DEV_NAME);
+        return -1;
+    }
+    return 0;
+}
+
+static int emulated_exitfn(CCIDCardState *base)
+{
+    EmulatedState *card = DO_UPCAST(EmulatedState, base, base);
+    VEvent *vevent = vevent_new(VEVENT_LAST, NULL, NULL);
+
+    vevent_queue_vevent(vevent); /* stop vevent thread */
+    pthread_mutex_lock(&card->apdu_thread_quit_mutex);
+    card->quit_apdu_thread = 1; /* stop handle_apdu thread */
+    pthread_cond_signal(&card->handle_apdu_cond);
+    pthread_cond_wait(&card->apdu_thread_quit_cond,&card->apdu_thread_quit_mutex);
+    /* handle_apdu thread stopped, can destroy all of it's mutexes */
+    pthread_cond_destroy(&card->handle_apdu_cond);
+    pthread_cond_destroy(&card->apdu_thread_quit_cond);
+    pthread_mutex_destroy(&card->apdu_thread_quit_mutex);
+    pthread_mutex_destroy(&card->handle_apdu_mutex);
+    pthread_mutex_destroy(&card->vreader_mutex);
+    pthread_mutex_destroy(&card->event_list_mutex);
+    return 0;
+}
+
+static CCIDCardInfo emulated_card_info = {
+    .qdev.name = EMULATED_DEV_NAME,
+    .qdev.size = sizeof(EmulatedState),
+    .initfn = emulated_initfn,
+    .exitfn = emulated_exitfn,
+    .get_atr = emulated_get_atr,
+    .apdu_from_guest = emulated_apdu_from_guest,
+    .qdev.unplug    = qdev_simple_unplug_cb,
+    .qdev.props     = (Property[]) {
+        DEFINE_PROP_STRING("backend", EmulatedState, backend),
+        DEFINE_PROP_STRING("cert1", EmulatedState, cert1),
+        DEFINE_PROP_STRING("cert2", EmulatedState, cert2),
+        DEFINE_PROP_STRING("cert3", EmulatedState, cert3),
+        DEFINE_PROP_STRING("db", EmulatedState, db),
+        DEFINE_PROP_UINT8("debug", EmulatedState, debug, 0),
+        DEFINE_PROP_END_OF_LIST(),
+    },
+};
+
+static void ccid_card_emulated_register_devices(void)
+{
+    ccid_card_qdev_register(&emulated_card_info);
+}
+
+device_init(ccid_card_emulated_register_devices)
hw/ccid-card-passthru.c +0 -1
index 6ec4f21..f9fb82c 100644
@@ -253,7 +253,6 @@ static CCIDCardInfo passthru_card_info = {
     .exitfn = passthru_exitfn,
     .get_atr = passthru_get_atr,
     .apdu_from_guest = passthru_apdu_from_guest,
-    .qdev.unplug    = qdev_simple_unplug_cb,
     .qdev.props     = (Property[]) {
         DEFINE_PROP_CHR("chardev", PassthruState, cs),
         DEFINE_PROP_UINT8("debug", PassthruState, debug, 0),