File: pcsc_driver.c

package info (click to toggle)
cardpeek 0.8.4-1
  • links: PTS
  • area: main
  • in suites: bullseye, buster, sid, stretch
  • size: 3,496 kB
  • sloc: ansic: 11,114; sh: 4,266; makefile: 82; xml: 58; objc: 38
file content (454 lines) | stat: -rw-r--r-- 13,326 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
/**********************************************************************
*
* This file is part of Cardpeek, the smartcard reader utility.
*
* Copyright 2009-2013 by 'L1L1'
*
* Cardpeek is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Cardpeek is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Cardpeek.  If not, see <http://www.gnu.org/licenses/>.
*
*/

#include <winscard.h>

#ifdef _WIN32
/*
 * On linux pioRecvPci is expected to point somewhere in the
 * SCardTransmit() call but on windows, we must make it NULL.
 * So here is an ugly trick.
 */
#define SCARD_PCI_NULL NULL
#elif defined(__APPLE__)
SCARD_IO_REQUEST pioRecvPci_dummy;
#define SCARD_PCI_NULL (&pioRecvPci_dummy)
#include <wintypes.h>
#define SCARD_ATTR_MAXINPUT 0x7A007
#else /* Linux et al. */
SCARD_IO_REQUEST pioRecvPci_dummy;
#define SCARD_PCI_NULL (&pioRecvPci_dummy)
#include <reader.h>
#endif

/* #ifndef _WIN32
 * #ifndef __APPLE__
 * #include <reader.h>
 * #endif
 *  SCARD_IO_REQUEST pioRecvPci_dummy;
 * #define SCARD_PCI_NULL (&pioRecvPci_dummy)
 * #else
 * *
   * On linux pioRecvPci is expected to point somewhere in the
   * SCardTransmit() call but on windows, we must make it NULL.
   * So here is an ugly trick.
   *
 * #define SCARD_PCI_NULL NULL
 * #endif
 * #ifdef __APPLE__
 * #include <wintypes.h>
 * #define SCARD_ATTR_MAXINPUT 0x7A007
 * #endif
 */

#define MAX_PCSC_READ_LENGTH 270

typedef struct
{
    LONG         hcontext;
    SCARDHANDLE  hcard;
    DWORD        protocol;
    LONG         status;
} pcsc_data_t;

static const char *pcsc_stringify_protocol(DWORD proto)
{
    static char proto_string[32];

    switch (proto)
    {
    case SCARD_PROTOCOL_T0:
        return "T=0";
    case SCARD_PROTOCOL_T1:
        return "T=1";
    case SCARD_PROTOCOL_RAW:
        return "Raw";
    }
    sprintf(proto_string,"UNKNOWN(0x%x)",(unsigned)proto);
    return proto_string;
}

static const char *pcsc_stringify_state(DWORD state)
{
    static char state_string[500];
    int state_string_len;

    *state_string = 0;

    if (state & SCARD_STATE_CHANGED)
        strcat(state_string," Changed state,");

    if (state & SCARD_STATE_IGNORE)
        strcat(state_string," Ignore reader,");

    if (state & SCARD_STATE_UNKNOWN)
        strcat(state_string," Unknown reader,");

    if (state & SCARD_STATE_UNAVAILABLE)
        strcat(state_string," Status unavailable,");

    if (state & SCARD_STATE_EMPTY)
        strcat(state_string," Card removed,");

    if (state & SCARD_STATE_PRESENT)
        strcat(state_string," Card present,");

    if (state & SCARD_STATE_EXCLUSIVE)
        strcat(state_string," Exclusive access,");

    if (state & SCARD_STATE_INUSE)
        strcat(state_string," Shared access,");

    if (state & SCARD_STATE_MUTE)
        strcat(state_string," Silent card,");

    state_string_len=strlen(state_string);
    if (state_string[state_string_len-1]==',')
        state_string[state_string_len-1]=0;
    else
        strcat(state_string,"UNDEFINED");

    return state_string;
}

