Skip to contentSkip to conversation

CCID smartcard reader fixes

PATCH In review Marc-André Lureau 2 participants 41 messages Aug 5 – Sep 30

lore
Share & tools
lore
#0 lore raw

cover CCID smartcard reader fixes

Hi,

While tackling some CVEs issues, I also found several correctness and robustness improvements/fixes. The series:

- has 3 CVE fixes (OOB/assert)
- fixes xHCI compatibility
- some endianness fixes
- blocks & fixes migration
- better spec compliancy

Tested on Linux with pcscd and Windows with OpenSC.

---
Marc-André Lureau (27):
hw/usb/dev-smartcard-reader: validate interrupt transfer length hw/usb/dev-smartcard-reader: fix OOB read from pending bulk-in ring hw/usb/dev-smartcard-reader: fix assert on pending answers overflow hw/usb/dev-smartcard-reader: decode bulk-out length as little-endian hw/usb/dev-smartcard-reader: fix dwMaxCCIDMessageLength descriptor hw/usb/dev-smartcard-reader: fix OOB read in atr_get_protocol_num() hw/usb/dev-smartcard-reader: block migration with pending queues hw/usb/dev-smartcard-reader: drop needless state fields hw/usb/dev-smartcard-reader: validate migrated fields in post_load hw/usb/dev-smartcard-reader: reset all I/O state on device reset hw/usb/dev-smartcard-reader: apply backpressure to bulk-out hw/usb/dev-smartcard-reader: fix RDR_to_PC_Parameters dwLength hw/usb/dev-smartcard-reader: reject oversized responses safely hw/usb/dev-smartcard-reader: release short bulk-in responses with xHCI hw/usb/dev-smartcard-reader: drop current_bulk_in pointer hw/usb/dev-smartcard-reader: derive queue counts from start/end indices hw/usb/dev-smartcard-reader: fix pending queue migration hw/usb/dev-smartcard-reader: handle Secure, Escape and SetDataRate commands hw/usb/dev-smartcard-reader: reject commands for invalid slots hw/usb/dev-smartcard-reader: zero bChainParameter in DataBlock responses hw/usb/dev-smartcard-reader: report error on XfrBlock with no card hw/usb/dev-smartcard-reader: stop advertising PIN support hw/usb/dev-smartcard-reader: validate per-command dwLength hw/usb/dev-smartcard-reader: use usb_packet_size() accessor hw/usb/dev-smartcard-reader: advertise T=1 protocol support hw/usb/dev-smartcard-reader: correct CCID_IccPowerOff hw/usb/ccid-card-emulated: free libcacard context

 hw/core/machine.c             |   4 +
 hw/usb/ccid-card-emulated.c   |   2 +
 hw/usb/dev-smartcard-reader.c | 523 ++++++++++++++++++++++++++++++++++--------
 3 files changed, 428 insertions(+), 101 deletions(-)

---
base-commit: 3e3ccab106f879b1512f8e0d51a827dd4de30e22
change-id: 20260805-smartcard-fixes-1df707e447ab

Best regards,

Signature · 1 line
Marc-André Lureau <[email protected]>
#1 lore raw

PATCH 1/27 hw/usb/dev-smartcard-reader: validate interrupt transfer length

A guest can submit an interrupt IN transfer shorter than the 2-byte RDR_to_PC_NotifySlotChange message. usb_packet_copy() asserts that the packet has enough space, so a zero- or one-byte request triggers an assertion failure, crashing QEMU.

Check the transfer length before copying and stall the endpoint when it is too short. The notification is preserved for a subsequent properly-sized transfer.

Note: a later refactoring patch will switch to usb_packet_size(), but this patch open-code p->iov.size for consistency with the rest of the code.

Fixes CVE-2026-18609
Fixes 367071447ec5 ("usb-ccid: add CCID bus")

Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/4128

---
 hw/usb/dev-smartcard-reader.c | 4 ++++
 1 file changed, 4 insertions(+)
hw/usb/dev-smartcard-reader.c +4 -0
index 964c142d1066..bba97a2b19e6 100644
@@ -1122,6 +1122,10 @@ static void ccid_handle_data(USBDevice *dev, USBPacket *p)
             break;
         case CCID_INT_IN_EP:
             if (s->notify_slot_change) {
+                if (p->iov.size < 2) {
+                    p->status = USB_RET_STALL;
+                    break;
+                }
                 /* page 56, RDR_to_PC_NotifySlotChange */
                 buf[0] = CCID_MESSAGE_TYPE_RDR_to_PC_NotifySlotChange;
                 buf[1] = s->bmSlotICCState;
Signature · 1 line
2.55.0
#2 lore raw

PATCH 2/27 hw/usb/dev-smartcard-reader: fix OOB read from pending bulk-in ring

In reply to Marc-André Lureau

ccid_bulk_in_get() decrements bulk_in_pending_num when a slot becomes active, but the slot is only truly free after ccid_bulk_in_release(). A guest can fill all 8 ring slots, partially read one (leaving pos non-zero), then send another command whose response reuses the active slot. The stale pos > new len makes the uint32_t subtraction in ccid_bulk_in_copy_to_guest() wrap, reading past data[].

Move the decrement to ccid_bulk_in_release() so the slot stays busy until then. Add an assert(pos <= len) before the subtraction.

In practice, the device advertises bMaxCCIDBusySlots=1, so a conforming host never has more than one command in flight and the ring never fills.

Fixes CVE-2026-18204
Fixes 367071447ec5 ("usb-ccid: add CCID bus")

Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/4086

---
 hw/usb/dev-smartcard-reader.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
hw/usb/dev-smartcard-reader.c +2 -2
index bba97a2b19e6..8241cd07648d 100644
@@ -580,6 +580,7 @@ static void ccid_bulk_in_release(USBCCIDState *s)
     assert(s->current_bulk_in != NULL);
     s->current_bulk_in->pos = 0;
     s->current_bulk_in = NULL;
+    s->bulk_in_pending_num--;
 }
 
 static void ccid_bulk_in_get(USBCCIDState *s)
@@ -587,8 +588,6 @@ static void ccid_bulk_in_get(USBCCIDState *s)
     if (s->current_bulk_in != NULL || s->bulk_in_pending_num == 0) {
         return;
     }
-    assert(s->bulk_in_pending_num > 0);
-    s->bulk_in_pending_num--;
     s->current_bulk_in =
         &s->bulk_in_pending[(s->bulk_in_pending_start++) % BULK_IN_PENDING_NUM];
 }
