xref: /qemu/hw/usb/ccid-card-passthru.c (revision abff1abf)
1 /*
2  * CCID Passthru Card Device emulation
3  *
4  * Copyright (c) 2011 Red Hat.
5  * Written by Alon Levy.
6  *
7  * This work is licensed under the terms of the GNU GPL, version 2.1 or later.
8  * See the COPYING file in the top-level directory.
9  */
10 
11 #include "qemu/osdep.h"
12 #include "qemu-common.h"
13 #include "qemu/units.h"
14 #include <libcacard.h>
15 #include "chardev/char-fe.h"
16 #include "hw/qdev-properties.h"
17 #include "migration/vmstate.h"
18 #include "qemu/error-report.h"
19 #include "qemu/module.h"
20 #include "qemu/sockets.h"
21 #include "ccid.h"
22 #include "qapi/error.h"
23 
24 #define DPRINTF(card, lvl, fmt, ...)                    \
25 do {                                                    \
26     if (lvl <= card->debug) {                           \
27         printf("ccid-card-passthru: " fmt , ## __VA_ARGS__);     \
28     }                                                   \
29 } while (0)
30 
31 #define D_WARN 1
32 #define D_INFO 2
33 #define D_MORE_INFO 3
34 #define D_VERBOSE 4
35 
36 /* TODO: do we still need this? */
37 static const uint8_t DEFAULT_ATR[] = {
38 /*
39  * From some example somewhere
40  * 0x3B, 0xB0, 0x18, 0x00, 0xD1, 0x81, 0x05, 0xB1, 0x40, 0x38, 0x1F, 0x03, 0x28
41  */
42 
43 /* From an Athena smart card */
44  0x3B, 0xD5, 0x18, 0xFF, 0x80, 0x91, 0xFE, 0x1F, 0xC3, 0x80, 0x73, 0xC8, 0x21,
45  0x13, 0x08
46 };
47 
48 #define VSCARD_IN_SIZE      (64 * KiB)
49 
50 /* maximum size of ATR - from 7816-3 */
51 #define MAX_ATR_SIZE        40
52 
53 typedef struct PassthruState PassthruState;
54 
55 struct PassthruState {
56     CCIDCardState base;
57     CharBackend cs;
58     uint8_t  vscard_in_data[VSCARD_IN_SIZE];
59     uint32_t vscard_in_pos;
60     uint32_t vscard_in_hdr;
61     uint8_t  atr[MAX_ATR_SIZE];
62     uint8_t  atr_length;
63     uint8_t  debug;
64 };
65 
66 #define TYPE_CCID_PASSTHRU "ccid-card-passthru"
67 #define PASSTHRU_CCID_CARD(obj) \
68     OBJECT_CHECK(PassthruState, (obj), TYPE_CCID_PASSTHRU)
69 
70 /*
71  * VSCard protocol over chardev
72  * This code should not depend on the card type.
73  */
74 
75 static void ccid_card_vscard_send_msg(PassthruState *s,
76         VSCMsgType type, uint32_t reader_id,
77         const uint8_t *payload, uint32_t length)
78 {
79     VSCMsgHeader scr_msg_header;
80 
81     scr_msg_header.type = htonl(type);
82     scr_msg_header.reader_id = htonl(reader_id);
83     scr_msg_header.length = htonl(length);
84     /* XXX this blocks entire thread. Rewrite to use
85      * qemu_chr_fe_write and background I/O callbacks */
86     qemu_chr_fe_write_all(&s->cs, (uint8_t *)&scr_msg_header,
87                           sizeof(VSCMsgHeader));
88     qemu_chr_fe_write_all(&s->cs, payload, length);
89 }
90 
91 static void ccid_card_vscard_send_apdu(PassthruState *s,
92     const uint8_t *apdu, uint32_t length)
93 {
94     ccid_card_vscard_send_msg(
95         s, VSC_APDU, VSCARD_MINIMAL_READER_ID, apdu, length);
96 }
97 
98 static void ccid_card_vscard_send_error(PassthruState *s,
99                     uint32_t reader_id, VSCErrorCode code)
100 {
101     VSCMsgError msg = {.code = htonl(code)};
102 
103     ccid_card_vscard_send_msg(
104         s, VSC_Error, reader_id, (uint8_t *)&msg, sizeof(msg));
105 }
106 
107 static void ccid_card_vscard_send_init(PassthruState *s)
108 {
109     VSCMsgInit msg = {
110         .version = htonl(VSCARD_VERSION),
111         .magic = VSCARD_MAGIC,
112         .capabilities = {0}
113     };
114 
115     ccid_card_vscard_send_msg(s, VSC_Init, VSCARD_UNDEFINED_READER_ID,
116                          (uint8_t *)&msg, sizeof(msg));
117 }
118 
119 static int ccid_card_vscard_can_read(void *opaque)
120 {
121     PassthruState *card = opaque;
122 
123     return VSCARD_IN_SIZE >= card->vscard_in_pos ?
124            VSCARD_IN_SIZE - card->vscard_in_pos : 0;
125 }
126 
127 static void ccid_card_vscard_handle_init(
128     PassthruState *card, VSCMsgHeader *hdr, VSCMsgInit *init)
129 {
130     uint32_t *capabilities;
131     int num_capabilities;
132     int i;
133 
134     capabilities = init->capabilities;
135     num_capabilities =
136         1 + ((hdr->length - sizeof(VSCMsgInit)) / sizeof(uint32_t));
137     init->version = ntohl(init->version);
138     for (i = 0 ; i < num_capabilities; ++i) {
139         capabilities[i] = ntohl(capabilities[i]);
140     }
141     if (init->magic != VSCARD_MAGIC) {
142         error_report("wrong magic");
143         /* we can't disconnect the chardev */
144     }
145     if (init->version != VSCARD_VERSION) {
146         DPRINTF(card, D_WARN,
147             "got version %d, have %d", init->version, VSCARD_VERSION);
148     }
149     /* future handling of capabilities, none exist atm */
150     ccid_card_vscard_send_init(card);
151 }
152 
153 static int check_atr(PassthruState *card, uint8_t *data, int len)
154 {
155     int historical_length, opt_bytes;
156     int td_count = 0;
157     int td;
158 
159     if (len < 2) {
160         return 0;
161     }
162     historical_length = data[1] & 0xf;
163     opt_bytes = 0;
164     if (data[0] != 0x3b && data[0] != 0x3f) {
165         DPRINTF(card, D_WARN, "atr's T0 is 0x%X, not in {0x3b, 0x3f}\n",
166                 data[0]);
167         return 0;
168     }
169     td_count = 0;
170     td = data[1] >> 4;
171     while (td && td_count < 2 && opt_bytes + historical_length + 2 < len) {
172         td_count++;
173         if (td & 0x1) {
174             opt_bytes++;
175         }
176         if (td & 0x2) {
177             opt_bytes++;
178         }
179         if (td & 0x4) {
180             opt_bytes++;
181         }
182         if (td & 0x8) {
183             opt_bytes++;
184             td = data[opt_bytes + 2] >> 4;
185         }
186     }
187     if (len < 2 + historical_length + opt_bytes) {
188         DPRINTF(card, D_WARN,
189             "atr too short: len %d, but historical_len %d, T1 0x%X\n",
190             len, historical_length, data[1]);
191         return 0;
192     }
193     if (len > 2 + historical_length + opt_bytes) {
194         DPRINTF(card, D_WARN,
195             "atr too long: len %d, but hist/opt %d/%d, T1 0x%X\n",
196             len, historical_length, opt_bytes, data[1]);
197         /* let it through */
198     }
199     DPRINTF(card, D_VERBOSE,
200             "atr passes check: %d total length, %d historical, %d optional\n",
201             len, historical_length, opt_bytes);
202 
203     return 1;
204 }
205 
206 static void ccid_card_vscard_handle_message(PassthruState *card,
207     VSCMsgHeader *scr_msg_header)
208 {
209     uint8_t *data = (uint8_t *)&scr_msg_header[1];
210 
211     switch (scr_msg_header->type) {
212     case VSC_ATR:
213         DPRINTF(card, D_INFO, "VSC_ATR %d\n", scr_msg_header->length);
214         if (scr_msg_header->length > MAX_ATR_SIZE) {
215             error_report("ATR size exceeds spec, ignoring");
216             ccid_card_vscard_send_error(card, scr_msg_header->reader_id,
217                                         VSC_GENERAL_ERROR);
218             break;
219         }
220         if (!check_atr(card, data, scr_msg_header->length)) {
221             error_report("ATR is inconsistent, ignoring");
222             ccid_card_vscard_send_error(card, scr_msg_header->reader_id,
223                                         VSC_GENERAL_ERROR);
224             break;
225         }
226         memcpy(card->atr, data, scr_msg_header->length);
227         card->atr_length = scr_msg_header->length;
228         ccid_card_card_inserted(&card->base);
229         ccid_card_vscard_send_error(card, scr_msg_header->reader_id,
230                                     VSC_SUCCESS);
231         break;
232     case VSC_APDU:
233         ccid_card_send_apdu_to_guest(
234             &card->base, data, scr_msg_header->length);
235         break;
236     case VSC_CardRemove:
237         DPRINTF(card, D_INFO, "VSC_CardRemove\n");
238         ccid_card_card_removed(&card->base);
239         ccid_card_vscard_send_error(card,
240             scr_msg_header->reader_id, VSC_SUCCESS);
241         break;
242     case VSC_Init:
243         ccid_card_vscard_handle_init(
244             card, scr_msg_header, (VSCMsgInit *)data);
245         break;
246     case VSC_Error:
247         ccid_card_card_error(&card->base, *(uint32_t *)data);
248         break;
249     case VSC_ReaderAdd:
250         if (ccid_card_ccid_attach(&card->base) < 0) {
251             ccid_card_vscard_send_error(card, VSCARD_UNDEFINED_READER_ID,
252                                       VSC_CANNOT_ADD_MORE_READERS);
253         } else {
254             ccid_card_vscard_send_error(card, VSCARD_MINIMAL_READER_ID,
255                                         VSC_SUCCESS);
256         }
257         break;
258     case VSC_ReaderRemove:
259         ccid_card_ccid_detach(&card->base);
260         ccid_card_vscard_send_error(card,
261             scr_msg_header->reader_id, VSC_SUCCESS);
262         break;
263     default:
264         printf("usb-ccid: chardev: unexpected message of type %X\n",
265                scr_msg_header->type);
266         ccid_card_vscard_send_error(card, scr_msg_header->reader_id,
267             VSC_GENERAL_ERROR);
268     }
269 }
270 
271 static void ccid_card_vscard_drop_connection(PassthruState *card)
272 {
273     qemu_chr_fe_deinit(&card->cs, true);
274     card->vscard_in_pos = card->vscard_in_hdr = 0;
275 }
276 
277 static void ccid_card_vscard_read(void *opaque, const uint8_t *buf, int size)
278 {
279     PassthruState *card = opaque;
280     VSCMsgHeader *hdr;
281 
282     if (card->vscard_in_pos + size > VSCARD_IN_SIZE) {
283         error_report("no room for data: pos %u +  size %d > %" PRId64 "."
284                      " dropping connection.",
285                      card->vscard_in_pos, size, VSCARD_IN_SIZE);
286         ccid_card_vscard_drop_connection(card);
287         return;
288     }
289     assert(card->vscard_in_pos < VSCARD_IN_SIZE);
290     assert(card->vscard_in_hdr < VSCARD_IN_SIZE);
291     memcpy(card->vscard_in_data + card->vscard_in_pos, buf, size);
292     card->vscard_in_pos += size;
293     hdr = (VSCMsgHeader *)(card->vscard_in_data + card->vscard_in_hdr);
294 
295     while ((card->vscard_in_pos - card->vscard_in_hdr >= sizeof(VSCMsgHeader))
296          &&(card->vscard_in_pos - card->vscard_in_hdr >=
297                                   sizeof(VSCMsgHeader) + ntohl(hdr->length))) {
298         hdr->reader_id = ntohl(hdr->reader_id);
299         hdr->length = ntohl(hdr->length);
300         hdr->type = ntohl(hdr->type);
301         ccid_card_vscard_handle_message(card, hdr);
302         card->vscard_in_hdr += hdr->length + sizeof(VSCMsgHeader);
303         hdr = (VSCMsgHeader *)(card->vscard_in_data + card->vscard_in_hdr);
304     }
305     if (card->vscard_in_hdr == card->vscard_in_pos) {
306         card->vscard_in_pos = card->vscard_in_hdr = 0;
307     }
308 }
309 
310 static void ccid_card_vscard_event(void *opaque, QEMUChrEvent event)
311 {
312     PassthruState *card = opaque;
313 
314     switch (event) {
315     case CHR_EVENT_BREAK:
316         card->vscard_in_pos = card->vscard_in_hdr = 0;
317         break;
318     case CHR_EVENT_OPENED:
319         DPRINTF(card, D_INFO, "%s: CHR_EVENT_OPENED\n", __func__);
320         break;
321     case CHR_EVENT_MUX_IN:
322     case CHR_EVENT_MUX_OUT:
323     case CHR_EVENT_CLOSED:
324         /* Ignore */
325         break;
326     }
327 }
328 
329 /* End VSCard handling */
330 
331 static void passthru_apdu_from_guest(
332     CCIDCardState *base, const uint8_t *apdu, uint32_t len)
333 {
334     PassthruState *card = PASSTHRU_CCID_CARD(base);
335 
336     if (!qemu_chr_fe_backend_connected(&card->cs)) {
337         printf("ccid-passthru: no chardev, discarding apdu length %d\n", len);
338         return;
339     }
340     ccid_card_vscard_send_apdu(card, apdu, len);
341 }
342 
343 static const uint8_t *passthru_get_atr(CCIDCardState *base, uint32_t *len)
344 {
345     PassthruState *card = PASSTHRU_CCID_CARD(base);
346 
347     *len = card->atr_length;
348     return card->atr;
349 }
350 
351 static void passthru_realize(CCIDCardState *base, Error **errp)
352 {
353     PassthruState *card = PASSTHRU_CCID_CARD(base);
354 
355     card->vscard_in_pos = 0;
356     card->vscard_in_hdr = 0;
357     if (qemu_chr_fe_backend_connected(&card->cs)) {
358         DPRINTF(card, D_INFO, "ccid-card-passthru: initing chardev");
359         qemu_chr_fe_set_handlers(&card->cs,
360             ccid_card_vscard_can_read,
361             ccid_card_vscard_read,
362             ccid_card_vscard_event, NULL, card, NULL, true);
363         ccid_card_vscard_send_init(card);
364     } else {
365         error_setg(errp, "missing chardev");
366         return;
367     }
368     card->debug = parse_debug_env("QEMU_CCID_PASSTHRU_DEBUG", D_VERBOSE,
369                                   card->debug);
370     assert(sizeof(DEFAULT_ATR) <= MAX_ATR_SIZE);
371     memcpy(card->atr, DEFAULT_ATR, sizeof(DEFAULT_ATR));
372     card->atr_length = sizeof(DEFAULT_ATR);
373 }
374 
375 static VMStateDescription passthru_vmstate = {
376     .name = "ccid-card-passthru",
377     .version_id = 1,
378     .minimum_version_id = 1,
379     .fields = (VMStateField[]) {
380         VMSTATE_BUFFER(vscard_in_data, PassthruState),
381         VMSTATE_UINT32(vscard_in_pos, PassthruState),
382         VMSTATE_UINT32(vscard_in_hdr, PassthruState),
383         VMSTATE_BUFFER(atr, PassthruState),
384         VMSTATE_UINT8(atr_length, PassthruState),
385         VMSTATE_END_OF_LIST()
386     }
387 };
388 
389 static Property passthru_card_properties[] = {
390     DEFINE_PROP_CHR("chardev", PassthruState, cs),
391     DEFINE_PROP_UINT8("debug", PassthruState, debug, 0),
392     DEFINE_PROP_END_OF_LIST(),
393 };
394 
395 static void passthru_class_initfn(ObjectClass *klass, void *data)
396 {
397     DeviceClass *dc = DEVICE_CLASS(klass);
398     CCIDCardClass *cc = CCID_CARD_CLASS(klass);
399 
400     cc->realize = passthru_realize;
401     cc->get_atr = passthru_get_atr;
402     cc->apdu_from_guest = passthru_apdu_from_guest;
403     set_bit(DEVICE_CATEGORY_INPUT, dc->categories);
404     dc->desc = "passthrough smartcard";
405     dc->vmsd = &passthru_vmstate;
406     device_class_set_props(dc, passthru_card_properties);
407 }
408 
409 static const TypeInfo passthru_card_info = {
410     .name          = TYPE_CCID_PASSTHRU,
411     .parent        = TYPE_CCID_CARD,
412     .instance_size = sizeof(PassthruState),
413     .class_init    = passthru_class_initfn,
414 };
415 
416 static void ccid_card_passthru_register_types(void)
417 {
418     type_register_static(&passthru_card_info);
419 }
420 
421 type_init(ccid_card_passthru_register_types)
422