static int pcsc_connect(cardreader_t *cr, unsigned prefered_protocol)
{
    DWORD attr_maxinput = 0;
    DWORD attr_maxinput_len = sizeof(unsigned int);
    SCARD_READERSTATE reader_state;
    pcsc_data_t* pcsc = cr->extra_data;
    int counter = 0;
    void *progress;

    memset(&reader_state,0,sizeof(reader_state));
    reader_state.szReader = cr->name+7;
    reader_state.dwCurrentState = SCARD_STATE_UNAWARE;
    pcsc->status = SCardGetStatusChange(pcsc->hcontext,INFINITE,&reader_state,1);

    if (pcsc->status != SCARD_S_SUCCESS)
    {
        log_printf(LOG_ERROR,"Failed to query reader status before connecting: %s (error 0x%08x).",
                pcsc_stringify_error(pcsc->status),
                pcsc->status );
        return 0;
    }

    progress = ui_inprogress_new("Connection","Waiting for the reader to connect to a card.");
    while ((reader_state.dwEventState & SCARD_STATE_PRESENT)==0)
    {
        reader_state.dwCurrentState = reader_state.dwEventState;
        if (((counter++)%30)==0)
        {
            log_printf(LOG_INFO,"Waiting for card to be present (current state: %s)...",
                    pcsc_stringify_state(reader_state.dwEventState));
        }

        if (!ui_inprogress_pulse(progress))
        {
            log_printf(LOG_ERROR,"Connection aborted by user");
            ui_inprogress_free(progress);
            pcsc->status = 0x6FFF;
            return 0;	    
        }

        pcsc->status = SCardGetStatusChange(pcsc->hcontext,100,&reader_state,1);
        if ((pcsc->status!=(LONG)SCARD_S_SUCCESS) && (pcsc->status!=(LONG)SCARD_E_TIMEOUT))
        {
            log_printf(LOG_ERROR,"Failed to query reader status change before connecting: %s (error 0x%08x/%08x).",
                    pcsc_stringify_error(pcsc->status),
                    pcsc->status,
                    SCARD_E_TIMEOUT );
            return 0;
        }
    }
    ui_inprogress_free(progress);

    log_printf(LOG_DEBUG,"Attempting to connect to '%s'",cr->name);
    pcsc->status = SCardConnect(pcsc->hcontext,
            cr->name+7,
            /* SCARD_SHARE_EXCLUSIVE, */
            SCARD_SHARE_SHARED,
            prefered_protocol,
            &(pcsc->hcard),
            &(cr->protocol));

    if (pcsc->status!=SCARD_S_SUCCESS)
    {
        log_printf(LOG_ERROR,"Connection failed: %s (error 0x%08x).",
                pcsc_stringify_error(pcsc->status),
                pcsc->status );
        return 0;
    }

    if (SCardGetAttrib(pcsc->hcard,SCARD_ATTR_MAXINPUT,(LPBYTE)&attr_maxinput,(LPDWORD)&attr_maxinput_len)==SCARD_S_SUCCESS)
        log_printf(LOG_INFO,"Reader maximum input length is %u bytes",attr_maxinput);
    else
        log_printf(LOG_DEBUG,"Could not determinate reader maximum input length");

    log_printf(LOG_INFO,"Connection successful, protocol is %s",pcsc_stringify_protocol(cr->protocol));
    cr->connected=1;

    return 1;
}

static int pcsc_disconnect(cardreader_t *cr)
{
    pcsc_data_t* pcsc = cr->extra_data;

    pcsc->status = SCardDisconnect(pcsc->hcard,SCARD_UNPOWER_CARD);
    if (pcsc->status==SCARD_S_SUCCESS)
    {
        cr->connected=0;
        log_printf(LOG_INFO,"Disconnected reader");
        return 1;
    }

    log_printf(LOG_ERROR,"Failed to disconnect reader: %s (error 0x%08x).",
               pcsc_stringify_error(pcsc->status),
               pcsc->status );
    return 0;
}

