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.
15 #include <PCSC/winscard.h>
21 #include "pcsc_funcs.h"
24 /* See ETSI GSM 11.11 and ETSI TS 102 221 for details.
26 * Command APDU: CLA INS P1 P2 P3 Data
27 * CLA (class of instruction): A0 for GSM, 00 for USIM
29 * P1 P2 P3 (parameters, P3 = length of Data)
30 * Response APDU: Data SW1 SW2
31 * SW1 SW2 (Status words)
32 * Commands (INS P1 P2 P3):
33 * SELECT: A4 00 00 02 <file_id, 2 bytes>
34 * GET RESPONSE: C0 00 00 <len>
35 * RUN GSM ALG: 88 00 00 00 <RAND len = 10>
36 * RUN UMTS ALG: 88 00 81 <len=0x22> data: 0x10 | RAND | 0x10 | AUTN
37 * P1 = ID of alg in card
38 * P2 = ID of secret key
39 * READ BINARY: B0 <offset high> <offset low> <len>
40 * READ RECORD: B2 <record number> <mode> <len>
41 * P2 (mode) = '02' (next record), '03' (previous record),
42 * '04' (absolute mode)
43 * VERIFY CHV: 20 00 <CHV number> 08
44 * CHANGE CHV: 24 00 <CHV number> 10
45 * DISABLE CHV: 26 00 01 08
46 * ENABLE CHV: 28 00 01 08
47 * UNBLOCK CHV: 2C 00 <00=CHV1, 02=CHV2> 10
51 /* GSM SIM commands */
52 #define SIM_CMD_SELECT 0xa0, 0xa4, 0x00, 0x00, 0x02
53 #define SIM_CMD_RUN_GSM_ALG 0xa0, 0x88, 0x00, 0x00, 0x10
54 #define SIM_CMD_GET_RESPONSE 0xa0, 0xc0, 0x00, 0x00
55 #define SIM_CMD_READ_BIN 0xa0, 0xb0, 0x00, 0x00
56 #define SIM_CMD_READ_RECORD 0xa0, 0xb2, 0x00, 0x00
57 #define SIM_CMD_VERIFY_CHV1 0xa0, 0x20, 0x00, 0x01, 0x08
61 #define USIM_CMD_RUN_UMTS_ALG 0x00, 0x88, 0x00, 0x81, 0x22
62 #define USIM_CMD_GET_RESPONSE 0x00, 0xc0, 0x00, 0x00
64 #define SIM_RECORD_MODE_ABSOLUTE 0x04
66 #define USIM_FSP_TEMPL_TAG 0x62
68 #define USIM_TLV_FILE_DESC 0x82
69 #define USIM_TLV_FILE_ID 0x83
70 #define USIM_TLV_DF_NAME 0x84
71 #define USIM_TLV_PROPR_INFO 0xA5
72 #define USIM_TLV_LIFE_CYCLE_STATUS 0x8A
73 #define USIM_TLV_FILE_SIZE 0x80
74 #define USIM_TLV_TOTAL_FILE_SIZE 0x81
75 #define USIM_TLV_PIN_STATUS_TEMPLATE 0xC6
76 #define USIM_TLV_SHORT_FILE_ID 0x88
77 #define USIM_TLV_SECURITY_ATTR_8B 0x8B
78 #define USIM_TLV_SECURITY_ATTR_8C 0x8C
79 #define USIM_TLV_SECURITY_ATTR_AB 0xAB
81 #define USIM_PS_DO_TAG 0x90
83 #define AKA_RAND_LEN 16
84 #define AKA_AUTN_LEN 16
85 #define AKA_AUTS_LEN 14
86 #define RES_MAX_LEN 16
92 * File type in first octet:
95 * 2F = Elementary File under the Master File
96 * 6F = Elementary File under a Dedicated File
98 #define SCARD_FILE_MF 0x3F00
99 #define SCARD_FILE_GSM_DF 0x7F20
100 #define SCARD_FILE_UMTS_DF 0x7F50
101 #define SCARD_FILE_GSM_EF_IMSI 0x6F07
102 #define SCARD_FILE_GSM_EF_AD 0x6FAD
103 #define SCARD_FILE_EF_DIR 0x2F00
104 #define SCARD_FILE_EF_ICCID 0x2FE2
105 #define SCARD_FILE_EF_CK 0x6FE1
106 #define SCARD_FILE_EF_IK 0x6FE2
108 #define SCARD_CHV1_OFFSET 13
109 #define SCARD_CHV1_FLAG 0x80
112 typedef enum { SCARD_GSM_SIM, SCARD_USIM } sim_types;
126 #ifdef __MINGW32_VERSION
127 /* MinGW does not yet support WinScard, so load the needed functions
128 * dynamically from winscard.dll for now. */
130 static HINSTANCE dll = NULL; /* winscard.dll */
132 static const SCARD_IO_REQUEST *dll_g_rgSCardT0Pci, *dll_g_rgSCardT1Pci;
134 #define SCARD_PCI_T0 (dll_g_rgSCardT0Pci)
136 #define SCARD_PCI_T1 (dll_g_rgSCardT1Pci)
139 static WINSCARDAPI LONG WINAPI
140 (*dll_SCardEstablishContext)(IN DWORD dwScope,
141 IN LPCVOID pvReserved1,
142 IN LPCVOID pvReserved2,
143 OUT LPSCARDCONTEXT phContext);
144 #define SCardEstablishContext dll_SCardEstablishContext
146 static long (*dll_SCardReleaseContext)(long hContext);
147 #define SCardReleaseContext dll_SCardReleaseContext
149 static WINSCARDAPI LONG WINAPI
150 (*dll_SCardListReadersA)(IN SCARDCONTEXT hContext,
152 OUT LPSTR mszReaders,
153 IN OUT LPDWORD pcchReaders);
154 #undef SCardListReaders
155 #define SCardListReaders dll_SCardListReadersA
157 static WINSCARDAPI LONG WINAPI
158 (*dll_SCardConnectA)(IN SCARDCONTEXT hContext,
160 IN DWORD dwShareMode,
161 IN DWORD dwPreferredProtocols,
162 OUT LPSCARDHANDLE phCard,
163 OUT LPDWORD pdwActiveProtocol);
165 #define SCardConnect dll_SCardConnectA
167 static WINSCARDAPI LONG WINAPI
168 (*dll_SCardDisconnect)(IN SCARDHANDLE hCard,
169 IN DWORD dwDisposition);
170 #define SCardDisconnect dll_SCardDisconnect
172 static WINSCARDAPI LONG WINAPI
173 (*dll_SCardTransmit)(IN SCARDHANDLE hCard,
174 IN LPCSCARD_IO_REQUEST pioSendPci,
175 IN LPCBYTE pbSendBuffer,
176 IN DWORD cbSendLength,
177 IN OUT LPSCARD_IO_REQUEST pioRecvPci,
178 OUT LPBYTE pbRecvBuffer,
179 IN OUT LPDWORD pcbRecvLength);
180 #define SCardTransmit dll_SCardTransmit
182 static WINSCARDAPI LONG WINAPI
183 (*dll_SCardBeginTransaction)(IN SCARDHANDLE hCard);
184 #define SCardBeginTransaction dll_SCardBeginTransaction
186 static WINSCARDAPI LONG WINAPI
187 (*dll_SCardEndTransaction)(IN SCARDHANDLE hCard, IN DWORD dwDisposition);
188 #define SCardEndTransaction dll_SCardEndTransaction
191 static int mingw_load_symbols(void)
198 dll = LoadLibrary("winscard");
200 wpa_printf(MSG_DEBUG, "WinSCard: Could not load winscard.dll "
207 dll_ ## s = (void *) GetProcAddress(dll, sym); \
208 if (dll_ ## s == NULL) \
211 LOADSYM(SCardEstablishContext);
212 LOADSYM(SCardReleaseContext);
213 LOADSYM(SCardListReadersA);
214 LOADSYM(SCardConnectA);
215 LOADSYM(SCardDisconnect);
216 LOADSYM(SCardTransmit);
217 LOADSYM(SCardBeginTransaction);
218 LOADSYM(SCardEndTransaction);
219 LOADSYM(g_rgSCardT0Pci);
220 LOADSYM(g_rgSCardT1Pci);
227 wpa_printf(MSG_DEBUG, "WinSCard: Could not get address for %s from "
228 "winscard.dll", sym);
235 static void mingw_unload_symbols(void)
244 #else /* __MINGW32_VERSION */
246 #define mingw_load_symbols() 0
247 #define mingw_unload_symbols() do { } while (0)
249 #endif /* __MINGW32_VERSION */
252 static int _scard_select_file(struct scard_data *scard, unsigned short file_id,
253 unsigned char *buf, size_t *buf_len,
254 sim_types sim_type, unsigned char *aid,
256 static int scard_select_file(struct scard_data *scard, unsigned short file_id,
257 unsigned char *buf, size_t *buf_len);
258 static int scard_verify_pin(struct scard_data *scard, const char *pin);
259 static int scard_get_record_len(struct scard_data *scard,
260 unsigned char recnum, unsigned char mode);
261 static int scard_read_record(struct scard_data *scard,
262 unsigned char *data, size_t len,
263 unsigned char recnum, unsigned char mode);
266 static int scard_parse_fsp_templ(unsigned char *buf, size_t buf_len,
267 int *ps_do, int *file_len)
269 unsigned char *pos, *end;
278 if (*pos != USIM_FSP_TEMPL_TAG) {
279 wpa_printf(MSG_DEBUG, "SCARD: file header did not "
280 "start with FSP template tag");
286 if (pos[0] < end - pos)
287 end = pos + 1 + pos[0];
289 wpa_hexdump(MSG_DEBUG, "SCARD: file header FSP template",
292 while (end - pos >= 2) {
293 unsigned char type, len;
297 wpa_printf(MSG_MSGDUMP, "SCARD: file header TLV 0x%02x len=%d",
301 if (len > (unsigned int) (end - pos))
305 case USIM_TLV_FILE_DESC:
306 wpa_hexdump(MSG_MSGDUMP, "SCARD: File Descriptor TLV",
309 case USIM_TLV_FILE_ID:
310 wpa_hexdump(MSG_MSGDUMP, "SCARD: File Identifier TLV",
313 case USIM_TLV_DF_NAME:
314 wpa_hexdump(MSG_MSGDUMP, "SCARD: DF name (AID) TLV",
317 case USIM_TLV_PROPR_INFO:
318 wpa_hexdump(MSG_MSGDUMP, "SCARD: Proprietary "
319 "information TLV", pos, len);
321 case USIM_TLV_LIFE_CYCLE_STATUS:
322 wpa_hexdump(MSG_MSGDUMP, "SCARD: Life Cycle Status "
323 "Integer TLV", pos, len);
325 case USIM_TLV_FILE_SIZE:
326 wpa_hexdump(MSG_MSGDUMP, "SCARD: File size TLV",
328 if ((len == 1 || len == 2) && file_len) {
330 *file_len = (int) pos[0];
332 *file_len = WPA_GET_BE16(pos);
333 wpa_printf(MSG_DEBUG, "SCARD: file_size=%d",
337 case USIM_TLV_TOTAL_FILE_SIZE:
338 wpa_hexdump(MSG_MSGDUMP, "SCARD: Total file size TLV",
341 case USIM_TLV_PIN_STATUS_TEMPLATE:
342 wpa_hexdump(MSG_MSGDUMP, "SCARD: PIN Status Template "
344 if (len >= 2 && pos[0] == USIM_PS_DO_TAG &&
345 pos[1] >= 1 && ps_do) {
346 wpa_printf(MSG_DEBUG, "SCARD: PS_DO=0x%02x",
348 *ps_do = (int) pos[2];
351 case USIM_TLV_SHORT_FILE_ID:
352 wpa_hexdump(MSG_MSGDUMP, "SCARD: Short File "
353 "Identifier (SFI) TLV", pos, len);
355 case USIM_TLV_SECURITY_ATTR_8B:
356 case USIM_TLV_SECURITY_ATTR_8C:
357 case USIM_TLV_SECURITY_ATTR_AB:
358 wpa_hexdump(MSG_MSGDUMP, "SCARD: Security attribute "
362 wpa_hexdump(MSG_MSGDUMP, "SCARD: Unrecognized TLV",
376 static int scard_pin_needed(struct scard_data *scard,
377 unsigned char *hdr, size_t hlen)
379 if (scard->sim_type == SCARD_GSM_SIM) {
380 if (hlen > SCARD_CHV1_OFFSET &&
381 !(hdr[SCARD_CHV1_OFFSET] & SCARD_CHV1_FLAG))
386 if (scard->sim_type == SCARD_USIM) {
388 if (scard_parse_fsp_templ(hdr, hlen, &ps_do, NULL))
390 /* TODO: there could be more than one PS_DO entry because of
391 * multiple PINs in key reference.. */
392 if (ps_do > 0 && (ps_do & 0x80))
401 static int scard_get_aid(struct scard_data *scard, unsigned char *aid,
406 unsigned char appl_template_tag; /* 0x61 */
407 unsigned char appl_template_len;
408 unsigned char appl_id_tag; /* 0x4f */
409 unsigned char aid_len;
410 unsigned char rid[5];
411 unsigned char appl_code[2]; /* 0x1002 for 3G USIM */
413 unsigned char buf[127], *aid_pos;
415 unsigned int aid_len = 0;
417 efdir = (struct efdir *) buf;
420 if (scard_select_file(scard, SCARD_FILE_EF_DIR, buf, &blen)) {
421 wpa_printf(MSG_DEBUG, "SCARD: Failed to read EF_DIR");
424 wpa_hexdump(MSG_DEBUG, "SCARD: EF_DIR select", buf, blen);
426 for (rec = 1; rec < 10; rec++) {
427 rlen = scard_get_record_len(scard, rec,
428 SIM_RECORD_MODE_ABSOLUTE);
430 wpa_printf(MSG_DEBUG, "SCARD: Failed to get EF_DIR "
435 if (rlen > (int) blen) {
436 wpa_printf(MSG_DEBUG, "SCARD: Too long EF_DIR record");
439 if (scard_read_record(scard, buf, rlen, rec,
440 SIM_RECORD_MODE_ABSOLUTE) < 0) {
441 wpa_printf(MSG_DEBUG, "SCARD: Failed to read "
442 "EF_DIR record %d", rec);
445 wpa_hexdump(MSG_DEBUG, "SCARD: EF_DIR record", buf, rlen);
447 if (efdir->appl_template_tag != 0x61) {
448 wpa_printf(MSG_DEBUG, "SCARD: Unexpected application "
450 efdir->appl_template_tag);
454 if (efdir->appl_template_len > rlen - 2) {
455 wpa_printf(MSG_DEBUG, "SCARD: Too long application "
456 "template (len=%d rlen=%d)",
457 efdir->appl_template_len, rlen);
461 if (efdir->appl_id_tag != 0x4f) {
462 wpa_printf(MSG_DEBUG, "SCARD: Unexpected application "
463 "identifier tag 0x%x", efdir->appl_id_tag);
467 aid_len = efdir->aid_len;
468 if (aid_len < 1 || aid_len > 16) {
469 wpa_printf(MSG_DEBUG, "SCARD: Invalid AID length %u",
474 wpa_hexdump(MSG_DEBUG, "SCARD: AID from EF_DIR record",
477 if (efdir->appl_code[0] == 0x10 &&
478 efdir->appl_code[1] == 0x02) {
479 wpa_printf(MSG_DEBUG, "SCARD: 3G USIM app found from "
480 "EF_DIR record %d", rec);
486 wpa_printf(MSG_DEBUG, "SCARD: 3G USIM app not found "
487 "from EF_DIR records");
491 if (aid_len > maxlen) {
492 wpa_printf(MSG_DEBUG, "SCARD: Too long AID");
496 os_memcpy(aid, aid_pos, aid_len);
503 * scard_init - Initialize SIM/USIM connection using PC/SC
504 * @reader: Reader name prefix to search for
505 * Returns: Pointer to private data structure, or %NULL on failure
507 * This function is used to initialize SIM/USIM connection. PC/SC is used to
508 * open connection to the SIM/USIM card. In addition, local flag is set if a
509 * PIN is needed to access some of the card functions. Once the connection is
510 * not needed anymore, scard_deinit() can be used to close it.
512 struct scard_data * scard_init(const char *reader)
521 struct scard_data *scard;
522 #ifdef CONFIG_NATIVE_WINDOWS
523 TCHAR *readers = NULL;
524 #else /* CONFIG_NATIVE_WINDOWS */
525 char *readers = NULL;
526 #endif /* CONFIG_NATIVE_WINDOWS */
527 unsigned char buf[100];
532 wpa_printf(MSG_DEBUG, "SCARD: initializing smart card interface");
533 if (mingw_load_symbols())
535 scard = os_zalloc(sizeof(*scard));
539 ret = SCardEstablishContext(SCARD_SCOPE_SYSTEM, NULL, NULL,
541 if (ret != SCARD_S_SUCCESS) {
542 wpa_printf(MSG_DEBUG, "SCARD: Could not establish smart card "
543 "context (err=%ld)", ret);
547 ret = SCardListReaders(scard->ctx, NULL, NULL, &len);
548 if (ret != SCARD_S_SUCCESS) {
549 wpa_printf(MSG_DEBUG, "SCARD: SCardListReaders failed "
557 readers = os_malloc(len);
558 if (readers == NULL) {
559 wpa_printf(MSG_INFO, "SCARD: malloc failed\n");
563 ret = SCardListReaders(scard->ctx, NULL, readers, &len);
564 if (ret != SCARD_S_SUCCESS) {
565 wpa_printf(MSG_DEBUG, "SCARD: SCardListReaders failed(2) "
570 wpa_printf(MSG_WARNING, "SCARD: No smart card readers "
574 wpa_hexdump_ascii(MSG_DEBUG, "SCARD: Readers", (u8 *) readers, len);
576 * readers is a list of available readers. The last entry is terminated
584 if (reader == NULL ||
585 os_strncmp(&readers[pos], reader, os_strlen(reader)) == 0)
587 while (pos < len && readers[pos])
589 pos++; /* skip separating null */
590 if (pos < len && readers[pos] == '\0')
591 pos = len; /* double null terminates list */
595 wpa_printf(MSG_WARNING, "SCARD: No reader with prefix '%s' "
601 wpa_printf(MSG_DEBUG, "SCARD: Selected reader='%S'", &readers[pos]);
603 wpa_printf(MSG_DEBUG, "SCARD: Selected reader='%s'", &readers[pos]);
606 ret = SCardConnect(scard->ctx, &readers[pos], SCARD_SHARE_SHARED,
607 SCARD_PROTOCOL_T0 | SCARD_PROTOCOL_T1,
608 &scard->card, &scard->protocol);
609 if (ret != SCARD_S_SUCCESS) {
610 if (ret == (long) SCARD_E_NO_SMARTCARD)
611 wpa_printf(MSG_INFO, "No smart card inserted.");
613 wpa_printf(MSG_WARNING, "SCardConnect err=%lx", ret);
620 wpa_printf(MSG_DEBUG, "SCARD: card=0x%x active_protocol=%lu (%s)",
621 (unsigned int) scard->card, (unsigned long) scard->protocol,
622 scard->protocol == SCARD_PROTOCOL_T0 ? "T0" : "T1");
624 ret = SCardBeginTransaction(scard->card);
625 if (ret != SCARD_S_SUCCESS) {
626 wpa_printf(MSG_DEBUG, "SCARD: Could not begin transaction: "
627 "0x%x", (unsigned int) ret);
634 wpa_printf(MSG_DEBUG, "SCARD: verifying USIM support");
635 if (_scard_select_file(scard, SCARD_FILE_MF, buf, &blen,
636 SCARD_USIM, NULL, 0)) {
637 wpa_printf(MSG_DEBUG, "SCARD: USIM is not supported. Trying to use GSM SIM");
638 scard->sim_type = SCARD_GSM_SIM;
640 wpa_printf(MSG_DEBUG, "SCARD: USIM is supported");
641 scard->sim_type = SCARD_USIM;
644 if (scard->sim_type == SCARD_GSM_SIM) {
646 if (scard_select_file(scard, SCARD_FILE_MF, buf, &blen)) {
647 wpa_printf(MSG_DEBUG, "SCARD: Failed to read MF");
652 if (scard_select_file(scard, SCARD_FILE_GSM_DF, buf, &blen)) {
653 wpa_printf(MSG_DEBUG, "SCARD: Failed to read GSM DF");
657 unsigned char aid[32];
660 aid_len = scard_get_aid(scard, aid, sizeof(aid));
662 wpa_printf(MSG_DEBUG, "SCARD: Failed to find AID for "
663 "3G USIM app - try to use standard 3G RID");
664 os_memcpy(aid, "\xa0\x00\x00\x00\x87", 5);
667 wpa_hexdump(MSG_DEBUG, "SCARD: 3G USIM AID", aid, aid_len);
669 /* Select based on AID = 3G RID from EF_DIR. This is usually
670 * starting with A0 00 00 00 87. */
672 if (_scard_select_file(scard, 0, buf, &blen, scard->sim_type,
674 wpa_printf(MSG_INFO, "SCARD: Failed to read 3G USIM "
676 wpa_hexdump(MSG_INFO, "SCARD: 3G USIM AID",
682 /* Verify whether CHV1 (PIN1) is needed to access the card. */
683 pin_needed = scard_pin_needed(scard, buf, blen);
684 if (pin_needed < 0) {
685 wpa_printf(MSG_DEBUG, "SCARD: Failed to determine whether PIN "
690 scard->pin1_required = 1;
691 wpa_printf(MSG_DEBUG, "PIN1 needed for SIM access (retry "
692 "counter=%d)", scard_get_pin_retry_counter(scard));
695 ret = SCardEndTransaction(scard->card, SCARD_LEAVE_CARD);
696 if (ret != SCARD_S_SUCCESS) {
697 wpa_printf(MSG_DEBUG, "SCARD: Could not end transaction: "
698 "0x%x", (unsigned int) ret);
705 SCardEndTransaction(scard->card, SCARD_LEAVE_CARD);
713 * scard_set_pin - Set PIN (CHV1/PIN1) code for accessing SIM/USIM commands
714 * @scard: Pointer to private data from scard_init()
715 * @pin: PIN code as an ASCII string (e.g., "1234")
716 * Returns: 0 on success, -1 on failure
718 int scard_set_pin(struct scard_data *scard, const char *pin)
723 /* Verify whether CHV1 (PIN1) is needed to access the card. */
724 if (scard->pin1_required) {
726 wpa_printf(MSG_DEBUG, "No PIN configured for SIM "
730 if (scard_verify_pin(scard, pin)) {
731 wpa_printf(MSG_INFO, "PIN verification failed for "
742 * scard_deinit - Deinitialize SIM/USIM connection
743 * @scard: Pointer to private data from scard_init()
745 * This function closes the SIM/USIM connect opened with scard_init().
747 void scard_deinit(struct scard_data *scard)
754 wpa_printf(MSG_DEBUG, "SCARD: deinitializing smart card interface");
756 ret = SCardDisconnect(scard->card, SCARD_UNPOWER_CARD);
757 if (ret != SCARD_S_SUCCESS) {
758 wpa_printf(MSG_DEBUG, "SCARD: Failed to disconnect "
759 "smart card (err=%ld)", ret);
764 ret = SCardReleaseContext(scard->ctx);
765 if (ret != SCARD_S_SUCCESS) {
766 wpa_printf(MSG_DEBUG, "Failed to release smart card "
767 "context (err=%ld)", ret);
771 mingw_unload_symbols();
775 static long scard_transmit(struct scard_data *scard,
776 unsigned char *_send, size_t send_len,
777 unsigned char *_recv, size_t *recv_len)
786 wpa_hexdump_key(MSG_DEBUG, "SCARD: scard_transmit: send",
789 ret = SCardTransmit(scard->card,
790 scard->protocol == SCARD_PROTOCOL_T1 ?
791 SCARD_PCI_T1 : SCARD_PCI_T0,
792 _send, (unsigned long) send_len,
795 if (ret == SCARD_S_SUCCESS) {
796 wpa_hexdump(MSG_DEBUG, "SCARD: scard_transmit: recv",
799 wpa_printf(MSG_WARNING, "SCARD: SCardTransmit failed "
806 static int _scard_select_file(struct scard_data *scard, unsigned short file_id,
807 unsigned char *buf, size_t *buf_len,
808 sim_types sim_type, unsigned char *aid,
812 unsigned char resp[3];
813 unsigned char cmd[50] = { SIM_CMD_SELECT };
815 unsigned char get_resp[5] = { SIM_CMD_GET_RESPONSE };
818 if (sim_type == SCARD_USIM) {
821 get_resp[0] = USIM_CLA;
824 wpa_printf(MSG_DEBUG, "SCARD: select file %04x", file_id);
826 wpa_hexdump(MSG_DEBUG, "SCARD: select file by AID",
828 if (5 + aidlen > sizeof(cmd))
830 cmd[2] = 0x04; /* Select by AID */
831 cmd[4] = aidlen; /* len */
832 os_memcpy(cmd + 5, aid, aidlen);
835 cmd[5] = file_id >> 8;
836 cmd[6] = file_id & 0xff;
840 ret = scard_transmit(scard, cmd, cmdlen, resp, &len);
841 if (ret != SCARD_S_SUCCESS) {
842 wpa_printf(MSG_WARNING, "SCARD: SCardTransmit failed "
848 wpa_printf(MSG_WARNING, "SCARD: unexpected resp len "
849 "%d (expected 2)", (int) len);
853 if (resp[0] == 0x98 && resp[1] == 0x04) {
854 /* Security status not satisfied (PIN_WLAN) */
855 wpa_printf(MSG_WARNING, "SCARD: Security status not satisfied "
860 if (resp[0] == 0x6e) {
861 wpa_printf(MSG_DEBUG, "SCARD: used CLA not supported");
865 if (resp[0] != 0x6c && resp[0] != 0x9f && resp[0] != 0x61) {
866 wpa_printf(MSG_WARNING, "SCARD: unexpected response 0x%02x "
867 "(expected 0x61, 0x6c, or 0x9f)", resp[0]);
870 /* Normal ending of command; resp[1] bytes available */
871 get_resp[4] = resp[1];
872 wpa_printf(MSG_DEBUG, "SCARD: trying to get response (%d bytes)",
876 ret = scard_transmit(scard, get_resp, sizeof(get_resp), buf, &rlen);
877 if (ret == SCARD_S_SUCCESS) {
878 *buf_len = resp[1] < rlen ? resp[1] : rlen;
882 wpa_printf(MSG_WARNING, "SCARD: SCardTransmit err=0x%lx\n", ret);
887 static int scard_select_file(struct scard_data *scard, unsigned short file_id,
888 unsigned char *buf, size_t *buf_len)
890 return _scard_select_file(scard, file_id, buf, buf_len,
891 scard->sim_type, NULL, 0);
895 static int scard_get_record_len(struct scard_data *scard, unsigned char recnum,
898 unsigned char buf[255];
899 unsigned char cmd[5] = { SIM_CMD_READ_RECORD /* , len */ };
903 if (scard->sim_type == SCARD_USIM)
907 cmd[4] = sizeof(buf);
910 ret = scard_transmit(scard, cmd, sizeof(cmd), buf, &blen);
911 if (ret != SCARD_S_SUCCESS) {
912 wpa_printf(MSG_DEBUG, "SCARD: failed to determine file "
913 "length for record %d", recnum);
917 wpa_hexdump(MSG_DEBUG, "SCARD: file length determination response",
920 if (blen < 2 || (buf[0] != 0x6c && buf[0] != 0x67)) {
921 wpa_printf(MSG_DEBUG, "SCARD: unexpected response to file "
922 "length determination");
930 static int scard_read_record(struct scard_data *scard,
931 unsigned char *data, size_t len,
932 unsigned char recnum, unsigned char mode)
934 unsigned char cmd[5] = { SIM_CMD_READ_RECORD /* , len */ };
935 size_t blen = len + 3;
939 if (scard->sim_type == SCARD_USIM)
945 buf = os_malloc(blen);
949 ret = scard_transmit(scard, cmd, sizeof(cmd), buf, &blen);
950 if (ret != SCARD_S_SUCCESS) {
954 if (blen != len + 2) {
955 wpa_printf(MSG_DEBUG, "SCARD: record read returned unexpected "
956 "length %ld (expected %ld)",
957 (long) blen, (long) len + 2);
962 if (buf[len] != 0x90 || buf[len + 1] != 0x00) {
963 wpa_printf(MSG_DEBUG, "SCARD: record read returned unexpected "
964 "status %02x %02x (expected 90 00)",
965 buf[len], buf[len + 1]);
970 os_memcpy(data, buf, len);
977 static int scard_read_file(struct scard_data *scard,
978 unsigned char *data, size_t len)
980 unsigned char cmd[5] = { SIM_CMD_READ_BIN /* , len */ };
981 size_t blen = len + 3;
987 buf = os_malloc(blen);
991 if (scard->sim_type == SCARD_USIM)
993 ret = scard_transmit(scard, cmd, sizeof(cmd), buf, &blen);
994 if (ret != SCARD_S_SUCCESS) {
998 if (blen != len + 2) {
999 wpa_printf(MSG_DEBUG, "SCARD: file read returned unexpected "
1000 "length %ld (expected %ld)",
1001 (long) blen, (long) len + 2);
1006 if (buf[len] != 0x90 || buf[len + 1] != 0x00) {
1007 wpa_printf(MSG_DEBUG, "SCARD: file read returned unexpected "
1008 "status %02x %02x (expected 90 00)",
1009 buf[len], buf[len + 1]);
1014 os_memcpy(data, buf, len);
1021 static int scard_verify_pin(struct scard_data *scard, const char *pin)
1024 unsigned char resp[3];
1025 unsigned char cmd[5 + 8] = { SIM_CMD_VERIFY_CHV1 };
1028 wpa_printf(MSG_DEBUG, "SCARD: verifying PIN");
1030 if (pin == NULL || os_strlen(pin) > 8)
1033 if (scard->sim_type == SCARD_USIM)
1035 os_memcpy(cmd + 5, pin, os_strlen(pin));
1036 os_memset(cmd + 5 + os_strlen(pin), 0xff, 8 - os_strlen(pin));
1039 ret = scard_transmit(scard, cmd, sizeof(cmd), resp, &len);
1040 if (ret != SCARD_S_SUCCESS)
1043 if (len != 2 || resp[0] != 0x90 || resp[1] != 0x00) {
1044 wpa_printf(MSG_WARNING, "SCARD: PIN verification failed");
1048 wpa_printf(MSG_DEBUG, "SCARD: PIN verified successfully");
1053 int scard_get_pin_retry_counter(struct scard_data *scard)
1056 unsigned char resp[3];
1057 unsigned char cmd[5] = { SIM_CMD_VERIFY_CHV1 };
1061 wpa_printf(MSG_DEBUG, "SCARD: fetching PIN retry counter");
1063 if (scard->sim_type == SCARD_USIM)
1065 cmd[4] = 0; /* Empty data */
1068 ret = scard_transmit(scard, cmd, sizeof(cmd), resp, &len);
1069 if (ret != SCARD_S_SUCCESS)
1073 wpa_printf(MSG_WARNING, "SCARD: failed to fetch PIN retry "
1078 val = WPA_GET_BE16(resp);
1079 if (val == 0x63c0 || val == 0x6983) {
1080 wpa_printf(MSG_DEBUG, "SCARD: PIN has been blocked");
1084 if (val >= 0x63c0 && val <= 0x63cf)
1085 return val & 0x000f;
1087 wpa_printf(MSG_DEBUG, "SCARD: Unexpected PIN retry counter response "
1094 * scard_get_imsi - Read IMSI from SIM/USIM card
1095 * @scard: Pointer to private data from scard_init()
1096 * @imsi: Buffer for IMSI
1097 * @len: Length of imsi buffer; set to IMSI length on success
1098 * Returns: 0 on success, -1 if IMSI file cannot be selected, -2 if IMSI file
1099 * selection returns invalid result code, -3 if parsing FSP template file fails
1100 * (USIM only), -4 if IMSI does not fit in the provided imsi buffer (len is set
1101 * to needed length), -5 if reading IMSI file fails.
1103 * This function can be used to read IMSI from the SIM/USIM card. If the IMSI
1104 * file is PIN protected, scard_set_pin() must have been used to set the
1105 * correct PIN code before calling scard_get_imsi().
1107 int scard_get_imsi(struct scard_data *scard, char *imsi, size_t *len)
1109 unsigned char buf[100];
1110 size_t blen, imsilen, i;
1113 wpa_printf(MSG_DEBUG, "SCARD: reading IMSI from (GSM) EF-IMSI");
1115 if (scard_select_file(scard, SCARD_FILE_GSM_EF_IMSI, buf, &blen))
1118 wpa_printf(MSG_WARNING, "SCARD: too short (GSM) EF-IMSI "
1119 "header (len=%ld)", (long) blen);
1123 if (scard->sim_type == SCARD_GSM_SIM) {
1124 blen = WPA_GET_BE16(&buf[2]);
1127 if (scard_parse_fsp_templ(buf, blen, NULL, &file_size))
1131 if (blen < 2 || blen > sizeof(buf)) {
1132 wpa_printf(MSG_DEBUG, "SCARD: invalid IMSI file length=%ld",
1137 imsilen = (blen - 2) * 2 + 1;
1138 wpa_printf(MSG_DEBUG, "SCARD: IMSI file length=%ld imsilen=%ld",
1139 (long) blen, (long) imsilen);
1140 if (blen < 2 || imsilen > *len) {
1145 if (scard_read_file(scard, buf, blen))
1149 *pos++ = '0' + (buf[1] >> 4 & 0x0f);
1150 for (i = 2; i < blen; i++) {
1151 unsigned char digit;
1153 digit = buf[i] & 0x0f;
1155 *pos++ = '0' + digit;
1159 digit = buf[i] >> 4 & 0x0f;
1161 *pos++ = '0' + digit;
1172 * scard_get_mnc_len - Read length of MNC in the IMSI from SIM/USIM card
1173 * @scard: Pointer to private data from scard_init()
1174 * Returns: length (>0) on success, -1 if administrative data file cannot be
1175 * selected, -2 if administrative data file selection returns invalid result
1176 * code, -3 if parsing FSP template file fails (USIM only), -4 if length of
1177 * the file is unexpected, -5 if reading file fails, -6 if MNC length is not
1178 * in range (i.e. 2 or 3), -7 if MNC length is not available.
1181 int scard_get_mnc_len(struct scard_data *scard)
1183 unsigned char buf[100];
1187 wpa_printf(MSG_DEBUG, "SCARD: reading MNC len from (GSM) EF-AD");
1189 if (scard_select_file(scard, SCARD_FILE_GSM_EF_AD, buf, &blen))
1192 wpa_printf(MSG_WARNING, "SCARD: too short (GSM) EF-AD "
1193 "header (len=%ld)", (long) blen);
1197 if (scard->sim_type == SCARD_GSM_SIM) {
1198 file_size = WPA_GET_BE16(&buf[2]);
1200 if (scard_parse_fsp_templ(buf, blen, NULL, &file_size))
1203 if (file_size == 3) {
1204 wpa_printf(MSG_DEBUG, "SCARD: MNC length not available");
1207 if (file_size < 4 || file_size > (int) sizeof(buf)) {
1208 wpa_printf(MSG_DEBUG, "SCARD: invalid file length=%ld",
1213 if (scard_read_file(scard, buf, file_size))
1215 buf[3] = buf[3] & 0x0f; /* upper nibble reserved for future use */
1216 if (buf[3] < 2 || buf[3] > 3) {
1217 wpa_printf(MSG_DEBUG, "SCARD: invalid MNC length=%ld",
1221 wpa_printf(MSG_DEBUG, "SCARD: MNC length=%ld", (long) buf[3]);
1227 * scard_gsm_auth - Run GSM authentication command on SIM card
1228 * @scard: Pointer to private data from scard_init()
1229 * @_rand: 16-byte RAND value from HLR/AuC
1230 * @sres: 4-byte buffer for SRES
1231 * @kc: 8-byte buffer for Kc
1232 * Returns: 0 on success, -1 if SIM/USIM connection has not been initialized,
1233 * -2 if authentication command execution fails, -3 if unknown response code
1234 * for authentication command is received, -4 if reading of response fails,
1235 * -5 if if response data is of unexpected length
1237 * This function performs GSM authentication using SIM/USIM card and the
1238 * provided RAND value from HLR/AuC. If authentication command can be completed
1239 * successfully, SRES and Kc values will be written into sres and kc buffers.
1241 int scard_gsm_auth(struct scard_data *scard, const unsigned char *_rand,
1242 unsigned char *sres, unsigned char *kc)
1244 unsigned char cmd[5 + 1 + 16] = { SIM_CMD_RUN_GSM_ALG };
1246 unsigned char get_resp[5] = { SIM_CMD_GET_RESPONSE };
1247 unsigned char resp[3], buf[12 + 3 + 2];
1254 wpa_hexdump(MSG_DEBUG, "SCARD: GSM auth - RAND", _rand, 16);
1255 if (scard->sim_type == SCARD_GSM_SIM) {
1257 os_memcpy(cmd + 5, _rand, 16);
1259 cmdlen = 5 + 1 + 16;
1264 os_memcpy(cmd + 6, _rand, 16);
1265 get_resp[0] = USIM_CLA;
1268 ret = scard_transmit(scard, cmd, cmdlen, resp, &len);
1269 if (ret != SCARD_S_SUCCESS)
1272 if ((scard->sim_type == SCARD_GSM_SIM &&
1273 (len != 2 || resp[0] != 0x9f || resp[1] != 0x0c)) ||
1274 (scard->sim_type == SCARD_USIM &&
1275 (len != 2 || resp[0] != 0x61 || resp[1] != 0x0e))) {
1276 wpa_printf(MSG_WARNING, "SCARD: unexpected response for GSM "
1277 "auth request (len=%ld resp=%02x %02x)",
1278 (long) len, resp[0], resp[1]);
1281 get_resp[4] = resp[1];
1284 ret = scard_transmit(scard, get_resp, sizeof(get_resp), buf, &len);
1285 if (ret != SCARD_S_SUCCESS)
1288 if (scard->sim_type == SCARD_GSM_SIM) {
1289 if (len != 4 + 8 + 2) {
1290 wpa_printf(MSG_WARNING, "SCARD: unexpected data "
1291 "length for GSM auth (len=%ld, expected 14)",
1295 os_memcpy(sres, buf, 4);
1296 os_memcpy(kc, buf + 4, 8);
1298 if (len != 1 + 4 + 1 + 8 + 2) {
1299 wpa_printf(MSG_WARNING, "SCARD: unexpected data "
1300 "length for USIM auth (len=%ld, "
1301 "expected 16)", (long) len);
1304 if (buf[0] != 4 || buf[5] != 8) {
1305 wpa_printf(MSG_WARNING, "SCARD: unexpected SREC/Kc "
1306 "length (%d %d, expected 4 8)",
1309 os_memcpy(sres, buf + 1, 4);
1310 os_memcpy(kc, buf + 6, 8);
1313 wpa_hexdump(MSG_DEBUG, "SCARD: GSM auth - SRES", sres, 4);
1314 wpa_hexdump(MSG_DEBUG, "SCARD: GSM auth - Kc", kc, 8);
1321 * scard_umts_auth - Run UMTS authentication command on USIM card
1322 * @scard: Pointer to private data from scard_init()
1323 * @_rand: 16-byte RAND value from HLR/AuC
1324 * @autn: 16-byte AUTN value from HLR/AuC
1325 * @res: 16-byte buffer for RES
1326 * @res_len: Variable that will be set to RES length
1327 * @ik: 16-byte buffer for IK
1328 * @ck: 16-byte buffer for CK
1329 * @auts: 14-byte buffer for AUTS
1330 * Returns: 0 on success, -1 on failure, or -2 if USIM reports synchronization
1333 * This function performs AKA authentication using USIM card and the provided
1334 * RAND and AUTN values from HLR/AuC. If authentication command can be
1335 * completed successfully, RES, IK, and CK values will be written into provided
1336 * buffers and res_len is set to length of received RES value. If USIM reports
1337 * synchronization failure, the received AUTS value will be written into auts
1338 * buffer. In this case, RES, IK, and CK are not valid.
1340 int scard_umts_auth(struct scard_data *scard, const unsigned char *_rand,
1341 const unsigned char *autn,
1342 unsigned char *res, size_t *res_len,
1343 unsigned char *ik, unsigned char *ck, unsigned char *auts)
1345 unsigned char cmd[5 + 1 + AKA_RAND_LEN + 1 + AKA_AUTN_LEN] =
1346 { USIM_CMD_RUN_UMTS_ALG };
1347 unsigned char get_resp[5] = { USIM_CMD_GET_RESPONSE };
1348 unsigned char resp[3], buf[64], *pos, *end;
1355 if (scard->sim_type == SCARD_GSM_SIM) {
1356 wpa_printf(MSG_ERROR, "SCARD: Non-USIM card - cannot do UMTS "
1361 wpa_hexdump(MSG_DEBUG, "SCARD: UMTS auth - RAND", _rand, AKA_RAND_LEN);
1362 wpa_hexdump(MSG_DEBUG, "SCARD: UMTS auth - AUTN", autn, AKA_AUTN_LEN);
1363 cmd[5] = AKA_RAND_LEN;
1364 os_memcpy(cmd + 6, _rand, AKA_RAND_LEN);
1365 cmd[6 + AKA_RAND_LEN] = AKA_AUTN_LEN;
1366 os_memcpy(cmd + 6 + AKA_RAND_LEN + 1, autn, AKA_AUTN_LEN);
1369 ret = scard_transmit(scard, cmd, sizeof(cmd), resp, &len);
1370 if (ret != SCARD_S_SUCCESS)
1373 if (len <= sizeof(resp))
1374 wpa_hexdump(MSG_DEBUG, "SCARD: UMTS alg response", resp, len);
1376 if (len == 2 && resp[0] == 0x98 && resp[1] == 0x62) {
1377 wpa_printf(MSG_WARNING, "SCARD: UMTS auth failed - "
1380 } else if (len != 2 || resp[0] != 0x61) {
1381 wpa_printf(MSG_WARNING, "SCARD: unexpected response for UMTS "
1382 "auth request (len=%ld resp=%02x %02x)",
1383 (long) len, resp[0], resp[1]);
1386 get_resp[4] = resp[1];
1389 ret = scard_transmit(scard, get_resp, sizeof(get_resp), buf, &len);
1390 if (ret != SCARD_S_SUCCESS || len > sizeof(buf))
1393 wpa_hexdump(MSG_DEBUG, "SCARD: UMTS get response result", buf, len);
1394 if (len >= 2 + AKA_AUTS_LEN && buf[0] == 0xdc &&
1395 buf[1] == AKA_AUTS_LEN) {
1396 wpa_printf(MSG_DEBUG, "SCARD: UMTS Synchronization-Failure");
1397 os_memcpy(auts, buf + 2, AKA_AUTS_LEN);
1398 wpa_hexdump(MSG_DEBUG, "SCARD: AUTS", auts, AKA_AUTS_LEN);
1400 } else if (len >= 6 + IK_LEN + CK_LEN && buf[0] == 0xdb) {
1405 if (pos[0] > RES_MAX_LEN || pos[0] > end - pos) {
1406 wpa_printf(MSG_DEBUG, "SCARD: Invalid RES");
1410 os_memcpy(res, pos, *res_len);
1412 wpa_hexdump(MSG_DEBUG, "SCARD: RES", res, *res_len);
1415 if (pos[0] != CK_LEN || CK_LEN > end - pos) {
1416 wpa_printf(MSG_DEBUG, "SCARD: Invalid CK");
1420 os_memcpy(ck, pos, CK_LEN);
1422 wpa_hexdump(MSG_DEBUG, "SCARD: CK", ck, CK_LEN);
1425 if (pos[0] != IK_LEN || IK_LEN > end - pos) {
1426 wpa_printf(MSG_DEBUG, "SCARD: Invalid IK");
1430 os_memcpy(ik, pos, IK_LEN);
1432 wpa_hexdump(MSG_DEBUG, "SCARD: IK", ik, IK_LEN);
1435 wpa_hexdump(MSG_DEBUG,
1436 "SCARD: Ignore extra data in end",
1443 wpa_printf(MSG_DEBUG, "SCARD: Unrecognized response");
1448 int scard_supports_umts(struct scard_data *scard)
1450 return scard->sim_type == SCARD_USIM;