Home | History | Annotate | Download | only in utils
      1 /*
      2  * WPA Supplicant / PC/SC smartcard interface for USIM, GSM SIM
      3  * Copyright (c) 2004-2007, 2012, Jouni Malinen <j (at) 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[0] < end - pos)
    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 (end - pos >= 2) {
    285 		unsigned char type, len;
    286 
    287 		type = pos[0];
    288 		len = pos[1];
    289 		wpa_printf(MSG_MSGDUMP, "SCARD: file header TLV 0x%02x len=%d",
    290 			   type, len);
    291 		pos += 2;
    292 
    293 		if (len > (unsigned int) (end - pos))
    294 			break;
    295 
    296 		switch (type) {
    297 		case USIM_TLV_FILE_DESC:
    298 			wpa_hexdump(MSG_MSGDUMP, "SCARD: File Descriptor TLV",
    299 				    pos, len);
    300 			break;
    301 		case USIM_TLV_FILE_ID:
    302 			wpa_hexdump(MSG_MSGDUMP, "SCARD: File Identifier TLV",
    303 				    pos, len);
    304 			break;
    305 		case USIM_TLV_DF_NAME:
    306 			wpa_hexdump(MSG_MSGDUMP, "SCARD: DF name (AID) TLV",
    307 				    pos, len);
    308 			break;
    309 		case USIM_TLV_PROPR_INFO:
    310 			wpa_hexdump(MSG_MSGDUMP, "SCARD: Proprietary "
    311 				    "information TLV", pos, len);
    312 			break;
    313 		case USIM_TLV_LIFE_CYCLE_STATUS:
    314 			wpa_hexdump(MSG_MSGDUMP, "SCARD: Life Cycle Status "
    315 				    "Integer TLV", pos, len);
    316 			break;
    317 		case USIM_TLV_FILE_SIZE:
    318 			wpa_hexdump(MSG_MSGDUMP, "SCARD: File size TLV",
    319 				    pos, len);
    320 			if ((len == 1 || len == 2) && file_len) {
    321 				if (len == 1)
    322 					*file_len = (int) pos[0];
    323 				else
    324 					*file_len = WPA_GET_BE16(pos);
    325 				wpa_printf(MSG_DEBUG, "SCARD: file_size=%d",
    326 					   *file_len);
    327 			}
    328 			break;
    329 		case USIM_TLV_TOTAL_FILE_SIZE:
    330 			wpa_hexdump(MSG_MSGDUMP, "SCARD: Total file size TLV",
    331 				    pos, len);
    332 			break;
    333 		case USIM_TLV_PIN_STATUS_TEMPLATE:
    334 			wpa_hexdump(MSG_MSGDUMP, "SCARD: PIN Status Template "
    335 				    "DO TLV", pos, len);
    336 			if (len >= 2 && pos[0] == USIM_PS_DO_TAG &&
    337 			    pos[1] >= 1 && ps_do) {
    338 				wpa_printf(MSG_DEBUG, "SCARD: PS_DO=0x%02x",
    339 					   pos[2]);
    340 				*ps_do = (int) pos[2];
    341 			}
    342 			break;
    343 		case USIM_TLV_SHORT_FILE_ID:
    344 			wpa_hexdump(MSG_MSGDUMP, "SCARD: Short File "
    345 				    "Identifier (SFI) TLV", pos, len);
    346 			break;
    347 		case USIM_TLV_SECURITY_ATTR_8B:
    348 		case USIM_TLV_SECURITY_ATTR_8C:
    349 		case USIM_TLV_SECURITY_ATTR_AB:
    350 			wpa_hexdump(MSG_MSGDUMP, "SCARD: Security attribute "
    351 				    "TLV", pos, len);
    352 			break;
    353 		default:
    354 			wpa_hexdump(MSG_MSGDUMP, "SCARD: Unrecognized TLV",
    355 				    pos, len);
    356 			break;
    357 		}
    358 
    359 		pos += len;
    360 
    361 		if (pos == end)
    362 			return 0;
    363 	}
    364 	return -1;
    365 }
    366 
    367 
    368 static int scard_pin_needed(struct scard_data *scard,
    369 			    unsigned char *hdr, size_t hlen)
    370 {
    371 	if (scard->sim_type == SCARD_GSM_SIM) {
    372 		if (hlen > SCARD_CHV1_OFFSET &&
    373 		    !(hdr[SCARD_CHV1_OFFSET] & SCARD_CHV1_FLAG))
    374 			return 1;
    375 		return 0;
    376 	}
    377 
    378 	if (scard->sim_type == SCARD_USIM) {
    379 		int ps_do;
    380 		if (scard_parse_fsp_templ(hdr, hlen, &ps_do, NULL))
    381 			return -1;
    382 		/* TODO: there could be more than one PS_DO entry because of
    383 		 * multiple PINs in key reference.. */
    384 		if (ps_do > 0 && (ps_do & 0x80))
    385 			return 1;
    386 		return 0;
    387 	}
    388 
    389 	return -1;
    390 }
    391 
    392 
    393 static int scard_get_aid(struct scard_data *scard, unsigned char *aid,
    394 			 size_t maxlen)
    395 {
    396 	int rlen, rec;
    397 	struct efdir {
    398 		unsigned char appl_template_tag; /* 0x61 */
    399 		unsigned char appl_template_len;
    400 		unsigned char appl_id_tag; /* 0x4f */
    401 		unsigned char aid_len;
    402 		unsigned char rid[5];
    403 		unsigned char appl_code[2]; /* 0x1002 for 3G USIM */
    404 	} *efdir;
    405 	unsigned char buf[127], *aid_pos;
    406 	size_t blen;
    407 	unsigned int aid_len = 0;
    408 
    409 	efdir = (struct efdir *) buf;
    410 	aid_pos = &buf[4];
    411 	blen = sizeof(buf);
    412 	if (scard_select_file(scard, SCARD_FILE_EF_DIR, buf, &blen)) {
    413 		wpa_printf(MSG_DEBUG, "SCARD: Failed to read EF_DIR");
    414 		return -1;
    415 	}
    416 	wpa_hexdump(MSG_DEBUG, "SCARD: EF_DIR select", buf, blen);
    417 
    418 	for (rec = 1; rec < 10; rec++) {
    419 		rlen = scard_get_record_len(scard, rec,
    420 					    SIM_RECORD_MODE_ABSOLUTE);
    421 		if (rlen < 0) {
    422 			wpa_printf(MSG_DEBUG, "SCARD: Failed to get EF_DIR "
    423 				   "record length");
    424 			return -1;
    425 		}
    426 		blen = sizeof(buf);
    427 		if (rlen > (int) blen) {
    428 			wpa_printf(MSG_DEBUG, "SCARD: Too long EF_DIR record");
    429 			return -1;
    430 		}
    431 		if (scard_read_record(scard, buf, rlen, rec,
    432 				      SIM_RECORD_MODE_ABSOLUTE) < 0) {
    433 			wpa_printf(MSG_DEBUG, "SCARD: Failed to read "
    434 				   "EF_DIR record %d", rec);
    435 			return -1;
    436 		}
    437 		wpa_hexdump(MSG_DEBUG, "SCARD: EF_DIR record", buf, rlen);
    438 
    439 		if (efdir->appl_template_tag != 0x61) {
    440 			wpa_printf(MSG_DEBUG, "SCARD: Unexpected application "
    441 				   "template tag 0x%x",
    442 				   efdir->appl_template_tag);
    443 			continue;
    444 		}
    445 
    446 		if (efdir->appl_template_len > rlen - 2) {
    447 			wpa_printf(MSG_DEBUG, "SCARD: Too long application "
    448 				   "template (len=%d rlen=%d)",
    449 				   efdir->appl_template_len, rlen);
    450 			continue;
    451 		}
    452 
    453 		if (efdir->appl_id_tag != 0x4f) {
    454 			wpa_printf(MSG_DEBUG, "SCARD: Unexpected application "
    455 				   "identifier tag 0x%x", efdir->appl_id_tag);
    456 			continue;
    457 		}
    458 
    459 		aid_len = efdir->aid_len;
    460 		if (aid_len < 1 || aid_len > 16) {
    461 			wpa_printf(MSG_DEBUG, "SCARD: Invalid AID length %u",
    462 				   aid_len);
    463 			continue;
    464 		}
    465 
    466 		wpa_hexdump(MSG_DEBUG, "SCARD: AID from EF_DIR record",
    467 			    aid_pos, aid_len);
    468 
    469 		if (efdir->appl_code[0] == 0x10 &&
    470 		    efdir->appl_code[1] == 0x02) {
    471 			wpa_printf(MSG_DEBUG, "SCARD: 3G USIM app found from "
    472 				   "EF_DIR record %d", rec);
    473 			break;
    474 		}
    475 	}
    476 
    477 	if (rec >= 10) {
    478 		wpa_printf(MSG_DEBUG, "SCARD: 3G USIM app not found "
    479 			   "from EF_DIR records");
    480 		return -1;
    481 	}
    482 
    483 	if (aid_len > maxlen) {
    484 		wpa_printf(MSG_DEBUG, "SCARD: Too long AID");
    485 		return -1;
    486 	}
    487 
    488 	os_memcpy(aid, aid_pos, aid_len);
    489 
    490 	return aid_len;
    491 }
    492 
    493 
    494 /**
    495  * scard_init - Initialize SIM/USIM connection using PC/SC
    496  * @reader: Reader name prefix to search for
    497  * Returns: Pointer to private data structure, or %NULL on failure
    498  *
    499  * This function is used to initialize SIM/USIM connection. PC/SC is used to
    500  * open connection to the SIM/USIM card. In addition, local flag is set if a
    501  * PIN is needed to access some of the card functions. Once the connection is
    502  * not needed anymore, scard_deinit() can be used to close it.
    503  */
    504 struct scard_data * scard_init(const char *reader)
    505 {
    506 	long ret;
    507 	unsigned long len, pos;
    508 	struct scard_data *scard;
    509 #ifdef CONFIG_NATIVE_WINDOWS
    510 	TCHAR *readers = NULL;
    511 #else /* CONFIG_NATIVE_WINDOWS */
    512 	char *readers = NULL;
    513 #endif /* CONFIG_NATIVE_WINDOWS */
    514 	unsigned char buf[100];
    515 	size_t blen;
    516 	int transaction = 0;
    517 	int pin_needed;
    518 
    519 	wpa_printf(MSG_DEBUG, "SCARD: initializing smart card interface");
    520 	if (mingw_load_symbols())
    521 		return NULL;
    522 	scard = os_zalloc(sizeof(*scard));
    523 	if (scard == NULL)
    524 		return NULL;
    525 
    526 	ret = SCardEstablishContext(SCARD_SCOPE_SYSTEM, NULL, NULL,
    527 				    &scard->ctx);
    528 	if (ret != SCARD_S_SUCCESS) {
    529 		wpa_printf(MSG_DEBUG, "SCARD: Could not establish smart card "
    530 			   "context (err=%ld)", ret);
    531 		goto failed;
    532 	}
    533 
    534 	ret = SCardListReaders(scard->ctx, NULL, NULL, &len);
    535 	if (ret != SCARD_S_SUCCESS) {
    536 		wpa_printf(MSG_DEBUG, "SCARD: SCardListReaders failed "
    537 			   "(err=%ld)", ret);
    538 		goto failed;
    539 	}
    540 
    541 #ifdef UNICODE
    542 	len *= 2;
    543 #endif /* UNICODE */
    544 	readers = os_malloc(len);
    545 	if (readers == NULL) {
    546 		wpa_printf(MSG_INFO, "SCARD: malloc failed\n");
    547 		goto failed;
    548 	}
    549 
    550 	ret = SCardListReaders(scard->ctx, NULL, readers, &len);
    551 	if (ret != SCARD_S_SUCCESS) {
    552 		wpa_printf(MSG_DEBUG, "SCARD: SCardListReaders failed(2) "
    553 			   "(err=%ld)", ret);
    554 		goto failed;
    555 	}
    556 	if (len < 3) {
    557 		wpa_printf(MSG_WARNING, "SCARD: No smart card readers "
    558 			   "available.");
    559 		goto failed;
    560 	}
    561 	wpa_hexdump_ascii(MSG_DEBUG, "SCARD: Readers", (u8 *) readers, len);
    562 	/*
    563 	 * readers is a list of available readers. The last entry is terminated
    564 	 * with double null.
    565 	 */
    566 	pos = 0;
    567 #ifdef UNICODE
    568 	/* TODO */
    569 #else /* UNICODE */
    570 	while (pos < len) {
    571 		if (reader == NULL ||
    572 		    os_strncmp(&readers[pos], reader, os_strlen(reader)) == 0)
    573 			break;
    574 		while (pos < len && readers[pos])
    575 			pos++;
    576 		pos++; /* skip separating null */
    577 		if (pos < len && readers[pos] == '\0')
    578 			pos = len; /* double null terminates list */
    579 	}
    580 #endif /* UNICODE */
    581 	if (pos >= len) {
    582 		wpa_printf(MSG_WARNING, "SCARD: No reader with prefix '%s' "
    583 			   "found", reader);
    584 		goto failed;
    585 	}
    586 
    587 #ifdef UNICODE
    588 	wpa_printf(MSG_DEBUG, "SCARD: Selected reader='%S'", &readers[pos]);
    589 #else /* UNICODE */
    590 	wpa_printf(MSG_DEBUG, "SCARD: Selected reader='%s'", &readers[pos]);
    591 #endif /* UNICODE */
    592 
    593 	ret = SCardConnect(scard->ctx, &readers[pos], SCARD_SHARE_SHARED,
    594 			   SCARD_PROTOCOL_T0 | SCARD_PROTOCOL_T1,
    595 			   &scard->card, &scard->protocol);
    596 	if (ret != SCARD_S_SUCCESS) {
    597 		if (ret == (long) SCARD_E_NO_SMARTCARD)
    598 			wpa_printf(MSG_INFO, "No smart card inserted.");
    599 		else
    600 			wpa_printf(MSG_WARNING, "SCardConnect err=%lx", ret);
    601 		goto failed;
    602 	}
    603 
    604 	os_free(readers);
    605 	readers = NULL;
    606 
    607 	wpa_printf(MSG_DEBUG, "SCARD: card=0x%x active_protocol=%lu (%s)",
    608 		   (unsigned int) scard->card, scard->protocol,
    609 		   scard->protocol == SCARD_PROTOCOL_T0 ? "T0" : "T1");
    610 
    611 	ret = SCardBeginTransaction(scard->card);
    612 	if (ret != SCARD_S_SUCCESS) {
    613 		wpa_printf(MSG_DEBUG, "SCARD: Could not begin transaction: "
    614 			   "0x%x", (unsigned int) ret);
    615 		goto failed;
    616 	}
    617 	transaction = 1;
    618 
    619 	blen = sizeof(buf);
    620 
    621 	wpa_printf(MSG_DEBUG, "SCARD: verifying USIM support");
    622 	if (_scard_select_file(scard, SCARD_FILE_MF, buf, &blen,
    623 			       SCARD_USIM, NULL, 0)) {
    624 		wpa_printf(MSG_DEBUG, "SCARD: USIM is not supported. Trying to use GSM SIM");
    625 		scard->sim_type = SCARD_GSM_SIM;
    626 	} else {
    627 		wpa_printf(MSG_DEBUG, "SCARD: USIM is supported");
    628 		scard->sim_type = SCARD_USIM;
    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 = WPA_GET_BE16(&buf[2]);
   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 = WPA_GET_BE16(&buf[2]);
   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 		get_resp[0] = USIM_CLA;
   1249 	}
   1250 	len = sizeof(resp);
   1251 	ret = scard_transmit(scard, cmd, cmdlen, resp, &len);
   1252 	if (ret != SCARD_S_SUCCESS)
   1253 		return -2;
   1254 
   1255 	if ((scard->sim_type == SCARD_GSM_SIM &&
   1256 	     (len != 2 || resp[0] != 0x9f || resp[1] != 0x0c)) ||
   1257 	    (scard->sim_type == SCARD_USIM &&
   1258 	     (len != 2 || resp[0] != 0x61 || resp[1] != 0x0e))) {
   1259 		wpa_printf(MSG_WARNING, "SCARD: unexpected response for GSM "
   1260 			   "auth request (len=%ld resp=%02x %02x)",
   1261 			   (long) len, resp[0], resp[1]);
   1262 		return -3;
   1263 	}
   1264 	get_resp[4] = resp[1];
   1265 
   1266 	len = sizeof(buf);
   1267 	ret = scard_transmit(scard, get_resp, sizeof(get_resp), buf, &len);
   1268 	if (ret != SCARD_S_SUCCESS)
   1269 		return -4;
   1270 
   1271 	if (scard->sim_type == SCARD_GSM_SIM) {
   1272 		if (len != 4 + 8 + 2) {
   1273 			wpa_printf(MSG_WARNING, "SCARD: unexpected data "
   1274 				   "length for GSM auth (len=%ld, expected 14)",
   1275 				   (long) len);
   1276 			return -5;
   1277 		}
   1278 		os_memcpy(sres, buf, 4);
   1279 		os_memcpy(kc, buf + 4, 8);
   1280 	} else {
   1281 		if (len != 1 + 4 + 1 + 8 + 2) {
   1282 			wpa_printf(MSG_WARNING, "SCARD: unexpected data "
   1283 				   "length for USIM auth (len=%ld, "
   1284 				   "expected 16)", (long) len);
   1285 			return -5;
   1286 		}
   1287 		if (buf[0] != 4 || buf[5] != 8) {
   1288 			wpa_printf(MSG_WARNING, "SCARD: unexpected SREC/Kc "
   1289 				   "length (%d %d, expected 4 8)",
   1290 				   buf[0], buf[5]);
   1291 		}
   1292 		os_memcpy(sres, buf + 1, 4);
   1293 		os_memcpy(kc, buf + 6, 8);
   1294 	}
   1295 
   1296 	wpa_hexdump(MSG_DEBUG, "SCARD: GSM auth - SRES", sres, 4);
   1297 	wpa_hexdump(MSG_DEBUG, "SCARD: GSM auth - Kc", kc, 8);
   1298 
   1299 	return 0;
   1300 }
   1301 
   1302 
   1303 /**
   1304  * scard_umts_auth - Run UMTS authentication command on USIM card
   1305  * @scard: Pointer to private data from scard_init()
   1306  * @_rand: 16-byte RAND value from HLR/AuC
   1307  * @autn: 16-byte AUTN value from HLR/AuC
   1308  * @res: 16-byte buffer for RES
   1309  * @res_len: Variable that will be set to RES length
   1310  * @ik: 16-byte buffer for IK
   1311  * @ck: 16-byte buffer for CK
   1312  * @auts: 14-byte buffer for AUTS
   1313  * Returns: 0 on success, -1 on failure, or -2 if USIM reports synchronization
   1314  * failure
   1315  *
   1316  * This function performs AKA authentication using USIM card and the provided
   1317  * RAND and AUTN values from HLR/AuC. If authentication command can be
   1318  * completed successfully, RES, IK, and CK values will be written into provided
   1319  * buffers and res_len is set to length of received RES value. If USIM reports
   1320  * synchronization failure, the received AUTS value will be written into auts
   1321  * buffer. In this case, RES, IK, and CK are not valid.
   1322  */
   1323 int scard_umts_auth(struct scard_data *scard, const unsigned char *_rand,
   1324 		    const unsigned char *autn,
   1325 		    unsigned char *res, size_t *res_len,
   1326 		    unsigned char *ik, unsigned char *ck, unsigned char *auts)
   1327 {
   1328 	unsigned char cmd[5 + 1 + AKA_RAND_LEN + 1 + AKA_AUTN_LEN] =
   1329 		{ USIM_CMD_RUN_UMTS_ALG };
   1330 	unsigned char get_resp[5] = { USIM_CMD_GET_RESPONSE };
   1331 	unsigned char resp[3], buf[64], *pos, *end;
   1332 	size_t len;
   1333 	long ret;
   1334 
   1335 	if (scard == NULL)
   1336 		return -1;
   1337 
   1338 	if (scard->sim_type == SCARD_GSM_SIM) {
   1339 		wpa_printf(MSG_ERROR, "SCARD: Non-USIM card - cannot do UMTS "
   1340 			   "auth");
   1341 		return -1;
   1342 	}
   1343 
   1344 	wpa_hexdump(MSG_DEBUG, "SCARD: UMTS auth - RAND", _rand, AKA_RAND_LEN);
   1345 	wpa_hexdump(MSG_DEBUG, "SCARD: UMTS auth - AUTN", autn, AKA_AUTN_LEN);
   1346 	cmd[5] = AKA_RAND_LEN;
   1347 	os_memcpy(cmd + 6, _rand, AKA_RAND_LEN);
   1348 	cmd[6 + AKA_RAND_LEN] = AKA_AUTN_LEN;
   1349 	os_memcpy(cmd + 6 + AKA_RAND_LEN + 1, autn, AKA_AUTN_LEN);
   1350 
   1351 	len = sizeof(resp);
   1352 	ret = scard_transmit(scard, cmd, sizeof(cmd), resp, &len);
   1353 	if (ret != SCARD_S_SUCCESS)
   1354 		return -1;
   1355 
   1356 	if (len <= sizeof(resp))
   1357 		wpa_hexdump(MSG_DEBUG, "SCARD: UMTS alg response", resp, len);
   1358 
   1359 	if (len == 2 && resp[0] == 0x98 && resp[1] == 0x62) {
   1360 		wpa_printf(MSG_WARNING, "SCARD: UMTS auth failed - "
   1361 			   "MAC != XMAC");
   1362 		return -1;
   1363 	} else if (len != 2 || resp[0] != 0x61) {
   1364 		wpa_printf(MSG_WARNING, "SCARD: unexpected response for UMTS "
   1365 			   "auth request (len=%ld resp=%02x %02x)",
   1366 			   (long) len, resp[0], resp[1]);
   1367 		return -1;
   1368 	}
   1369 	get_resp[4] = resp[1];
   1370 
   1371 	len = sizeof(buf);
   1372 	ret = scard_transmit(scard, get_resp, sizeof(get_resp), buf, &len);
   1373 	if (ret != SCARD_S_SUCCESS || len > sizeof(buf))
   1374 		return -1;
   1375 
   1376 	wpa_hexdump(MSG_DEBUG, "SCARD: UMTS get response result", buf, len);
   1377 	if (len >= 2 + AKA_AUTS_LEN && buf[0] == 0xdc &&
   1378 	    buf[1] == AKA_AUTS_LEN) {
   1379 		wpa_printf(MSG_DEBUG, "SCARD: UMTS Synchronization-Failure");
   1380 		os_memcpy(auts, buf + 2, AKA_AUTS_LEN);
   1381 		wpa_hexdump(MSG_DEBUG, "SCARD: AUTS", auts, AKA_AUTS_LEN);
   1382 		return -2;
   1383 	} else if (len >= 6 + IK_LEN + CK_LEN && buf[0] == 0xdb) {
   1384 		pos = buf + 1;
   1385 		end = buf + len;
   1386 
   1387 		/* RES */
   1388 		if (pos[0] > RES_MAX_LEN || pos[0] > end - pos) {
   1389 			wpa_printf(MSG_DEBUG, "SCARD: Invalid RES");
   1390 			return -1;
   1391 		}
   1392 		*res_len = *pos++;
   1393 		os_memcpy(res, pos, *res_len);
   1394 		pos += *res_len;
   1395 		wpa_hexdump(MSG_DEBUG, "SCARD: RES", res, *res_len);
   1396 
   1397 		/* CK */
   1398 		if (pos[0] != CK_LEN || CK_LEN > end - pos) {
   1399 			wpa_printf(MSG_DEBUG, "SCARD: Invalid CK");
   1400 			return -1;
   1401 		}
   1402 		pos++;
   1403 		os_memcpy(ck, pos, CK_LEN);
   1404 		pos += CK_LEN;
   1405 		wpa_hexdump(MSG_DEBUG, "SCARD: CK", ck, CK_LEN);
   1406 
   1407 		/* IK */
   1408 		if (pos[0] != IK_LEN || IK_LEN > end - pos) {
   1409 			wpa_printf(MSG_DEBUG, "SCARD: Invalid IK");
   1410 			return -1;
   1411 		}
   1412 		pos++;
   1413 		os_memcpy(ik, pos, IK_LEN);
   1414 		pos += IK_LEN;
   1415 		wpa_hexdump(MSG_DEBUG, "SCARD: IK", ik, IK_LEN);
   1416 
   1417 		if (end > pos) {
   1418 			wpa_hexdump(MSG_DEBUG,
   1419 				    "SCARD: Ignore extra data in end",
   1420 				    pos, end - pos);
   1421 		}
   1422 
   1423 		return 0;
   1424 	}
   1425 
   1426 	wpa_printf(MSG_DEBUG, "SCARD: Unrecognized response");
   1427 	return -1;
   1428 }
   1429 
   1430 
   1431 int scard_supports_umts(struct scard_data *scard)
   1432 {
   1433 	return scard->sim_type == SCARD_USIM;
   1434 }
   1435