@@ -1078,6 +1077,7 @@ static void ccid_bulk_in_copy_to_guest(USBCCIDState *s, USBPacket *p,
 
     ccid_bulk_in_get(s);
     if (s->current_bulk_in != NULL) {
+        assert(s->current_bulk_in->pos <= s->current_bulk_in->len);
         len = MIN(s->current_bulk_in->len - s->current_bulk_in->pos,
                   p->iov.size);
         if (len) {
Signature · 1 line
2.55.0
#3 lore raw

Re: [PATCH 02/27] hw/usb/dev-smartcard-reader: fix OOB read from pending bulk-in ring

Quoted 13 lines · Marc-André Lureau

ccid_bulk_in_get() decrements bulk_in_pending_num when a slot becomes active, but the slot is only truly free after ccid_bulk_in_release(). A guest can fill all 8 ring slots, partially read one (leaving pos non-zero), then send another command whose response reuses the active slot. The stale pos > new len makes the uint32_t subtraction in ccid_bulk_in_copy_to_guest() wrap, reading past data[].

Move the decrement to ccid_bulk_in_release() so the slot stays busy until then. Add an assert(pos <= len) before the subtraction.

In practice, the device advertises bMaxCCIDBusySlots=1, so a conforming host never has more than one command in flight and the ring never fills.

Quoted 8 lines
Fixes CVE-2026-18204
Fixes 367071447ec5 ("usb-ccid: add CCID bus")

Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/4086

---
  hw/usb/dev-smartcard-reader.c | 4 ++--
  1 file changed, 2 insertions(+), 2 deletions(-)

See my comments on previous version:
https://lore.kernel.org/qemu-devel/[email protected]/

#4 lore raw

PATCH 3/27 hw/usb/dev-smartcard-reader: fix assert on pending answers overflow

In reply to Marc-André Lureau

A guest can send PC_to_RDR_XfrBlock USB messages faster than the async card backend can process them. When the pending_answers ring buffer (128 entries) fills, ccid_add_pending_answer() hits an assert() and crashes QEMU.

The CCID spec (section 4) states that a slot can only accept one command at a time. A second command to a busy slot must be rejected with CMD_SLOT_BUSY (section 6.2.6).

Enforce this by checking pending_answers_num before queuing a new APDU. When the slot is already busy, report ERROR_CMD_SLOT_BUSY and send a DataBlock error response back to the guest.

Fixes CVE-2026-18410
Fixes 367071447ec5 ("usb-ccid: add CCID bus")

Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/3997

---
 hw/usb/dev-smartcard-reader.c | 8 ++++++++
 1 file changed, 8 insertions(+)
hw/usb/dev-smartcard-reader.c +8 -0
index 8241cd07648d..9fc6bbca0f2d 100644
@@ -166,6 +166,7 @@ enum {
     ERROR_XFR_PARITY_ERROR  = -3,
     ERROR_XFR_OVERRUN       = -4,
     ERROR_HW_ERROR          = -5,
+    ERROR_CMD_SLOT_BUSY     = -32,
 };
 
 /* 6.2.6 RDR_to_PC_SlotStatus definitions */
@@ -945,6 +946,13 @@ static void ccid_on_apdu_from_guest(USBCCIDState *s, CCID_XferBlock *recv)
         ccid_write_data_block_error(s, recv->hdr.bSlot, recv->hdr.bSeq);
         return;
     }
+    if (s->pending_answers_num > 0) {
+        DPRINTF(s, D_WARN,
+                "usb-ccid: slot already busy, rejecting apdu\n");
+        ccid_report_error_failed(s, ERROR_CMD_SLOT_BUSY);
+        ccid_write_data_block_error(s, recv->hdr.bSlot, recv->hdr.bSeq);
+        return;
+    }
     len = le32_to_cpu(recv->hdr.dwLength);
     DPRINTF(s, 1, "%s: seq %d, len %u\n", __func__,
                 recv->hdr.bSeq, len);
Signature · 1 line
2.55.0
#5 lore raw

PATCH 4/27 hw/usb/dev-smartcard-reader: decode bulk-out length as little-endian

In reply to Marc-André Lureau

The CCID Rev 1.1 specification states in section 1.3, Document Conventions, that fields larger than one byte are stored in little-endian format. The bulk message header's dwLength field is a four-byte field described in section 6, CCID Messages.

Decode dwLength with le32_to_cpu() before using it to assemble and validate Bulk-OUT messages. This fixes message handling on big-endian hosts.

---
 hw/usb/dev-smartcard-reader.c | 10 ++++++----
 1 file changed, 6 insertions(+), 4 deletions(-)
hw/usb/dev-smartcard-reader.c +6 -4
index 9fc6bbca0f2d..3580465df368 100644
@@ -989,6 +989,7 @@ static const char *ccid_message_type_to_str(uint8_t type)
 static void ccid_handle_bulk_out(USBCCIDState *s, USBPacket *p)
 {
     CCID_Header *ccid_header;
+    uint32_t payload_len;
 
     if (p->iov.size + s->bulk_out_pos > BULK_OUT_DATA_SIZE) {
         goto err;
@@ -1001,17 +1002,18 @@ static void ccid_handle_bulk_out(USBCCIDState *s, USBPacket *p)
     }
 
     ccid_header = (CCID_Header *)s->bulk_out_data;
-    if ((s->bulk_out_pos - 10 < ccid_header->dwLength) &&
+    payload_len = le32_to_cpu(ccid_header->dwLength);
+    if ((s->bulk_out_pos - 10 < payload_len) &&
         (p->iov.size == CCID_MAX_PACKET_SIZE)) {
         DPRINTF(s, D_VERBOSE,
                 "usb-ccid: bulk_in: expecting more packets (%u/%u)\n",
-                s->bulk_out_pos - 10, ccid_header->dwLength);
+                s->bulk_out_pos - 10, payload_len);
         return;
     }
-    if (s->bulk_out_pos - 10 != ccid_header->dwLength) {
+    if (s->bulk_out_pos - 10 != payload_len) {
         DPRINTF(s, 1,
                 "usb-ccid: bulk_in: message size mismatch (got %u, expected %u)\n",
-                s->bulk_out_pos - 10, ccid_header->dwLength);
+                s->bulk_out_pos - 10, payload_len);
         goto err;
     }
 
Signature · 1 line
2.55.0
Reviewed-by on v1 4/27
#6 lore raw

Re: [PATCH 04/27] hw/usb/dev-smartcard-reader: decode bulk-out length as little-endian

Quoted 5 lines · Marc-André Lureau

The CCID Rev 1.1 specification states in section 1.3, Document Conventions, that fields larger than one byte are stored in little-endian format. The bulk message header's dwLength field is a four-byte field described in section 6, CCID Messages.

Quoted 8 lines

Decode dwLength with le32_to_cpu() before using it to assemble and validate Bulk-OUT messages. This fixes message handling on big-endian hosts.

---
  hw/usb/dev-smartcard-reader.c | 10 ++++++----
  1 file changed, 6 insertions(+), 4 deletions(-)
#7 lore raw

PATCH 5/27 hw/usb/dev-smartcard-reader: fix dwMaxCCIDMessageLength descriptor

In reply to Marc-André Lureau

The CCID class descriptor advertises dwMaxCCIDMessageLength = 65554 (the extended-APDU maximum), but bulk-IN storage is only 384 bytes. Since the device operates at TPDU level, the spec minimum is just wMaxPacketSize (64 bytes), and the actual limit is the bulk-IN buffer.

Set dwMaxCCIDMessageLength to BULK_IN_BUF_SIZE (384) so the advertised capability matches the implementation. Guard the change behind a machine-compat property so older machine types preserve the original descriptor for guest reproducibility.

Fixes 367071447ec5 ("usb-ccid: add CCID bus")
---
 hw/core/machine.c             |  1 +
 hw/usb/dev-smartcard-reader.c | 12 +++++++++++-
 2 files changed, 12 insertions(+), 1 deletion(-)
hw/core/machine.c +1 -0
index 73b4d82b4a1d..01e50ebe05e0 100644
@@ -51,6 +51,7 @@ GlobalProperty hw_compat_11_0[] = {
     { TYPE_ARM_SMMUV3, "ssidsize", "0" },
     { TYPE_ARM_SMMUV3, "oas", "44" },
     { "migration", "switchover-ack-legacy", "on" },
+    { "usb-ccid", "x-accurate-message-length", "off" },
 };
 const size_t hw_compat_11_0_len = G_N_ELEMENTS(hw_compat_11_0);
 
hw/usb/dev-smartcard-reader.c +11 -1
index 3580465df368..a14062948071 100644
@@ -314,6 +314,7 @@ struct USBCCIDState {
     uint8_t  powered;
     uint8_t  notify_slot_change;
     uint8_t  debug;
+    bool accurate_message_length;
 };
 
 /*
@@ -326,7 +327,7 @@ struct USBCCIDState {
  *   0dc3:1004 Athena Smartcard Solutions, Inc.
  */
 
-static const uint8_t qemu_ccid_descriptor[] = {
+static uint8_t qemu_ccid_descriptor[] = {
         /* Smart Card Device Class Descriptor */
         0x36,       /* u8  bLength; */
         0x21,       /* u8  bDescriptorType; Functional */
@@ -387,7 +388,10 @@ static const uint8_t qemu_ccid_descriptor[] = {
                      * u32 dwMaxCCIDMessageLength; For extended APDU in
                      * [261 + 10 , 65544 + 10]. Otherwise the minimum is
                      * wMaxPacketSize of the Bulk-OUT endpoint
+                     *
+                     * Corrected to BULK_IN_BUF_SIZE when x-accurate-message-length
                      */
+#define CCID_DESC_OFFSET_DW_MAX_MSG_LEN 44
         0x12, 0x00, 0x01, 0x00,
         0xFF,       /*
                      * u8  bClassGetResponse; Significant only for CCID that
@@ -1329,6 +1333,10 @@ static void ccid_realize(USBDevice *dev, Error **errp)
 {
     USBCCIDState *s = USB_CCID_DEV(dev);
 
+    if (s->accurate_message_length) {
+        stl_le_p(&qemu_ccid_descriptor[CCID_DESC_OFFSET_DW_MAX_MSG_LEN],
+                 BULK_IN_BUF_SIZE);
+    }
     usb_desc_create_serial(dev);
     usb_desc_init(dev);
     qbus_init(&s->bus, sizeof(s->bus), TYPE_CCID_BUS, DEVICE(dev), NULL);
@@ -1445,6 +1453,8 @@ static const VMStateDescription ccid_vmstate = {
 
 static const Property ccid_properties[] = {
     DEFINE_PROP_UINT8("debug", USBCCIDState, debug, 0),
+    DEFINE_PROP_BOOL("x-accurate-message-length", USBCCIDState,
+                     accurate_message_length, true),
 };
 
 static void ccid_class_initfn(ObjectClass *klass, const void *data)
Signature · 1 line
2.55.0
#8 lore raw

PATCH 6/27 hw/usb/dev-smartcard-reader: fix OOB read in atr_get_protocol_num()

In reply to Marc-André Lureau

atr_get_protocol_num() computes the TD1 offset from the T0 presence bits without checking that the byte exists in the ATR buffer. A truncated ATR causes an out-of-bounds read.

Validate the offset before dereferencing and fall back to T=0.

This is only triggerable by a buggy backend.

Fixes 2f8f916b6d44 ("dev-smartcard-reader: copy atr protocol to ccid parameters")
---
 hw/usb/dev-smartcard-reader.c | 3 +++
 1 file changed, 3 insertions(+)
hw/usb/dev-smartcard-reader.c +3 -0
index a14062948071..a147cd19f388 100644
@@ -836,6 +836,9 @@ static uint8_t atr_get_protocol_num(const uint8_t *atr, uint32_t len)
     }
     i = 1 + !!(atr[1] & 0x10) + !!(atr[1] & 0x20) + !!(atr[1] & 0x40);
     i += !!(atr[1] & 0x80);
+    if (i >= len) {
+        return 0;
+    }
     return atr[i] & 0x0f;
 }
 
Signature · 1 line
2.55.0
#9 lore raw

PATCH 7/27 hw/usb/dev-smartcard-reader: block migration with pending queues

In reply to Marc-André Lureau

Several queue state fields are not included in the vmstate:
bulk_in_pending_num, pending_answers_start, and pending_answers_end. Also if current_bulk_in != NULL (ongoing transfer). Migrating while any of these are non-zero produces inconsistent state on the destination.

Rather than extending the vmstate (which would require a version bump and migration compat machinery), block migration when the queues are non-empty. In practice this window is very short since the CMD_SLOT_BUSY enforcement limits pending_answers to at most one entry.

Convert pre_save to the pre_save_errp form so it can report the error cleanly. Follow up patches will add migration blocker and new migration version.

Fixes 367071447ec5 ("usb-ccid: add CCID bus")
---
 hw/usb/dev-smartcard-reader.c | 13 ++++++++++---
 1 file changed, 10 insertions(+), 3 deletions(-)
hw/usb/dev-smartcard-reader.c +10 -3
index a147cd19f388..1b8f0e10e172 100644
@@ -1377,13 +1377,20 @@ static int ccid_post_load(void *opaque, int version_id)
     return 0;
 }
 
-static int ccid_pre_save(void *opaque)
+static bool ccid_pre_save(void *opaque, Error **errp)
 {
     USBCCIDState *s = opaque;
 
+    if (s->pending_answers_num || s->bulk_in_pending_num ||
+        s->current_bulk_in) {
+        error_setg(errp, "usb-ccid has pending queue state which cannot be "
+                   "migrated safely");
+        return false;
+    }
+
     s->state_vmstate = s->dev.state;
 
-    return 0;
+    return true;
 }
 
 static const VMStateDescription bulk_in_vmstate = {
@@ -1426,7 +1433,7 @@ static const VMStateDescription ccid_vmstate = {
     .version_id = 1,
     .minimum_version_id = 1,
     .post_load = ccid_post_load,
-    .pre_save = ccid_pre_save,
+    .pre_save_errp = ccid_pre_save,
     .fields = (const VMStateField[]) {
         VMSTATE_STRUCT(dev, USBCCIDState, 1, usb_device_vmstate, USBDevice),
         VMSTATE_UINT8(debug, USBCCIDState),
Signature · 1 line
2.55.0
#10 lore raw

PATCH 8/27 hw/usb/dev-smartcard-reader: drop needless state fields

In reply to Marc-André Lureau

The field is never used, it could potentially do break on malicious migration stream.

---
 hw/usb/dev-smartcard-reader.c | 6 ++----
 1 file changed, 2 insertions(+), 4 deletions(-)
hw/usb/dev-smartcard-reader.c +2 -4
index 1b8f0e10e172..c6a9faf00d6f 100644
@@ -308,7 +308,6 @@ struct USBCCIDState {
     uint8_t  bmCommandStatus;
     uint8_t  bProtocolNum;
     CCID_ProtocolDataStructure abProtocolDataStructure;
-    uint32_t ulProtocolDataStructureSize;
     uint32_t state_vmstate;
     uint8_t  bmSlotICCState;
     uint8_t  powered;
@@ -762,9 +761,8 @@ static void ccid_write_slot_status(USBCCIDState *s, CCID_Header *recv)
 static void ccid_write_parameters(USBCCIDState *s, CCID_Header *recv)
 {
     CCID_Parameter *h;
-    uint32_t len = s->ulProtocolDataStructureSize;
 
-    h = ccid_reserve_recv_buf(s, sizeof(CCID_Parameter) + len);
+    h = ccid_reserve_recv_buf(s, sizeof(CCID_Parameter));
     if (h == NULL) {
         return;
     }
@@ -1447,7 +1445,7 @@ static const VMStateDescription ccid_vmstate = {
         VMSTATE_UINT8(bmCommandStatus, USBCCIDState),
         VMSTATE_UINT8(bProtocolNum, USBCCIDState),
         VMSTATE_BUFFER(abProtocolDataStructure.data, USBCCIDState),
-        VMSTATE_UINT32(ulProtocolDataStructureSize, USBCCIDState),
+        VMSTATE_UNUSED(4), /* was ulProtocolDataStructureSize */
         VMSTATE_STRUCT_ARRAY(bulk_in_pending, USBCCIDState,
                        BULK_IN_PENDING_NUM, 1, bulk_in_vmstate, BulkIn),
         VMSTATE_UINT32(bulk_in_pending_start, USBCCIDState),
Signature · 1 line
2.55.0
#11 lore raw

PATCH 9/27 hw/usb/dev-smartcard-reader: validate migrated fields in post_load

In reply to Marc-André Lureau

Validate fields loaded from the migration stream to reject crafted or corrupt data before it can cause harm.

---
 hw/usb/dev-smartcard-reader.c | 20 ++++++++++++++++++++
 1 file changed, 20 insertions(+)
hw/usb/dev-smartcard-reader.c +20 -0
index c6a9faf00d6f..bed641be4512 100644
@@ -1364,6 +1364,26 @@ static void ccid_realize(USBDevice *dev, Error **errp)
 static int ccid_post_load(void *opaque, int version_id)
 {
     USBCCIDState *s = opaque;
+    int i;
+
+    if (s->bulk_in_pending_end - s->bulk_in_pending_start > BULK_IN_PENDING_NUM) {
+        return -EINVAL;
+    }
+
+    if (s->pending_answers_num > PENDING_ANSWERS_NUM) {
+        return -EINVAL;
+    }
+
+    if (s->bulk_out_pos > BULK_OUT_DATA_SIZE) {
+        return -EINVAL;
+    }
+
+    for (i = 0; i < BULK_IN_PENDING_NUM; i++) {
+        if (s->bulk_in_pending[i].len > BULK_IN_BUF_SIZE ||
+            s->bulk_in_pending[i].pos > s->bulk_in_pending[i].len) {
+            return -EINVAL;
+        }
+    }
 
     /*
      * This must be done after usb_device_attach, which sets state to ATTACHED,
Signature · 1 line
2.55.0
#12 lore raw

PATCH 10/27 hw/usb/dev-smartcard-reader: reset all I/O state on device reset

In reply to Marc-André Lureau

Clear bulk-in entries (len/pos), current_bulk_in pointer, bulk-out position, error status, and protocol parameters during reset. Previously only the bulk-in ring buffer indices and pending answers were cleared, leaving stale state that could corrupt subsequent transfers.

Move ccid_reset() after its callees to avoid forward declarations.

Drop redundant initialization from realize() since it calls reset().

Fixes 367071447ec5 ("usb-ccid: add CCID bus")
---
 hw/usb/dev-smartcard-reader.c | 60 +++++++++++++++++++++++--------------------
 1 file changed, 32 insertions(+), 28 deletions(-)
hw/usb/dev-smartcard-reader.c +32 -28
index bed641be4512..12c82c8f6458 100644
@@ -574,9 +574,16 @@ static void ccid_remove_pending_answer(USBCCIDState *s,
 
 static void ccid_bulk_in_clear(USBCCIDState *s)
 {
+    int i;
+
+    for (i = 0; i < BULK_IN_PENDING_NUM; i++) {
+        s->bulk_in_pending[i].len = 0;
+        s->bulk_in_pending[i].pos = 0;
+    }
     s->bulk_in_pending_start = 0;
     s->bulk_in_pending_end = 0;
     s->bulk_in_pending_num = 0;
+    s->current_bulk_in = NULL;
 }
 
 static void ccid_bulk_in_release(USBCCIDState *s)
@@ -621,26 +628,6 @@ static void *ccid_reserve_recv_buf(USBCCIDState *s, uint16_t len)
     return bulk_in->data;
 }
 
-static void ccid_reset(USBCCIDState *s)
-{
-    ccid_bulk_in_clear(s);
-    ccid_clear_pending_answers(s);
-}
-
-static void ccid_detach(USBCCIDState *s)
-{
-    ccid_reset(s);
-}
-
-static void ccid_handle_reset(USBDevice *dev)
-{
-    USBCCIDState *s = USB_CCID_DEV(dev);
-
-    DPRINTF(s, 1, "Reset\n");
-
-    ccid_reset(s);
-}
-
 static const char *ccid_control_to_str(USBCCIDState *s, int request)
 {
     switch (request) {
@@ -918,6 +905,31 @@ static void ccid_reset_parameters(USBCCIDState *s)
    s->abProtocolDataStructure = defaultProtocolDataStructure;
 }
 
+static void ccid_reset(USBCCIDState *s)
+{
+    ccid_bulk_in_clear(s);
+    ccid_clear_pending_answers(s);
+    s->bulk_out_pos = 0;
+    s->last_answer_error = 0;
+    s->notify_slot_change = false;
+    ccid_reset_error_status(s);
+    ccid_reset_parameters(s);
+}
+
+static void ccid_detach(USBCCIDState *s)
+{
+    ccid_reset(s);
+}
+
+static void ccid_handle_reset(USBDevice *dev)
+{
+    USBCCIDState *s = USB_CCID_DEV(dev);
+
+    DPRINTF(s, 1, "Reset\n");
+
+    ccid_reset(s);
+}
+
 /* NOTE: only a single slot is supported (SLOT_0) */
 static void ccid_on_slot_change(USBCCIDState *s, bool full)
 {
@@ -1349,14 +1361,6 @@ static void ccid_realize(USBDevice *dev, Error **errp)
     s->dev.speedmask = USB_SPEED_MASK_FULL;
     s->notify_slot_change = false;
     s->powered = true;
-    s->pending_answers_num = 0;
-    s->last_answer_error = 0;
-    s->bulk_in_pending_start = 0;
-    s->bulk_in_pending_end = 0;
-    s->current_bulk_in = NULL;
-    ccid_reset_error_status(s);
-    s->bulk_out_pos = 0;
-    ccid_reset_parameters(s);
     ccid_reset(s);
     s->debug = parse_debug_env("QEMU_CCID_DEBUG", D_VERBOSE, s->debug);
 }
Signature · 1 line
2.55.0
#13 lore raw

PATCH 11/27 hw/usb/dev-smartcard-reader: apply backpressure to bulk-out

In reply to Marc-André Lureau

A guest can send bulk-out commands faster than the card backend produces responses. Each XfrBlock adds a pending answer slot, and other commands immediately allocate a bulk_in_pending entry. Once all BULK_IN_PENDING_NUM slots are full, ccid_reserve_recv_buf() returns NULL and responses are silently dropped.

NAK the bulk-out endpoint at message boundaries when bulk_in_pending_num
+ pending_answers_num >= BULK_IN_PENDING_NUM, so the guest retries later, giving the response pipeline time to drain.

Change ccid_write_data_block_answer() to peek the next answer before attempting to write the data block: if the bulk-in ring is full, the pending answer is preserved for retry rather than being consumed and lost. Update ccid_flush_pending_answers() to break on failure so it does not loop forever when the ring is full.

Fixes 367071447ec5 ("usb-ccid: add CCID bus")
---
 hw/usb/dev-smartcard-reader.c | 38 ++++++++++++++++++++++++++++++--------
 1 file changed, 30 insertions(+), 8 deletions(-)
hw/usb/dev-smartcard-reader.c +30 -8
index 12c82c8f6458..279fef03652b 100644
@@ -765,13 +765,13 @@ static void ccid_write_parameters(USBCCIDState *s, CCID_Header *recv)
     usb_wakeup(s->bulk, 0);
 }
 
-static void ccid_write_data_block(USBCCIDState *s, uint8_t slot, uint8_t seq,
+static bool ccid_write_data_block(USBCCIDState *s, uint8_t slot, uint8_t seq,
                                   const uint8_t *data, uint32_t len)
 {
     CCID_DataBlock *p = ccid_reserve_recv_buf(s, sizeof(*p) + len);
 
     if (p == NULL) {
-        return;
+        return false;
     }
     p->b.hdr.bMessageType = CCID_MESSAGE_TYPE_RDR_to_PC_DataBlock;
     p->b.hdr.dwLength = cpu_to_le32(len);
@@ -788,6 +788,7 @@ static void ccid_write_data_block(USBCCIDState *s, uint8_t slot, uint8_t seq,
     }
     ccid_reset_error_status(s);
     usb_wakeup(s->bulk, 0);
+    return true;
 }
 
 static void ccid_report_error_failed(USBCCIDState *s, uint8_t error)
@@ -796,19 +797,26 @@ static void ccid_report_error_failed(USBCCIDState *s, uint8_t error)
     s->bError = error;
 }
 
-static void ccid_write_data_block_answer(USBCCIDState *s,
-    const uint8_t *data, uint32_t len)
+static Answer *ccid_peek_next_answer(USBCCIDState *s);
+
+static bool ccid_write_data_block_answer(USBCCIDState *s,
+                                         const uint8_t *data, uint32_t len)
 {
-    uint8_t seq;
     uint8_t slot;
+    uint8_t seq;
+    Answer *answer;
 
     if (!ccid_has_pending_answers(s)) {
         DPRINTF(s, D_WARN, "error: no pending answer to return to guest\n");
         ccid_report_error_failed(s, ERROR_ICC_MUTE);
-        return;
+        return false;
+    }
+    answer = ccid_peek_next_answer(s);
+    if (!ccid_write_data_block(s, answer->slot, answer->seq, data, len)) {
+        return false;
     }
     ccid_remove_pending_answer(s, &slot, &seq);
-    ccid_write_data_block(s, slot, seq, data, len);
+    return true;
 }
 
 static uint8_t atr_get_protocol_num(const uint8_t *atr, uint32_t len)
@@ -1008,6 +1016,18 @@ static void ccid_handle_bulk_out(USBCCIDState *s, USBPacket *p)
     CCID_Header *ccid_header;
     uint32_t payload_len;
 
+    /*
+     * Every accepted command either queues a response immediately or commits a
+     * slot to a later APDU response. Apply backpressure before consuming the
+     * first packet when all response slots are committed.
+     */
+    if (s->bulk_out_pos == 0 && /* start of message */
+        s->bulk_in_pending_num + s->pending_answers_num >=
+            BULK_IN_PENDING_NUM) {
+        p->status = USB_RET_NAK;
+        return;
+    }
+
     if (p->iov.size + s->bulk_out_pos > BULK_OUT_DATA_SIZE) {
         goto err;
     }
@@ -1190,7 +1210,9 @@ static void ccid_unrealize(USBDevice *dev)
 static void ccid_flush_pending_answers(USBCCIDState *s)
 {
     while (ccid_has_pending_answers(s)) {
-        ccid_write_data_block_answer(s, NULL, 0);
+        if (!ccid_write_data_block_answer(s, NULL, 0)) {
+            break;
+        }
     }
 }
 
Signature · 1 line
2.55.0
Reviewed-by on v1 11/27
#14 lore raw

Re: [PATCH 11/27] hw/usb/dev-smartcard-reader: apply backpressure to bulk-out

Quoted 16 lines · Marc-André Lureau

A guest can send bulk-out commands faster than the card backend produces responses. Each XfrBlock adds a pending answer slot, and other commands immediately allocate a bulk_in_pending entry. Once all BULK_IN_PENDING_NUM slots are full, ccid_reserve_recv_buf() returns NULL and responses are silently dropped.

NAK the bulk-out endpoint at message boundaries when bulk_in_pending_num
+ pending_answers_num >= BULK_IN_PENDING_NUM, so the guest retries later, giving the response pipeline time to drain.

Change ccid_write_data_block_answer() to peek the next answer before attempting to write the data block: if the bulk-in ring is full, the pending answer is preserved for retry rather than being consumed and lost. Update ccid_flush_pending_answers() to break on failure so it does not loop forever when the ring is full.

Quoted 5 lines
Fixes 367071447ec5 ("usb-ccid: add CCID bus")
---
  hw/usb/dev-smartcard-reader.c | 38 ++++++++++++++++++++++++++++++--------
  1 file changed, 30 insertions(+), 8 deletions(-)
#15 lore raw

PATCH 12/27 hw/usb/dev-smartcard-reader: fix RDR_to_PC_Parameters dwLength

In reply to Marc-André Lureau

dwLength in the RDR_to_PC_Parameters response was always set to 0 instead of the protocol-dependent size mandated by the CCID spec (5 for T=0, 7 for T=1). Since bulk_in->len is what determines how many bytes the guest actually reads, the reservation size must also match the wire message size.

Set dwLength from bProtocolNum and compute the reservation size accordingly, so the guest receives a spec-compliant response.

Fixes 367071447ec5 ("usb-ccid: add CCID bus")
---
 hw/usb/dev-smartcard-reader.c | 7 ++++---
 1 file changed, 4 insertions(+), 3 deletions(-)
hw/usb/dev-smartcard-reader.c +4 -3
index 279fef03652b..16f248a0969f 100644
@@ -748,19 +748,20 @@ static void ccid_write_slot_status(USBCCIDState *s, CCID_Header *recv)
 static void ccid_write_parameters(USBCCIDState *s, CCID_Header *recv)
 {
     CCID_Parameter *h;
+    uint32_t dwLength = s->bProtocolNum == 1 ? 7 : 5;
 
-    h = ccid_reserve_recv_buf(s, sizeof(CCID_Parameter));
+    h = ccid_reserve_recv_buf(s, sizeof(h->b) + sizeof(h->bProtocolNum) + dwLength);
     if (h == NULL) {
         return;
     }
     h->b.hdr.bMessageType = CCID_MESSAGE_TYPE_RDR_to_PC_Parameters;
-    h->b.hdr.dwLength = 0;
+    h->b.hdr.dwLength = cpu_to_le32(dwLength);
     h->b.hdr.bSlot = recv->bSlot;
     h->b.hdr.bSeq = recv->bSeq;
     h->b.bStatus = ccid_calc_status(s);
     h->b.bError = s->bError;
     h->bProtocolNum = s->bProtocolNum;
-    h->abProtocolDataStructure = s->abProtocolDataStructure;
+    memcpy(&h->abProtocolDataStructure, &s->abProtocolDataStructure, dwLength);
     ccid_reset_error_status(s);
     usb_wakeup(s->bulk, 0);
 }
Signature · 1 line
2.55.0
#16 lore raw

PATCH 13/27 hw/usb/dev-smartcard-reader: reject oversized responses safely

In reply to Marc-André Lureau

ccid_reserve_recv_buf() takes a uint16_t length, so the result of sizeof(CCID_DataBlock) + len silently truncates when the sum exceeds 65535. This could bypass the BULK_IN_BUF_SIZE check inside the function, leading to a buffer overrun on the fixed-size BulkIn.data array.

The response length comes from the card backend (passthru chardev or libcacard), not from the guest, so this is not guest-exploitable but still worth hardening against a buggy or compromised backend.

Fix this by adding explicit overflow-safe checks in both callers that add a header to the payload: ccid_write_data_block() returns false on oversized input, and ccid_write_data_block_answer() reports ERROR_HW_ERROR to the guest and sends a zero-length data block so the answer queue stays in sync.

Fixes 367071447ec5 ("usb-ccid: add CCID bus")
---
 hw/usb/dev-smartcard-reader.c | 16 +++++++++++++++-
 1 file changed, 15 insertions(+), 1 deletion(-)
hw/usb/dev-smartcard-reader.c +15 -1
index 16f248a0969f..d91376826c5c 100644
@@ -769,7 +769,13 @@ static void ccid_write_parameters(USBCCIDState *s, CCID_Header *recv)
 static bool ccid_write_data_block(USBCCIDState *s, uint8_t slot, uint8_t seq,
                                   const uint8_t *data, uint32_t len)
 {
-    CCID_DataBlock *p = ccid_reserve_recv_buf(s, sizeof(*p) + len);
+    CCID_DataBlock *p;
+
+    if (len > BULK_IN_BUF_SIZE - sizeof(*p)) {
+        DPRINTF(s, D_WARN, "data block is too large (%u bytes)\n", len);
+        return false;
+    }
+    p = ccid_reserve_recv_buf(s, sizeof(*p) + len);
 
     if (p == NULL) {
         return false;
@@ -813,6 +819,14 @@ static bool ccid_write_data_block_answer(USBCCIDState *s,
         return false;
     }
     answer = ccid_peek_next_answer(s);
+    if (len > BULK_IN_BUF_SIZE - sizeof(CCID_DataBlock)) {
+        DPRINTF(s, D_WARN,
+                "APDU response is too large (%u bytes), returning an error\n",
+                len);
+        ccid_report_error_failed(s, ERROR_HW_ERROR);
+        data = NULL;
+        len = 0;
+    }
     if (!ccid_write_data_block(s, answer->slot, answer->seq, data, len)) {
         return false;
     }
Signature · 1 line
2.55.0
#17 lore raw

PATCH 14/27 hw/usb/dev-smartcard-reader: release short bulk-in responses with xHCI

In reply to Marc-André Lureau

USBPacket describes the host controller's complete transfer request, not necessarily one packet on the USB wire. xHCI maps the buffers from all TRBs in a transfer descriptor into a single USBPacket, so p->iov.size can be much larger than the CCID bulk endpoint's 64-byte wMaxPacketSize.

The smartcard reader kept a completed bulk-in response queued whenever the last copied chunk was exactly 64 bytes. This is necessary when the guest requested exactly 64 bytes: the next IN request must receive a zero-length packet to mark the end of the response. It is wrong when xHCI supplied a larger buffer, however. In that case the 64-byte result is already short relative to the USBPacket and xHCI completes the TD. Keeping the response current leaves it waiting for a ZLP request which never arrives and prevents later smartcard responses from being delivered. Release an exact-64-byte response when it is shorter than the host controller request, while retaining it for a request of exactly one maximum-sized packet.

This fixes smartcard reader with xHCI.

---
 hw/usb/dev-smartcard-reader.c | 7 +++----
 1 file changed, 3 insertions(+), 4 deletions(-)
hw/usb/dev-smartcard-reader.c +3 -4
index d91376826c5c..699e236f624e 100644
@@ -1132,8 +1132,7 @@ err:
     s->bulk_out_pos = 0;
 }
 
-static void ccid_bulk_in_copy_to_guest(USBCCIDState *s, USBPacket *p,
-    unsigned int max_packet_size)
+static void ccid_bulk_in_copy_to_guest(USBCCIDState *s, USBPacket *p)
 {
     int len = 0;
 
@@ -1148,7 +1147,7 @@ static void ccid_bulk_in_copy_to_guest(USBCCIDState *s, USBPacket *p,
         }
         s->current_bulk_in->pos += len;
         if (s->current_bulk_in->pos == s->current_bulk_in->len
-            && len != max_packet_size) {
+            && (len != CCID_MAX_PACKET_SIZE || len < p->iov.size)) {
             ccid_bulk_in_release(s);
         }
     } else {
@@ -1180,7 +1179,7 @@ static void ccid_handle_data(USBDevice *dev, USBPacket *p)
     case USB_TOKEN_IN:
         switch (p->ep->nr) {
         case CCID_BULK_IN_EP:
-            ccid_bulk_in_copy_to_guest(s, p, dev->ep_ctl.max_packet_size);
+            ccid_bulk_in_copy_to_guest(s, p);
             break;
         case CCID_INT_IN_EP:
             if (s->notify_slot_change) {
Signature · 1 line
2.55.0
Reviewed-by on v1 14/27
#18 lore raw

Re: [PATCH 14/27] hw/usb/dev-smartcard-reader: release short bulk-in responses with xHCI

Quoted 17 lines · Marc-André Lureau

USBPacket describes the host controller's complete transfer request, not necessarily one packet on the USB wire. xHCI maps the buffers from all TRBs in a transfer descriptor into a single USBPacket, so p->iov.size can be much larger than the CCID bulk endpoint's 64-byte wMaxPacketSize.

The smartcard reader kept a completed bulk-in response queued whenever the last copied chunk was exactly 64 bytes. This is necessary when the guest requested exactly 64 bytes: the next IN request must receive a zero-length packet to mark the end of the response. It is wrong when xHCI supplied a larger buffer, however. In that case the 64-byte result is already short relative to the USBPacket and xHCI completes the TD. Keeping the response current leaves it waiting for a ZLP request which never arrives and prevents later smartcard responses from being delivered. Release an exact-64-byte response when it is shorter than the host controller request, while retaining it for a request of exactly one maximum-sized packet.

Quoted 6 lines

This fixes smartcard reader with xHCI.

---
  hw/usb/dev-smartcard-reader.c | 7 +++----
  1 file changed, 3 insertions(+), 4 deletions(-)
#19 lore raw

PATCH 15/27 hw/usb/dev-smartcard-reader: drop current_bulk_in pointer

In reply to Marc-André Lureau

Replace the eagerly-dequeued current_bulk_in pointer with a ccid_bulk_in_peek() that returns the head of the ring without advancing it. The element now stays at bulk_in_pending[start] while being partially consumed, and start is advanced together with the num decrement in ccid_bulk_in_release().

This removes a field from USBCCIDState and simplifies the bulk-in ring buffer lifecycle from three states (queued, grabbed, released) down to two (queued, released).

Note that this changes the semantic of bulk_in_pending_start in the migration stream too. But since migration with pending current_bulk_in was broken, this doesn't make further damages.

---
 hw/usb/dev-smartcard-reader.c | 42 +++++++++++++++++++++---------------------
 1 file changed, 21 insertions(+), 21 deletions(-)
hw/usb/dev-smartcard-reader.c +21 -21
index 699e236f624e..3f128791f3ef 100644
@@ -296,7 +296,6 @@ struct USBCCIDState {
     uint32_t bulk_in_pending_start;
     uint32_t bulk_in_pending_end; /* first free */
     uint32_t bulk_in_pending_num;
-    BulkIn *current_bulk_in;
     uint8_t  bulk_out_data[BULK_OUT_DATA_SIZE];
     uint32_t bulk_out_pos;
     uint64_t last_answer_error;
@@ -583,24 +582,27 @@ static void ccid_bulk_in_clear(USBCCIDState *s)
     s->bulk_in_pending_start = 0;
     s->bulk_in_pending_end = 0;
     s->bulk_in_pending_num = 0;
-    s->current_bulk_in = NULL;
 }
 
 static void ccid_bulk_in_release(USBCCIDState *s)
 {
-    assert(s->current_bulk_in != NULL);
-    s->current_bulk_in->pos = 0;
-    s->current_bulk_in = NULL;
+    BulkIn *bulk_in;
+
+    assert(s->bulk_in_pending_num > 0);
+    bulk_in =
+        &s->bulk_in_pending[s->bulk_in_pending_start % BULK_IN_PENDING_NUM];
+    bulk_in->pos = 0;
+    s->bulk_in_pending_start++;
     s->bulk_in_pending_num--;
 }
 
-static void ccid_bulk_in_get(USBCCIDState *s)
+static BulkIn *ccid_bulk_in_peek(USBCCIDState *s)
 {
-    if (s->current_bulk_in != NULL || s->bulk_in_pending_num == 0) {
-        return;
+    if (s->bulk_in_pending_num == 0) {
+        return NULL;
     }
-    s->current_bulk_in =
-        &s->bulk_in_pending[(s->bulk_in_pending_start++) % BULK_IN_PENDING_NUM];
+    return &s->bulk_in_pending[
+        s->bulk_in_pending_start % BULK_IN_PENDING_NUM];
 }
 
 static void *ccid_reserve_recv_buf(USBCCIDState *s, uint16_t len)
@@ -1135,18 +1137,17 @@ err:
 static void ccid_bulk_in_copy_to_guest(USBCCIDState *s, USBPacket *p)
 {
     int len = 0;
+    BulkIn *bulk_in;
 
-    ccid_bulk_in_get(s);
-    if (s->current_bulk_in != NULL) {
-        assert(s->current_bulk_in->pos <= s->current_bulk_in->len);
-        len = MIN(s->current_bulk_in->len - s->current_bulk_in->pos,
-                  p->iov.size);
+    bulk_in = ccid_bulk_in_peek(s);
+    if (bulk_in != NULL) {
+        assert(bulk_in->pos <= bulk_in->len);
+        len = MIN(bulk_in->len - bulk_in->pos, p->iov.size);
         if (len) {
-            usb_packet_copy(p, s->current_bulk_in->data +
-                            s->current_bulk_in->pos, len);
+            usb_packet_copy(p, bulk_in->data + bulk_in->pos, len);
         }
-        s->current_bulk_in->pos += len;
-        if (s->current_bulk_in->pos == s->current_bulk_in->len
+        bulk_in->pos += len;
+        if (bulk_in->pos == bulk_in->len
             && (len != CCID_MAX_PACKET_SIZE || len < p->iov.size)) {
             ccid_bulk_in_release(s);
         }
@@ -1439,8 +1440,7 @@ static bool ccid_pre_save(void *opaque, Error **errp)
 {
     USBCCIDState *s = opaque;
 
-    if (s->pending_answers_num || s->bulk_in_pending_num ||
-        s->current_bulk_in) {
+    if (s->pending_answers_num || s->bulk_in_pending_num) {
         error_setg(errp, "usb-ccid has pending queue state which cannot be "
                    "migrated safely");
         return false;
Signature · 1 line
2.55.0
Reviewed-by on v1 15/27
#20 lore raw

Re: [PATCH 15/27] hw/usb/dev-smartcard-reader: drop current_bulk_in pointer

Quoted 10 lines · Marc-André Lureau

Replace the eagerly-dequeued current_bulk_in pointer with a ccid_bulk_in_peek() that returns the head of the ring without advancing it. The element now stays at bulk_in_pending[start] while being partially consumed, and start is advanced together with the num decrement in ccid_bulk_in_release().

This removes a field from USBCCIDState and simplifies the bulk-in ring buffer lifecycle from three states (queued, grabbed, released) down to two (queued, released).

Quoted 8 lines

Note that this changes the semantic of bulk_in_pending_start in the migration stream too. But since migration with pending current_bulk_in was broken, this doesn't make further damages.

---
  hw/usb/dev-smartcard-reader.c | 42 +++++++++++++++++++++---------------------
  1 file changed, 21 insertions(+), 21 deletions(-)

Great.

#21 lore raw

PATCH 16/27 hw/usb/dev-smartcard-reader: derive queue counts from start/end indices

In reply to Marc-André Lureau

Replace the redundant bulk_in_pending_num and pending_answers_num shadow counters with helper functions that compute the count from (end - start). This removes redundant bookkeeping and potential issues.

pending_answers_num is kept for migration reasons, but since pending_answers_{start,end} are not migrated, we can just do a best effort for the following migration fix.

---
 hw/usb/dev-smartcard-reader.c | 47 +++++++++++++++++++++++++------------------
 1 file changed, 27 insertions(+), 20 deletions(-)
hw/usb/dev-smartcard-reader.c +27 -20
index 3f128791f3ef..e3c86cb90e6c 100644
@@ -295,14 +295,13 @@ struct USBCCIDState {
     BulkIn bulk_in_pending[BULK_IN_PENDING_NUM]; /* circular */
     uint32_t bulk_in_pending_start;
     uint32_t bulk_in_pending_end; /* first free */
-    uint32_t bulk_in_pending_num;
     uint8_t  bulk_out_data[BULK_OUT_DATA_SIZE];
     uint32_t bulk_out_pos;
     uint64_t last_answer_error;
     Answer pending_answers[PENDING_ANSWERS_NUM];
     uint32_t pending_answers_start;
     uint32_t pending_answers_end;
-    uint32_t pending_answers_num;
+    uint32_t pending_answers_num; /* for migration compatibility */
     uint8_t  bError;
     uint8_t  bmCommandStatus;
     uint8_t  bProtocolNum;
@@ -315,6 +314,20 @@ struct USBCCIDState {
     bool accurate_message_length;
 };
 
+static uint32_t ccid_bulk_in_pending_num(USBCCIDState *s)
+{
+    uint32_t n = s->bulk_in_pending_end - s->bulk_in_pending_start;
+    assert(n <= BULK_IN_PENDING_NUM);
+    return n;
+}
+
+static uint32_t ccid_pending_answers_num(USBCCIDState *s)
+{
+    uint32_t n = s->pending_answers_end - s->pending_answers_start;
+    assert(n <= PENDING_ANSWERS_NUM);
+    return n;
+}
+
 /*
  * CCID Spec chapter 4: CCID uses a standard device descriptor per Chapter 9,
  * "USB Device Framework", section 9.6.1, in the Universal Serial Bus
@@ -513,12 +526,11 @@ static void ccid_card_apdu_from_guest(CCIDCardState *card,
 
 static bool ccid_has_pending_answers(USBCCIDState *s)
 {
-    return s->pending_answers_num > 0;
+    return ccid_pending_answers_num(s) > 0;
 }
 
 static void ccid_clear_pending_answers(USBCCIDState *s)
 {
-    s->pending_answers_num = 0;
     s->pending_answers_start = 0;
     s->pending_answers_end = 0;
 }
@@ -533,7 +545,7 @@ static void ccid_print_pending_answers(USBCCIDState *s)
         DPRINTF(s, D_VERBOSE, " empty\n");
         return;
     }
-    for (i = s->pending_answers_start, count = s->pending_answers_num ;
+    for (i = s->pending_answers_start, count = ccid_pending_answers_num(s) ;
          count > 0; count--, i++) {
         answer = &s->pending_answers[i % PENDING_ANSWERS_NUM];
         if (count == 1) {
@@ -548,8 +560,7 @@ static void ccid_add_pending_answer(USBCCIDState *s, CCID_Header *hdr)
 {
     Answer *answer;
 
-    assert(s->pending_answers_num < PENDING_ANSWERS_NUM);
-    s->pending_answers_num++;
+    assert(ccid_pending_answers_num(s) < PENDING_ANSWERS_NUM);
     answer =
         &s->pending_answers[(s->pending_answers_end++) % PENDING_ANSWERS_NUM];
     answer->slot = hdr->bSlot;
@@ -562,8 +573,7 @@ static void ccid_remove_pending_answer(USBCCIDState *s,
 {
     Answer *answer;
 
-    assert(s->pending_answers_num > 0);
-    s->pending_answers_num--;
+    assert(ccid_pending_answers_num(s) > 0);
     answer =
         &s->pending_answers[(s->pending_answers_start++) % PENDING_ANSWERS_NUM];
     *slot = answer->slot;
@@ -581,24 +591,22 @@ static void ccid_bulk_in_clear(USBCCIDState *s)
     }
     s->bulk_in_pending_start = 0;
     s->bulk_in_pending_end = 0;
-    s->bulk_in_pending_num = 0;
 }
 
 static void ccid_bulk_in_release(USBCCIDState *s)
 {
     BulkIn *bulk_in;
 
-    assert(s->bulk_in_pending_num > 0);
+    assert(ccid_bulk_in_pending_num(s) > 0);
     bulk_in =
         &s->bulk_in_pending[s->bulk_in_pending_start % BULK_IN_PENDING_NUM];
     bulk_in->pos = 0;
     s->bulk_in_pending_start++;
-    s->bulk_in_pending_num--;
 }
 
 static BulkIn *ccid_bulk_in_peek(USBCCIDState *s)
 {
-    if (s->bulk_in_pending_num == 0) {
+    if (ccid_bulk_in_pending_num(s) == 0) {
         return NULL;
     }
     return &s->bulk_in_pending[
@@ -618,14 +626,13 @@ static void *ccid_reserve_recv_buf(USBCCIDState *s, uint16_t len)
                            __func__, len, BULK_IN_BUF_SIZE);
         return NULL;
     }
-    if (s->bulk_in_pending_num >= BULK_IN_PENDING_NUM) {
+    if (ccid_bulk_in_pending_num(s) >= BULK_IN_PENDING_NUM) {
         DPRINTF(s, D_WARN, "usb-ccid.c: %s: No free bulk_in buffers. "
                            "discarding message.\n", __func__);
         return NULL;
     }
     bulk_in =
         &s->bulk_in_pending[(s->bulk_in_pending_end++) % BULK_IN_PENDING_NUM];
-    s->bulk_in_pending_num++;
     bulk_in->len = len;
     return bulk_in->data;
 }
@@ -988,7 +995,7 @@ static void ccid_on_apdu_from_guest(USBCCIDState *s, CCID_XferBlock *recv)
         ccid_write_data_block_error(s, recv->hdr.bSlot, recv->hdr.bSeq);
         return;
     }
-    if (s->pending_answers_num > 0) {
+    if (ccid_pending_answers_num(s) > 0) {
         DPRINTF(s, D_WARN,
                 "usb-ccid: slot already busy, rejecting apdu\n");
         ccid_report_error_failed(s, ERROR_CMD_SLOT_BUSY);
@@ -1039,7 +1046,7 @@ static void ccid_handle_bulk_out(USBCCIDState *s, USBPacket *p)
      * first packet when all response slots are committed.
      */
     if (s->bulk_out_pos == 0 && /* start of message */
-        s->bulk_in_pending_num + s->pending_answers_num >=
+        ccid_bulk_in_pending_num(s) + ccid_pending_answers_num(s) >=
             BULK_IN_PENDING_NUM) {
         p->status = USB_RET_NAK;
         return;
@@ -1233,7 +1240,7 @@ static void ccid_flush_pending_answers(USBCCIDState *s)
 
 static Answer *ccid_peek_next_answer(USBCCIDState *s)
 {
-    return s->pending_answers_num == 0
+    return ccid_pending_answers_num(s) == 0
         ? NULL
         : &s->pending_answers[s->pending_answers_start % PENDING_ANSWERS_NUM];
 }
@@ -1440,7 +1447,7 @@ static bool ccid_pre_save(void *opaque, Error **errp)
 {
     USBCCIDState *s = opaque;
 
-    if (s->pending_answers_num || s->bulk_in_pending_num) {
+    if (ccid_pending_answers_num(s) || ccid_bulk_in_pending_num(s)) {
         error_setg(errp, "usb-ccid has pending queue state which cannot be "
                    "migrated safely");
         return false;
@@ -1512,7 +1519,7 @@ static const VMStateDescription ccid_vmstate = {
         VMSTATE_UINT32(bulk_in_pending_end, USBCCIDState),
         VMSTATE_STRUCT_ARRAY(pending_answers, USBCCIDState,
                         PENDING_ANSWERS_NUM, 1, answer_vmstate, Answer),
-        VMSTATE_UINT32(pending_answers_num, USBCCIDState),
+        VMSTATE_UINT32(pending_answers_num, USBCCIDState), /* for compatibility */
         VMSTATE_UNUSED(1), /* was migration_state */
         VMSTATE_UINT32(state_vmstate, USBCCIDState),
         VMSTATE_END_OF_LIST()
Signature · 1 line
2.55.0
Reviewed-by on v1 16/27
#22 lore raw

Re: [PATCH 16/27] hw/usb/dev-smartcard-reader: derive queue counts from start/end indices

Quoted 4 lines · Marc-André Lureau

Replace the redundant bulk_in_pending_num and pending_answers_num shadow counters with helper functions that compute the count from (end - start). This removes redundant bookkeeping and potential issues.

Quoted 8 lines

pending_answers_num is kept for migration reasons, but since pending_answers_{start,end} are not migrated, we can just do a best effort for the following migration fix.

---
  hw/usb/dev-smartcard-reader.c | 47 +++++++++++++++++++++++++------------------
  1 file changed, 27 insertions(+), 20 deletions(-)
#23 lore raw

PATCH 17/27 hw/usb/dev-smartcard-reader: fix pending queue migration

In reply to Marc-André Lureau

The original vmstate migrated the bulk_in_pending and pending_answers arrays but not the pending_answers queue indices (pending_answers_start, pending_answers_end). This made migration silently lose in-flight smartcard responses.

Add a vmstate subsection "usb-ccid/pending-answers" that migrates the missing pending_answers indices. A compat property x-migrate-pending-answers (default on, off for <= 11.0) gates the subsection so older machine types keep the old behavior.

Populate pending_answers_num in pre_save so post_load can reconstruct start/end when loading from an older source that lacks the subsection.

When the subsection is absent, post_load derives pending_answers start/end from the legacy count. Validate all wire-sourced indices and bulk-in entry bounds on load.

---
 hw/core/machine.c             |  1 +
 hw/usb/dev-smartcard-reader.c | 70 ++++++++++++++++++++++++++++++++++++++++---
 2 files changed, 67 insertions(+), 4 deletions(-)
hw/core/machine.c +1 -0
index 01e50ebe05e0..28842f53ae4f 100644
@@ -52,6 +52,7 @@ GlobalProperty hw_compat_11_0[] = {
     { TYPE_ARM_SMMUV3, "oas", "44" },
     { "migration", "switchover-ack-legacy", "on" },
     { "usb-ccid", "x-accurate-message-length", "off" },
+    { "usb-ccid", "x-migrate-pending-answers", "off" },
 };
 const size_t hw_compat_11_0_len = G_N_ELEMENTS(hw_compat_11_0);
 
hw/usb/dev-smartcard-reader.c +66 -4

123 lines not on this page · raw message

Signature · 1 line
2.55.0
#24 lore raw

PATCH 18/27 hw/usb/dev-smartcard-reader: handle Secure, Escape and SetDataRate commands

In reply to Marc-André Lureau

The CCID device defines message types for PC_to_RDR_Secure, Escape and SetDataRateAndClockFrequency but the bulk-out handler lets them fall through to the default case, which responds with RDR_to_PC_SlotStatus. The CCID spec requires each command to use its own response type: Secure must reply with RDR_to_PC_DataBlock, Escape with RDR_to_PC_Escape, and SetDataRateAndClockFrequency with RDR_to_PC_DataRateAndClockFrequency.

Add explicit cases that report ERROR_CMD_NOT_SUPPORTED using the correct response message types, along with the corresponding structs and response writer functions.

Fixes 367071447ec5 ("usb-ccid: add CCID bus")
---
 hw/usb/dev-smartcard-reader.c | 62 +++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 62 insertions(+)
hw/usb/dev-smartcard-reader.c +62 -0
index 5ca50c111217..e7bc5f6d4ae0 100644
@@ -232,6 +232,19 @@ typedef struct QEMU_PACKED CCID_DataBlock {
     uint8_t      abData[];
 } CCID_DataBlock;
 
+typedef struct QEMU_PACKED CCID_Escape {
+    CCID_BULK_IN b;
+    uint8_t      bRFU;
+    uint8_t      abData[];
+} CCID_Escape;
+
+typedef struct QEMU_PACKED CCID_DataRateAndClockFrequency {
+    CCID_BULK_IN b;
+    uint8_t      bRFU;
+    uint32_t     dwClockFrequency;
+    uint32_t     dwDataRate;
+} CCID_DataRateAndClockFrequency;
+
 /* 6.1.4 PC_to_RDR_XfrBlock */
 typedef struct QEMU_PACKED CCID_XferBlock {
     CCID_Header  hdr;
@@ -739,6 +752,43 @@ static void ccid_reset_error_status(USBCCIDState *s)
     s->bmCommandStatus = COMMAND_STATUS_NO_ERROR;
 }
 
+static void ccid_write_escape(USBCCIDState *s, CCID_Header *recv)
+{
+    CCID_Escape *h = ccid_reserve_recv_buf(s, sizeof(*h));
+    if (h == NULL) {
+        return;
+    }
+    h->b.hdr.bMessageType = CCID_MESSAGE_TYPE_RDR_to_PC_Escape;
+    h->b.hdr.dwLength = 0;
+    h->b.hdr.bSlot = recv->bSlot;
+    h->b.hdr.bSeq = recv->bSeq;
+    h->b.bStatus = ccid_calc_status(s);
+    h->b.bError = s->bError;
+    h->bRFU = 0;
+    ccid_reset_error_status(s);
+    usb_wakeup(s->bulk, 0);
+}
+
+static void ccid_write_data_rate_and_clock(USBCCIDState *s, CCID_Header *recv)
+{
+    CCID_DataRateAndClockFrequency *h = ccid_reserve_recv_buf(s, sizeof(*h));
+    if (h == NULL) {
+        return;
+    }
+    h->b.hdr.bMessageType =
+        CCID_MESSAGE_TYPE_RDR_to_PC_DataRateAndClockFrequency;
+    h->b.hdr.dwLength = cpu_to_le32(8);
+    h->b.hdr.bSlot = recv->bSlot;
+    h->b.hdr.bSeq = recv->bSeq;
+    h->b.bStatus = ccid_calc_status(s);
+    h->b.bError = s->bError;
+    h->bRFU = 0;
+    h->dwClockFrequency = 0;
+    h->dwDataRate = 0;
+    ccid_reset_error_status(s);
+    usb_wakeup(s->bulk, 0);
+}
+
 static void ccid_write_slot_status(USBCCIDState *s, CCID_Header *recv)
 {
     CCID_SlotStatus *h = ccid_reserve_recv_buf(s, sizeof(CCID_SlotStatus));
@@ -1123,6 +1173,18 @@ static void ccid_handle_bulk_out(USBCCIDState *s, USBPacket *p)
         ccid_report_error_failed(s, 0);
         ccid_write_slot_status(s, ccid_header);
         break;
+    case CCID_MESSAGE_TYPE_PC_to_RDR_Secure:
+        ccid_report_error_failed(s, ERROR_CMD_NOT_SUPPORTED);
+        ccid_write_data_block_error(s, ccid_header->bSlot, ccid_header->bSeq);
+        break;
+    case CCID_MESSAGE_TYPE_PC_to_RDR_Escape:
+        ccid_report_error_failed(s, ERROR_CMD_NOT_SUPPORTED);
+        ccid_write_escape(s, ccid_header);
+        break;
+    case CCID_MESSAGE_TYPE_PC_to_RDR_SetDataRateAndClockFrequency:
+        ccid_report_error_failed(s, ERROR_CMD_NOT_SUPPORTED);
+        ccid_write_data_rate_and_clock(s, ccid_header);
+        break;
     default:
         DPRINTF(s, 1,
                 "handle_data: ERROR: unhandled message type %Xh\n",
Signature · 1 line
2.55.0
#25 lore raw

PATCH 19/27 hw/usb/dev-smartcard-reader: reject commands for invalid slots

In reply to Marc-André Lureau

The descriptor advertises bMaxSlotIndex = 0 (single slot), but ccid_handle_bulk_out() never validated bSlot. Commands addressed to non-existent slots were silently processed against slot 0 state.

Reject them with bError = 5 (slot does not exist) per CCID Rev 1.1 section 6.2.7.

---
 hw/usb/dev-smartcard-reader.c | 38 ++++++++++++++++++++++++++++++++++++++
 1 file changed, 38 insertions(+)
hw/usb/dev-smartcard-reader.c +38 -0
index e7bc5f6d4ae0..cc7356c77413 100644
@@ -167,6 +167,7 @@ enum {
     ERROR_XFR_OVERRUN       = -4,
     ERROR_HW_ERROR          = -5,
     ERROR_CMD_SLOT_BUSY     = -32,
+    ERROR_SLOT_NOT_EXIST    = 5,
 };
 
 /* 6.2.6 RDR_to_PC_SlotStatus definitions */
@@ -1087,6 +1088,35 @@ static const char *ccid_message_type_to_str(uint8_t type)
     return "unknown";
 }
 
+/*
+ * Send the spec-mandated response type for the given command with the
+ * error already staged via ccid_report_error_failed().
+ */
+static void ccid_write_error_response(USBCCIDState *s, CCID_Header *recv)
+{
+    switch (recv->bMessageType) {
+    case CCID_MESSAGE_TYPE_PC_to_RDR_IccPowerOn:
+    case CCID_MESSAGE_TYPE_PC_to_RDR_XfrBlock:
+    case CCID_MESSAGE_TYPE_PC_to_RDR_Secure:
+        ccid_write_data_block_error(s, recv->bSlot, recv->bSeq);
+        break;
+    case CCID_MESSAGE_TYPE_PC_to_RDR_GetParameters:
+    case CCID_MESSAGE_TYPE_PC_to_RDR_ResetParameters:
+    case CCID_MESSAGE_TYPE_PC_to_RDR_SetParameters:
+        ccid_write_parameters(s, recv);
+        break;
+    case CCID_MESSAGE_TYPE_PC_to_RDR_Escape:
+        ccid_write_escape(s, recv);
+        break;
+    case CCID_MESSAGE_TYPE_PC_to_RDR_SetDataRateAndClockFrequency:
+        ccid_write_data_rate_and_clock(s, recv);
+        break;
+    default:
+        ccid_write_slot_status(s, recv);
+        break;
+    }
+}
+
 static void ccid_handle_bulk_out(USBCCIDState *s, USBPacket *p)
 {
     CCID_Header *ccid_header;
@@ -1130,6 +1160,14 @@ static void ccid_handle_bulk_out(USBCCIDState *s, USBPacket *p)
         goto err;
     }
 
+    if (ccid_header->bSlot != 0) {
+        DPRINTF(s, 1, "usb-ccid: bad slot %d\n", ccid_header->bSlot);
+        ccid_report_error_failed(s, ERROR_SLOT_NOT_EXIST);
+        ccid_write_error_response(s, ccid_header);
+        s->bulk_out_pos = 0;
+        return;
+    }
+
     DPRINTF(s, D_MORE_INFO, "%s %x %s\n", __func__,
             ccid_header->bMessageType,
             ccid_message_type_to_str(ccid_header->bMessageType));
Signature · 1 line
2.55.0
Reviewed-by on v1 19/27
#26 lore raw

Re: [PATCH 19/27] hw/usb/dev-smartcard-reader: reject commands for invalid slots

Quoted 11 lines · Marc-André Lureau

The descriptor advertises bMaxSlotIndex = 0 (single slot), but ccid_handle_bulk_out() never validated bSlot. Commands addressed to non-existent slots were silently processed against slot 0 state.

Reject them with bError = 5 (slot does not exist) per CCID Rev 1.1 section 6.2.7.

---
  hw/usb/dev-smartcard-reader.c | 38 ++++++++++++++++++++++++++++++++++++++
  1 file changed, 38 insertions(+)
#27 lore raw

PATCH 20/27 hw/usb/dev-smartcard-reader: zero bChainParameter in DataBlock responses

In reply to Marc-André Lureau

ccid_write_data_block() initializes every CCID_DataBlock field except bChainParameter. Since bulk-in buffers are reused without zeroing, a stale non-zero value can make the guest CCID driver misinterpret a complete response as chained.

This device never chains responses, so set bChainParameter to 00h as required by CCID Rev 1.1 section 6.2.1 for TPDU-level exchange.

---
 hw/usb/dev-smartcard-reader.c | 1 +
 1 file changed, 1 insertion(+)
hw/usb/dev-smartcard-reader.c +1 -0
index cc7356c77413..208a14dbd1b3 100644
@@ -848,6 +848,7 @@ static bool ccid_write_data_block(USBCCIDState *s, uint8_t slot, uint8_t seq,
     p->b.hdr.bSeq = seq;
     p->b.bStatus = ccid_calc_status(s);
     p->b.bError = s->bError;
+    p->bChainParameter = 0;
     if (p->b.bError) {
         DPRINTF(s, D_VERBOSE, "error %d\n", p->b.bError);
     }
Signature · 1 line
2.55.0
Reviewed-by on v1 20/27
#28 lore raw

Re: [PATCH 20/27] hw/usb/dev-smartcard-reader: zero bChainParameter in DataBlock responses

Quoted 5 lines · Marc-André Lureau

ccid_write_data_block() initializes every CCID_DataBlock field except bChainParameter. Since bulk-in buffers are reused without zeroing, a stale non-zero value can make the guest CCID driver misinterpret a complete response as chained.

Quoted 7 lines

This device never chains responses, so set bChainParameter to 00h as required by CCID Rev 1.1 section 6.2.1 for TPDU-level exchange.

---
  hw/usb/dev-smartcard-reader.c | 1 +
  1 file changed, 1 insertion(+)
#29 lore raw

PATCH 21/27 hw/usb/dev-smartcard-reader: report error on XfrBlock with no card

In reply to Marc-André Lureau

ccid_on_apdu_from_guest() returns an empty DataBlock when no card is active, but without first setting failed command status. This makes bStatus report success and leaves bError unset, violating CCID Rev 1.1 section 6.1.4 which requires failed status with ICC_MUTE.

Call ccid_report_error_failed() with ERROR_ICC_MUTE before queuing the response, matching the existing pattern in the slot-busy error path.

---
 hw/usb/dev-smartcard-reader.c | 1 +
 1 file changed, 1 insertion(+)
hw/usb/dev-smartcard-reader.c +1 -0
index 208a14dbd1b3..65ceed57541a 100644
@@ -1046,6 +1046,7 @@ static void ccid_on_apdu_from_guest(USBCCIDState *s, CCID_XferBlock *recv)
     if (ccid_card_status(s) != ICC_STATUS_PRESENT_ACTIVE) {
         DPRINTF(s, 1,
                 "usb-ccid: not sending apdu to client, no card connected\n");
+        ccid_report_error_failed(s, ERROR_ICC_MUTE);
         ccid_write_data_block_error(s, recv->hdr.bSlot, recv->hdr.bSeq);
         return;
     }
Signature · 1 line
2.55.0
#30 lore raw

PATCH 22/27 hw/usb/dev-smartcard-reader: stop advertising PIN support

In reply to Marc-André Lureau

The CCID descriptor claims bPINSupport=1 (PIN Verification) but the device does not implement it, returning CMD_NOT_SUPPORTED for Secure commands. Stop advertising the capability by default, gated behind an x-pin-support property for backward compatibility.

Fixes 367071447ec5 ("usb-ccid: add CCID bus")
---
 hw/core/machine.c             |  1 +
 hw/usb/dev-smartcard-reader.c | 12 +++++++++++-
 2 files changed, 12 insertions(+), 1 deletion(-)
hw/core/machine.c +1 -0
index 28842f53ae4f..790d947e28d1 100644
@@ -52,6 +52,7 @@ GlobalProperty hw_compat_11_0[] = {
     { TYPE_ARM_SMMUV3, "oas", "44" },
     { "migration", "switchover-ack-legacy", "on" },
     { "usb-ccid", "x-accurate-message-length", "off" },
+    { "usb-ccid", "x-pin-support", "on" },
     { "usb-ccid", "x-migrate-pending-answers", "off" },
 };
 const size_t hw_compat_11_0_len = G_N_ELEMENTS(hw_compat_11_0);
hw/usb/dev-smartcard-reader.c +11 -1
index 65ceed57541a..a973a0396bb3 100644
@@ -328,6 +328,7 @@ struct USBCCIDState {
     bool accurate_message_length;
     bool migrate_pending_answers;
     bool pending_answers_loaded;
+    bool pin_support;
 };
 
 static uint32_t ccid_bulk_in_pending_num(USBCCIDState *s)
@@ -436,10 +437,14 @@ static uint8_t qemu_ccid_descriptor[] = {
                      * u16 wLcdLayout; XXYY Number of lines (XX) and chars per
                      * line for LCD display used for PIN entry. 0000 - no LCD
                      */
-        0x01,       /*
+                    /*
                      * u8  bPINSupport; 01h PIN Verification,
                      *                  02h PIN Modification
+                     *
+                     * Corrected to 0 when !x-pin-support
                      */
+#define CCID_DESC_OFFSET_B_PIN_SUPPORT 52
+        0x01,
         0x01,       /* u8  bMaxCCIDBusySlots; */
 };
 
@@ -1498,6 +1503,9 @@ static void ccid_realize(USBDevice *dev, Error **errp)
         stl_le_p(&qemu_ccid_descriptor[CCID_DESC_OFFSET_DW_MAX_MSG_LEN],
                  BULK_IN_BUF_SIZE);
     }
+    if (!s->pin_support) {
+        qemu_ccid_descriptor[CCID_DESC_OFFSET_B_PIN_SUPPORT] = 0;
+    }
     usb_desc_create_serial(dev);
     usb_desc_init(dev);
     qbus_init(&s->bus, sizeof(s->bus), TYPE_CCID_BUS, DEVICE(dev), NULL);
@@ -1692,6 +1700,8 @@ static const Property ccid_properties[] = {
     DEFINE_PROP_UINT8("debug", USBCCIDState, debug, 0),
     DEFINE_PROP_BOOL("x-accurate-message-length", USBCCIDState,
                      accurate_message_length, true),
+    DEFINE_PROP_BOOL("x-pin-support", USBCCIDState,
+                     pin_support, false),
     DEFINE_PROP_BOOL("x-migrate-pending-answers", USBCCIDState,
                      migrate_pending_answers, true),
 };
Signature · 1 line
2.55.0
#31 lore raw

PATCH 23/27 hw/usb/dev-smartcard-reader: validate per-command dwLength

In reply to Marc-André Lureau

The bulk-out parser validates that dwLength matches the received byte count, but does not check whether dwLength is correct for each command type before dispatch. For example, SetParameters copies protocol bytes from the payload even when dwLength is zero, reading stale data left in the fixed bulk_out_data buffer from earlier commands.

Add per-command dwLength checks before dispatching:
- Commands with no payload (GetSlotStatus, IccPowerOn/Off, Get/ResetParameters, Mechanical): require dwLength == 0
- SetParameters: require exactly 5 bytes for T=0 or 7 for T=1
- SetDataRateAndClockFrequency: require exactly 8 bytes
- XfrBlock: variable length, already bounded by the buffer
- Secure, Escape: variable length, unsupported and no payload access

Malformed messages are rejected with ERROR_BAD_DWLENGTH.

---
 hw/usb/dev-smartcard-reader.c | 42 +++++++++++++++++++++++++++++++++++++++++-
 1 file changed, 41 insertions(+), 1 deletion(-)
hw/usb/dev-smartcard-reader.c +41 -1
index a973a0396bb3..bee118cb4ff9 100644
@@ -167,6 +167,7 @@ enum {
     ERROR_XFR_OVERRUN       = -4,
     ERROR_HW_ERROR          = -5,
     ERROR_CMD_SLOT_BUSY     = -32,
+    ERROR_BAD_DWLENGTH      = 1,
     ERROR_SLOT_NOT_EXIST    = 5,
 };
 
@@ -1180,9 +1181,15 @@ static void ccid_handle_bulk_out(USBCCIDState *s, USBPacket *p)
             ccid_message_type_to_str(ccid_header->bMessageType));
     switch (ccid_header->bMessageType) {
     case CCID_MESSAGE_TYPE_PC_to_RDR_GetSlotStatus:
+        if (payload_len != 0) {
+            goto bad_length;
+        }
         ccid_write_slot_status(s, ccid_header);
         break;
     case CCID_MESSAGE_TYPE_PC_to_RDR_IccPowerOn:
+        if (payload_len != 0) {
+            goto bad_length;
+        }
         DPRINTF(s, 1, "%s: PowerOn: %d\n", __func__,
                 ((CCID_IccPowerOn *)(ccid_header))->bPowerSelect);
         s->powered = true;
@@ -1193,6 +1200,9 @@ static void ccid_handle_bulk_out(USBCCIDState *s, USBPacket *p)
         ccid_write_data_block_atr(s, ccid_header);
         break;
     case CCID_MESSAGE_TYPE_PC_to_RDR_IccPowerOff:
+        if (payload_len != 0) {
+            goto bad_length;
+        }
         ccid_reset_error_status(s);
         s->powered = false;
         ccid_write_slot_status(s, ccid_header);
@@ -1200,21 +1210,38 @@ static void ccid_handle_bulk_out(USBCCIDState *s, USBPacket *p)
     case CCID_MESSAGE_TYPE_PC_to_RDR_XfrBlock:
         ccid_on_apdu_from_guest(s, (CCID_XferBlock *)s->bulk_out_data);
         break;
-    case CCID_MESSAGE_TYPE_PC_to_RDR_SetParameters:
+    case CCID_MESSAGE_TYPE_PC_to_RDR_SetParameters: {
+        CCID_SetParameters *ph = (CCID_SetParameters *)s->bulk_out_data;
+        uint32_t protocol_num = ph->bProtocolNum & 3;
+        uint32_t expected = (protocol_num == 1) ? 7 : 5;
+
+        if (protocol_num <= 1 && payload_len != expected) {
+            goto bad_length;
+        }
         ccid_reset_error_status(s);
         ccid_set_parameters(s, ccid_header);
         ccid_write_parameters(s, ccid_header);
         break;
+    }
     case CCID_MESSAGE_TYPE_PC_to_RDR_ResetParameters:
+        if (payload_len != 0) {
+            goto bad_length;
+        }
         ccid_reset_error_status(s);
         ccid_reset_parameters(s);
         ccid_write_parameters(s, ccid_header);
         break;
     case CCID_MESSAGE_TYPE_PC_to_RDR_GetParameters:
+        if (payload_len != 0) {
+            goto bad_length;
+        }
         ccid_reset_error_status(s);
         ccid_write_parameters(s, ccid_header);
         break;
     case CCID_MESSAGE_TYPE_PC_to_RDR_Mechanical:
+        if (payload_len != 0) {
+            goto bad_length;
+        }
         ccid_report_error_failed(s, 0);
         ccid_write_slot_status(s, ccid_header);
         break;
@@ -1227,6 +1254,9 @@ static void ccid_handle_bulk_out(USBCCIDState *s, USBPacket *p)
         ccid_write_escape(s, ccid_header);
         break;
     case CCID_MESSAGE_TYPE_PC_to_RDR_SetDataRateAndClockFrequency:
+        if (payload_len != 8) {
+            goto bad_length;
+        }
         ccid_report_error_failed(s, ERROR_CMD_NOT_SUPPORTED);
         ccid_write_data_rate_and_clock(s, ccid_header);
         break;
@@ -1245,6 +1275,16 @@ static void ccid_handle_bulk_out(USBCCIDState *s, USBPacket *p)
     s->bulk_out_pos = 0;
     return;
 
+bad_length:
+    DPRINTF(s, 1,
+            "usb-ccid: bad dwLength %u for %s\n",
+            payload_len,
+            ccid_message_type_to_str(ccid_header->bMessageType));
+    ccid_report_error_failed(s, ERROR_BAD_DWLENGTH);
+    ccid_write_error_response(s, ccid_header);
+    s->bulk_out_pos = 0;
+    return;
+
 err:
     p->status = USB_RET_STALL;
     s->bulk_out_pos = 0;
Signature · 1 line
2.55.0
#32 lore raw

PATCH 24/27 hw/usb/dev-smartcard-reader: use usb_packet_size() accessor

In reply to Marc-André Lureau

Replace direct p->iov.size accesses with usb_packet_size(), which correctly handles combined packets.

---
 hw/usb/dev-smartcard-reader.c | 20 ++++++++++----------
 1 file changed, 10 insertions(+), 10 deletions(-)
hw/usb/dev-smartcard-reader.c +10 -10
index bee118cb4ff9..8520a2dab216 100644
@@ -1142,11 +1142,11 @@ static void ccid_handle_bulk_out(USBCCIDState *s, USBPacket *p)
         return;
     }
 
-    if (p->iov.size + s->bulk_out_pos > BULK_OUT_DATA_SIZE) {
+    if (usb_packet_size(p) + s->bulk_out_pos > BULK_OUT_DATA_SIZE) {
         goto err;
     }
-    usb_packet_copy(p, s->bulk_out_data + s->bulk_out_pos, p->iov.size);
-    s->bulk_out_pos += p->iov.size;
+    usb_packet_copy(p, s->bulk_out_data + s->bulk_out_pos, usb_packet_size(p));
+    s->bulk_out_pos += usb_packet_size(p);
     if (s->bulk_out_pos < 10) {
         DPRINTF(s, 1, "%s: header incomplete\n", __func__);
         goto err;
@@ -1155,7 +1155,7 @@ static void ccid_handle_bulk_out(USBCCIDState *s, USBPacket *p)
     ccid_header = (CCID_Header *)s->bulk_out_data;
     payload_len = le32_to_cpu(ccid_header->dwLength);
     if ((s->bulk_out_pos - 10 < payload_len) &&
-        (p->iov.size == CCID_MAX_PACKET_SIZE)) {
+        (usb_packet_size(p) == CCID_MAX_PACKET_SIZE)) {
         DPRINTF(s, D_VERBOSE,
                 "usb-ccid: bulk_in: expecting more packets (%u/%u)\n",
                 s->bulk_out_pos - 10, payload_len);
@@ -1298,7 +1298,7 @@ static void ccid_bulk_in_copy_to_guest(USBCCIDState *s, USBPacket *p)
     bulk_in = ccid_bulk_in_peek(s);
     if (bulk_in != NULL) {
         assert(bulk_in->pos <= bulk_in->len);
-        len = MIN(bulk_in->len - bulk_in->pos, p->iov.size);
+        len = MIN(bulk_in->len - bulk_in->pos, usb_packet_size(p));
         if (len) {
             usb_packet_copy(p, bulk_in->data + bulk_in->pos, len);
         }
@@ -1314,12 +1314,12 @@ static void ccid_bulk_in_copy_to_guest(USBCCIDState *s, USBPacket *p)
     if (len) {
         DPRINTF(s, D_MORE_INFO,
                 "%s: %zd/%d req/act to guest (BULK_IN)\n",
-                __func__, p->iov.size, len);
+                __func__, usb_packet_size(p), len);
     }
-    if (len < p->iov.size) {
+    if (len < usb_packet_size(p)) {
         DPRINTF(s, 1,
                 "%s: returning short (EREMOTEIO) %d < %zd\n",
-                __func__, len, p->iov.size);
+                __func__, len, usb_packet_size(p));
     }
 }
 
@@ -1340,7 +1340,7 @@ static void ccid_handle_data(USBDevice *dev, USBPacket *p)
             break;
         case CCID_INT_IN_EP:
             if (s->notify_slot_change) {
-                if (p->iov.size < 2) {
+                if (usb_packet_size(p) < 2) {
                     p->status = USB_RET_STALL;
                     break;
                 }
@@ -1353,7 +1353,7 @@ static void ccid_handle_data(USBDevice *dev, USBPacket *p)
                 DPRINTF(s, D_INFO,
                         "handle_data: int_in: notify_slot_change %X, "
                         "requested len %zd\n",
-                        s->bmSlotICCState, p->iov.size);
+                        s->bmSlotICCState, usb_packet_size(p));
             } else {
                 p->status = USB_RET_NAK;
             }
Signature · 1 line
2.55.0
Reviewed-by on v1 24/27
#33 lore raw

Re: [PATCH 24/27] hw/usb/dev-smartcard-reader: use usb_packet_size() accessor

Quoted 7 lines · Marc-André Lureau

Replace direct p->iov.size accesses with usb_packet_size(), which correctly handles combined packets.

---
  hw/usb/dev-smartcard-reader.c | 20 ++++++++++----------
  1 file changed, 10 insertions(+), 10 deletions(-)
#34 lore raw

PATCH 25/27 hw/usb/dev-smartcard-reader: advertise T=1 protocol support

In reply to Marc-André Lureau

The CCID descriptor only advertised T=0, but it actually handles t=1 since it shuttles framed blocks to the backend. libcacard advertized T=0 in the ATR, so it works fine. This allows passthrough cards to work at t=1 if they need to.

Add a configurable property to also advertise T=1 in the dwProtocols field, enabled by default.

Use the correct error code (7, ICC protocol not supported) instead of CMD_NOT_SUPPORTED when SetParameters receives an invalid protocol.

Note: I only tested with libcacard emulation.

---
 hw/core/machine.c             |  1 +
 hw/usb/dev-smartcard-reader.c | 10 +++++++++-
 2 files changed, 10 insertions(+), 1 deletion(-)
hw/core/machine.c +1 -0
index 790d947e28d1..e9fecdec18df 100644
@@ -53,6 +53,7 @@ GlobalProperty hw_compat_11_0[] = {
     { "migration", "switchover-ack-legacy", "on" },
     { "usb-ccid", "x-accurate-message-length", "off" },
     { "usb-ccid", "x-pin-support", "on" },
+    { "usb-ccid", "x-t1-support", "off" },
     { "usb-ccid", "x-migrate-pending-answers", "off" },
 };
 const size_t hw_compat_11_0_len = G_N_ELEMENTS(hw_compat_11_0);
hw/usb/dev-smartcard-reader.c +9 -1
index 8520a2dab216..99086befe0b8 100644
@@ -169,6 +169,7 @@ enum {
     ERROR_CMD_SLOT_BUSY     = -32,
     ERROR_BAD_DWLENGTH      = 1,
     ERROR_SLOT_NOT_EXIST    = 5,
+    ERROR_PROTOCOL_INVALID  = 7,
 };
 
 /* 6.2.6 RDR_to_PC_SlotStatus definitions */
@@ -330,6 +331,7 @@ struct USBCCIDState {
     bool migrate_pending_answers;
     bool pending_answers_loaded;
     bool pin_support;
+    bool t1_support;
 };
 
 static uint32_t ccid_bulk_in_pending_num(USBCCIDState *s)
@@ -368,6 +370,7 @@ static uint8_t qemu_ccid_descriptor[] = {
                      */
         0x07,       /* u8  bVoltageSupport; 01h - 5.0v, 02h - 3.0, 03 - 1.8 */
 
+#define CCID_DESC_OFFSET_DW_PROTOCOLS 0x06
         0x01, 0x00, /* u32 dwProtocols; RRRR PPPP. RRRR = 0000h.*/
         0x00, 0x00, /* PPPP: 0001h = Protocol T=0, 0002h = Protocol T=1 */
                     /* u32 dwDefaultClock; in kHZ (0x0fa0 is 4 MHz) */
@@ -968,7 +971,7 @@ static void ccid_set_parameters(USBCCIDState *s, CCID_Header *recv)
     uint32_t protocol_num = ph->bProtocolNum & 3;
 
     if (protocol_num != 0 && protocol_num != 1) {
-        ccid_report_error_failed(s, ERROR_CMD_NOT_SUPPORTED);
+        ccid_report_error_failed(s, ERROR_PROTOCOL_INVALID);
         return;
     }
     s->bProtocolNum = protocol_num;
@@ -1546,6 +1549,9 @@ static void ccid_realize(USBDevice *dev, Error **errp)
     if (!s->pin_support) {
         qemu_ccid_descriptor[CCID_DESC_OFFSET_B_PIN_SUPPORT] = 0;
     }
+    if (s->t1_support) {
+        qemu_ccid_descriptor[CCID_DESC_OFFSET_DW_PROTOCOLS] |= 0x2;
+    }
     usb_desc_create_serial(dev);
     usb_desc_init(dev);
     qbus_init(&s->bus, sizeof(s->bus), TYPE_CCID_BUS, DEVICE(dev), NULL);
@@ -1742,6 +1748,8 @@ static const Property ccid_properties[] = {
                      accurate_message_length, true),
     DEFINE_PROP_BOOL("x-pin-support", USBCCIDState,
                      pin_support, false),
+    DEFINE_PROP_BOOL("x-t1-support", USBCCIDState,
+                     t1_support, true),
     DEFINE_PROP_BOOL("x-migrate-pending-answers", USBCCIDState,
                      migrate_pending_answers, true),
 };
Signature · 1 line
2.55.0
#35 lore raw

PATCH 26/27 hw/usb/dev-smartcard-reader: correct CCID_IccPowerOff

In reply to Marc-André Lureau

The struct has 3 bytes reserved according to spec. Fortunately, it's not used yet.

---
 hw/usb/dev-smartcard-reader.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
hw/usb/dev-smartcard-reader.c +1 -1
index 99086befe0b8..752571043ee6 100644
@@ -264,7 +264,7 @@ typedef struct QEMU_PACKED CCID_IccPowerOn {
 
 typedef struct QEMU_PACKED CCID_IccPowerOff {
     CCID_Header hdr;
-    uint16_t    abRFU;
+    uint8_t     abRFU[3];
 } CCID_IccPowerOff;
 
 typedef struct QEMU_PACKED CCID_SetParameters {
Signature · 1 line
2.55.0
Reviewed-by on v1 26/27
#36 lore raw

Re: [PATCH 26/27] hw/usb/dev-smartcard-reader: correct CCID_IccPowerOff

Quoted 13 lines · Marc-André Lureau

The struct has 3 bytes reserved according to spec. Fortunately, it's not used yet.

---
  hw/usb/dev-smartcard-reader.c | 2 +-
  1 file changed, 1 insertion(+), 1 deletion(-)
hw/usb/dev-smartcard-reader.c +0 -0
index 99086befe0b8..752571043ee6 100644

hw/usb/dev-smartcard-reader.c typedef struct QEMU_PACKED CCID_IccPowerOn { · line 268

Quoted 6 lines
hw/usb/dev-smartcard-reader.c +1 -1
@@ -264,7 +264,7 @@ typedef struct QEMU_PACKED CCID_IccPowerOn {
 
  typedef struct QEMU_PACKED CCID_IccPowerOff {
      CCID_Header hdr;
-    uint16_t    abRFU;
+    uint8_t     abRFU[3];
  } CCID_IccPowerOff;

Nice finding...

#37 lore raw

PATCH 27/27 hw/usb/ccid-card-emulated: free libcacard context

In reply to Marc-André Lureau

libcacard uses a global context, but we can call finalize since vcard_emul_init() would have failed earlier if a second card context was used.

This fixes libtss2-fapi leaks spotted by ASAN.

---
 hw/usb/ccid-card-emulated.c | 2 ++
 1 file changed, 2 insertions(+)
hw/usb/ccid-card-emulated.c +2 -0
index 985f21997aa8..6c8eec39faa9 100644
@@ -580,6 +580,8 @@ static void emulated_unrealize(CCIDCardState *base)
     qemu_mutex_destroy(&card->handle_apdu_mutex);
     qemu_mutex_destroy(&card->vreader_mutex);
     qemu_mutex_destroy(&card->event_list_mutex);
+
+    vcard_emul_finalize();
 }
 
 static const Property emulated_card_properties[] = {
Signature · 1 line
2.55.0
#38 lore raw
In reply to Marc-André Lureau

Hi all

Quoted 12 lines · Marc-André Lureau

Hi,

While tackling some CVEs issues, I also found several correctness and robustness improvements/fixes. The series:

- has 3 CVE fixes (OOB/assert)
- fixes xHCI compatibility
- some endianness fixes
- blocks & fixes migration
- better spec compliancy

almost a month, and no feedback. Should I just send a PR?

#39 lore raw

Hi

Quoted 11 lines · Marc-André Lureau

Hi all

Quoted 6 lines · Marc-André Lureau

Hi,

While tackling some CVEs issues, I also found several correctness and robustness improvements/fixes. The series:

Quoted 8 lines
Quoted 6 lines

- has 3 CVE fixes (OOB/assert)
- fixes xHCI compatibility
- some endianness fixes
- blocks & fixes migration
- better spec compliancy

almost a month, and no feedback. Should I just send a PR?

I don't know what else to do at this point but to beg people to take a look or just send the PR. Any opinion?

thanks

#40 lore raw
Quoted 22 lines · Marc-André Lureau

Hi

Quoted 18 lines · Marc-André Lureau

Hi all

Quoted 12 lines · Marc-André Lureau

Hi,

While tackling some CVEs issues, I also found several correctness and robustness improvements/fixes. The series:

- has 3 CVE fixes (OOB/assert)
- fixes xHCI compatibility
- some endianness fixes
- blocks & fixes migration
- better spec compliancy

Quoted 4 lines
Quoted 1 line

almost a month, and no feedback. Should I just send a PR?

I don't know what else to do at this point but to beg people to take a look or just send the PR. Any opinion?

Sorry for the delay.

I left a comment on the CVE-2026-18204 fix. Please -- if you agree it is correct -- squash it before sending the PR.