2 * WPA Supplicant / PC/SC smartcard interface for USIM, GSM SIM
3 * Copyright (c) 2004-2007, 2012, Jouni Malinen <j@w1.fi>
5 * This software may be distributed under the terms of the BSD license.
6 * See README for more details.
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.
17 #include "pcsc_funcs.h"
20 /* See ETSI GSM 11.11 and ETSI TS 102 221 for details.
22 * Command APDU: CLA INS P1 P2 P3 Data
23 * CLA (class of instruction): A0 for GSM, 00 for USIM
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
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
57 #define USIM_CMD_RUN_UMTS_ALG 0x00, 0x88, 0x00, 0x81, 0x22
58 #define USIM_CMD_GET_RESPONSE 0x00, 0xc0, 0x00, 0x00
60 #define SIM_RECORD_MODE_ABSOLUTE 0x04
62 #define USIM_FSP_TEMPL_TAG 0x62
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
77 #define USIM_PS_DO_TAG 0x90
79 #define AKA_RAND_LEN 16
80 #define AKA_AUTN_LEN 16
81 #define AKA_AUTS_LEN 14
82 #define RES_MAX_LEN 16
88 * File type in first octet:
91 * 2F = Elementary File under the Master File
92 * 6F = Elementary File under a Dedicated File
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
104 #define SCARD_CHV1_OFFSET 13
105 #define SCARD_CHV1_FLAG 0x80
108 typedef enum { SCARD_GSM_SIM, SCARD_USIM } sim_types;
118 #ifdef __MINGW32_VERSION
119 /* MinGW does not yet support WinScard, so load the needed functions
120 * dynamically from winscard.dll for now. */
122 static HINSTANCE dll = NULL; /* winscard.dll */
124 static const SCARD_IO_REQUEST *dll_g_rgSCardT0Pci, *dll_g_rgSCardT1Pci;
126 #define SCARD_PCI_T0 (dll_g_rgSCardT0Pci)
128 #define SCARD_PCI_T1 (dll_g_rgSCardT1Pci)
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
138 static long (*dll_SCardReleaseContext)(long hContext);
139 #define SCardReleaseContext dll_SCardReleaseContext
141 static WINSCARDAPI LONG WINAPI
142 (*dll_SCardListReadersA)(IN SCARDCONTEXT hContext,
144 OUT LPSTR mszReaders,
145 IN OUT LPDWORD pcchReaders);
146 #undef SCardListReaders
147 #define SCardListReaders dll_SCardListReadersA
149 static WINSCARDAPI LONG WINAPI
150 (*dll_SCardConnectA)(IN SCARDCONTEXT hContext,
152 IN DWORD dwShareMode,
153 IN DWORD dwPreferredProtocols,
154 OUT LPSCARDHANDLE phCard,
155 OUT LPDWORD pdwActiveProtocol);
157 #define SCardConnect dll_SCardConnectA
159 static WINSCARDAPI LONG WINAPI
160 (*dll_SCardDisconnect)(IN SCARDHANDLE hCard,
161 IN DWORD dwDisposition);
162 #define SCardDisconnect dll_SCardDisconnect
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
174 static WINSCARDAPI LONG WINAPI
175 (*dll_SCardBeginTransaction)(IN SCARDHANDLE hCard);
176 #define SCardBeginTransaction dll_SCardBeginTransaction
178 static WINSCARDAPI LONG WINAPI
179 (*dll_SCardEndTransaction)(IN SCARDHANDLE hCard, IN DWORD dwDisposition);
180 #define SCardEndTransaction dll_SCardEndTransaction
183 static int mingw_load_symbols(void)
190 dll = LoadLibrary("winscard");
192 wpa_printf(MSG_DEBUG, "WinSCard: Could not load winscard.dll "
199 dll_ ## s = (void *) GetProcAddress(dll, sym); \
200 if (dll_ ## s == NULL) \
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);
219 wpa_printf(MSG_DEBUG, "WinSCard: Could not get address for %s from "
220 "winscard.dll", sym);
227 static void mingw_unload_symbols(void)
236 #else /* __MINGW32_VERSION */
238 #define mingw_load_symbols() 0
239 #define mingw_unload_symbols() do { } while (0)
241 #endif /* __MINGW32_VERSION */
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,
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);
258 static int scard_parse_fsp_templ(unsigned char *buf, size_t buf_len,
259 int *ps_do, int *file_len)
261 unsigned char *pos, *end;
270 if (*pos != USIM_FSP_TEMPL_TAG) {
271 wpa_printf(MSG_DEBUG, "SCARD: file header did not "
272 "start with FSP template tag");
278 if ((pos + pos[0]) < end)
279 end = pos + 1 + pos[0];
281 wpa_hexdump(MSG_DEBUG, "SCARD: file header FSP template",
284 while (end - pos >= 2) {
285 unsigned char type, len;
289 wpa_printf(MSG_MSGDUMP, "SCARD: file header TLV 0x%02x len=%d",
293 if (len > (unsigned int) (end - pos))
297 case USIM_TLV_FILE_DESC:
298 wpa_hexdump(MSG_MSGDUMP, "SCARD: File Descriptor TLV",
301 case USIM_TLV_FILE_ID:
302 wpa_hexdump(MSG_MSGDUMP, "SCARD: File Identifier TLV",
305 case USIM_TLV_DF_NAME:
306 wpa_hexdump(MSG_MSGDUMP, "SCARD: DF name (AID) TLV",
309 case USIM_TLV_PROPR_INFO:
310 wpa_hexdump(MSG_MSGDUMP, "SCARD: Proprietary "
311 "information TLV", pos, len);
313 case USIM_TLV_LIFE_CYCLE_STATUS:
314 wpa_hexdump(MSG_MSGDUMP, "SCARD: Life Cycle Status "
315 "Integer TLV", pos, len);
317 case USIM_TLV_FILE_SIZE:
318 wpa_hexdump(MSG_MSGDUMP, "SCARD: File size TLV",
320 if ((len == 1 || len == 2) && file_len) {
322 *file_len = (int) pos[0];
324 *file_len = WPA_GET_BE16(pos);
325 wpa_printf(MSG_DEBUG, "SCARD: file_size=%d",
329 case USIM_TLV_TOTAL_FILE_SIZE:
330 wpa_hexdump(MSG_MSGDUMP, "SCARD: Total file size TLV",
333 case USIM_TLV_PIN_STATUS_TEMPLATE:
334 wpa_hexdump(MSG_MSGDUMP, "SCARD: PIN Status Template "
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",
340 *ps_do = (int) pos[2];
343 case USIM_TLV_SHORT_FILE_ID:
344 wpa_hexdump(MSG_MSGDUMP, "SCARD: Short File "
345 "Identifier (SFI) TLV", pos, len);
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 "
354 wpa_hexdump(MSG_MSGDUMP, "SCARD: Unrecognized TLV",
368 static int scard_pin_needed(struct scard_data *scard,
369 unsigned char *hdr, size_t hlen)
371 if (scard->sim_type == SCARD_GSM_SIM) {
372 if (hlen > SCARD_CHV1_OFFSET &&
373 !(hdr[SCARD_CHV1_OFFSET] & SCARD_CHV1_FLAG))
378 if (scard->sim_type == SCARD_USIM) {
380 if (scard_parse_fsp_templ(hdr, hlen, &ps_do, NULL))
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))
393 static int scard_get_aid(struct scard_data *scard, unsigned char *aid,
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 */
405 unsigned char buf[127], *aid_pos;
407 unsigned int aid_len = 0;
409 efdir = (struct efdir *) buf;
412 if (scard_select_file(scard, SCARD_FILE_EF_DIR, buf, &blen)) {
413 wpa_printf(MSG_DEBUG, "SCARD: Failed to read EF_DIR");
416 wpa_hexdump(MSG_DEBUG, "SCARD: EF_DIR select", buf, blen);
418 for (rec = 1; rec < 10; rec++) {
419 rlen = scard_get_record_len(scard, rec,
420 SIM_RECORD_MODE_ABSOLUTE);
422 wpa_printf(MSG_DEBUG, "SCARD: Failed to get EF_DIR "
427 if (rlen > (int) blen) {
428 wpa_printf(MSG_DEBUG, "SCARD: Too long EF_DIR record");
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);
437 wpa_hexdump(MSG_DEBUG, "SCARD: EF_DIR record", buf, rlen);
439 if (efdir->appl_template_tag != 0x61) {
440 wpa_printf(MSG_DEBUG, "SCARD: Unexpected application "
442 efdir->appl_template_tag);
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);
453 if (efdir->appl_id_tag != 0x4f) {
454 wpa_printf(MSG_DEBUG, "SCARD: Unexpected application "
455 "identifier tag 0x%x", efdir->appl_id_tag);
459 aid_len = efdir->aid_len;
460 if (aid_len < 1 || aid_len > 16) {
461 wpa_printf(MSG_DEBUG, "SCARD: Invalid AID length %u",
466 wpa_hexdump(MSG_DEBUG, "SCARD: AID from EF_DIR record",
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);
478 wpa_printf(MSG_DEBUG, "SCARD: 3G USIM app not found "
479 "from EF_DIR records");
483 if (aid_len > maxlen) {
484 wpa_printf(MSG_DEBUG, "SCARD: Too long AID");
488 os_memcpy(aid, aid_pos, aid_len);
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
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.
504 struct scard_data * scard_init(const char *reader)
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];
519 wpa_printf(MSG_DEBUG, "SCARD: initializing smart card interface");
520 if (mingw_load_symbols())
522 scard = os_zalloc(sizeof(*scard));
526 ret = SCardEstablishContext(SCARD_SCOPE_SYSTEM, NULL, NULL,
528 if (ret != SCARD_S_SUCCESS) {
529 wpa_printf(MSG_DEBUG, "SCARD: Could not establish smart card "
530 "context (err=%ld)", ret);
534 ret = SCardListReaders(scard->ctx, NULL, NULL, &len);
535 if (ret != SCARD_S_SUCCESS) {
536 wpa_printf(MSG_DEBUG, "SCARD: SCardListReaders failed "
544 readers = os_malloc(len);
545 if (readers == NULL) {
546 wpa_printf(MSG_INFO, "SCARD: malloc failed\n");
550 ret = SCardListReaders(scard->ctx, NULL, readers, &len);
551 if (ret != SCARD_S_SUCCESS) {
552 wpa_printf(MSG_DEBUG, "SCARD: SCardListReaders failed(2) "
557 wpa_printf(MSG_WARNING, "SCARD: No smart card readers "
561 wpa_hexdump_ascii(MSG_DEBUG, "SCARD: Readers", (u8 *) readers, len);
563 * readers is a list of available readers. The last entry is terminated
571 if (reader == NULL ||
572 os_strncmp(&readers[pos], reader, os_strlen(reader)) == 0)
574 while (pos < len && readers[pos])
576 pos++; /* skip separating null */
577 if (pos < len && readers[pos] == '\0')
578 pos = len; /* double null terminates list */
582 wpa_printf(MSG_WARNING, "SCARD: No reader with prefix '%s' "
588 wpa_printf(MSG_DEBUG, "SCARD: Selected reader='%S'", &readers[pos]);
590 wpa_printf(MSG_DEBUG, "SCARD: Selected reader='%s'", &readers[pos]);
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.");
600 wpa_printf(MSG_WARNING, "SCardConnect err=%lx", ret);
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");
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);
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;
627 wpa_printf(MSG_DEBUG, "SCARD: USIM is supported");
628 scard->sim_type = SCARD_USIM;
631 if (scard->sim_type == SCARD_GSM_SIM) {
633 if (scard_select_file(scard, SCARD_FILE_MF, buf, &blen)) {
634 wpa_printf(MSG_DEBUG, "SCARD: Failed to read MF");
639 if (scard_select_file(scard, SCARD_FILE_GSM_DF, buf, &blen)) {
640 wpa_printf(MSG_DEBUG, "SCARD: Failed to read GSM DF");
644 unsigned char aid[32];
647 aid_len = scard_get_aid(scard, aid, sizeof(aid));
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);
654 wpa_hexdump(MSG_DEBUG, "SCARD: 3G USIM AID", aid, aid_len);
656 /* Select based on AID = 3G RID from EF_DIR. This is usually
657 * starting with A0 00 00 00 87. */
659 if (_scard_select_file(scard, 0, buf, &blen, scard->sim_type,
661 wpa_printf(MSG_INFO, "SCARD: Failed to read 3G USIM "
663 wpa_hexdump(MSG_INFO, "SCARD: 3G USIM AID",
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 "
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));
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);
692 SCardEndTransaction(scard->card, SCARD_LEAVE_CARD);
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
705 int scard_set_pin(struct scard_data *scard, const char *pin)
710 /* Verify whether CHV1 (PIN1) is needed to access the card. */
711 if (scard->pin1_required) {
713 wpa_printf(MSG_DEBUG, "No PIN configured for SIM "
717 if (scard_verify_pin(scard, pin)) {
718 wpa_printf(MSG_INFO, "PIN verification failed for "
729 * scard_deinit - Deinitialize SIM/USIM connection
730 * @scard: Pointer to private data from scard_init()
732 * This function closes the SIM/USIM connect opened with scard_init().
734 void scard_deinit(struct scard_data *scard)
741 wpa_printf(MSG_DEBUG, "SCARD: deinitializing smart card interface");
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);
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);
758 mingw_unload_symbols();
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)
769 wpa_hexdump_key(MSG_DEBUG, "SCARD: scard_transmit: send",
772 ret = SCardTransmit(scard->card,
773 scard->protocol == SCARD_PROTOCOL_T1 ?
774 SCARD_PCI_T1 : SCARD_PCI_T0,
775 _send, (unsigned long) send_len,
778 if (ret == SCARD_S_SUCCESS) {
779 wpa_hexdump(MSG_DEBUG, "SCARD: scard_transmit: recv",
782 wpa_printf(MSG_WARNING, "SCARD: SCardTransmit failed "
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,
795 unsigned char resp[3];
796 unsigned char cmd[50] = { SIM_CMD_SELECT };
798 unsigned char get_resp[5] = { SIM_CMD_GET_RESPONSE };
801 if (sim_type == SCARD_USIM) {
804 get_resp[0] = USIM_CLA;
807 wpa_printf(MSG_DEBUG, "SCARD: select file %04x", file_id);
809 wpa_hexdump(MSG_DEBUG, "SCARD: select file by AID",
811 if (5 + aidlen > sizeof(cmd))
813 cmd[2] = 0x04; /* Select by AID */
814 cmd[4] = aidlen; /* len */
815 os_memcpy(cmd + 5, aid, aidlen);
818 cmd[5] = file_id >> 8;
819 cmd[6] = file_id & 0xff;
823 ret = scard_transmit(scard, cmd, cmdlen, resp, &len);
824 if (ret != SCARD_S_SUCCESS) {
825 wpa_printf(MSG_WARNING, "SCARD: SCardTransmit failed "
831 wpa_printf(MSG_WARNING, "SCARD: unexpected resp len "
832 "%d (expected 2)", (int) len);
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 "
843 if (resp[0] == 0x6e) {
844 wpa_printf(MSG_DEBUG, "SCARD: used CLA not supported");
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]);
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)",
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;
865 wpa_printf(MSG_WARNING, "SCARD: SCardTransmit err=0x%lx\n", ret);
870 static int scard_select_file(struct scard_data *scard, unsigned short file_id,
871 unsigned char *buf, size_t *buf_len)
873 return _scard_select_file(scard, file_id, buf, buf_len,
874 scard->sim_type, NULL, 0);
878 static int scard_get_record_len(struct scard_data *scard, unsigned char recnum,
881 unsigned char buf[255];
882 unsigned char cmd[5] = { SIM_CMD_READ_RECORD /* , len */ };
886 if (scard->sim_type == SCARD_USIM)
890 cmd[4] = 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);
900 wpa_hexdump(MSG_DEBUG, "SCARD: file length determination response",
903 if (blen < 2 || (buf[0] != 0x6c && buf[0] != 0x67)) {
904 wpa_printf(MSG_DEBUG, "SCARD: unexpected response to file "
905 "length determination");
913 static int scard_read_record(struct scard_data *scard,
914 unsigned char *data, size_t len,
915 unsigned char recnum, unsigned char mode)
917 unsigned char cmd[5] = { SIM_CMD_READ_RECORD /* , len */ };
918 size_t blen = len + 3;
922 if (scard->sim_type == SCARD_USIM)
928 buf = os_malloc(blen);
932 ret = scard_transmit(scard, cmd, sizeof(cmd), buf, &blen);
933 if (ret != SCARD_S_SUCCESS) {
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);
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]);
953 os_memcpy(data, buf, len);
960 static int scard_read_file(struct scard_data *scard,
961 unsigned char *data, size_t len)
963 unsigned char cmd[5] = { SIM_CMD_READ_BIN /* , len */ };
964 size_t blen = len + 3;
970 buf = os_malloc(blen);
974 if (scard->sim_type == SCARD_USIM)
976 ret = scard_transmit(scard, cmd, sizeof(cmd), buf, &blen);
977 if (ret != SCARD_S_SUCCESS) {
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);
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]);
997 os_memcpy(data, buf, len);
1004 static int scard_verify_pin(struct scard_data *scard, const char *pin)
1007 unsigned char resp[3];
1008 unsigned char cmd[5 + 8] = { SIM_CMD_VERIFY_CHV1 };
1011 wpa_printf(MSG_DEBUG, "SCARD: verifying PIN");
1013 if (pin == NULL || os_strlen(pin) > 8)
1016 if (scard->sim_type == SCARD_USIM)
1018 os_memcpy(cmd + 5, pin, os_strlen(pin));
1019 os_memset(cmd + 5 + os_strlen(pin), 0xff, 8 - os_strlen(pin));
1022 ret = scard_transmit(scard, cmd, sizeof(cmd), resp, &len);
1023 if (ret != SCARD_S_SUCCESS)
1026 if (len != 2 || resp[0] != 0x90 || resp[1] != 0x00) {
1027 wpa_printf(MSG_WARNING, "SCARD: PIN verification failed");
1031 wpa_printf(MSG_DEBUG, "SCARD: PIN verified successfully");
1036 int scard_get_pin_retry_counter(struct scard_data *scard)
1039 unsigned char resp[3];
1040 unsigned char cmd[5] = { SIM_CMD_VERIFY_CHV1 };
1044 wpa_printf(MSG_DEBUG, "SCARD: fetching PIN retry counter");
1046 if (scard->sim_type == SCARD_USIM)
1048 cmd[4] = 0; /* Empty data */
1051 ret = scard_transmit(scard, cmd, sizeof(cmd), resp, &len);
1052 if (ret != SCARD_S_SUCCESS)
1056 wpa_printf(MSG_WARNING, "SCARD: failed to fetch PIN retry "
1061 val = WPA_GET_BE16(resp);
1062 if (val == 0x63c0 || val == 0x6983) {
1063 wpa_printf(MSG_DEBUG, "SCARD: PIN has been blocked");
1067 if (val >= 0x63c0 && val <= 0x63cf)
1068 return val & 0x000f;
1070 wpa_printf(MSG_DEBUG, "SCARD: Unexpected PIN retry counter response "
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.
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().
1090 int scard_get_imsi(struct scard_data *scard, char *imsi, size_t *len)
1092 unsigned char buf[100];
1093 size_t blen, imsilen, i;
1096 wpa_printf(MSG_DEBUG, "SCARD: reading IMSI from (GSM) EF-IMSI");
1098 if (scard_select_file(scard, SCARD_FILE_GSM_EF_IMSI, buf, &blen))
1101 wpa_printf(MSG_WARNING, "SCARD: too short (GSM) EF-IMSI "
1102 "header (len=%ld)", (long) blen);
1106 if (scard->sim_type == SCARD_GSM_SIM) {
1107 blen = WPA_GET_BE16(&buf[2]);
1110 if (scard_parse_fsp_templ(buf, blen, NULL, &file_size))
1114 if (blen < 2 || blen > sizeof(buf)) {
1115 wpa_printf(MSG_DEBUG, "SCARD: invalid IMSI file length=%ld",
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) {
1128 if (scard_read_file(scard, buf, blen))
1132 *pos++ = '0' + (buf[1] >> 4 & 0x0f);
1133 for (i = 2; i < blen; i++) {
1134 unsigned char digit;
1136 digit = buf[i] & 0x0f;
1138 *pos++ = '0' + digit;
1142 digit = buf[i] >> 4 & 0x0f;
1144 *pos++ = '0' + digit;
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.
1164 int scard_get_mnc_len(struct scard_data *scard)
1166 unsigned char buf[100];
1170 wpa_printf(MSG_DEBUG, "SCARD: reading MNC len from (GSM) EF-AD");
1172 if (scard_select_file(scard, SCARD_FILE_GSM_EF_AD, buf, &blen))
1175 wpa_printf(MSG_WARNING, "SCARD: too short (GSM) EF-AD "
1176 "header (len=%ld)", (long) blen);
1180 if (scard->sim_type == SCARD_GSM_SIM) {
1181 file_size = WPA_GET_BE16(&buf[2]);
1183 if (scard_parse_fsp_templ(buf, blen, NULL, &file_size))
1186 if (file_size == 3) {
1187 wpa_printf(MSG_DEBUG, "SCARD: MNC length not available");
1190 if (file_size < 4 || file_size > (int) sizeof(buf)) {
1191 wpa_printf(MSG_DEBUG, "SCARD: invalid file length=%ld",
1196 if (scard_read_file(scard, buf, file_size))
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",
1204 wpa_printf(MSG_DEBUG, "SCARD: MNC length=%ld", (long) buf[3]);
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
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.
1224 int scard_gsm_auth(struct scard_data *scard, const unsigned char *_rand,
1225 unsigned char *sres, unsigned char *kc)
1227 unsigned char cmd[5 + 1 + 16] = { SIM_CMD_RUN_GSM_ALG };
1229 unsigned char get_resp[5] = { SIM_CMD_GET_RESPONSE };
1230 unsigned char resp[3], buf[12 + 3 + 2];
1237 wpa_hexdump(MSG_DEBUG, "SCARD: GSM auth - RAND", _rand, 16);
1238 if (scard->sim_type == SCARD_GSM_SIM) {
1240 os_memcpy(cmd + 5, _rand, 16);
1242 cmdlen = 5 + 1 + 16;
1247 os_memcpy(cmd + 6, _rand, 16);
1248 get_resp[0] = USIM_CLA;
1251 ret = scard_transmit(scard, cmd, cmdlen, resp, &len);
1252 if (ret != SCARD_S_SUCCESS)
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]);
1264 get_resp[4] = resp[1];
1267 ret = scard_transmit(scard, get_resp, sizeof(get_resp), buf, &len);
1268 if (ret != SCARD_S_SUCCESS)
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)",
1278 os_memcpy(sres, buf, 4);
1279 os_memcpy(kc, buf + 4, 8);
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);
1287 if (buf[0] != 4 || buf[5] != 8) {
1288 wpa_printf(MSG_WARNING, "SCARD: unexpected SREC/Kc "
1289 "length (%d %d, expected 4 8)",
1292 os_memcpy(sres, buf + 1, 4);
1293 os_memcpy(kc, buf + 6, 8);
1296 wpa_hexdump(MSG_DEBUG, "SCARD: GSM auth - SRES", sres, 4);
1297 wpa_hexdump(MSG_DEBUG, "SCARD: GSM auth - Kc", kc, 8);
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
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.
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)
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;
1338 if (scard->sim_type == SCARD_GSM_SIM) {
1339 wpa_printf(MSG_ERROR, "SCARD: Non-USIM card - cannot do UMTS "
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);
1352 ret = scard_transmit(scard, cmd, sizeof(cmd), resp, &len);
1353 if (ret != SCARD_S_SUCCESS)
1356 if (len <= sizeof(resp))
1357 wpa_hexdump(MSG_DEBUG, "SCARD: UMTS alg response", resp, len);
1359 if (len == 2 && resp[0] == 0x98 && resp[1] == 0x62) {
1360 wpa_printf(MSG_WARNING, "SCARD: UMTS auth failed - "
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]);
1369 get_resp[4] = resp[1];
1372 ret = scard_transmit(scard, get_resp, sizeof(get_resp), buf, &len);
1373 if (ret != SCARD_S_SUCCESS || len > sizeof(buf))
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);
1383 } else if (len >= 6 + IK_LEN + CK_LEN && buf[0] == 0xdb) {
1388 if (pos[0] > RES_MAX_LEN || pos + pos[0] > end) {
1389 wpa_printf(MSG_DEBUG, "SCARD: Invalid RES");
1393 os_memcpy(res, pos, *res_len);
1395 wpa_hexdump(MSG_DEBUG, "SCARD: RES", res, *res_len);
1398 if (pos[0] != CK_LEN || pos + CK_LEN > end) {
1399 wpa_printf(MSG_DEBUG, "SCARD: Invalid CK");
1403 os_memcpy(ck, pos, CK_LEN);
1405 wpa_hexdump(MSG_DEBUG, "SCARD: CK", ck, CK_LEN);
1408 if (pos[0] != IK_LEN || pos + IK_LEN > end) {
1409 wpa_printf(MSG_DEBUG, "SCARD: Invalid IK");
1413 os_memcpy(ik, pos, IK_LEN);
1415 wpa_hexdump(MSG_DEBUG, "SCARD: IK", ik, IK_LEN);
1418 wpa_hexdump(MSG_DEBUG,
1419 "SCARD: Ignore extra data in end",
1426 wpa_printf(MSG_DEBUG, "SCARD: Unrecognized response");
1431 int scard_supports_umts(struct scard_data *scard)
1433 return scard->sim_type == SCARD_USIM;