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