static int pcsc_reset(cardreader_t *cr)
{
    pcsc_data_t* pcsc = cr->extra_data;

    pcsc->status = SCardReconnect(pcsc->hcard,
                                  SCARD_SHARE_SHARED, 
                                  /* SCARD_SHARE_EXCLUSIVE, */
                                  cr->protocol,
                                  SCARD_RESET_CARD,
                                  &(cr->protocol));

#ifdef __APPLE__
    pcsc->status = SCardReconnect(pcsc->hcard,
                                  SCARD_SHARE_SHARED,
                                  /* SCARD_SHARE_EXCLUSIVE, */
                                  cr->protocol,
                                  SCARD_LEAVE_CARD,
                                  &(cr->protocol));
#endif

    if (pcsc->status==SCARD_S_SUCCESS)
    {
        log_printf(LOG_INFO,"Reconnected reader");
        cr->connected=1;
        return 1;
    }

    log_printf(LOG_ERROR,"Failed to reconnect reader: %s (error 0x%08x).",
               pcsc_stringify_error(pcsc->status),
               pcsc->status );
    cr->connected=0;
    return 0;
}

static unsigned short pcsc_transmit(cardreader_t* cr,
                                    const bytestring_t* command,
                                    bytestring_t* result)
{
    pcsc_data_t* pcsc = cr->extra_data;
    BYTE REC_DAT[MAX_PCSC_READ_LENGTH];
    DWORD REC_LEN=MAX_PCSC_READ_LENGTH;
    unsigned short SW;

    if (cr->protocol==SCARD_PROTOCOL_T0)
    {
        pcsc->status = SCardTransmit(pcsc->hcard,SCARD_PCI_T0,
                bytestring_get_data(command),
                bytestring_get_size(command),
                SCARD_PCI_NULL,
                REC_DAT,&REC_LEN);
    }
    else if (cr->protocol==SCARD_PROTOCOL_T1)
    {
        pcsc->status = SCardTransmit(pcsc->hcard,SCARD_PCI_T1,
                bytestring_get_data(command),
                bytestring_get_size(command),
                SCARD_PCI_NULL,
                REC_DAT,&REC_LEN);

    }
    else
    {
        log_printf(LOG_ERROR,"Unknown smartcard protocol: %i",cr->protocol);
        return CARDPEEK_ERROR_SW;
    }

    if (pcsc->status!=SCARD_S_SUCCESS)
    {
        log_printf(LOG_ERROR,"Failed to transmit command to card: %s (error 0x%08x).",
                pcsc_stringify_error(pcsc->status),
                pcsc->status );
        return CARDPEEK_ERROR_SW;
    }

    if (REC_LEN>=2)
    {
        bytestring_assign_data(result,REC_LEN-2,REC_DAT);
        SW = (REC_DAT[REC_LEN-2]<<8)|REC_DAT[REC_LEN-1];
    }
    else if (REC_LEN==1)
    {
        bytestring_clear(result);
        SW = REC_DAT[0];
    }
    else
    {
        log_printf(LOG_ERROR,"Transmited %i bytes to the card (%s), but received a response of length %i, without any status word included.",
                bytestring_get_size(command),
                pcsc_stringify_protocol(cr->protocol),
                REC_LEN);
        return CARDPEEK_ERROR_SW;
    }

    return SW;
}

