SCARD: Add function for fetching PIN retry counter
[mech_eap.git] / src / utils / pcsc_funcs.c
1 /*
2  * WPA Supplicant / PC/SC smartcard interface for USIM, GSM SIM
3  * Copyright (c) 2004-2007, 2012, Jouni Malinen <j@w1.fi>
4  *
5  * This software may be distributed under the terms of the BSD license.
6  * See README for more details.
7  *
8  * This file implements wrapper functions for accessing GSM SIM and 3GPP USIM
9  * cards through PC/SC smartcard library. These functions are used to implement
10  * authentication routines for EAP-SIM and EAP-AKA.
11  */
12
13 #include "includes.h"
14 #include <winscard.h>
15
16 #include "common.h"
17 #include "pcsc_funcs.h"
18
19
20 /* See ETSI GSM 11.11 and ETSI TS 102 221 for details.
21  * SIM commands:
22  * Command APDU: CLA INS P1 P2 P3 Data
23  *   CLA (class of instruction): A0 for GSM, 00 for USIM
24  *   INS (instruction)
25  *   P1 P2 P3 (parameters, P3 = length of Data)
26  * Response APDU: Data SW1 SW2
27  *   SW1 SW2 (Status words)
28  * Commands (INS P1 P2 P3):
29  *   SELECT: A4 00 00 02 <file_id, 2 bytes>
30  *   GET RESPONSE: C0 00 00 <len>
31  *   RUN GSM ALG: 88 00 00 00 <RAND len = 10>
32  *   RUN UMTS ALG: 88 00 81 <len=0x22> data: 0x10 | RAND | 0x10 | AUTN
33  *      P1 = ID of alg in card
34  *      P2 = ID of secret key
35  *   READ BINARY: B0 <offset high> <offset low> <len>
36  *   READ RECORD: B2 <record number> <mode> <len>
37  *      P2 (mode) = '02' (next record), '03' (previous record),
38  *                  '04' (absolute mode)
39  *   VERIFY CHV: 20 00 <CHV number> 08
40  *   CHANGE CHV: 24 00 <CHV number> 10
41  *   DISABLE CHV: 26 00 01 08
42  *   ENABLE CHV: 28 00 01 08
43  *   UNBLOCK CHV: 2C 00 <00=CHV1, 02=CHV2> 10
44  *   SLEEP: FA 00 00 00
45  */
46
47 /* GSM SIM commands */
48 #define SIM_CMD_SELECT                  0xa0, 0xa4, 0x00, 0x00, 0x02
49 #define SIM_CMD_RUN_GSM_ALG             0xa0, 0x88, 0x00, 0x00, 0x10
50 #define SIM_CMD_GET_RESPONSE            0xa0, 0xc0, 0x00, 0x00
51 #define SIM_CMD_READ_BIN                0xa0, 0xb0, 0x00, 0x00
52 #define SIM_CMD_READ_RECORD             0xa0, 0xb2, 0x00, 0x00
53 #define SIM_CMD_VERIFY_CHV1             0xa0, 0x20, 0x00, 0x01, 0x08
54
55 /* USIM commands */
56 #define USIM_CLA                        0x00
57 #define USIM_CMD_RUN_UMTS_ALG           0x00, 0x88, 0x00, 0x81, 0x22
58 #define USIM_CMD_GET_RESPONSE           0x00, 0xc0, 0x00, 0x00
59
60 #define SIM_RECORD_MODE_ABSOLUTE 0x04
61
62 #define USIM_FSP_TEMPL_TAG              0x62
63
64 #define USIM_TLV_FILE_DESC              0x82
65 #define USIM_TLV_FILE_ID                0x83
66 #define USIM_TLV_DF_NAME                0x84
67 #define USIM_TLV_PROPR_INFO             0xA5
68 #define USIM_TLV_LIFE_CYCLE_STATUS      0x8A
69 #define USIM_TLV_FILE_SIZE              0x80
70 #define USIM_TLV_TOTAL_FILE_SIZE        0x81
71 #define USIM_TLV_PIN_STATUS_TEMPLATE    0xC6
72 #define USIM_TLV_SHORT_FILE_ID          0x88
73 #define USIM_TLV_SECURITY_ATTR_8B       0x8B
74 #define USIM_TLV_SECURITY_ATTR_8C       0x8C
75 #define USIM_TLV_SECURITY_ATTR_AB       0xAB
76
77 #define USIM_PS_DO_TAG                  0x90
78
79 #define AKA_RAND_LEN 16
80 #define AKA_AUTN_LEN 16
81 #define AKA_AUTS_LEN 14
82 #define RES_MAX_LEN 16
83 #define IK_LEN 16
84 #define CK_LEN 16
85
86
87 typedef enum { SCARD_GSM_SIM, SCARD_USIM } sim_types;
88
89 struct scard_data {
90         SCARDCONTEXT ctx;
91         SCARDHANDLE card;
92         DWORD protocol;
93         sim_types sim_type;
94         int pin1_required;
95 };
96
97 #ifdef __MINGW32_VERSION
98 /* MinGW does not yet support WinScard, so load the needed functions
99  * dynamically from winscard.dll for now. */
100
101 static HINSTANCE dll = NULL; /* winscard.dll */
102
103 static const SCARD_IO_REQUEST *dll_g_rgSCardT0Pci, *dll_g_rgSCardT1Pci;
104 #undef SCARD_PCI_T0
105 #define SCARD_PCI_T0 (dll_g_rgSCardT0Pci)
106 #undef SCARD_PCI_T1
107 #define SCARD_PCI_T1 (dll_g_rgSCardT1Pci)
108
109
110 static WINSCARDAPI LONG WINAPI
111 (*dll_SCardEstablishContext)(IN DWORD dwScope,
112                              IN LPCVOID pvReserved1,
113                              IN LPCVOID pvReserved2,
114                              OUT LPSCARDCONTEXT phContext);
115 #define SCardEstablishContext dll_SCardEstablishContext
116
117 static long (*dll_SCardReleaseContext)(long hContext);
118 #define SCardReleaseContext dll_SCardReleaseContext
119
120 static WINSCARDAPI LONG WINAPI
121 (*dll_SCardListReadersA)(IN SCARDCONTEXT hContext,
122                          IN LPCSTR mszGroups,
123                          OUT LPSTR mszReaders,
124                          IN OUT LPDWORD pcchReaders);
125 #undef SCardListReaders
126 #define SCardListReaders dll_SCardListReadersA
127
128 static WINSCARDAPI LONG WINAPI
129 (*dll_SCardConnectA)(IN SCARDCONTEXT hContext,
130                      IN LPCSTR szReader,
131                      IN DWORD dwShareMode,
132                      IN DWORD dwPreferredProtocols,
133                      OUT LPSCARDHANDLE phCard,
134                      OUT LPDWORD pdwActiveProtocol);
135 #undef SCardConnect
136 #define SCardConnect dll_SCardConnectA
137
138 static WINSCARDAPI LONG WINAPI
139 (*dll_SCardDisconnect)(IN SCARDHANDLE hCard,
140                        IN DWORD dwDisposition);
141 #define SCardDisconnect dll_SCardDisconnect
142
143 static WINSCARDAPI LONG WINAPI
144 (*dll_SCardTransmit)(IN SCARDHANDLE hCard,
145                      IN LPCSCARD_IO_REQUEST pioSendPci,
146                      IN LPCBYTE pbSendBuffer,
147                      IN DWORD cbSendLength,
148                      IN OUT LPSCARD_IO_REQUEST pioRecvPci,
149                      OUT LPBYTE pbRecvBuffer,
150                      IN OUT LPDWORD pcbRecvLength);
151 #define SCardTransmit dll_SCardTransmit
152
153 static WINSCARDAPI LONG WINAPI
154 (*dll_SCardBeginTransaction)(IN SCARDHANDLE hCard);
155 #define SCardBeginTransaction dll_SCardBeginTransaction
156
157 static WINSCARDAPI LONG WINAPI
158 (*dll_SCardEndTransaction)(IN SCARDHANDLE hCard, IN DWORD dwDisposition);
159 #define SCardEndTransaction dll_SCardEndTransaction
160
161
162 static int mingw_load_symbols(void)
163 {
164         char *sym;
165
166         if (dll)
167                 return 0;
168
169         dll = LoadLibrary("winscard");
170         if (dll == NULL) {
171                 wpa_printf(MSG_DEBUG, "WinSCard: Could not load winscard.dll "
172                            "library");
173                 return -1;
174         }
175
176 #define LOADSYM(s) \
177         sym = #s; \
178         dll_ ## s = (void *) GetProcAddress(dll, sym); \
179         if (dll_ ## s == NULL) \
180                 goto fail;
181
182         LOADSYM(SCardEstablishContext);
183         LOADSYM(SCardReleaseContext);
184         LOADSYM(SCardListReadersA);
185         LOADSYM(SCardConnectA);
186         LOADSYM(SCardDisconnect);
187         LOADSYM(SCardTransmit);
188         LOADSYM(SCardBeginTransaction);
189         LOADSYM(SCardEndTransaction);
190         LOADSYM(g_rgSCardT0Pci);
191         LOADSYM(g_rgSCardT1Pci);
192
193 #undef LOADSYM
194
195         return 0;
196
197 fail:
198         wpa_printf(MSG_DEBUG, "WinSCard: Could not get address for %s from "
199                    "winscard.dll", sym);
200         FreeLibrary(dll);
201         dll = NULL;
202         return -1;
203 }
204
205
206 static void mingw_unload_symbols(void)
207 {
208         if (dll == NULL)
209                 return;
210
211         FreeLibrary(dll);
212         dll = NULL;
213 }
214
215 #else /* __MINGW32_VERSION */
216
217 #define mingw_load_symbols() 0
218 #define mingw_unload_symbols() do { } while (0)
219
220 #endif /* __MINGW32_VERSION */
221
222
223 static int _scard_select_file(struct scard_data *scard, unsigned short file_id,
224                               unsigned char *buf, size_t *buf_len,
225                               sim_types sim_type, unsigned char *aid,
226                               size_t aidlen);
227 static int scard_select_file(struct scard_data *scard, unsigned short file_id,
228                              unsigned char *buf, size_t *buf_len);
229 static int scard_verify_pin(struct scard_data *scard, const char *pin);
230 static int scard_get_record_len(struct scard_data *scard,
231                                 unsigned char recnum, unsigned char mode);
232 static int scard_read_record(struct scard_data *scard,
233                              unsigned char *data, size_t len,
234                              unsigned char recnum, unsigned char mode);
235
236
237 static int scard_parse_fsp_templ(unsigned char *buf, size_t buf_len,
238                                  int *ps_do, int *file_len)
239 {
240         unsigned char *pos, *end;
241
242         if (ps_do)
243                 *ps_do = -1;
244         if (file_len)
245                 *file_len = -1;
246
247         pos = buf;
248         end = pos + buf_len;
249         if (*pos != USIM_FSP_TEMPL_TAG) {
250                 wpa_printf(MSG_DEBUG, "SCARD: file header did not "
251                            "start with FSP template tag");
252                 return -1;
253         }
254         pos++;
255         if (pos >= end)
256                 return -1;
257         if ((pos + pos[0]) < end)
258                 end = pos + 1 + pos[0];
259         pos++;
260         wpa_hexdump(MSG_DEBUG, "SCARD: file header FSP template",
261                     pos, end - pos);
262
263         while (pos + 1 < end) {
264                 wpa_printf(MSG_MSGDUMP, "SCARD: file header TLV 0x%02x len=%d",
265                            pos[0], pos[1]);
266                 if (pos + 2 + pos[1] > end)
267                         break;
268
269                 switch (pos[0]) {
270                 case USIM_TLV_FILE_DESC:
271                         wpa_hexdump(MSG_MSGDUMP, "SCARD: File Descriptor TLV",
272                                     pos + 2, pos[1]);
273                         break;
274                 case USIM_TLV_FILE_ID:
275                         wpa_hexdump(MSG_MSGDUMP, "SCARD: File Identifier TLV",
276                                     pos + 2, pos[1]);
277                         break;
278                 case USIM_TLV_DF_NAME:
279                         wpa_hexdump(MSG_MSGDUMP, "SCARD: DF name (AID) TLV",
280                                     pos + 2, pos[1]);
281                         break;
282                 case USIM_TLV_PROPR_INFO:
283                         wpa_hexdump(MSG_MSGDUMP, "SCARD: Proprietary "
284                                     "information TLV", pos + 2, pos[1]);
285                         break;
286                 case USIM_TLV_LIFE_CYCLE_STATUS:
287                         wpa_hexdump(MSG_MSGDUMP, "SCARD: Life Cycle Status "
288                                     "Integer TLV", pos + 2, pos[1]);
289                         break;
290                 case USIM_TLV_FILE_SIZE:
291                         wpa_hexdump(MSG_MSGDUMP, "SCARD: File size TLV",
292                                     pos + 2, pos[1]);
293                         if ((pos[1] == 1 || pos[1] == 2) && file_len) {
294                                 if (pos[1] == 1)
295                                         *file_len = (int) pos[2];
296                                 else
297                                         *file_len = ((int) pos[2] << 8) |
298                                                 (int) pos[3];
299                                 wpa_printf(MSG_DEBUG, "SCARD: file_size=%d",
300                                            *file_len);
301                         }
302                         break;
303                 case USIM_TLV_TOTAL_FILE_SIZE:
304                         wpa_hexdump(MSG_MSGDUMP, "SCARD: Total file size TLV",
305                                     pos + 2, pos[1]);
306                         break;
307                 case USIM_TLV_PIN_STATUS_TEMPLATE:
308                         wpa_hexdump(MSG_MSGDUMP, "SCARD: PIN Status Template "
309                                     "DO TLV", pos + 2, pos[1]);
310                         if (pos[1] >= 2 && pos[2] == USIM_PS_DO_TAG &&
311                             pos[3] >= 1 && ps_do) {
312                                 wpa_printf(MSG_DEBUG, "SCARD: PS_DO=0x%02x",
313                                            pos[4]);
314                                 *ps_do = (int) pos[4];
315                         }
316                         break;
317                 case USIM_TLV_SHORT_FILE_ID:
318                         wpa_hexdump(MSG_MSGDUMP, "SCARD: Short File "
319                                     "Identifier (SFI) TLV", pos + 2, pos[1]);
320                         break;
321                 case USIM_TLV_SECURITY_ATTR_8B:
322                 case USIM_TLV_SECURITY_ATTR_8C:
323                 case USIM_TLV_SECURITY_ATTR_AB:
324                         wpa_hexdump(MSG_MSGDUMP, "SCARD: Security attribute "
325                                     "TLV", pos + 2, pos[1]);
326                         break;
327                 default:
328                         wpa_hexdump(MSG_MSGDUMP, "SCARD: Unrecognized TLV",
329                                     pos, 2 + pos[1]);
330                         break;
331                 }
332
333                 pos += 2 + pos[1];
334
335                 if (pos == end)
336                         return 0;
337         }
338         return -1;
339 }
340
341
342 static int scard_pin_needed(struct scard_data *scard,
343                             unsigned char *hdr, size_t hlen)
344 {
345         if (scard->sim_type == SCARD_GSM_SIM) {
346                 if (hlen > SCARD_CHV1_OFFSET &&
347                     !(hdr[SCARD_CHV1_OFFSET] & SCARD_CHV1_FLAG))
348                         return 1;
349                 return 0;
350         }
351
352         if (scard->sim_type == SCARD_USIM) {
353                 int ps_do;
354                 if (scard_parse_fsp_templ(hdr, hlen, &ps_do, NULL))
355                         return -1;
356                 /* TODO: there could be more than one PS_DO entry because of
357                  * multiple PINs in key reference.. */
358                 if (ps_do > 0 && (ps_do & 0x80))
359                         return 1;
360                 return 0;
361         }
362
363         return -1;
364 }
365
366
367 static int scard_get_aid(struct scard_data *scard, unsigned char *aid,
368                          size_t maxlen)
369 {
370         int rlen, rec;
371         struct efdir {
372                 unsigned char appl_template_tag; /* 0x61 */
373                 unsigned char appl_template_len;
374                 unsigned char appl_id_tag; /* 0x4f */
375                 unsigned char aid_len;
376                 unsigned char rid[5];
377                 unsigned char appl_code[2]; /* 0x1002 for 3G USIM */
378         } *efdir;
379         unsigned char buf[100];
380         size_t blen;
381
382         efdir = (struct efdir *) buf;
383         blen = sizeof(buf);
384         if (scard_select_file(scard, SCARD_FILE_EF_DIR, buf, &blen)) {
385                 wpa_printf(MSG_DEBUG, "SCARD: Failed to read EF_DIR");
386                 return -1;
387         }
388         wpa_hexdump(MSG_DEBUG, "SCARD: EF_DIR select", buf, blen);
389
390         for (rec = 1; rec < 10; rec++) {
391                 rlen = scard_get_record_len(scard, rec,
392                                             SIM_RECORD_MODE_ABSOLUTE);
393                 if (rlen < 0) {
394                         wpa_printf(MSG_DEBUG, "SCARD: Failed to get EF_DIR "
395                                    "record length");
396                         return -1;
397                 }
398                 blen = sizeof(buf);
399                 if (rlen > (int) blen) {
400                         wpa_printf(MSG_DEBUG, "SCARD: Too long EF_DIR record");
401                         return -1;
402                 }
403                 if (scard_read_record(scard, buf, rlen, rec,
404                                       SIM_RECORD_MODE_ABSOLUTE) < 0) {
405                         wpa_printf(MSG_DEBUG, "SCARD: Failed to read "
406                                    "EF_DIR record %d", rec);
407                         return -1;
408                 }
409                 wpa_hexdump(MSG_DEBUG, "SCARD: EF_DIR record", buf, rlen);
410
411                 if (efdir->appl_template_tag != 0x61) {
412                         wpa_printf(MSG_DEBUG, "SCARD: Unexpected application "
413                                    "template tag 0x%x",
414                                    efdir->appl_template_tag);
415                         continue;
416                 }
417
418                 if (efdir->appl_template_len > rlen - 2) {
419                         wpa_printf(MSG_DEBUG, "SCARD: Too long application "
420                                    "template (len=%d rlen=%d)",
421                                    efdir->appl_template_len, rlen);
422                         continue;
423                 }
424
425                 if (efdir->appl_id_tag != 0x4f) {
426                         wpa_printf(MSG_DEBUG, "SCARD: Unexpected application "
427                                    "identifier tag 0x%x", efdir->appl_id_tag);
428                         continue;
429                 }
430
431                 if (efdir->aid_len < 1 || efdir->aid_len > 16) {
432                         wpa_printf(MSG_DEBUG, "SCARD: Invalid AID length %d",
433                                    efdir->aid_len);
434                         continue;
435                 }
436
437                 wpa_hexdump(MSG_DEBUG, "SCARD: AID from EF_DIR record",
438                             efdir->rid, efdir->aid_len);
439
440                 if (efdir->appl_code[0] == 0x10 &&
441                     efdir->appl_code[1] == 0x02) {
442                         wpa_printf(MSG_DEBUG, "SCARD: 3G USIM app found from "
443                                    "EF_DIR record %d", rec);
444                         break;
445                 }
446         }
447
448         if (rec >= 10) {
449                 wpa_printf(MSG_DEBUG, "SCARD: 3G USIM app not found "
450                            "from EF_DIR records");
451                 return -1;
452         }
453
454         if (efdir->aid_len > maxlen) {
455                 wpa_printf(MSG_DEBUG, "SCARD: Too long AID");
456                 return -1;
457         }
458
459         os_memcpy(aid, efdir->rid, efdir->aid_len);
460
461         return efdir->aid_len;
462 }
463
464
465 /**
466  * scard_init - Initialize SIM/USIM connection using PC/SC
467  * @sim_type: Allowed SIM types (SIM, USIM, or both)
468  * @reader: Reader name prefix to search for
469  * Returns: Pointer to private data structure, or %NULL on failure
470  *
471  * This function is used to initialize SIM/USIM connection. PC/SC is used to
472  * open connection to the SIM/USIM card and the card is verified to support the
473  * selected sim_type. In addition, local flag is set if a PIN is needed to
474  * access some of the card functions. Once the connection is not needed
475  * anymore, scard_deinit() can be used to close it.
476  */
477 struct scard_data * scard_init(scard_sim_type sim_type, const char *reader)
478 {
479         long ret;
480         unsigned long len, pos;
481         struct scard_data *scard;
482 #ifdef CONFIG_NATIVE_WINDOWS
483         TCHAR *readers = NULL;
484 #else /* CONFIG_NATIVE_WINDOWS */
485         char *readers = NULL;
486 #endif /* CONFIG_NATIVE_WINDOWS */
487         unsigned char buf[100];
488         size_t blen;
489         int transaction = 0;
490         int pin_needed;
491
492         wpa_printf(MSG_DEBUG, "SCARD: initializing smart card interface");
493         if (mingw_load_symbols())
494                 return NULL;
495         scard = os_zalloc(sizeof(*scard));
496         if (scard == NULL)
497                 return NULL;
498
499         ret = SCardEstablishContext(SCARD_SCOPE_SYSTEM, NULL, NULL,
500                                     &scard->ctx);
501         if (ret != SCARD_S_SUCCESS) {
502                 wpa_printf(MSG_DEBUG, "SCARD: Could not establish smart card "
503                            "context (err=%ld)", ret);
504                 goto failed;
505         }
506
507         ret = SCardListReaders(scard->ctx, NULL, NULL, &len);
508         if (ret != SCARD_S_SUCCESS) {
509                 wpa_printf(MSG_DEBUG, "SCARD: SCardListReaders failed "
510                            "(err=%ld)", ret);
511                 goto failed;
512         }
513
514 #ifdef UNICODE
515         len *= 2;
516 #endif /* UNICODE */
517         readers = os_malloc(len);
518         if (readers == NULL) {
519                 wpa_printf(MSG_INFO, "SCARD: malloc failed\n");
520                 goto failed;
521         }
522
523         ret = SCardListReaders(scard->ctx, NULL, readers, &len);
524         if (ret != SCARD_S_SUCCESS) {
525                 wpa_printf(MSG_DEBUG, "SCARD: SCardListReaders failed(2) "
526                            "(err=%ld)", ret);
527                 goto failed;
528         }
529         if (len < 3) {
530                 wpa_printf(MSG_WARNING, "SCARD: No smart card readers "
531                            "available.");
532                 goto failed;
533         }
534         wpa_hexdump_ascii(MSG_DEBUG, "SCARD: Readers", (u8 *) readers, len);
535         /*
536          * readers is a list of available readers. The last entry is terminated
537          * with double null.
538          */
539         pos = 0;
540 #ifdef UNICODE
541         /* TODO */
542 #else /* UNICODE */
543         while (pos < len) {
544                 if (reader == NULL ||
545                     os_strncmp(&readers[pos], reader, os_strlen(reader)) == 0)
546                         break;
547                 while (pos < len && readers[pos])
548                         pos++;
549                 pos++; /* skip separating null */
550                 if (pos < len && readers[pos] == '\0')
551                         pos = len; /* double null terminates list */
552         }
553 #endif /* UNICODE */
554         if (pos >= len) {
555                 wpa_printf(MSG_WARNING, "SCARD: No reader with prefix '%s' "
556                            "found", reader);
557                 goto failed;
558         }
559
560 #ifdef UNICODE
561         wpa_printf(MSG_DEBUG, "SCARD: Selected reader='%S'", &readers[pos]);
562 #else /* UNICODE */
563         wpa_printf(MSG_DEBUG, "SCARD: Selected reader='%s'", &readers[pos]);
564 #endif /* UNICODE */
565
566         ret = SCardConnect(scard->ctx, &readers[pos], SCARD_SHARE_SHARED,
567                            SCARD_PROTOCOL_T0 | SCARD_PROTOCOL_T1,
568                            &scard->card, &scard->protocol);
569         if (ret != SCARD_S_SUCCESS) {
570                 if (ret == (long) SCARD_E_NO_SMARTCARD)
571                         wpa_printf(MSG_INFO, "No smart card inserted.");
572                 else
573                         wpa_printf(MSG_WARNING, "SCardConnect err=%lx", ret);
574                 goto failed;
575         }
576
577         os_free(readers);
578         readers = NULL;
579
580         wpa_printf(MSG_DEBUG, "SCARD: card=0x%x active_protocol=%lu (%s)",
581                    (unsigned int) scard->card, scard->protocol,
582                    scard->protocol == SCARD_PROTOCOL_T0 ? "T0" : "T1");
583
584         ret = SCardBeginTransaction(scard->card);
585         if (ret != SCARD_S_SUCCESS) {
586                 wpa_printf(MSG_DEBUG, "SCARD: Could not begin transaction: "
587                            "0x%x", (unsigned int) ret);
588                 goto failed;
589         }
590         transaction = 1;
591
592         blen = sizeof(buf);
593
594         scard->sim_type = SCARD_GSM_SIM;
595         if (sim_type == SCARD_USIM_ONLY || sim_type == SCARD_TRY_BOTH) {
596                 wpa_printf(MSG_DEBUG, "SCARD: verifying USIM support");
597                 if (_scard_select_file(scard, SCARD_FILE_MF, buf, &blen,
598                                        SCARD_USIM, NULL, 0)) {
599                         wpa_printf(MSG_DEBUG, "SCARD: USIM is not supported");
600                         if (sim_type == SCARD_USIM_ONLY)
601                                 goto failed;
602                         wpa_printf(MSG_DEBUG, "SCARD: Trying to use GSM SIM");
603                         scard->sim_type = SCARD_GSM_SIM;
604                 } else {
605                         wpa_printf(MSG_DEBUG, "SCARD: USIM is supported");
606                         scard->sim_type = SCARD_USIM;
607                 }
608         }
609
610         if (scard->sim_type == SCARD_GSM_SIM) {
611                 blen = sizeof(buf);
612                 if (scard_select_file(scard, SCARD_FILE_MF, buf, &blen)) {
613                         wpa_printf(MSG_DEBUG, "SCARD: Failed to read MF");
614                         goto failed;
615                 }
616
617                 blen = sizeof(buf);
618                 if (scard_select_file(scard, SCARD_FILE_GSM_DF, buf, &blen)) {
619                         wpa_printf(MSG_DEBUG, "SCARD: Failed to read GSM DF");
620                         goto failed;
621                 }
622         } else {
623                 unsigned char aid[32];
624                 int aid_len;
625
626                 aid_len = scard_get_aid(scard, aid, sizeof(aid));
627                 if (aid_len < 0) {
628                         wpa_printf(MSG_DEBUG, "SCARD: Failed to find AID for "
629                                    "3G USIM app - try to use standard 3G RID");
630                         os_memcpy(aid, "\xa0\x00\x00\x00\x87", 5);
631                         aid_len = 5;
632                 }
633                 wpa_hexdump(MSG_DEBUG, "SCARD: 3G USIM AID", aid, aid_len);
634
635                 /* Select based on AID = 3G RID from EF_DIR. This is usually
636                  * starting with A0 00 00 00 87. */
637                 blen = sizeof(buf);
638                 if (_scard_select_file(scard, 0, buf, &blen, scard->sim_type,
639                                        aid, aid_len)) {
640                         wpa_printf(MSG_INFO, "SCARD: Failed to read 3G USIM "
641                                    "app");
642                         wpa_hexdump(MSG_INFO, "SCARD: 3G USIM AID",
643                                     aid, aid_len);
644                         goto failed;
645                 }
646         }
647
648         /* Verify whether CHV1 (PIN1) is needed to access the card. */
649         pin_needed = scard_pin_needed(scard, buf, blen);
650         if (pin_needed < 0) {
651                 wpa_printf(MSG_DEBUG, "SCARD: Failed to determine whether PIN "
652                            "is needed");
653                 goto failed;
654         }
655         if (pin_needed) {
656                 scard->pin1_required = 1;
657                 wpa_printf(MSG_DEBUG, "PIN1 needed for SIM access (retry "
658                            "counter=%d)", scard_get_pin_retry_counter(scard));
659         }
660
661         ret = SCardEndTransaction(scard->card, SCARD_LEAVE_CARD);
662         if (ret != SCARD_S_SUCCESS) {
663                 wpa_printf(MSG_DEBUG, "SCARD: Could not end transaction: "
664                            "0x%x", (unsigned int) ret);
665         }
666
667         return scard;
668
669 failed:
670         if (transaction)
671                 SCardEndTransaction(scard->card, SCARD_LEAVE_CARD);
672         os_free(readers);
673         scard_deinit(scard);
674         return NULL;
675 }
676
677
678 /**
679  * scard_set_pin - Set PIN (CHV1/PIN1) code for accessing SIM/USIM commands
680  * @scard: Pointer to private data from scard_init()
681  * @pin: PIN code as an ASCII string (e.g., "1234")
682  * Returns: 0 on success, -1 on failure
683  */
684 int scard_set_pin(struct scard_data *scard, const char *pin)
685 {
686         if (scard == NULL)
687                 return -1;
688
689         /* Verify whether CHV1 (PIN1) is needed to access the card. */
690         if (scard->pin1_required) {
691                 if (pin == NULL) {
692                         wpa_printf(MSG_DEBUG, "No PIN configured for SIM "
693                                    "access");
694                         return -1;
695                 }
696                 if (scard_verify_pin(scard, pin)) {
697                         wpa_printf(MSG_INFO, "PIN verification failed for "
698                                 "SIM access");
699                         return -1;
700                 }
701         }
702
703         return 0;
704 }
705
706
707 /**
708  * scard_deinit - Deinitialize SIM/USIM connection
709  * @scard: Pointer to private data from scard_init()
710  *
711  * This function closes the SIM/USIM connect opened with scard_init().
712  */
713 void scard_deinit(struct scard_data *scard)
714 {
715         long ret;
716
717         if (scard == NULL)
718                 return;
719
720         wpa_printf(MSG_DEBUG, "SCARD: deinitializing smart card interface");
721         if (scard->card) {
722                 ret = SCardDisconnect(scard->card, SCARD_UNPOWER_CARD);
723                 if (ret != SCARD_S_SUCCESS) {
724                         wpa_printf(MSG_DEBUG, "SCARD: Failed to disconnect "
725                                    "smart card (err=%ld)", ret);
726                 }
727         }
728
729         if (scard->ctx) {
730                 ret = SCardReleaseContext(scard->ctx);
731                 if (ret != SCARD_S_SUCCESS) {
732                         wpa_printf(MSG_DEBUG, "Failed to release smart card "
733                                    "context (err=%ld)", ret);
734                 }
735         }
736         os_free(scard);
737         mingw_unload_symbols();
738 }
739
740
741 static long scard_transmit(struct scard_data *scard,
742                            unsigned char *_send, size_t send_len,
743                            unsigned char *_recv, size_t *recv_len)
744 {
745         long ret;
746         unsigned long rlen;
747
748         wpa_hexdump_key(MSG_DEBUG, "SCARD: scard_transmit: send",
749                         _send, send_len);
750         rlen = *recv_len;
751         ret = SCardTransmit(scard->card,
752                             scard->protocol == SCARD_PROTOCOL_T1 ?
753                             SCARD_PCI_T1 : SCARD_PCI_T0,
754                             _send, (unsigned long) send_len,
755                             NULL, _recv, &rlen);
756         *recv_len = rlen;
757         if (ret == SCARD_S_SUCCESS) {
758                 wpa_hexdump(MSG_DEBUG, "SCARD: scard_transmit: recv",
759                             _recv, rlen);
760         } else {
761                 wpa_printf(MSG_WARNING, "SCARD: SCardTransmit failed "
762                            "(err=0x%lx)", ret);
763         }
764         return ret;
765 }
766
767
768 static int _scard_select_file(struct scard_data *scard, unsigned short file_id,
769                               unsigned char *buf, size_t *buf_len,
770                               sim_types sim_type, unsigned char *aid,
771                               size_t aidlen)
772 {
773         long ret;
774         unsigned char resp[3];
775         unsigned char cmd[50] = { SIM_CMD_SELECT };
776         int cmdlen;
777         unsigned char get_resp[5] = { SIM_CMD_GET_RESPONSE };
778         size_t len, rlen;
779
780         if (sim_type == SCARD_USIM) {
781                 cmd[0] = USIM_CLA;
782                 cmd[3] = 0x04;
783                 get_resp[0] = USIM_CLA;
784         }
785
786         wpa_printf(MSG_DEBUG, "SCARD: select file %04x", file_id);
787         if (aid) {
788                 wpa_hexdump(MSG_DEBUG, "SCARD: select file by AID",
789                             aid, aidlen);
790                 if (5 + aidlen > sizeof(cmd))
791                         return -1;
792                 cmd[2] = 0x04; /* Select by AID */
793                 cmd[4] = aidlen; /* len */
794                 os_memcpy(cmd + 5, aid, aidlen);
795                 cmdlen = 5 + aidlen;
796         } else {
797                 cmd[5] = file_id >> 8;
798                 cmd[6] = file_id & 0xff;
799                 cmdlen = 7;
800         }
801         len = sizeof(resp);
802         ret = scard_transmit(scard, cmd, cmdlen, resp, &len);
803         if (ret != SCARD_S_SUCCESS) {
804                 wpa_printf(MSG_WARNING, "SCARD: SCardTransmit failed "
805                            "(err=0x%lx)", ret);
806                 return -1;
807         }
808
809         if (len != 2) {
810                 wpa_printf(MSG_WARNING, "SCARD: unexpected resp len "
811                            "%d (expected 2)", (int) len);
812                 return -1;
813         }
814
815         if (resp[0] == 0x98 && resp[1] == 0x04) {
816                 /* Security status not satisfied (PIN_WLAN) */
817                 wpa_printf(MSG_WARNING, "SCARD: Security status not satisfied "
818                            "(PIN_WLAN)");
819                 return -1;
820         }
821
822         if (resp[0] == 0x6e) {
823                 wpa_printf(MSG_DEBUG, "SCARD: used CLA not supported");
824                 return -1;
825         }
826
827         if (resp[0] != 0x6c && resp[0] != 0x9f && resp[0] != 0x61) {
828                 wpa_printf(MSG_WARNING, "SCARD: unexpected response 0x%02x "
829                            "(expected 0x61, 0x6c, or 0x9f)", resp[0]);
830                 return -1;
831         }
832         /* Normal ending of command; resp[1] bytes available */
833         get_resp[4] = resp[1];
834         wpa_printf(MSG_DEBUG, "SCARD: trying to get response (%d bytes)",
835                    resp[1]);
836
837         rlen = *buf_len;
838         ret = scard_transmit(scard, get_resp, sizeof(get_resp), buf, &rlen);
839         if (ret == SCARD_S_SUCCESS) {
840                 *buf_len = resp[1] < rlen ? resp[1] : rlen;
841                 return 0;
842         }
843
844         wpa_printf(MSG_WARNING, "SCARD: SCardTransmit err=0x%lx\n", ret);
845         return -1;
846 }
847
848
849 static int scard_select_file(struct scard_data *scard, unsigned short file_id,
850                              unsigned char *buf, size_t *buf_len)
851 {
852         return _scard_select_file(scard, file_id, buf, buf_len,
853                                   scard->sim_type, NULL, 0);
854 }
855
856
857 static int scard_get_record_len(struct scard_data *scard, unsigned char recnum,
858                                 unsigned char mode)
859 {
860         unsigned char buf[255];
861         unsigned char cmd[5] = { SIM_CMD_READ_RECORD /* , len */ };
862         size_t blen;
863         long ret;
864
865         if (scard->sim_type == SCARD_USIM)
866                 cmd[0] = USIM_CLA;
867         cmd[2] = recnum;
868         cmd[3] = mode;
869         cmd[4] = sizeof(buf);
870
871         blen = sizeof(buf);
872         ret = scard_transmit(scard, cmd, sizeof(cmd), buf, &blen);
873         if (ret != SCARD_S_SUCCESS) {
874                 wpa_printf(MSG_DEBUG, "SCARD: failed to determine file "
875                            "length for record %d", recnum);
876                 return -1;
877         }
878
879         wpa_hexdump(MSG_DEBUG, "SCARD: file length determination response",
880                     buf, blen);
881
882         if (blen < 2 || (buf[0] != 0x6c && buf[0] != 0x67)) {
883                 wpa_printf(MSG_DEBUG, "SCARD: unexpected response to file "
884                            "length determination");
885                 return -1;
886         }
887
888         return buf[1];
889 }
890
891
892 static int scard_read_record(struct scard_data *scard,
893                              unsigned char *data, size_t len,
894                              unsigned char recnum, unsigned char mode)
895 {
896         unsigned char cmd[5] = { SIM_CMD_READ_RECORD /* , len */ };
897         size_t blen = len + 3;
898         unsigned char *buf;
899         long ret;
900
901         if (scard->sim_type == SCARD_USIM)
902                 cmd[0] = USIM_CLA;
903         cmd[2] = recnum;
904         cmd[3] = mode;
905         cmd[4] = len;
906
907         buf = os_malloc(blen);
908         if (buf == NULL)
909                 return -1;
910
911         ret = scard_transmit(scard, cmd, sizeof(cmd), buf, &blen);
912         if (ret != SCARD_S_SUCCESS) {
913                 os_free(buf);
914                 return -2;
915         }
916         if (blen != len + 2) {
917                 wpa_printf(MSG_DEBUG, "SCARD: record read returned unexpected "
918                            "length %ld (expected %ld)",
919                            (long) blen, (long) len + 2);
920                 os_free(buf);
921                 return -3;
922         }
923
924         if (buf[len] != 0x90 || buf[len + 1] != 0x00) {
925                 wpa_printf(MSG_DEBUG, "SCARD: record read returned unexpected "
926                            "status %02x %02x (expected 90 00)",
927                            buf[len], buf[len + 1]);
928                 os_free(buf);
929                 return -4;
930         }
931
932         os_memcpy(data, buf, len);
933         os_free(buf);
934
935         return 0;
936 }
937
938
939 static int scard_read_file(struct scard_data *scard,
940                            unsigned char *data, size_t len)
941 {
942         unsigned char cmd[5] = { SIM_CMD_READ_BIN /* , len */ };
943         size_t blen = len + 3;
944         unsigned char *buf;
945         long ret;
946
947         cmd[4] = len;
948
949         buf = os_malloc(blen);
950         if (buf == NULL)
951                 return -1;
952
953         if (scard->sim_type == SCARD_USIM)
954                 cmd[0] = USIM_CLA;
955         ret = scard_transmit(scard, cmd, sizeof(cmd), buf, &blen);
956         if (ret != SCARD_S_SUCCESS) {
957                 os_free(buf);
958                 return -2;
959         }
960         if (blen != len + 2) {
961                 wpa_printf(MSG_DEBUG, "SCARD: file read returned unexpected "
962                            "length %ld (expected %ld)",
963                            (long) blen, (long) len + 2);
964                 os_free(buf);
965                 return -3;
966         }
967
968         if (buf[len] != 0x90 || buf[len + 1] != 0x00) {
969                 wpa_printf(MSG_DEBUG, "SCARD: file read returned unexpected "
970                            "status %02x %02x (expected 90 00)",
971                            buf[len], buf[len + 1]);
972                 os_free(buf);
973                 return -4;
974         }
975
976         os_memcpy(data, buf, len);
977         os_free(buf);
978
979         return 0;
980 }
981
982
983 static int scard_verify_pin(struct scard_data *scard, const char *pin)
984 {
985         long ret;
986         unsigned char resp[3];
987         unsigned char cmd[5 + 8] = { SIM_CMD_VERIFY_CHV1 };
988         size_t len;
989
990         wpa_printf(MSG_DEBUG, "SCARD: verifying PIN");
991
992         if (pin == NULL || os_strlen(pin) > 8)
993                 return -1;
994
995         if (scard->sim_type == SCARD_USIM)
996                 cmd[0] = USIM_CLA;
997         os_memcpy(cmd + 5, pin, os_strlen(pin));
998         os_memset(cmd + 5 + os_strlen(pin), 0xff, 8 - os_strlen(pin));
999
1000         len = sizeof(resp);
1001         ret = scard_transmit(scard, cmd, sizeof(cmd), resp, &len);
1002         if (ret != SCARD_S_SUCCESS)
1003                 return -2;
1004
1005         if (len != 2 || resp[0] != 0x90 || resp[1] != 0x00) {
1006                 wpa_printf(MSG_WARNING, "SCARD: PIN verification failed");
1007                 return -1;
1008         }
1009
1010         wpa_printf(MSG_DEBUG, "SCARD: PIN verified successfully");
1011         return 0;
1012 }
1013
1014
1015 int scard_get_pin_retry_counter(struct scard_data *scard)
1016 {
1017         long ret;
1018         unsigned char resp[3];
1019         unsigned char cmd[5] = { SIM_CMD_VERIFY_CHV1 };
1020         size_t len;
1021         u16 val;
1022
1023         wpa_printf(MSG_DEBUG, "SCARD: fetching PIN retry counter");
1024
1025         if (scard->sim_type == SCARD_USIM)
1026                 cmd[0] = USIM_CLA;
1027         cmd[4] = 0; /* Empty data */
1028
1029         len = sizeof(resp);
1030         ret = scard_transmit(scard, cmd, sizeof(cmd), resp, &len);
1031         if (ret != SCARD_S_SUCCESS)
1032                 return -2;
1033
1034         if (len != 2) {
1035                 wpa_printf(MSG_WARNING, "SCARD: failed to fetch PIN retry "
1036                            "counter");
1037                 return -1;
1038         }
1039
1040         val = WPA_GET_BE16(resp);
1041         if (val == 0x63c0 || val == 0x6983) {
1042                 wpa_printf(MSG_DEBUG, "SCARD: PIN has been blocked");
1043                 return 0;
1044         }
1045
1046         if (val >= 0x63c0 && val <= 0x63cf)
1047                 return val & 0x000f;
1048
1049         wpa_printf(MSG_DEBUG, "SCARD: Unexpected PIN retry counter response "
1050                    "value 0x%x", val);
1051         return 0;
1052 }
1053
1054
1055 /**
1056  * scard_get_imsi - Read IMSI from SIM/USIM card
1057  * @scard: Pointer to private data from scard_init()
1058  * @imsi: Buffer for IMSI
1059  * @len: Length of imsi buffer; set to IMSI length on success
1060  * Returns: 0 on success, -1 if IMSI file cannot be selected, -2 if IMSI file
1061  * selection returns invalid result code, -3 if parsing FSP template file fails
1062  * (USIM only), -4 if IMSI does not fit in the provided imsi buffer (len is set
1063  * to needed length), -5 if reading IMSI file fails.
1064  *
1065  * This function can be used to read IMSI from the SIM/USIM card. If the IMSI
1066  * file is PIN protected, scard_set_pin() must have been used to set the
1067  * correct PIN code before calling scard_get_imsi().
1068  */
1069 int scard_get_imsi(struct scard_data *scard, char *imsi, size_t *len)
1070 {
1071         unsigned char buf[100];
1072         size_t blen, imsilen, i;
1073         char *pos;
1074
1075         wpa_printf(MSG_DEBUG, "SCARD: reading IMSI from (GSM) EF-IMSI");
1076         blen = sizeof(buf);
1077         if (scard_select_file(scard, SCARD_FILE_GSM_EF_IMSI, buf, &blen))
1078                 return -1;
1079         if (blen < 4) {
1080                 wpa_printf(MSG_WARNING, "SCARD: too short (GSM) EF-IMSI "
1081                            "header (len=%ld)", (long) blen);
1082                 return -2;
1083         }
1084
1085         if (scard->sim_type == SCARD_GSM_SIM) {
1086                 blen = (buf[2] << 8) | buf[3];
1087         } else {
1088                 int file_size;
1089                 if (scard_parse_fsp_templ(buf, blen, NULL, &file_size))
1090                         return -3;
1091                 blen = file_size;
1092         }
1093         if (blen < 2 || blen > sizeof(buf)) {
1094                 wpa_printf(MSG_DEBUG, "SCARD: invalid IMSI file length=%ld",
1095                            (long) blen);
1096                 return -3;
1097         }
1098
1099         imsilen = (blen - 2) * 2 + 1;
1100         wpa_printf(MSG_DEBUG, "SCARD: IMSI file length=%ld imsilen=%ld",
1101                    (long) blen, (long) imsilen);
1102         if (blen < 2 || imsilen > *len) {
1103                 *len = imsilen;
1104                 return -4;
1105         }
1106
1107         if (scard_read_file(scard, buf, blen))
1108                 return -5;
1109
1110         pos = imsi;
1111         *pos++ = '0' + (buf[1] >> 4 & 0x0f);
1112         for (i = 2; i < blen; i++) {
1113                 unsigned char digit;
1114
1115                 digit = buf[i] & 0x0f;
1116                 if (digit < 10)
1117                         *pos++ = '0' + digit;
1118                 else
1119                         imsilen--;
1120
1121                 digit = buf[i] >> 4 & 0x0f;
1122                 if (digit < 10)
1123                         *pos++ = '0' + digit;
1124                 else
1125                         imsilen--;
1126         }
1127         *len = imsilen;
1128
1129         return 0;
1130 }
1131
1132
1133 /**
1134  * scard_get_mnc_len - Read length of MNC in the IMSI from SIM/USIM card
1135  * @scard: Pointer to private data from scard_init()
1136  * Returns: length (>0) on success, -1 if administrative data file cannot be
1137  * selected, -2 if administrative data file selection returns invalid result
1138  * code, -3 if parsing FSP template file fails (USIM only), -4 if length of
1139  * the file is unexpected, -5 if reading file fails, -6 if MNC length is not
1140  * in range (i.e. 2 or 3), -7 if MNC length is not available.
1141  *
1142  */
1143 int scard_get_mnc_len(struct scard_data *scard)
1144 {
1145         unsigned char buf[100];
1146         size_t blen;
1147         int file_size;
1148
1149         wpa_printf(MSG_DEBUG, "SCARD: reading MNC len from (GSM) EF-AD");
1150         blen = sizeof(buf);
1151         if (scard_select_file(scard, SCARD_FILE_GSM_EF_AD, buf, &blen))
1152                 return -1;
1153         if (blen < 4) {
1154                 wpa_printf(MSG_WARNING, "SCARD: too short (GSM) EF-AD "
1155                            "header (len=%ld)", (long) blen);
1156                 return -2;
1157         }
1158
1159         if (scard->sim_type == SCARD_GSM_SIM) {
1160                 file_size = (buf[2] << 8) | buf[3];
1161         } else {
1162                 if (scard_parse_fsp_templ(buf, blen, NULL, &file_size))
1163                         return -3;
1164         }
1165         if (file_size == 3) {
1166                 wpa_printf(MSG_DEBUG, "SCARD: MNC length not available");
1167                 return -7;
1168         }
1169         if (file_size < 4 || file_size > (int) sizeof(buf)) {
1170                 wpa_printf(MSG_DEBUG, "SCARD: invalid file length=%ld",
1171                            (long) file_size);
1172                 return -4;
1173         }
1174
1175         if (scard_read_file(scard, buf, file_size))
1176                 return -5;
1177         buf[3] = buf[3] & 0x0f; /* upper nibble reserved for future use  */
1178         if (buf[3] < 2 || buf[3] > 3) {
1179                 wpa_printf(MSG_DEBUG, "SCARD: invalid MNC length=%ld",
1180                            (long) buf[3]);
1181                 return -6;
1182         }
1183         wpa_printf(MSG_DEBUG, "SCARD: MNC length=%ld", (long) buf[3]);
1184         return buf[3];
1185 }
1186
1187
1188 /**
1189  * scard_gsm_auth - Run GSM authentication command on SIM card
1190  * @scard: Pointer to private data from scard_init()
1191  * @_rand: 16-byte RAND value from HLR/AuC
1192  * @sres: 4-byte buffer for SRES
1193  * @kc: 8-byte buffer for Kc
1194  * Returns: 0 on success, -1 if SIM/USIM connection has not been initialized,
1195  * -2 if authentication command execution fails, -3 if unknown response code
1196  * for authentication command is received, -4 if reading of response fails,
1197  * -5 if if response data is of unexpected length
1198  *
1199  * This function performs GSM authentication using SIM/USIM card and the
1200  * provided RAND value from HLR/AuC. If authentication command can be completed
1201  * successfully, SRES and Kc values will be written into sres and kc buffers.
1202  */
1203 int scard_gsm_auth(struct scard_data *scard, const unsigned char *_rand,
1204                    unsigned char *sres, unsigned char *kc)
1205 {
1206         unsigned char cmd[5 + 1 + 16] = { SIM_CMD_RUN_GSM_ALG };
1207         int cmdlen;
1208         unsigned char get_resp[5] = { SIM_CMD_GET_RESPONSE };
1209         unsigned char resp[3], buf[12 + 3 + 2];
1210         size_t len;
1211         long ret;
1212
1213         if (scard == NULL)
1214                 return -1;
1215
1216         wpa_hexdump(MSG_DEBUG, "SCARD: GSM auth - RAND", _rand, 16);
1217         if (scard->sim_type == SCARD_GSM_SIM) {
1218                 cmdlen = 5 + 16;
1219                 os_memcpy(cmd + 5, _rand, 16);
1220         } else {
1221                 cmdlen = 5 + 1 + 16;
1222                 cmd[0] = USIM_CLA;
1223                 cmd[3] = 0x80;
1224                 cmd[4] = 17;
1225                 cmd[5] = 16;
1226                 os_memcpy(cmd + 6, _rand, 16);
1227         }
1228         len = sizeof(resp);
1229         ret = scard_transmit(scard, cmd, cmdlen, resp, &len);
1230         if (ret != SCARD_S_SUCCESS)
1231                 return -2;
1232
1233         if ((scard->sim_type == SCARD_GSM_SIM &&
1234              (len != 2 || resp[0] != 0x9f || resp[1] != 0x0c)) ||
1235             (scard->sim_type == SCARD_USIM &&
1236              (len != 2 || resp[0] != 0x61 || resp[1] != 0x0e))) {
1237                 wpa_printf(MSG_WARNING, "SCARD: unexpected response for GSM "
1238                            "auth request (len=%ld resp=%02x %02x)",
1239                            (long) len, resp[0], resp[1]);
1240                 return -3;
1241         }
1242         get_resp[4] = resp[1];
1243
1244         len = sizeof(buf);
1245         ret = scard_transmit(scard, get_resp, sizeof(get_resp), buf, &len);
1246         if (ret != SCARD_S_SUCCESS)
1247                 return -4;
1248
1249         if (scard->sim_type == SCARD_GSM_SIM) {
1250                 if (len != 4 + 8 + 2) {
1251                         wpa_printf(MSG_WARNING, "SCARD: unexpected data "
1252                                    "length for GSM auth (len=%ld, expected 14)",
1253                                    (long) len);
1254                         return -5;
1255                 }
1256                 os_memcpy(sres, buf, 4);
1257                 os_memcpy(kc, buf + 4, 8);
1258         } else {
1259                 if (len != 1 + 4 + 1 + 8 + 2) {
1260                         wpa_printf(MSG_WARNING, "SCARD: unexpected data "
1261                                    "length for USIM auth (len=%ld, "
1262                                    "expected 16)", (long) len);
1263                         return -5;
1264                 }
1265                 if (buf[0] != 4 || buf[5] != 8) {
1266                         wpa_printf(MSG_WARNING, "SCARD: unexpected SREC/Kc "
1267                                    "length (%d %d, expected 4 8)",
1268                                    buf[0], buf[5]);
1269                 }
1270                 os_memcpy(sres, buf + 1, 4);
1271                 os_memcpy(kc, buf + 6, 8);
1272         }
1273
1274         wpa_hexdump(MSG_DEBUG, "SCARD: GSM auth - SRES", sres, 4);
1275         wpa_hexdump(MSG_DEBUG, "SCARD: GSM auth - Kc", kc, 8);
1276
1277         return 0;
1278 }
1279
1280
1281 /**
1282  * scard_umts_auth - Run UMTS authentication command on USIM card
1283  * @scard: Pointer to private data from scard_init()
1284  * @_rand: 16-byte RAND value from HLR/AuC
1285  * @autn: 16-byte AUTN value from HLR/AuC
1286  * @res: 16-byte buffer for RES
1287  * @res_len: Variable that will be set to RES length
1288  * @ik: 16-byte buffer for IK
1289  * @ck: 16-byte buffer for CK
1290  * @auts: 14-byte buffer for AUTS
1291  * Returns: 0 on success, -1 on failure, or -2 if USIM reports synchronization
1292  * failure
1293  *
1294  * This function performs AKA authentication using USIM card and the provided
1295  * RAND and AUTN values from HLR/AuC. If authentication command can be
1296  * completed successfully, RES, IK, and CK values will be written into provided
1297  * buffers and res_len is set to length of received RES value. If USIM reports
1298  * synchronization failure, the received AUTS value will be written into auts
1299  * buffer. In this case, RES, IK, and CK are not valid.
1300  */
1301 int scard_umts_auth(struct scard_data *scard, const unsigned char *_rand,
1302                     const unsigned char *autn,
1303                     unsigned char *res, size_t *res_len,
1304                     unsigned char *ik, unsigned char *ck, unsigned char *auts)
1305 {
1306         unsigned char cmd[5 + 1 + AKA_RAND_LEN + 1 + AKA_AUTN_LEN] =
1307                 { USIM_CMD_RUN_UMTS_ALG };
1308         unsigned char get_resp[5] = { USIM_CMD_GET_RESPONSE };
1309         unsigned char resp[3], buf[64], *pos, *end;
1310         size_t len;
1311         long ret;
1312
1313         if (scard == NULL)
1314                 return -1;
1315
1316         if (scard->sim_type == SCARD_GSM_SIM) {
1317                 wpa_printf(MSG_ERROR, "SCARD: Non-USIM card - cannot do UMTS "
1318                            "auth");
1319                 return -1;
1320         }
1321
1322         wpa_hexdump(MSG_DEBUG, "SCARD: UMTS auth - RAND", _rand, AKA_RAND_LEN);
1323         wpa_hexdump(MSG_DEBUG, "SCARD: UMTS auth - AUTN", autn, AKA_AUTN_LEN);
1324         cmd[5] = AKA_RAND_LEN;
1325         os_memcpy(cmd + 6, _rand, AKA_RAND_LEN);
1326         cmd[6 + AKA_RAND_LEN] = AKA_AUTN_LEN;
1327         os_memcpy(cmd + 6 + AKA_RAND_LEN + 1, autn, AKA_AUTN_LEN);
1328
1329         len = sizeof(resp);
1330         ret = scard_transmit(scard, cmd, sizeof(cmd), resp, &len);
1331         if (ret != SCARD_S_SUCCESS)
1332                 return -1;
1333
1334         if (len <= sizeof(resp))
1335                 wpa_hexdump(MSG_DEBUG, "SCARD: UMTS alg response", resp, len);
1336
1337         if (len == 2 && resp[0] == 0x98 && resp[1] == 0x62) {
1338                 wpa_printf(MSG_WARNING, "SCARD: UMTS auth failed - "
1339                            "MAC != XMAC");
1340                 return -1;
1341         } else if (len != 2 || resp[0] != 0x61) {
1342                 wpa_printf(MSG_WARNING, "SCARD: unexpected response for UMTS "
1343                            "auth request (len=%ld resp=%02x %02x)",
1344                            (long) len, resp[0], resp[1]);
1345                 return -1;
1346         }
1347         get_resp[4] = resp[1];
1348
1349         len = sizeof(buf);
1350         ret = scard_transmit(scard, get_resp, sizeof(get_resp), buf, &len);
1351         if (ret != SCARD_S_SUCCESS || len > sizeof(buf))
1352                 return -1;
1353
1354         wpa_hexdump(MSG_DEBUG, "SCARD: UMTS get response result", buf, len);
1355         if (len >= 2 + AKA_AUTS_LEN && buf[0] == 0xdc &&
1356             buf[1] == AKA_AUTS_LEN) {
1357                 wpa_printf(MSG_DEBUG, "SCARD: UMTS Synchronization-Failure");
1358                 os_memcpy(auts, buf + 2, AKA_AUTS_LEN);
1359                 wpa_hexdump(MSG_DEBUG, "SCARD: AUTS", auts, AKA_AUTS_LEN);
1360                 return -2;
1361         } else if (len >= 6 + IK_LEN + CK_LEN && buf[0] == 0xdb) {
1362                 pos = buf + 1;
1363                 end = buf + len;
1364
1365                 /* RES */
1366                 if (pos[0] > RES_MAX_LEN || pos + pos[0] > end) {
1367                         wpa_printf(MSG_DEBUG, "SCARD: Invalid RES");
1368                         return -1;
1369                 }
1370                 *res_len = *pos++;
1371                 os_memcpy(res, pos, *res_len);
1372                 pos += *res_len;
1373                 wpa_hexdump(MSG_DEBUG, "SCARD: RES", res, *res_len);
1374
1375                 /* CK */
1376                 if (pos[0] != CK_LEN || pos + CK_LEN > end) {
1377                         wpa_printf(MSG_DEBUG, "SCARD: Invalid CK");
1378                         return -1;
1379                 }
1380                 pos++;
1381                 os_memcpy(ck, pos, CK_LEN);
1382                 pos += CK_LEN;
1383                 wpa_hexdump(MSG_DEBUG, "SCARD: CK", ck, CK_LEN);
1384
1385                 /* IK */
1386                 if (pos[0] != IK_LEN || pos + IK_LEN > end) {
1387                         wpa_printf(MSG_DEBUG, "SCARD: Invalid IK");
1388                         return -1;
1389                 }
1390                 pos++;
1391                 os_memcpy(ik, pos, IK_LEN);
1392                 pos += IK_LEN;
1393                 wpa_hexdump(MSG_DEBUG, "SCARD: IK", ik, IK_LEN);
1394
1395                 return 0;
1396         }
1397
1398         wpa_printf(MSG_DEBUG, "SCARD: Unrecognized response");
1399         return -1;
1400 }