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
87 typedef enum { SCARD_GSM_SIM, SCARD_USIM } sim_types;
97 #ifdef __MINGW32_VERSION
98 /* MinGW does not yet support WinScard, so load the needed functions
99 * dynamically from winscard.dll for now. */
101 static HINSTANCE dll = NULL; /* winscard.dll */
103 static const SCARD_IO_REQUEST *dll_g_rgSCardT0Pci, *dll_g_rgSCardT1Pci;
105 #define SCARD_PCI_T0 (dll_g_rgSCardT0Pci)
107 #define SCARD_PCI_T1 (dll_g_rgSCardT1Pci)
110 static WINSCARDAPI LONG WINAPI
111 (*dll_SCardEstablishContext)(IN DWORD dwScope,
112 IN LPCVOID pvReserved1,
113 IN LPCVOID pvReserved2,
114 OUT LPSCARDCONTEXT phContext);
115 #define SCardEstablishContext dll_SCardEstablishContext
117 static long (*dll_SCardReleaseContext)(long hContext);
118 #define SCardReleaseContext dll_SCardReleaseContext
120 static WINSCARDAPI LONG WINAPI
121 (*dll_SCardListReadersA)(IN SCARDCONTEXT hContext,
123 OUT LPSTR mszReaders,
124 IN OUT LPDWORD pcchReaders);
125 #undef SCardListReaders
126 #define SCardListReaders dll_SCardListReadersA
128 static WINSCARDAPI LONG WINAPI
129 (*dll_SCardConnectA)(IN SCARDCONTEXT hContext,
131 IN DWORD dwShareMode,
132 IN DWORD dwPreferredProtocols,
133 OUT LPSCARDHANDLE phCard,
134 OUT LPDWORD pdwActiveProtocol);
136 #define SCardConnect dll_SCardConnectA
138 static WINSCARDAPI LONG WINAPI
139 (*dll_SCardDisconnect)(IN SCARDHANDLE hCard,
140 IN DWORD dwDisposition);
141 #define SCardDisconnect dll_SCardDisconnect
143 static WINSCARDAPI LONG WINAPI
144 (*dll_SCardTransmit)(IN SCARDHANDLE hCard,
145 IN LPCSCARD_IO_REQUEST pioSendPci,
146 IN LPCBYTE pbSendBuffer,
147 IN DWORD cbSendLength,
148 IN OUT LPSCARD_IO_REQUEST pioRecvPci,
149 OUT LPBYTE pbRecvBuffer,
150 IN OUT LPDWORD pcbRecvLength);
151 #define SCardTransmit dll_SCardTransmit
153 static WINSCARDAPI LONG WINAPI
154 (*dll_SCardBeginTransaction)(IN SCARDHANDLE hCard);
155 #define SCardBeginTransaction dll_SCardBeginTransaction
157 static WINSCARDAPI LONG WINAPI
158 (*dll_SCardEndTransaction)(IN SCARDHANDLE hCard, IN DWORD dwDisposition);
159 #define SCardEndTransaction dll_SCardEndTransaction
162 static int mingw_load_symbols(void)
169 dll = LoadLibrary("winscard");
171 wpa_printf(MSG_DEBUG, "WinSCard: Could not load winscard.dll "
178 dll_ ## s = (void *) GetProcAddress(dll, sym); \
179 if (dll_ ## s == NULL) \
182 LOADSYM(SCardEstablishContext);
183 LOADSYM(SCardReleaseContext);
184 LOADSYM(SCardListReadersA);
185 LOADSYM(SCardConnectA);
186 LOADSYM(SCardDisconnect);
187 LOADSYM(SCardTransmit);
188 LOADSYM(SCardBeginTransaction);
189 LOADSYM(SCardEndTransaction);
190 LOADSYM(g_rgSCardT0Pci);
191 LOADSYM(g_rgSCardT1Pci);
198 wpa_printf(MSG_DEBUG, "WinSCard: Could not get address for %s from "
199 "winscard.dll", sym);
206 static void mingw_unload_symbols(void)
215 #else /* __MINGW32_VERSION */
217 #define mingw_load_symbols() 0
218 #define mingw_unload_symbols() do { } while (0)
220 #endif /* __MINGW32_VERSION */
223 static int _scard_select_file(struct scard_data *scard, unsigned short file_id,
224 unsigned char *buf, size_t *buf_len,
225 sim_types sim_type, unsigned char *aid,
227 static int scard_select_file(struct scard_data *scard, unsigned short file_id,
228 unsigned char *buf, size_t *buf_len);
229 static int scard_verify_pin(struct scard_data *scard, const char *pin);
230 static int scard_get_record_len(struct scard_data *scard,
231 unsigned char recnum, unsigned char mode);
232 static int scard_read_record(struct scard_data *scard,
233 unsigned char *data, size_t len,
234 unsigned char recnum, unsigned char mode);
237 static int scard_parse_fsp_templ(unsigned char *buf, size_t buf_len,
238 int *ps_do, int *file_len)
240 unsigned char *pos, *end;
249 if (*pos != USIM_FSP_TEMPL_TAG) {
250 wpa_printf(MSG_DEBUG, "SCARD: file header did not "
251 "start with FSP template tag");
257 if ((pos + pos[0]) < end)
258 end = pos + 1 + pos[0];
260 wpa_hexdump(MSG_DEBUG, "SCARD: file header FSP template",
263 while (pos + 1 < end) {
264 wpa_printf(MSG_MSGDUMP, "SCARD: file header TLV 0x%02x len=%d",
266 if (pos + 2 + pos[1] > end)
270 case USIM_TLV_FILE_DESC:
271 wpa_hexdump(MSG_MSGDUMP, "SCARD: File Descriptor TLV",
274 case USIM_TLV_FILE_ID:
275 wpa_hexdump(MSG_MSGDUMP, "SCARD: File Identifier TLV",
278 case USIM_TLV_DF_NAME:
279 wpa_hexdump(MSG_MSGDUMP, "SCARD: DF name (AID) TLV",
282 case USIM_TLV_PROPR_INFO:
283 wpa_hexdump(MSG_MSGDUMP, "SCARD: Proprietary "
284 "information TLV", pos + 2, pos[1]);
286 case USIM_TLV_LIFE_CYCLE_STATUS:
287 wpa_hexdump(MSG_MSGDUMP, "SCARD: Life Cycle Status "
288 "Integer TLV", pos + 2, pos[1]);
290 case USIM_TLV_FILE_SIZE:
291 wpa_hexdump(MSG_MSGDUMP, "SCARD: File size TLV",
293 if ((pos[1] == 1 || pos[1] == 2) && file_len) {
295 *file_len = (int) pos[2];
297 *file_len = ((int) pos[2] << 8) |
299 wpa_printf(MSG_DEBUG, "SCARD: file_size=%d",
303 case USIM_TLV_TOTAL_FILE_SIZE:
304 wpa_hexdump(MSG_MSGDUMP, "SCARD: Total file size TLV",
307 case USIM_TLV_PIN_STATUS_TEMPLATE:
308 wpa_hexdump(MSG_MSGDUMP, "SCARD: PIN Status Template "
309 "DO TLV", pos + 2, pos[1]);
310 if (pos[1] >= 2 && pos[2] == USIM_PS_DO_TAG &&
311 pos[3] >= 1 && ps_do) {
312 wpa_printf(MSG_DEBUG, "SCARD: PS_DO=0x%02x",
314 *ps_do = (int) pos[4];
317 case USIM_TLV_SHORT_FILE_ID:
318 wpa_hexdump(MSG_MSGDUMP, "SCARD: Short File "
319 "Identifier (SFI) TLV", pos + 2, pos[1]);
321 case USIM_TLV_SECURITY_ATTR_8B:
322 case USIM_TLV_SECURITY_ATTR_8C:
323 case USIM_TLV_SECURITY_ATTR_AB:
324 wpa_hexdump(MSG_MSGDUMP, "SCARD: Security attribute "
325 "TLV", pos + 2, pos[1]);
328 wpa_hexdump(MSG_MSGDUMP, "SCARD: Unrecognized TLV",
342 static int scard_pin_needed(struct scard_data *scard,
343 unsigned char *hdr, size_t hlen)
345 if (scard->sim_type == SCARD_GSM_SIM) {
346 if (hlen > SCARD_CHV1_OFFSET &&
347 !(hdr[SCARD_CHV1_OFFSET] & SCARD_CHV1_FLAG))
352 if (scard->sim_type == SCARD_USIM) {
354 if (scard_parse_fsp_templ(hdr, hlen, &ps_do, NULL))
356 /* TODO: there could be more than one PS_DO entry because of
357 * multiple PINs in key reference.. */
358 if (ps_do > 0 && (ps_do & 0x80))
367 static int scard_get_aid(struct scard_data *scard, unsigned char *aid,
372 unsigned char appl_template_tag; /* 0x61 */
373 unsigned char appl_template_len;
374 unsigned char appl_id_tag; /* 0x4f */
375 unsigned char aid_len;
376 unsigned char rid[5];
377 unsigned char appl_code[2]; /* 0x1002 for 3G USIM */
379 unsigned char buf[100];
382 efdir = (struct efdir *) buf;
384 if (scard_select_file(scard, SCARD_FILE_EF_DIR, buf, &blen)) {
385 wpa_printf(MSG_DEBUG, "SCARD: Failed to read EF_DIR");
388 wpa_hexdump(MSG_DEBUG, "SCARD: EF_DIR select", buf, blen);
390 for (rec = 1; rec < 10; rec++) {
391 rlen = scard_get_record_len(scard, rec,
392 SIM_RECORD_MODE_ABSOLUTE);
394 wpa_printf(MSG_DEBUG, "SCARD: Failed to get EF_DIR "
399 if (rlen > (int) blen) {
400 wpa_printf(MSG_DEBUG, "SCARD: Too long EF_DIR record");
403 if (scard_read_record(scard, buf, rlen, rec,
404 SIM_RECORD_MODE_ABSOLUTE) < 0) {
405 wpa_printf(MSG_DEBUG, "SCARD: Failed to read "
406 "EF_DIR record %d", rec);
409 wpa_hexdump(MSG_DEBUG, "SCARD: EF_DIR record", buf, rlen);
411 if (efdir->appl_template_tag != 0x61) {
412 wpa_printf(MSG_DEBUG, "SCARD: Unexpected application "
414 efdir->appl_template_tag);
418 if (efdir->appl_template_len > rlen - 2) {
419 wpa_printf(MSG_DEBUG, "SCARD: Too long application "
420 "template (len=%d rlen=%d)",
421 efdir->appl_template_len, rlen);
425 if (efdir->appl_id_tag != 0x4f) {
426 wpa_printf(MSG_DEBUG, "SCARD: Unexpected application "
427 "identifier tag 0x%x", efdir->appl_id_tag);
431 if (efdir->aid_len < 1 || efdir->aid_len > 16) {
432 wpa_printf(MSG_DEBUG, "SCARD: Invalid AID length %d",
437 wpa_hexdump(MSG_DEBUG, "SCARD: AID from EF_DIR record",
438 efdir->rid, efdir->aid_len);
440 if (efdir->appl_code[0] == 0x10 &&
441 efdir->appl_code[1] == 0x02) {
442 wpa_printf(MSG_DEBUG, "SCARD: 3G USIM app found from "
443 "EF_DIR record %d", rec);
449 wpa_printf(MSG_DEBUG, "SCARD: 3G USIM app not found "
450 "from EF_DIR records");
454 if (efdir->aid_len > maxlen) {
455 wpa_printf(MSG_DEBUG, "SCARD: Too long AID");
459 os_memcpy(aid, efdir->rid, efdir->aid_len);
461 return efdir->aid_len;
466 * scard_init - Initialize SIM/USIM connection using PC/SC
467 * @sim_type: Allowed SIM types (SIM, USIM, or both)
468 * @reader: Reader name prefix to search for
469 * Returns: Pointer to private data structure, or %NULL on failure
471 * This function is used to initialize SIM/USIM connection. PC/SC is used to
472 * open connection to the SIM/USIM card and the card is verified to support the
473 * selected sim_type. In addition, local flag is set if a PIN is needed to
474 * access some of the card functions. Once the connection is not needed
475 * anymore, scard_deinit() can be used to close it.
477 struct scard_data * scard_init(scard_sim_type sim_type, const char *reader)
480 unsigned long len, pos;
481 struct scard_data *scard;
482 #ifdef CONFIG_NATIVE_WINDOWS
483 TCHAR *readers = NULL;
484 #else /* CONFIG_NATIVE_WINDOWS */
485 char *readers = NULL;
486 #endif /* CONFIG_NATIVE_WINDOWS */
487 unsigned char buf[100];
492 wpa_printf(MSG_DEBUG, "SCARD: initializing smart card interface");
493 if (mingw_load_symbols())
495 scard = os_zalloc(sizeof(*scard));
499 ret = SCardEstablishContext(SCARD_SCOPE_SYSTEM, NULL, NULL,
501 if (ret != SCARD_S_SUCCESS) {
502 wpa_printf(MSG_DEBUG, "SCARD: Could not establish smart card "
503 "context (err=%ld)", ret);
507 ret = SCardListReaders(scard->ctx, NULL, NULL, &len);
508 if (ret != SCARD_S_SUCCESS) {
509 wpa_printf(MSG_DEBUG, "SCARD: SCardListReaders failed "
517 readers = os_malloc(len);
518 if (readers == NULL) {
519 wpa_printf(MSG_INFO, "SCARD: malloc failed\n");
523 ret = SCardListReaders(scard->ctx, NULL, readers, &len);
524 if (ret != SCARD_S_SUCCESS) {
525 wpa_printf(MSG_DEBUG, "SCARD: SCardListReaders failed(2) "
530 wpa_printf(MSG_WARNING, "SCARD: No smart card readers "
534 wpa_hexdump_ascii(MSG_DEBUG, "SCARD: Readers", (u8 *) readers, len);
536 * readers is a list of available readers. The last entry is terminated
544 if (reader == NULL ||
545 os_strncmp(&readers[pos], reader, os_strlen(reader)) == 0)
547 while (pos < len && readers[pos])
549 pos++; /* skip separating null */
550 if (pos < len && readers[pos] == '\0')
551 pos = len; /* double null terminates list */
555 wpa_printf(MSG_WARNING, "SCARD: No reader with prefix '%s' "
561 wpa_printf(MSG_DEBUG, "SCARD: Selected reader='%S'", &readers[pos]);
563 wpa_printf(MSG_DEBUG, "SCARD: Selected reader='%s'", &readers[pos]);
566 ret = SCardConnect(scard->ctx, &readers[pos], SCARD_SHARE_SHARED,
567 SCARD_PROTOCOL_T0 | SCARD_PROTOCOL_T1,
568 &scard->card, &scard->protocol);
569 if (ret != SCARD_S_SUCCESS) {
570 if (ret == (long) SCARD_E_NO_SMARTCARD)
571 wpa_printf(MSG_INFO, "No smart card inserted.");
573 wpa_printf(MSG_WARNING, "SCardConnect err=%lx", ret);
580 wpa_printf(MSG_DEBUG, "SCARD: card=0x%x active_protocol=%lu (%s)",
581 (unsigned int) scard->card, scard->protocol,
582 scard->protocol == SCARD_PROTOCOL_T0 ? "T0" : "T1");
584 ret = SCardBeginTransaction(scard->card);
585 if (ret != SCARD_S_SUCCESS) {
586 wpa_printf(MSG_DEBUG, "SCARD: Could not begin transaction: "
587 "0x%x", (unsigned int) ret);
594 scard->sim_type = SCARD_GSM_SIM;
595 if (sim_type == SCARD_USIM_ONLY || sim_type == SCARD_TRY_BOTH) {
596 wpa_printf(MSG_DEBUG, "SCARD: verifying USIM support");
597 if (_scard_select_file(scard, SCARD_FILE_MF, buf, &blen,
598 SCARD_USIM, NULL, 0)) {
599 wpa_printf(MSG_DEBUG, "SCARD: USIM is not supported");
600 if (sim_type == SCARD_USIM_ONLY)
602 wpa_printf(MSG_DEBUG, "SCARD: Trying to use GSM SIM");
603 scard->sim_type = SCARD_GSM_SIM;
605 wpa_printf(MSG_DEBUG, "SCARD: USIM is supported");
606 scard->sim_type = SCARD_USIM;
610 if (scard->sim_type == SCARD_GSM_SIM) {
612 if (scard_select_file(scard, SCARD_FILE_MF, buf, &blen)) {
613 wpa_printf(MSG_DEBUG, "SCARD: Failed to read MF");
618 if (scard_select_file(scard, SCARD_FILE_GSM_DF, buf, &blen)) {
619 wpa_printf(MSG_DEBUG, "SCARD: Failed to read GSM DF");
623 unsigned char aid[32];
626 aid_len = scard_get_aid(scard, aid, sizeof(aid));
628 wpa_printf(MSG_DEBUG, "SCARD: Failed to find AID for "
629 "3G USIM app - try to use standard 3G RID");
630 os_memcpy(aid, "\xa0\x00\x00\x00\x87", 5);
633 wpa_hexdump(MSG_DEBUG, "SCARD: 3G USIM AID", aid, aid_len);
635 /* Select based on AID = 3G RID from EF_DIR. This is usually
636 * starting with A0 00 00 00 87. */
638 if (_scard_select_file(scard, 0, buf, &blen, scard->sim_type,
640 wpa_printf(MSG_INFO, "SCARD: Failed to read 3G USIM "
642 wpa_hexdump(MSG_INFO, "SCARD: 3G USIM AID",
648 /* Verify whether CHV1 (PIN1) is needed to access the card. */
649 pin_needed = scard_pin_needed(scard, buf, blen);
650 if (pin_needed < 0) {
651 wpa_printf(MSG_DEBUG, "SCARD: Failed to determine whether PIN "
656 scard->pin1_required = 1;
657 wpa_printf(MSG_DEBUG, "PIN1 needed for SIM access (retry "
658 "counter=%d)", scard_get_pin_retry_counter(scard));
661 ret = SCardEndTransaction(scard->card, SCARD_LEAVE_CARD);
662 if (ret != SCARD_S_SUCCESS) {
663 wpa_printf(MSG_DEBUG, "SCARD: Could not end transaction: "
664 "0x%x", (unsigned int) ret);
671 SCardEndTransaction(scard->card, SCARD_LEAVE_CARD);
679 * scard_set_pin - Set PIN (CHV1/PIN1) code for accessing SIM/USIM commands
680 * @scard: Pointer to private data from scard_init()
681 * @pin: PIN code as an ASCII string (e.g., "1234")
682 * Returns: 0 on success, -1 on failure
684 int scard_set_pin(struct scard_data *scard, const char *pin)
689 /* Verify whether CHV1 (PIN1) is needed to access the card. */
690 if (scard->pin1_required) {
692 wpa_printf(MSG_DEBUG, "No PIN configured for SIM "
696 if (scard_verify_pin(scard, pin)) {
697 wpa_printf(MSG_INFO, "PIN verification failed for "
708 * scard_deinit - Deinitialize SIM/USIM connection
709 * @scard: Pointer to private data from scard_init()
711 * This function closes the SIM/USIM connect opened with scard_init().
713 void scard_deinit(struct scard_data *scard)
720 wpa_printf(MSG_DEBUG, "SCARD: deinitializing smart card interface");
722 ret = SCardDisconnect(scard->card, SCARD_UNPOWER_CARD);
723 if (ret != SCARD_S_SUCCESS) {
724 wpa_printf(MSG_DEBUG, "SCARD: Failed to disconnect "
725 "smart card (err=%ld)", ret);
730 ret = SCardReleaseContext(scard->ctx);
731 if (ret != SCARD_S_SUCCESS) {
732 wpa_printf(MSG_DEBUG, "Failed to release smart card "
733 "context (err=%ld)", ret);
737 mingw_unload_symbols();
741 static long scard_transmit(struct scard_data *scard,
742 unsigned char *_send, size_t send_len,
743 unsigned char *_recv, size_t *recv_len)
748 wpa_hexdump_key(MSG_DEBUG, "SCARD: scard_transmit: send",
751 ret = SCardTransmit(scard->card,
752 scard->protocol == SCARD_PROTOCOL_T1 ?
753 SCARD_PCI_T1 : SCARD_PCI_T0,
754 _send, (unsigned long) send_len,
757 if (ret == SCARD_S_SUCCESS) {
758 wpa_hexdump(MSG_DEBUG, "SCARD: scard_transmit: recv",
761 wpa_printf(MSG_WARNING, "SCARD: SCardTransmit failed "
768 static int _scard_select_file(struct scard_data *scard, unsigned short file_id,
769 unsigned char *buf, size_t *buf_len,
770 sim_types sim_type, unsigned char *aid,
774 unsigned char resp[3];
775 unsigned char cmd[50] = { SIM_CMD_SELECT };
777 unsigned char get_resp[5] = { SIM_CMD_GET_RESPONSE };
780 if (sim_type == SCARD_USIM) {
783 get_resp[0] = USIM_CLA;
786 wpa_printf(MSG_DEBUG, "SCARD: select file %04x", file_id);
788 wpa_hexdump(MSG_DEBUG, "SCARD: select file by AID",
790 if (5 + aidlen > sizeof(cmd))
792 cmd[2] = 0x04; /* Select by AID */
793 cmd[4] = aidlen; /* len */
794 os_memcpy(cmd + 5, aid, aidlen);
797 cmd[5] = file_id >> 8;
798 cmd[6] = file_id & 0xff;
802 ret = scard_transmit(scard, cmd, cmdlen, resp, &len);
803 if (ret != SCARD_S_SUCCESS) {
804 wpa_printf(MSG_WARNING, "SCARD: SCardTransmit failed "
810 wpa_printf(MSG_WARNING, "SCARD: unexpected resp len "
811 "%d (expected 2)", (int) len);
815 if (resp[0] == 0x98 && resp[1] == 0x04) {
816 /* Security status not satisfied (PIN_WLAN) */
817 wpa_printf(MSG_WARNING, "SCARD: Security status not satisfied "
822 if (resp[0] == 0x6e) {
823 wpa_printf(MSG_DEBUG, "SCARD: used CLA not supported");
827 if (resp[0] != 0x6c && resp[0] != 0x9f && resp[0] != 0x61) {
828 wpa_printf(MSG_WARNING, "SCARD: unexpected response 0x%02x "
829 "(expected 0x61, 0x6c, or 0x9f)", resp[0]);
832 /* Normal ending of command; resp[1] bytes available */
833 get_resp[4] = resp[1];
834 wpa_printf(MSG_DEBUG, "SCARD: trying to get response (%d bytes)",
838 ret = scard_transmit(scard, get_resp, sizeof(get_resp), buf, &rlen);
839 if (ret == SCARD_S_SUCCESS) {
840 *buf_len = resp[1] < rlen ? resp[1] : rlen;
844 wpa_printf(MSG_WARNING, "SCARD: SCardTransmit err=0x%lx\n", ret);
849 static int scard_select_file(struct scard_data *scard, unsigned short file_id,
850 unsigned char *buf, size_t *buf_len)
852 return _scard_select_file(scard, file_id, buf, buf_len,
853 scard->sim_type, NULL, 0);
857 static int scard_get_record_len(struct scard_data *scard, unsigned char recnum,
860 unsigned char buf[255];
861 unsigned char cmd[5] = { SIM_CMD_READ_RECORD /* , len */ };
865 if (scard->sim_type == SCARD_USIM)
869 cmd[4] = sizeof(buf);
872 ret = scard_transmit(scard, cmd, sizeof(cmd), buf, &blen);
873 if (ret != SCARD_S_SUCCESS) {
874 wpa_printf(MSG_DEBUG, "SCARD: failed to determine file "
875 "length for record %d", recnum);
879 wpa_hexdump(MSG_DEBUG, "SCARD: file length determination response",
882 if (blen < 2 || (buf[0] != 0x6c && buf[0] != 0x67)) {
883 wpa_printf(MSG_DEBUG, "SCARD: unexpected response to file "
884 "length determination");
892 static int scard_read_record(struct scard_data *scard,
893 unsigned char *data, size_t len,
894 unsigned char recnum, unsigned char mode)
896 unsigned char cmd[5] = { SIM_CMD_READ_RECORD /* , len */ };
897 size_t blen = len + 3;
901 if (scard->sim_type == SCARD_USIM)
907 buf = os_malloc(blen);
911 ret = scard_transmit(scard, cmd, sizeof(cmd), buf, &blen);
912 if (ret != SCARD_S_SUCCESS) {
916 if (blen != len + 2) {
917 wpa_printf(MSG_DEBUG, "SCARD: record read returned unexpected "
918 "length %ld (expected %ld)",
919 (long) blen, (long) len + 2);
924 if (buf[len] != 0x90 || buf[len + 1] != 0x00) {
925 wpa_printf(MSG_DEBUG, "SCARD: record read returned unexpected "
926 "status %02x %02x (expected 90 00)",
927 buf[len], buf[len + 1]);
932 os_memcpy(data, buf, len);
939 static int scard_read_file(struct scard_data *scard,
940 unsigned char *data, size_t len)
942 unsigned char cmd[5] = { SIM_CMD_READ_BIN /* , len */ };
943 size_t blen = len + 3;
949 buf = os_malloc(blen);
953 if (scard->sim_type == SCARD_USIM)
955 ret = scard_transmit(scard, cmd, sizeof(cmd), buf, &blen);
956 if (ret != SCARD_S_SUCCESS) {
960 if (blen != len + 2) {
961 wpa_printf(MSG_DEBUG, "SCARD: file read returned unexpected "
962 "length %ld (expected %ld)",
963 (long) blen, (long) len + 2);
968 if (buf[len] != 0x90 || buf[len + 1] != 0x00) {
969 wpa_printf(MSG_DEBUG, "SCARD: file read returned unexpected "
970 "status %02x %02x (expected 90 00)",
971 buf[len], buf[len + 1]);
976 os_memcpy(data, buf, len);
983 static int scard_verify_pin(struct scard_data *scard, const char *pin)
986 unsigned char resp[3];
987 unsigned char cmd[5 + 8] = { SIM_CMD_VERIFY_CHV1 };
990 wpa_printf(MSG_DEBUG, "SCARD: verifying PIN");
992 if (pin == NULL || os_strlen(pin) > 8)
995 if (scard->sim_type == SCARD_USIM)
997 os_memcpy(cmd + 5, pin, os_strlen(pin));
998 os_memset(cmd + 5 + os_strlen(pin), 0xff, 8 - os_strlen(pin));
1001 ret = scard_transmit(scard, cmd, sizeof(cmd), resp, &len);
1002 if (ret != SCARD_S_SUCCESS)
1005 if (len != 2 || resp[0] != 0x90 || resp[1] != 0x00) {
1006 wpa_printf(MSG_WARNING, "SCARD: PIN verification failed");
1010 wpa_printf(MSG_DEBUG, "SCARD: PIN verified successfully");
1015 int scard_get_pin_retry_counter(struct scard_data *scard)
1018 unsigned char resp[3];
1019 unsigned char cmd[5] = { SIM_CMD_VERIFY_CHV1 };
1023 wpa_printf(MSG_DEBUG, "SCARD: fetching PIN retry counter");
1025 if (scard->sim_type == SCARD_USIM)
1027 cmd[4] = 0; /* Empty data */
1030 ret = scard_transmit(scard, cmd, sizeof(cmd), resp, &len);
1031 if (ret != SCARD_S_SUCCESS)
1035 wpa_printf(MSG_WARNING, "SCARD: failed to fetch PIN retry "
1040 val = WPA_GET_BE16(resp);
1041 if (val == 0x63c0 || val == 0x6983) {
1042 wpa_printf(MSG_DEBUG, "SCARD: PIN has been blocked");
1046 if (val >= 0x63c0 && val <= 0x63cf)
1047 return val & 0x000f;
1049 wpa_printf(MSG_DEBUG, "SCARD: Unexpected PIN retry counter response "
1056 * scard_get_imsi - Read IMSI from SIM/USIM card
1057 * @scard: Pointer to private data from scard_init()
1058 * @imsi: Buffer for IMSI
1059 * @len: Length of imsi buffer; set to IMSI length on success
1060 * Returns: 0 on success, -1 if IMSI file cannot be selected, -2 if IMSI file
1061 * selection returns invalid result code, -3 if parsing FSP template file fails
1062 * (USIM only), -4 if IMSI does not fit in the provided imsi buffer (len is set
1063 * to needed length), -5 if reading IMSI file fails.
1065 * This function can be used to read IMSI from the SIM/USIM card. If the IMSI
1066 * file is PIN protected, scard_set_pin() must have been used to set the
1067 * correct PIN code before calling scard_get_imsi().
1069 int scard_get_imsi(struct scard_data *scard, char *imsi, size_t *len)
1071 unsigned char buf[100];
1072 size_t blen, imsilen, i;
1075 wpa_printf(MSG_DEBUG, "SCARD: reading IMSI from (GSM) EF-IMSI");
1077 if (scard_select_file(scard, SCARD_FILE_GSM_EF_IMSI, buf, &blen))
1080 wpa_printf(MSG_WARNING, "SCARD: too short (GSM) EF-IMSI "
1081 "header (len=%ld)", (long) blen);
1085 if (scard->sim_type == SCARD_GSM_SIM) {
1086 blen = (buf[2] << 8) | buf[3];
1089 if (scard_parse_fsp_templ(buf, blen, NULL, &file_size))
1093 if (blen < 2 || blen > sizeof(buf)) {
1094 wpa_printf(MSG_DEBUG, "SCARD: invalid IMSI file length=%ld",
1099 imsilen = (blen - 2) * 2 + 1;
1100 wpa_printf(MSG_DEBUG, "SCARD: IMSI file length=%ld imsilen=%ld",
1101 (long) blen, (long) imsilen);
1102 if (blen < 2 || imsilen > *len) {
1107 if (scard_read_file(scard, buf, blen))
1111 *pos++ = '0' + (buf[1] >> 4 & 0x0f);
1112 for (i = 2; i < blen; i++) {
1113 unsigned char digit;
1115 digit = buf[i] & 0x0f;
1117 *pos++ = '0' + digit;
1121 digit = buf[i] >> 4 & 0x0f;
1123 *pos++ = '0' + digit;
1134 * scard_get_mnc_len - Read length of MNC in the IMSI from SIM/USIM card
1135 * @scard: Pointer to private data from scard_init()
1136 * Returns: length (>0) on success, -1 if administrative data file cannot be
1137 * selected, -2 if administrative data file selection returns invalid result
1138 * code, -3 if parsing FSP template file fails (USIM only), -4 if length of
1139 * the file is unexpected, -5 if reading file fails, -6 if MNC length is not
1140 * in range (i.e. 2 or 3), -7 if MNC length is not available.
1143 int scard_get_mnc_len(struct scard_data *scard)
1145 unsigned char buf[100];
1149 wpa_printf(MSG_DEBUG, "SCARD: reading MNC len from (GSM) EF-AD");
1151 if (scard_select_file(scard, SCARD_FILE_GSM_EF_AD, buf, &blen))
1154 wpa_printf(MSG_WARNING, "SCARD: too short (GSM) EF-AD "
1155 "header (len=%ld)", (long) blen);
1159 if (scard->sim_type == SCARD_GSM_SIM) {
1160 file_size = (buf[2] << 8) | buf[3];
1162 if (scard_parse_fsp_templ(buf, blen, NULL, &file_size))
1165 if (file_size == 3) {
1166 wpa_printf(MSG_DEBUG, "SCARD: MNC length not available");
1169 if (file_size < 4 || file_size > (int) sizeof(buf)) {
1170 wpa_printf(MSG_DEBUG, "SCARD: invalid file length=%ld",
1175 if (scard_read_file(scard, buf, file_size))
1177 buf[3] = buf[3] & 0x0f; /* upper nibble reserved for future use */
1178 if (buf[3] < 2 || buf[3] > 3) {
1179 wpa_printf(MSG_DEBUG, "SCARD: invalid MNC length=%ld",
1183 wpa_printf(MSG_DEBUG, "SCARD: MNC length=%ld", (long) buf[3]);
1189 * scard_gsm_auth - Run GSM authentication command on SIM card
1190 * @scard: Pointer to private data from scard_init()
1191 * @_rand: 16-byte RAND value from HLR/AuC
1192 * @sres: 4-byte buffer for SRES
1193 * @kc: 8-byte buffer for Kc
1194 * Returns: 0 on success, -1 if SIM/USIM connection has not been initialized,
1195 * -2 if authentication command execution fails, -3 if unknown response code
1196 * for authentication command is received, -4 if reading of response fails,
1197 * -5 if if response data is of unexpected length
1199 * This function performs GSM authentication using SIM/USIM card and the
1200 * provided RAND value from HLR/AuC. If authentication command can be completed
1201 * successfully, SRES and Kc values will be written into sres and kc buffers.
1203 int scard_gsm_auth(struct scard_data *scard, const unsigned char *_rand,
1204 unsigned char *sres, unsigned char *kc)
1206 unsigned char cmd[5 + 1 + 16] = { SIM_CMD_RUN_GSM_ALG };
1208 unsigned char get_resp[5] = { SIM_CMD_GET_RESPONSE };
1209 unsigned char resp[3], buf[12 + 3 + 2];
1216 wpa_hexdump(MSG_DEBUG, "SCARD: GSM auth - RAND", _rand, 16);
1217 if (scard->sim_type == SCARD_GSM_SIM) {
1219 os_memcpy(cmd + 5, _rand, 16);
1221 cmdlen = 5 + 1 + 16;
1226 os_memcpy(cmd + 6, _rand, 16);
1229 ret = scard_transmit(scard, cmd, cmdlen, resp, &len);
1230 if (ret != SCARD_S_SUCCESS)
1233 if ((scard->sim_type == SCARD_GSM_SIM &&
1234 (len != 2 || resp[0] != 0x9f || resp[1] != 0x0c)) ||
1235 (scard->sim_type == SCARD_USIM &&
1236 (len != 2 || resp[0] != 0x61 || resp[1] != 0x0e))) {
1237 wpa_printf(MSG_WARNING, "SCARD: unexpected response for GSM "
1238 "auth request (len=%ld resp=%02x %02x)",
1239 (long) len, resp[0], resp[1]);
1242 get_resp[4] = resp[1];
1245 ret = scard_transmit(scard, get_resp, sizeof(get_resp), buf, &len);
1246 if (ret != SCARD_S_SUCCESS)
1249 if (scard->sim_type == SCARD_GSM_SIM) {
1250 if (len != 4 + 8 + 2) {
1251 wpa_printf(MSG_WARNING, "SCARD: unexpected data "
1252 "length for GSM auth (len=%ld, expected 14)",
1256 os_memcpy(sres, buf, 4);
1257 os_memcpy(kc, buf + 4, 8);
1259 if (len != 1 + 4 + 1 + 8 + 2) {
1260 wpa_printf(MSG_WARNING, "SCARD: unexpected data "
1261 "length for USIM auth (len=%ld, "
1262 "expected 16)", (long) len);
1265 if (buf[0] != 4 || buf[5] != 8) {
1266 wpa_printf(MSG_WARNING, "SCARD: unexpected SREC/Kc "
1267 "length (%d %d, expected 4 8)",
1270 os_memcpy(sres, buf + 1, 4);
1271 os_memcpy(kc, buf + 6, 8);
1274 wpa_hexdump(MSG_DEBUG, "SCARD: GSM auth - SRES", sres, 4);
1275 wpa_hexdump(MSG_DEBUG, "SCARD: GSM auth - Kc", kc, 8);
1282 * scard_umts_auth - Run UMTS authentication command on USIM card
1283 * @scard: Pointer to private data from scard_init()
1284 * @_rand: 16-byte RAND value from HLR/AuC
1285 * @autn: 16-byte AUTN value from HLR/AuC
1286 * @res: 16-byte buffer for RES
1287 * @res_len: Variable that will be set to RES length
1288 * @ik: 16-byte buffer for IK
1289 * @ck: 16-byte buffer for CK
1290 * @auts: 14-byte buffer for AUTS
1291 * Returns: 0 on success, -1 on failure, or -2 if USIM reports synchronization
1294 * This function performs AKA authentication using USIM card and the provided
1295 * RAND and AUTN values from HLR/AuC. If authentication command can be
1296 * completed successfully, RES, IK, and CK values will be written into provided
1297 * buffers and res_len is set to length of received RES value. If USIM reports
1298 * synchronization failure, the received AUTS value will be written into auts
1299 * buffer. In this case, RES, IK, and CK are not valid.
1301 int scard_umts_auth(struct scard_data *scard, const unsigned char *_rand,
1302 const unsigned char *autn,
1303 unsigned char *res, size_t *res_len,
1304 unsigned char *ik, unsigned char *ck, unsigned char *auts)
1306 unsigned char cmd[5 + 1 + AKA_RAND_LEN + 1 + AKA_AUTN_LEN] =
1307 { USIM_CMD_RUN_UMTS_ALG };
1308 unsigned char get_resp[5] = { USIM_CMD_GET_RESPONSE };
1309 unsigned char resp[3], buf[64], *pos, *end;
1316 if (scard->sim_type == SCARD_GSM_SIM) {
1317 wpa_printf(MSG_ERROR, "SCARD: Non-USIM card - cannot do UMTS "
1322 wpa_hexdump(MSG_DEBUG, "SCARD: UMTS auth - RAND", _rand, AKA_RAND_LEN);
1323 wpa_hexdump(MSG_DEBUG, "SCARD: UMTS auth - AUTN", autn, AKA_AUTN_LEN);
1324 cmd[5] = AKA_RAND_LEN;
1325 os_memcpy(cmd + 6, _rand, AKA_RAND_LEN);
1326 cmd[6 + AKA_RAND_LEN] = AKA_AUTN_LEN;
1327 os_memcpy(cmd + 6 + AKA_RAND_LEN + 1, autn, AKA_AUTN_LEN);
1330 ret = scard_transmit(scard, cmd, sizeof(cmd), resp, &len);
1331 if (ret != SCARD_S_SUCCESS)
1334 if (len <= sizeof(resp))
1335 wpa_hexdump(MSG_DEBUG, "SCARD: UMTS alg response", resp, len);
1337 if (len == 2 && resp[0] == 0x98 && resp[1] == 0x62) {
1338 wpa_printf(MSG_WARNING, "SCARD: UMTS auth failed - "
1341 } else if (len != 2 || resp[0] != 0x61) {
1342 wpa_printf(MSG_WARNING, "SCARD: unexpected response for UMTS "
1343 "auth request (len=%ld resp=%02x %02x)",
1344 (long) len, resp[0], resp[1]);
1347 get_resp[4] = resp[1];
1350 ret = scard_transmit(scard, get_resp, sizeof(get_resp), buf, &len);
1351 if (ret != SCARD_S_SUCCESS || len > sizeof(buf))
1354 wpa_hexdump(MSG_DEBUG, "SCARD: UMTS get response result", buf, len);
1355 if (len >= 2 + AKA_AUTS_LEN && buf[0] == 0xdc &&
1356 buf[1] == AKA_AUTS_LEN) {
1357 wpa_printf(MSG_DEBUG, "SCARD: UMTS Synchronization-Failure");
1358 os_memcpy(auts, buf + 2, AKA_AUTS_LEN);
1359 wpa_hexdump(MSG_DEBUG, "SCARD: AUTS", auts, AKA_AUTS_LEN);
1361 } else if (len >= 6 + IK_LEN + CK_LEN && buf[0] == 0xdb) {
1366 if (pos[0] > RES_MAX_LEN || pos + pos[0] > end) {
1367 wpa_printf(MSG_DEBUG, "SCARD: Invalid RES");
1371 os_memcpy(res, pos, *res_len);
1373 wpa_hexdump(MSG_DEBUG, "SCARD: RES", res, *res_len);
1376 if (pos[0] != CK_LEN || pos + CK_LEN > end) {
1377 wpa_printf(MSG_DEBUG, "SCARD: Invalid CK");
1381 os_memcpy(ck, pos, CK_LEN);
1383 wpa_hexdump(MSG_DEBUG, "SCARD: CK", ck, CK_LEN);
1386 if (pos[0] != IK_LEN || pos + IK_LEN > end) {
1387 wpa_printf(MSG_DEBUG, "SCARD: Invalid IK");
1391 os_memcpy(ik, pos, IK_LEN);
1393 wpa_hexdump(MSG_DEBUG, "SCARD: IK", ik, IK_LEN);
1398 wpa_printf(MSG_DEBUG, "SCARD: Unrecognized response");