static const bytestring_t* pcsc_last_atr(cardreader_t* cr)
{
    pcsc_data_t* pcsc = cr->extra_data;
    DWORD state;
    DWORD protocol;
    BYTE pbAtr[MAX_ATR_SIZE];
    DWORD atrlen=MAX_ATR_SIZE;
    char readername[MAX_READERNAME];
    DWORD readernamelen=MAX_READERNAME;
    /*char *tmp;*/

    pcsc->status = SCardStatus(pcsc->hcard,
                               readername,&readernamelen,
                               &state,
                               &protocol,
                               pbAtr,&atrlen);

    if (pcsc->status==SCARD_S_SUCCESS)
    {
        bytestring_assign_data(cr->atr,atrlen,pbAtr);
        /*tmp = bytestring_to_format("%D",cr->atr);
        log_printf(LOG_INFO,"ATR is %i bytes: %s",atrlen,tmp);
        free(tmp);*/
    }
    else
    {
        bytestring_clear(cr->atr);
        log_printf(LOG_ERROR,"Failed to query card status: %s (error 0x%08x).",
                   pcsc_stringify_error(pcsc->status),
                   pcsc->status );
    }
    return cr->atr;
}

#define NUM_INFO_FIELDS 3

static char **pcsc_get_info(cardreader_t* cr)
{
    pcsc_data_t* pcsc = cr->extra_data;
    DWORD state = 0;
    DWORD protocol;
    BYTE pbAtr[MAX_ATR_SIZE];
    DWORD atrlen=MAX_ATR_SIZE;
    char readername[MAX_READERNAME];
    DWORD readernamelen=MAX_READERNAME;
    char num_buf[20];
    char **info;

    pcsc->status = SCardStatus(pcsc->hcard,
                               readername,&readernamelen,
                               &state,
                               &protocol,
                               pbAtr,&atrlen);

    if (pcsc->status!=SCARD_S_SUCCESS)
    {
        cr->connected = 0;
        info = g_malloc(3 * sizeof(char *));

        info[0]=g_strdup("pcsc_status");
        sprintf(num_buf,"%u",(unsigned)(pcsc->status));
        info[1]=g_strdup(num_buf);

        info[2]=NULL;

        return info;
    }

    info = g_malloc((NUM_INFO_FIELDS*2+1)*sizeof(char *));

    info[0]=g_strdup("state");
    sprintf(num_buf,"%u",(unsigned)(state));
    info[1]=g_strdup(num_buf);

    bytestring_assign_data(cr->atr,atrlen,pbAtr);
    info[2]=g_strdup("atr");
    info[3]=bytestring_to_format("%D",cr->atr);

    info[4]=g_strdup("pcsc_status");
    sprintf(num_buf,"%u",(unsigned)(pcsc->status));
    info[5]=g_strdup(num_buf); 

    info[NUM_INFO_FIELDS*2]=NULL;

    return info;
}

static int pcsc_fail(cardreader_t* cr)
{
    pcsc_data_t* pcsc = cr->extra_data;
    return (pcsc->status!=SCARD_S_SUCCESS);
}

static void pcsc_finalize(cardreader_t* cr)
{
    pcsc_data_t* pcsc = cr->extra_data;
    SCardReleaseContext(pcsc->hcontext);
    free(pcsc);
}

static int pcsc_initialize(cardreader_t *reader)
{
    pcsc_data_t* pcsc = malloc(sizeof(pcsc_data_t));

    memset(pcsc,0,sizeof(pcsc_data_t));

    pcsc->status = SCardEstablishContext(SCARD_SCOPE_SYSTEM, NULL, NULL,
                                         &(pcsc->hcontext));
    if (pcsc->status!=SCARD_S_SUCCESS)
    {
        log_printf(LOG_ERROR,"Failed to establish PCSC card manager context: %s (error 0x%08x).",
                   pcsc_stringify_error(pcsc->status),
                   pcsc->status );
        return 0;
    }

    reader->extra_data = pcsc;

    reader->connect      = pcsc_connect;
    reader->disconnect   = pcsc_disconnect;
    reader->reset        = pcsc_reset;
    reader->transmit     = pcsc_transmit;
    reader->last_atr     = pcsc_last_atr;
    reader->get_info     = pcsc_get_info;
    reader->fail         = pcsc_fail;
    reader->finalize     = pcsc_finalize;
    return 1;
}