Interworking: Read IMSI if not read at supplicant start
[mech_eap.git] / wpa_supplicant / interworking.c
1 /*
2  * Interworking (IEEE 802.11u)
3  * Copyright (c) 2011-2013, Qualcomm Atheros, Inc.
4  * Copyright (c) 2011-2014, Jouni Malinen <j@w1.fi>
5  *
6  * This software may be distributed under the terms of the BSD license.
7  * See README for more details.
8  */
9
10 #include "includes.h"
11
12 #include "common.h"
13 #include "common/ieee802_11_defs.h"
14 #include "common/gas.h"
15 #include "common/wpa_ctrl.h"
16 #include "utils/pcsc_funcs.h"
17 #include "utils/eloop.h"
18 #include "drivers/driver.h"
19 #include "eap_common/eap_defs.h"
20 #include "eap_peer/eap.h"
21 #include "eap_peer/eap_methods.h"
22 #include "eapol_supp/eapol_supp_sm.h"
23 #include "rsn_supp/wpa.h"
24 #include "wpa_supplicant_i.h"
25 #include "config.h"
26 #include "config_ssid.h"
27 #include "bss.h"
28 #include "scan.h"
29 #include "notify.h"
30 #include "gas_query.h"
31 #include "hs20_supplicant.h"
32 #include "interworking.h"
33
34
35 #if defined(EAP_SIM) | defined(EAP_SIM_DYNAMIC)
36 #define INTERWORKING_3GPP
37 #else
38 #if defined(EAP_AKA) | defined(EAP_AKA_DYNAMIC)
39 #define INTERWORKING_3GPP
40 #else
41 #if defined(EAP_AKA_PRIME) | defined(EAP_AKA_PRIME_DYNAMIC)
42 #define INTERWORKING_3GPP
43 #endif
44 #endif
45 #endif
46
47 static void interworking_next_anqp_fetch(struct wpa_supplicant *wpa_s);
48 static struct wpa_cred * interworking_credentials_available_realm(
49         struct wpa_supplicant *wpa_s, struct wpa_bss *bss, int ignore_bw,
50         int *excluded);
51 static struct wpa_cred * interworking_credentials_available_3gpp(
52         struct wpa_supplicant *wpa_s, struct wpa_bss *bss, int ignore_bw,
53         int *excluded);
54
55
56 static int cred_prio_cmp(const struct wpa_cred *a, const struct wpa_cred *b)
57 {
58         if (a->priority > b->priority)
59                 return 1;
60         if (a->priority < b->priority)
61                 return -1;
62         if (a->provisioning_sp == NULL || b->provisioning_sp == NULL ||
63             os_strcmp(a->provisioning_sp, b->provisioning_sp) != 0)
64                 return 0;
65         if (a->sp_priority < b->sp_priority)
66                 return 1;
67         if (a->sp_priority > b->sp_priority)
68                 return -1;
69         return 0;
70 }
71
72
73 static void interworking_reconnect(struct wpa_supplicant *wpa_s)
74 {
75         if (wpa_s->wpa_state >= WPA_AUTHENTICATING) {
76                 wpa_supplicant_cancel_sched_scan(wpa_s);
77                 wpa_supplicant_deauthenticate(wpa_s,
78                                               WLAN_REASON_DEAUTH_LEAVING);
79         }
80         wpa_s->disconnected = 0;
81         wpa_s->reassociate = 1;
82
83         if (wpa_supplicant_fast_associate(wpa_s) >= 0)
84                 return;
85
86         wpa_supplicant_req_scan(wpa_s, 0, 0);
87 }
88
89
90 static struct wpabuf * anqp_build_req(u16 info_ids[], size_t num_ids,
91                                       struct wpabuf *extra)
92 {
93         struct wpabuf *buf;
94         size_t i;
95         u8 *len_pos;
96
97         buf = gas_anqp_build_initial_req(0, 4 + num_ids * 2 +
98                                          (extra ? wpabuf_len(extra) : 0));
99         if (buf == NULL)
100                 return NULL;
101
102         len_pos = gas_anqp_add_element(buf, ANQP_QUERY_LIST);
103         for (i = 0; i < num_ids; i++)
104                 wpabuf_put_le16(buf, info_ids[i]);
105         gas_anqp_set_element_len(buf, len_pos);
106         if (extra)
107                 wpabuf_put_buf(buf, extra);
108
109         gas_anqp_set_len(buf);
110
111         return buf;
112 }
113
114
115 static void interworking_anqp_resp_cb(void *ctx, const u8 *dst,
116                                       u8 dialog_token,
117                                       enum gas_query_result result,
118                                       const struct wpabuf *adv_proto,
119                                       const struct wpabuf *resp,
120                                       u16 status_code)
121 {
122         struct wpa_supplicant *wpa_s = ctx;
123
124         wpa_printf(MSG_DEBUG, "ANQP: Response callback dst=" MACSTR
125                    " dialog_token=%u result=%d status_code=%u",
126                    MAC2STR(dst), dialog_token, result, status_code);
127         anqp_resp_cb(wpa_s, dst, dialog_token, result, adv_proto, resp,
128                      status_code);
129         interworking_next_anqp_fetch(wpa_s);
130 }
131
132
133 static int cred_with_roaming_consortium(struct wpa_supplicant *wpa_s)
134 {
135         struct wpa_cred *cred;
136
137         for (cred = wpa_s->conf->cred; cred; cred = cred->next) {
138                 if (cred->roaming_consortium_len)
139                         return 1;
140                 if (cred->required_roaming_consortium_len)
141                         return 1;
142         }
143         return 0;
144 }
145
146
147 static int cred_with_3gpp(struct wpa_supplicant *wpa_s)
148 {
149         struct wpa_cred *cred;
150
151         for (cred = wpa_s->conf->cred; cred; cred = cred->next) {
152                 if (cred->pcsc || cred->imsi)
153                         return 1;
154         }
155         return 0;
156 }
157
158
159 static int cred_with_nai_realm(struct wpa_supplicant *wpa_s)
160 {
161         struct wpa_cred *cred;
162
163         for (cred = wpa_s->conf->cred; cred; cred = cred->next) {
164                 if (cred->pcsc || cred->imsi)
165                         continue;
166                 if (!cred->eap_method)
167                         return 1;
168                 if (cred->realm && cred->roaming_consortium_len == 0)
169                         return 1;
170         }
171         return 0;
172 }
173
174
175 static int cred_with_domain(struct wpa_supplicant *wpa_s)
176 {
177         struct wpa_cred *cred;
178
179         for (cred = wpa_s->conf->cred; cred; cred = cred->next) {
180                 if (cred->domain || cred->pcsc || cred->imsi ||
181                     cred->roaming_partner)
182                         return 1;
183         }
184         return 0;
185 }
186
187
188 #ifdef CONFIG_HS20
189
190 static int cred_with_min_backhaul(struct wpa_supplicant *wpa_s)
191 {
192         struct wpa_cred *cred;
193
194         for (cred = wpa_s->conf->cred; cred; cred = cred->next) {
195                 if (cred->min_dl_bandwidth_home ||
196                     cred->min_ul_bandwidth_home ||
197                     cred->min_dl_bandwidth_roaming ||
198                     cred->min_ul_bandwidth_roaming)
199                         return 1;
200         }
201         return 0;
202 }
203
204
205 static int cred_with_conn_capab(struct wpa_supplicant *wpa_s)
206 {
207         struct wpa_cred *cred;
208
209         for (cred = wpa_s->conf->cred; cred; cred = cred->next) {
210                 if (cred->num_req_conn_capab)
211                         return 1;
212         }
213         return 0;
214 }
215
216 #endif /* CONFIG_HS20 */
217
218
219 static int additional_roaming_consortiums(struct wpa_bss *bss)
220 {
221         const u8 *ie;
222         ie = wpa_bss_get_ie(bss, WLAN_EID_ROAMING_CONSORTIUM);
223         if (ie == NULL || ie[1] == 0)
224                 return 0;
225         return ie[2]; /* Number of ANQP OIs */
226 }
227
228
229 static void interworking_continue_anqp(void *eloop_ctx, void *sock_ctx)
230 {
231         struct wpa_supplicant *wpa_s = eloop_ctx;
232         interworking_next_anqp_fetch(wpa_s);
233 }
234
235
236 static int interworking_anqp_send_req(struct wpa_supplicant *wpa_s,
237                                       struct wpa_bss *bss)
238 {
239         struct wpabuf *buf;
240         int ret = 0;
241         int res;
242         u16 info_ids[8];
243         size_t num_info_ids = 0;
244         struct wpabuf *extra = NULL;
245         int all = wpa_s->fetch_all_anqp;
246
247         wpa_printf(MSG_DEBUG, "Interworking: ANQP Query Request to " MACSTR,
248                    MAC2STR(bss->bssid));
249         wpa_s->interworking_gas_bss = bss;
250
251         info_ids[num_info_ids++] = ANQP_CAPABILITY_LIST;
252         if (all) {
253                 info_ids[num_info_ids++] = ANQP_VENUE_NAME;
254                 info_ids[num_info_ids++] = ANQP_NETWORK_AUTH_TYPE;
255         }
256         if (all || (cred_with_roaming_consortium(wpa_s) &&
257                     additional_roaming_consortiums(bss)))
258                 info_ids[num_info_ids++] = ANQP_ROAMING_CONSORTIUM;
259         if (all)
260                 info_ids[num_info_ids++] = ANQP_IP_ADDR_TYPE_AVAILABILITY;
261         if (all || cred_with_nai_realm(wpa_s))
262                 info_ids[num_info_ids++] = ANQP_NAI_REALM;
263         if (all || cred_with_3gpp(wpa_s)) {
264                 info_ids[num_info_ids++] = ANQP_3GPP_CELLULAR_NETWORK;
265                 wpa_supplicant_scard_init(wpa_s, NULL);
266         }
267         if (all || cred_with_domain(wpa_s))
268                 info_ids[num_info_ids++] = ANQP_DOMAIN_NAME;
269         wpa_hexdump(MSG_DEBUG, "Interworking: ANQP Query info",
270                     (u8 *) info_ids, num_info_ids * 2);
271
272 #ifdef CONFIG_HS20
273         if (wpa_bss_get_vendor_ie(bss, HS20_IE_VENDOR_TYPE)) {
274                 u8 *len_pos;
275
276                 extra = wpabuf_alloc(100);
277                 if (!extra)
278                         return -1;
279
280                 len_pos = gas_anqp_add_element(extra, ANQP_VENDOR_SPECIFIC);
281                 wpabuf_put_be24(extra, OUI_WFA);
282                 wpabuf_put_u8(extra, HS20_ANQP_OUI_TYPE);
283                 wpabuf_put_u8(extra, HS20_STYPE_QUERY_LIST);
284                 wpabuf_put_u8(extra, 0); /* Reserved */
285                 wpabuf_put_u8(extra, HS20_STYPE_CAPABILITY_LIST);
286                 if (all)
287                         wpabuf_put_u8(extra,
288                                       HS20_STYPE_OPERATOR_FRIENDLY_NAME);
289                 if (all || cred_with_min_backhaul(wpa_s))
290                         wpabuf_put_u8(extra, HS20_STYPE_WAN_METRICS);
291                 if (all || cred_with_conn_capab(wpa_s))
292                         wpabuf_put_u8(extra, HS20_STYPE_CONNECTION_CAPABILITY);
293                 if (all)
294                         wpabuf_put_u8(extra, HS20_STYPE_OPERATING_CLASS);
295                 if (all)
296                         wpabuf_put_u8(extra, HS20_STYPE_OSU_PROVIDERS_LIST);
297                 gas_anqp_set_element_len(extra, len_pos);
298         }
299 #endif /* CONFIG_HS20 */
300
301         buf = anqp_build_req(info_ids, num_info_ids, extra);
302         wpabuf_free(extra);
303         if (buf == NULL)
304                 return -1;
305
306         res = gas_query_req(wpa_s->gas, bss->bssid, bss->freq, buf,
307                             interworking_anqp_resp_cb, wpa_s);
308         if (res < 0) {
309                 wpa_printf(MSG_DEBUG, "ANQP: Failed to send Query Request");
310                 wpabuf_free(buf);
311                 ret = -1;
312                 eloop_register_timeout(0, 0, interworking_continue_anqp, wpa_s,
313                                        NULL);
314         } else
315                 wpa_printf(MSG_DEBUG, "ANQP: Query started with dialog token "
316                            "%u", res);
317
318         return ret;
319 }
320
321
322 struct nai_realm_eap {
323         u8 method;
324         u8 inner_method;
325         enum nai_realm_eap_auth_inner_non_eap inner_non_eap;
326         u8 cred_type;
327         u8 tunneled_cred_type;
328 };
329
330 struct nai_realm {
331         u8 encoding;
332         char *realm;
333         u8 eap_count;
334         struct nai_realm_eap *eap;
335 };
336
337
338 static void nai_realm_free(struct nai_realm *realms, u16 count)
339 {
340         u16 i;
341
342         if (realms == NULL)
343                 return;
344         for (i = 0; i < count; i++) {
345                 os_free(realms[i].eap);
346                 os_free(realms[i].realm);
347         }
348         os_free(realms);
349 }
350
351
352 static const u8 * nai_realm_parse_eap(struct nai_realm_eap *e, const u8 *pos,
353                                       const u8 *end)
354 {
355         u8 elen, auth_count, a;
356         const u8 *e_end;
357
358         if (pos + 3 > end) {
359                 wpa_printf(MSG_DEBUG, "No room for EAP Method fixed fields");
360                 return NULL;
361         }
362
363         elen = *pos++;
364         if (pos + elen > end || elen < 2) {
365                 wpa_printf(MSG_DEBUG, "No room for EAP Method subfield");
366                 return NULL;
367         }
368         e_end = pos + elen;
369         e->method = *pos++;
370         auth_count = *pos++;
371         wpa_printf(MSG_DEBUG, "EAP Method: len=%u method=%u auth_count=%u",
372                    elen, e->method, auth_count);
373
374         for (a = 0; a < auth_count; a++) {
375                 u8 id, len;
376
377                 if (pos + 2 > end || pos + 2 + pos[1] > end) {
378                         wpa_printf(MSG_DEBUG, "No room for Authentication "
379                                    "Parameter subfield");
380                         return NULL;
381                 }
382
383                 id = *pos++;
384                 len = *pos++;
385
386                 switch (id) {
387                 case NAI_REALM_EAP_AUTH_NON_EAP_INNER_AUTH:
388                         if (len < 1)
389                                 break;
390                         e->inner_non_eap = *pos;
391                         if (e->method != EAP_TYPE_TTLS)
392                                 break;
393                         switch (*pos) {
394                         case NAI_REALM_INNER_NON_EAP_PAP:
395                                 wpa_printf(MSG_DEBUG, "EAP-TTLS/PAP");
396                                 break;
397                         case NAI_REALM_INNER_NON_EAP_CHAP:
398                                 wpa_printf(MSG_DEBUG, "EAP-TTLS/CHAP");
399                                 break;
400                         case NAI_REALM_INNER_NON_EAP_MSCHAP:
401                                 wpa_printf(MSG_DEBUG, "EAP-TTLS/MSCHAP");
402                                 break;
403                         case NAI_REALM_INNER_NON_EAP_MSCHAPV2:
404                                 wpa_printf(MSG_DEBUG, "EAP-TTLS/MSCHAPV2");
405                                 break;
406                         }
407                         break;
408                 case NAI_REALM_EAP_AUTH_INNER_AUTH_EAP_METHOD:
409                         if (len < 1)
410                                 break;
411                         e->inner_method = *pos;
412                         wpa_printf(MSG_DEBUG, "Inner EAP method: %u",
413                                    e->inner_method);
414                         break;
415                 case NAI_REALM_EAP_AUTH_CRED_TYPE:
416                         if (len < 1)
417                                 break;
418                         e->cred_type = *pos;
419                         wpa_printf(MSG_DEBUG, "Credential Type: %u",
420                                    e->cred_type);
421                         break;
422                 case NAI_REALM_EAP_AUTH_TUNNELED_CRED_TYPE:
423                         if (len < 1)
424                                 break;
425                         e->tunneled_cred_type = *pos;
426                         wpa_printf(MSG_DEBUG, "Tunneled EAP Method Credential "
427                                    "Type: %u", e->tunneled_cred_type);
428                         break;
429                 default:
430                         wpa_printf(MSG_DEBUG, "Unsupported Authentication "
431                                    "Parameter: id=%u len=%u", id, len);
432                         wpa_hexdump(MSG_DEBUG, "Authentication Parameter "
433                                     "Value", pos, len);
434                         break;
435                 }
436
437                 pos += len;
438         }
439
440         return e_end;
441 }
442
443
444 static const u8 * nai_realm_parse_realm(struct nai_realm *r, const u8 *pos,
445                                         const u8 *end)
446 {
447         u16 len;
448         const u8 *f_end;
449         u8 realm_len, e;
450
451         if (end - pos < 4) {
452                 wpa_printf(MSG_DEBUG, "No room for NAI Realm Data "
453                            "fixed fields");
454                 return NULL;
455         }
456
457         len = WPA_GET_LE16(pos); /* NAI Realm Data field Length */
458         pos += 2;
459         if (pos + len > end || len < 3) {
460                 wpa_printf(MSG_DEBUG, "No room for NAI Realm Data "
461                            "(len=%u; left=%u)",
462                            len, (unsigned int) (end - pos));
463                 return NULL;
464         }
465         f_end = pos + len;
466
467         r->encoding = *pos++;
468         realm_len = *pos++;
469         if (pos + realm_len > f_end) {
470                 wpa_printf(MSG_DEBUG, "No room for NAI Realm "
471                            "(len=%u; left=%u)",
472                            realm_len, (unsigned int) (f_end - pos));
473                 return NULL;
474         }
475         wpa_hexdump_ascii(MSG_DEBUG, "NAI Realm", pos, realm_len);
476         r->realm = dup_binstr(pos, realm_len);
477         if (r->realm == NULL)
478                 return NULL;
479         pos += realm_len;
480
481         if (pos + 1 > f_end) {
482                 wpa_printf(MSG_DEBUG, "No room for EAP Method Count");
483                 return NULL;
484         }
485         r->eap_count = *pos++;
486         wpa_printf(MSG_DEBUG, "EAP Count: %u", r->eap_count);
487         if (pos + r->eap_count * 3 > f_end) {
488                 wpa_printf(MSG_DEBUG, "No room for EAP Methods");
489                 return NULL;
490         }
491         r->eap = os_calloc(r->eap_count, sizeof(struct nai_realm_eap));
492         if (r->eap == NULL)
493                 return NULL;
494
495         for (e = 0; e < r->eap_count; e++) {
496                 pos = nai_realm_parse_eap(&r->eap[e], pos, f_end);
497                 if (pos == NULL)
498                         return NULL;
499         }
500
501         return f_end;
502 }
503
504
505 static struct nai_realm * nai_realm_parse(struct wpabuf *anqp, u16 *count)
506 {
507         struct nai_realm *realm;
508         const u8 *pos, *end;
509         u16 i, num;
510
511         if (anqp == NULL || wpabuf_len(anqp) < 2)
512                 return NULL;
513
514         pos = wpabuf_head_u8(anqp);
515         end = pos + wpabuf_len(anqp);
516         num = WPA_GET_LE16(pos);
517         wpa_printf(MSG_DEBUG, "NAI Realm Count: %u", num);
518         pos += 2;
519
520         if (num * 5 > end - pos) {
521                 wpa_printf(MSG_DEBUG, "Invalid NAI Realm Count %u - not "
522                            "enough data (%u octets) for that many realms",
523                            num, (unsigned int) (end - pos));
524                 return NULL;
525         }
526
527         realm = os_calloc(num, sizeof(struct nai_realm));
528         if (realm == NULL)
529                 return NULL;
530
531         for (i = 0; i < num; i++) {
532                 pos = nai_realm_parse_realm(&realm[i], pos, end);
533                 if (pos == NULL) {
534                         nai_realm_free(realm, num);
535                         return NULL;
536                 }
537         }
538
539         *count = num;
540         return realm;
541 }
542
543
544 static int nai_realm_match(struct nai_realm *realm, const char *home_realm)
545 {
546         char *tmp, *pos, *end;
547         int match = 0;
548
549         if (realm->realm == NULL || home_realm == NULL)
550                 return 0;
551
552         if (os_strchr(realm->realm, ';') == NULL)
553                 return os_strcasecmp(realm->realm, home_realm) == 0;
554
555         tmp = os_strdup(realm->realm);
556         if (tmp == NULL)
557                 return 0;
558
559         pos = tmp;
560         while (*pos) {
561                 end = os_strchr(pos, ';');
562                 if (end)
563                         *end = '\0';
564                 if (os_strcasecmp(pos, home_realm) == 0) {
565                         match = 1;
566                         break;
567                 }
568                 if (end == NULL)
569                         break;
570                 pos = end + 1;
571         }
572
573         os_free(tmp);
574
575         return match;
576 }
577
578
579 static int nai_realm_cred_username(struct nai_realm_eap *eap)
580 {
581         if (eap_get_name(EAP_VENDOR_IETF, eap->method) == NULL)
582                 return 0; /* method not supported */
583
584         if (eap->method != EAP_TYPE_TTLS && eap->method != EAP_TYPE_PEAP &&
585             eap->method != EAP_TYPE_FAST) {
586                 /* Only tunneled methods with username/password supported */
587                 return 0;
588         }
589
590         if (eap->method == EAP_TYPE_PEAP || eap->method == EAP_TYPE_FAST) {
591                 if (eap->inner_method &&
592                     eap_get_name(EAP_VENDOR_IETF, eap->inner_method) == NULL)
593                         return 0;
594                 if (!eap->inner_method &&
595                     eap_get_name(EAP_VENDOR_IETF, EAP_TYPE_MSCHAPV2) == NULL)
596                         return 0;
597         }
598
599         if (eap->method == EAP_TYPE_TTLS) {
600                 if (eap->inner_method == 0 && eap->inner_non_eap == 0)
601                         return 1; /* Assume TTLS/MSCHAPv2 is used */
602                 if (eap->inner_method &&
603                     eap_get_name(EAP_VENDOR_IETF, eap->inner_method) == NULL)
604                         return 0;
605                 if (eap->inner_non_eap &&
606                     eap->inner_non_eap != NAI_REALM_INNER_NON_EAP_PAP &&
607                     eap->inner_non_eap != NAI_REALM_INNER_NON_EAP_CHAP &&
608                     eap->inner_non_eap != NAI_REALM_INNER_NON_EAP_MSCHAP &&
609                     eap->inner_non_eap != NAI_REALM_INNER_NON_EAP_MSCHAPV2)
610                         return 0;
611         }
612
613         if (eap->inner_method &&
614             eap->inner_method != EAP_TYPE_GTC &&
615             eap->inner_method != EAP_TYPE_MSCHAPV2)
616                 return 0;
617
618         return 1;
619 }
620
621
622 static int nai_realm_cred_cert(struct nai_realm_eap *eap)
623 {
624         if (eap_get_name(EAP_VENDOR_IETF, eap->method) == NULL)
625                 return 0; /* method not supported */
626
627         if (eap->method != EAP_TYPE_TLS) {
628                 /* Only EAP-TLS supported for credential authentication */
629                 return 0;
630         }
631
632         return 1;
633 }
634
635
636 static struct nai_realm_eap * nai_realm_find_eap(struct wpa_cred *cred,
637                                                  struct nai_realm *realm)
638 {
639         u8 e;
640
641         if (cred == NULL ||
642             cred->username == NULL ||
643             cred->username[0] == '\0' ||
644             ((cred->password == NULL ||
645               cred->password[0] == '\0') &&
646              (cred->private_key == NULL ||
647               cred->private_key[0] == '\0')))
648                 return NULL;
649
650         for (e = 0; e < realm->eap_count; e++) {
651                 struct nai_realm_eap *eap = &realm->eap[e];
652                 if (cred->password && cred->password[0] &&
653                     nai_realm_cred_username(eap))
654                         return eap;
655                 if (cred->private_key && cred->private_key[0] &&
656                     nai_realm_cred_cert(eap))
657                         return eap;
658         }
659
660         return NULL;
661 }
662
663
664 #ifdef INTERWORKING_3GPP
665
666 static int plmn_id_match(struct wpabuf *anqp, const char *imsi, int mnc_len)
667 {
668         u8 plmn[3], plmn2[3];
669         const u8 *pos, *end;
670         u8 udhl;
671
672         /*
673          * See Annex A of 3GPP TS 24.234 v8.1.0 for description. The network
674          * operator is allowed to include only two digits of the MNC, so allow
675          * matches based on both two and three digit MNC assumptions. Since some
676          * SIM/USIM cards may not expose MNC length conveniently, we may be
677          * provided the default MNC length 3 here and as such, checking with MNC
678          * length 2 is justifiable even though 3GPP TS 24.234 does not mention
679          * that case. Anyway, MCC/MNC pair where both 2 and 3 digit MNC is used
680          * with otherwise matching values would not be good idea in general, so
681          * this should not result in selecting incorrect networks.
682          */
683         /* Match with 3 digit MNC */
684         plmn[0] = (imsi[0] - '0') | ((imsi[1] - '0') << 4);
685         plmn[1] = (imsi[2] - '0') | ((imsi[5] - '0') << 4);
686         plmn[2] = (imsi[3] - '0') | ((imsi[4] - '0') << 4);
687         /* Match with 2 digit MNC */
688         plmn2[0] = (imsi[0] - '0') | ((imsi[1] - '0') << 4);
689         plmn2[1] = (imsi[2] - '0') | 0xf0;
690         plmn2[2] = (imsi[3] - '0') | ((imsi[4] - '0') << 4);
691
692         if (anqp == NULL)
693                 return 0;
694         pos = wpabuf_head_u8(anqp);
695         end = pos + wpabuf_len(anqp);
696         if (pos + 2 > end)
697                 return 0;
698         if (*pos != 0) {
699                 wpa_printf(MSG_DEBUG, "Unsupported GUD version 0x%x", *pos);
700                 return 0;
701         }
702         pos++;
703         udhl = *pos++;
704         if (pos + udhl > end) {
705                 wpa_printf(MSG_DEBUG, "Invalid UDHL");
706                 return 0;
707         }
708         end = pos + udhl;
709
710         wpa_printf(MSG_DEBUG, "Interworking: Matching against MCC/MNC alternatives: %02x:%02x:%02x or %02x:%02x:%02x (IMSI %s, MNC length %d)",
711                    plmn[0], plmn[1], plmn[2], plmn2[0], plmn2[1], plmn2[2],
712                    imsi, mnc_len);
713
714         while (pos + 2 <= end) {
715                 u8 iei, len;
716                 const u8 *l_end;
717                 iei = *pos++;
718                 len = *pos++ & 0x7f;
719                 if (pos + len > end)
720                         break;
721                 l_end = pos + len;
722
723                 if (iei == 0 && len > 0) {
724                         /* PLMN List */
725                         u8 num, i;
726                         wpa_hexdump(MSG_DEBUG, "Interworking: PLMN List information element",
727                                     pos, len);
728                         num = *pos++;
729                         for (i = 0; i < num; i++) {
730                                 if (pos + 3 > l_end)
731                                         break;
732                                 if (os_memcmp(pos, plmn, 3) == 0 ||
733                                     os_memcmp(pos, plmn2, 3) == 0)
734                                         return 1; /* Found matching PLMN */
735                                 pos += 3;
736                         }
737                 } else {
738                         wpa_hexdump(MSG_DEBUG, "Interworking: Unrecognized 3GPP information element",
739                                     pos, len);
740                 }
741
742                 pos = l_end;
743         }
744
745         return 0;
746 }
747
748
749 static int build_root_nai(char *nai, size_t nai_len, const char *imsi,
750                           size_t mnc_len, char prefix)
751 {
752         const char *sep, *msin;
753         char *end, *pos;
754         size_t msin_len, plmn_len;
755
756         /*
757          * TS 23.003, Clause 14 (3GPP to WLAN Interworking)
758          * Root NAI:
759          * <aka:0|sim:1><IMSI>@wlan.mnc<MNC>.mcc<MCC>.3gppnetwork.org
760          * <MNC> is zero-padded to three digits in case two-digit MNC is used
761          */
762
763         if (imsi == NULL || os_strlen(imsi) > 16) {
764                 wpa_printf(MSG_DEBUG, "No valid IMSI available");
765                 return -1;
766         }
767         sep = os_strchr(imsi, '-');
768         if (sep) {
769                 plmn_len = sep - imsi;
770                 msin = sep + 1;
771         } else if (mnc_len && os_strlen(imsi) >= 3 + mnc_len) {
772                 plmn_len = 3 + mnc_len;
773                 msin = imsi + plmn_len;
774         } else
775                 return -1;
776         if (plmn_len != 5 && plmn_len != 6)
777                 return -1;
778         msin_len = os_strlen(msin);
779
780         pos = nai;
781         end = nai + nai_len;
782         if (prefix)
783                 *pos++ = prefix;
784         os_memcpy(pos, imsi, plmn_len);
785         pos += plmn_len;
786         os_memcpy(pos, msin, msin_len);
787         pos += msin_len;
788         pos += os_snprintf(pos, end - pos, "@wlan.mnc");
789         if (plmn_len == 5) {
790                 *pos++ = '0';
791                 *pos++ = imsi[3];
792                 *pos++ = imsi[4];
793         } else {
794                 *pos++ = imsi[3];
795                 *pos++ = imsi[4];
796                 *pos++ = imsi[5];
797         }
798         pos += os_snprintf(pos, end - pos, ".mcc%c%c%c.3gppnetwork.org",
799                            imsi[0], imsi[1], imsi[2]);
800
801         return 0;
802 }
803
804
805 static int set_root_nai(struct wpa_ssid *ssid, const char *imsi, char prefix)
806 {
807         char nai[100];
808         if (build_root_nai(nai, sizeof(nai), imsi, 0, prefix) < 0)
809                 return -1;
810         return wpa_config_set_quoted(ssid, "identity", nai);
811 }
812
813 #endif /* INTERWORKING_3GPP */
814
815
816 static int already_connected(struct wpa_supplicant *wpa_s,
817                              struct wpa_cred *cred, struct wpa_bss *bss)
818 {
819         struct wpa_ssid *ssid, *sel_ssid;
820         struct wpa_bss *selected;
821
822         if (wpa_s->wpa_state < WPA_ASSOCIATED || wpa_s->current_ssid == NULL)
823                 return 0;
824
825         ssid = wpa_s->current_ssid;
826         if (ssid->parent_cred != cred)
827                 return 0;
828
829         if (ssid->ssid_len != bss->ssid_len ||
830             os_memcmp(ssid->ssid, bss->ssid, bss->ssid_len) != 0)
831                 return 0;
832
833         sel_ssid = NULL;
834         selected = wpa_supplicant_pick_network(wpa_s, &sel_ssid);
835         if (selected && sel_ssid && sel_ssid->priority > ssid->priority)
836                 return 0; /* higher priority network in scan results */
837
838         return 1;
839 }
840
841
842 static void remove_duplicate_network(struct wpa_supplicant *wpa_s,
843                                      struct wpa_cred *cred,
844                                      struct wpa_bss *bss)
845 {
846         struct wpa_ssid *ssid;
847
848         for (ssid = wpa_s->conf->ssid; ssid; ssid = ssid->next) {
849                 if (ssid->parent_cred != cred)
850                         continue;
851                 if (ssid->ssid_len != bss->ssid_len ||
852                     os_memcmp(ssid->ssid, bss->ssid, bss->ssid_len) != 0)
853                         continue;
854
855                 break;
856         }
857
858         if (ssid == NULL)
859                 return;
860
861         wpa_printf(MSG_DEBUG, "Interworking: Remove duplicate network entry for the same credential");
862
863         if (ssid == wpa_s->current_ssid) {
864                 wpa_sm_set_config(wpa_s->wpa, NULL);
865                 eapol_sm_notify_config(wpa_s->eapol, NULL, NULL);
866                 wpa_supplicant_deauthenticate(wpa_s,
867                                               WLAN_REASON_DEAUTH_LEAVING);
868         }
869
870         wpas_notify_network_removed(wpa_s, ssid);
871         wpa_config_remove_network(wpa_s->conf, ssid->id);
872 }
873
874
875 static int interworking_set_hs20_params(struct wpa_supplicant *wpa_s,
876                                         struct wpa_ssid *ssid)
877 {
878         if (wpa_config_set(ssid, "key_mgmt",
879                            wpa_s->conf->pmf != NO_MGMT_FRAME_PROTECTION ?
880                            "WPA-EAP WPA-EAP-SHA256" : "WPA-EAP", 0) < 0)
881                 return -1;
882         if (wpa_config_set(ssid, "proto", "RSN", 0) < 0)
883                 return -1;
884         if (wpa_config_set(ssid, "pairwise", "CCMP", 0) < 0)
885                 return -1;
886         return 0;
887 }
888
889
890 static int interworking_connect_3gpp(struct wpa_supplicant *wpa_s,
891                                      struct wpa_cred *cred,
892                                      struct wpa_bss *bss)
893 {
894 #ifdef INTERWORKING_3GPP
895         struct wpa_ssid *ssid;
896         int eap_type;
897         int res;
898         char prefix;
899
900         if (bss->anqp == NULL || bss->anqp->anqp_3gpp == NULL)
901                 return -1;
902
903         wpa_printf(MSG_DEBUG, "Interworking: Connect with " MACSTR " (3GPP)",
904                    MAC2STR(bss->bssid));
905
906         if (already_connected(wpa_s, cred, bss)) {
907                 wpa_msg(wpa_s, MSG_INFO, INTERWORKING_ALREADY_CONNECTED MACSTR,
908                         MAC2STR(bss->bssid));
909                 return 0;
910         }
911
912         remove_duplicate_network(wpa_s, cred, bss);
913
914         ssid = wpa_config_add_network(wpa_s->conf);
915         if (ssid == NULL)
916                 return -1;
917         ssid->parent_cred = cred;
918
919         wpas_notify_network_added(wpa_s, ssid);
920         wpa_config_set_network_defaults(ssid);
921         ssid->priority = cred->priority;
922         ssid->temporary = 1;
923         ssid->ssid = os_zalloc(bss->ssid_len + 1);
924         if (ssid->ssid == NULL)
925                 goto fail;
926         os_memcpy(ssid->ssid, bss->ssid, bss->ssid_len);
927         ssid->ssid_len = bss->ssid_len;
928
929         if (interworking_set_hs20_params(wpa_s, ssid) < 0)
930                 goto fail;
931
932         eap_type = EAP_TYPE_SIM;
933         if (cred->pcsc && wpa_s->scard && scard_supports_umts(wpa_s->scard))
934                 eap_type = EAP_TYPE_AKA;
935         if (cred->eap_method && cred->eap_method[0].vendor == EAP_VENDOR_IETF) {
936                 if (cred->eap_method[0].method == EAP_TYPE_SIM ||
937                     cred->eap_method[0].method == EAP_TYPE_AKA ||
938                     cred->eap_method[0].method == EAP_TYPE_AKA_PRIME)
939                         eap_type = cred->eap_method[0].method;
940         }
941
942         switch (eap_type) {
943         case EAP_TYPE_SIM:
944                 prefix = '1';
945                 res = wpa_config_set(ssid, "eap", "SIM", 0);
946                 break;
947         case EAP_TYPE_AKA:
948                 prefix = '0';
949                 res = wpa_config_set(ssid, "eap", "AKA", 0);
950                 break;
951         case EAP_TYPE_AKA_PRIME:
952                 prefix = '6';
953                 res = wpa_config_set(ssid, "eap", "AKA'", 0);
954                 break;
955         default:
956                 res = -1;
957                 break;
958         }
959         if (res < 0) {
960                 wpa_printf(MSG_DEBUG, "Selected EAP method (%d) not supported",
961                            eap_type);
962                 goto fail;
963         }
964
965         if (!cred->pcsc && set_root_nai(ssid, cred->imsi, prefix) < 0) {
966                 wpa_printf(MSG_DEBUG, "Failed to set Root NAI");
967                 goto fail;
968         }
969
970         if (cred->milenage && cred->milenage[0]) {
971                 if (wpa_config_set_quoted(ssid, "password",
972                                           cred->milenage) < 0)
973                         goto fail;
974         } else if (cred->pcsc) {
975                 if (wpa_config_set_quoted(ssid, "pcsc", "") < 0)
976                         goto fail;
977                 if (wpa_s->conf->pcsc_pin &&
978                     wpa_config_set_quoted(ssid, "pin", wpa_s->conf->pcsc_pin)
979                     < 0)
980                         goto fail;
981         }
982
983         wpa_s->next_ssid = ssid;
984         wpa_config_update_prio_list(wpa_s->conf);
985         interworking_reconnect(wpa_s);
986
987         return 0;
988
989 fail:
990         wpas_notify_network_removed(wpa_s, ssid);
991         wpa_config_remove_network(wpa_s->conf, ssid->id);
992 #endif /* INTERWORKING_3GPP */
993         return -1;
994 }
995
996
997 static int roaming_consortium_element_match(const u8 *ie, const u8 *rc_id,
998                                             size_t rc_len)
999 {
1000         const u8 *pos, *end;
1001         u8 lens;
1002
1003         if (ie == NULL)
1004                 return 0;
1005
1006         pos = ie + 2;
1007         end = ie + 2 + ie[1];
1008
1009         /* Roaming Consortium element:
1010          * Number of ANQP OIs
1011          * OI #1 and #2 lengths
1012          * OI #1, [OI #2], [OI #3]
1013          */
1014
1015         if (pos + 2 > end)
1016                 return 0;
1017
1018         pos++; /* skip Number of ANQP OIs */
1019         lens = *pos++;
1020         if (pos + (lens & 0x0f) + (lens >> 4) > end)
1021                 return 0;
1022
1023         if ((lens & 0x0f) == rc_len && os_memcmp(pos, rc_id, rc_len) == 0)
1024                 return 1;
1025         pos += lens & 0x0f;
1026
1027         if ((lens >> 4) == rc_len && os_memcmp(pos, rc_id, rc_len) == 0)
1028                 return 1;
1029         pos += lens >> 4;
1030
1031         if (pos < end && (size_t) (end - pos) == rc_len &&
1032             os_memcmp(pos, rc_id, rc_len) == 0)
1033                 return 1;
1034
1035         return 0;
1036 }
1037
1038
1039 static int roaming_consortium_anqp_match(const struct wpabuf *anqp,
1040                                          const u8 *rc_id, size_t rc_len)
1041 {
1042         const u8 *pos, *end;
1043         u8 len;
1044
1045         if (anqp == NULL)
1046                 return 0;
1047
1048         pos = wpabuf_head(anqp);
1049         end = pos + wpabuf_len(anqp);
1050
1051         /* Set of <OI Length, OI> duples */
1052         while (pos < end) {
1053                 len = *pos++;
1054                 if (pos + len > end)
1055                         break;
1056                 if (len == rc_len && os_memcmp(pos, rc_id, rc_len) == 0)
1057                         return 1;
1058                 pos += len;
1059         }
1060
1061         return 0;
1062 }
1063
1064
1065 static int roaming_consortium_match(const u8 *ie, const struct wpabuf *anqp,
1066                                     const u8 *rc_id, size_t rc_len)
1067 {
1068         return roaming_consortium_element_match(ie, rc_id, rc_len) ||
1069                 roaming_consortium_anqp_match(anqp, rc_id, rc_len);
1070 }
1071
1072
1073 static int cred_no_required_oi_match(struct wpa_cred *cred, struct wpa_bss *bss)
1074 {
1075         const u8 *ie;
1076
1077         if (cred->required_roaming_consortium_len == 0)
1078                 return 0;
1079
1080         ie = wpa_bss_get_ie(bss, WLAN_EID_ROAMING_CONSORTIUM);
1081
1082         if (ie == NULL &&
1083             (bss->anqp == NULL || bss->anqp->roaming_consortium == NULL))
1084                 return 1;
1085
1086         return !roaming_consortium_match(ie,
1087                                          bss->anqp ?
1088                                          bss->anqp->roaming_consortium : NULL,
1089                                          cred->required_roaming_consortium,
1090                                          cred->required_roaming_consortium_len);
1091 }
1092
1093
1094 static int cred_excluded_ssid(struct wpa_cred *cred, struct wpa_bss *bss)
1095 {
1096         size_t i;
1097
1098         if (!cred->excluded_ssid)
1099                 return 0;
1100
1101         for (i = 0; i < cred->num_excluded_ssid; i++) {
1102                 struct excluded_ssid *e = &cred->excluded_ssid[i];
1103                 if (bss->ssid_len == e->ssid_len &&
1104                     os_memcmp(bss->ssid, e->ssid, e->ssid_len) == 0)
1105                         return 1;
1106         }
1107
1108         return 0;
1109 }
1110
1111
1112 static int cred_below_min_backhaul(struct wpa_supplicant *wpa_s,
1113                                    struct wpa_cred *cred, struct wpa_bss *bss)
1114 {
1115         int res;
1116         unsigned int dl_bandwidth, ul_bandwidth;
1117         const u8 *wan;
1118         u8 wan_info, dl_load, ul_load;
1119         u16 lmd;
1120         u32 ul_speed, dl_speed;
1121
1122         if (!cred->min_dl_bandwidth_home &&
1123             !cred->min_ul_bandwidth_home &&
1124             !cred->min_dl_bandwidth_roaming &&
1125             !cred->min_ul_bandwidth_roaming)
1126                 return 0; /* No bandwidth constraint specified */
1127
1128         if (bss->anqp == NULL || bss->anqp->hs20_wan_metrics == NULL)
1129                 return 0; /* No WAN Metrics known - ignore constraint */
1130
1131         wan = wpabuf_head(bss->anqp->hs20_wan_metrics);
1132         wan_info = wan[0];
1133         if (wan_info & BIT(3))
1134                 return 1; /* WAN link at capacity */
1135         lmd = WPA_GET_LE16(wan + 11);
1136         if (lmd == 0)
1137                 return 0; /* Downlink/Uplink Load was not measured */
1138         dl_speed = WPA_GET_LE32(wan + 1);
1139         ul_speed = WPA_GET_LE32(wan + 5);
1140         dl_load = wan[9];
1141         ul_load = wan[10];
1142
1143         if (dl_speed >= 0xffffff)
1144                 dl_bandwidth = dl_speed / 255 * (255 - dl_load);
1145         else
1146                 dl_bandwidth = dl_speed * (255 - dl_load) / 255;
1147
1148         if (ul_speed >= 0xffffff)
1149                 ul_bandwidth = ul_speed / 255 * (255 - ul_load);
1150         else
1151                 ul_bandwidth = ul_speed * (255 - ul_load) / 255;
1152
1153         res = interworking_home_sp_cred(wpa_s, cred, bss->anqp ?
1154                                         bss->anqp->domain_name : NULL);
1155         if (res > 0) {
1156                 if (cred->min_dl_bandwidth_home > dl_bandwidth)
1157                         return 1;
1158                 if (cred->min_ul_bandwidth_home > ul_bandwidth)
1159                         return 1;
1160         } else {
1161                 if (cred->min_dl_bandwidth_roaming > dl_bandwidth)
1162                         return 1;
1163                 if (cred->min_ul_bandwidth_roaming > ul_bandwidth)
1164                         return 1;
1165         }
1166
1167         return 0;
1168 }
1169
1170
1171 static int cred_over_max_bss_load(struct wpa_supplicant *wpa_s,
1172                                   struct wpa_cred *cred, struct wpa_bss *bss)
1173 {
1174         const u8 *ie;
1175         int res;
1176
1177         if (!cred->max_bss_load)
1178                 return 0; /* No BSS Load constraint specified */
1179
1180         ie = wpa_bss_get_ie(bss, WLAN_EID_BSS_LOAD);
1181         if (ie == NULL || ie[1] < 3)
1182                 return 0; /* No BSS Load advertised */
1183
1184         res = interworking_home_sp_cred(wpa_s, cred, bss->anqp ?
1185                                         bss->anqp->domain_name : NULL);
1186         if (res <= 0)
1187                 return 0; /* Not a home network */
1188
1189         return ie[4] > cred->max_bss_load;
1190 }
1191
1192
1193 static int has_proto_match(const u8 *pos, const u8 *end, u8 proto)
1194 {
1195         while (pos + 4 <= end) {
1196                 if (pos[0] == proto && pos[3] == 1 /* Open */)
1197                         return 1;
1198                 pos += 4;
1199         }
1200
1201         return 0;
1202 }
1203
1204
1205 static int has_proto_port_match(const u8 *pos, const u8 *end, u8 proto,
1206                                 u16 port)
1207 {
1208         while (pos + 4 <= end) {
1209                 if (pos[0] == proto && WPA_GET_LE16(&pos[1]) == port &&
1210                     pos[3] == 1 /* Open */)
1211                         return 1;
1212                 pos += 4;
1213         }
1214
1215         return 0;
1216 }
1217
1218
1219 static int cred_conn_capab_missing(struct wpa_supplicant *wpa_s,
1220                                    struct wpa_cred *cred, struct wpa_bss *bss)
1221 {
1222         int res;
1223         const u8 *capab, *end;
1224         unsigned int i, j;
1225         int *ports;
1226
1227         if (!cred->num_req_conn_capab)
1228                 return 0; /* No connection capability constraint specified */
1229
1230         if (bss->anqp == NULL || bss->anqp->hs20_connection_capability == NULL)
1231                 return 0; /* No Connection Capability known - ignore constraint
1232                            */
1233
1234         res = interworking_home_sp_cred(wpa_s, cred, bss->anqp ?
1235                                         bss->anqp->domain_name : NULL);
1236         if (res > 0)
1237                 return 0; /* No constraint in home network */
1238
1239         capab = wpabuf_head(bss->anqp->hs20_connection_capability);
1240         end = capab + wpabuf_len(bss->anqp->hs20_connection_capability);
1241
1242         for (i = 0; i < cred->num_req_conn_capab; i++) {
1243                 ports = cred->req_conn_capab_port[i];
1244                 if (!ports) {
1245                         if (!has_proto_match(capab, end,
1246                                              cred->req_conn_capab_proto[i]))
1247                                 return 1;
1248                 } else {
1249                         for (j = 0; ports[j] > -1; j++) {
1250                                 if (!has_proto_port_match(
1251                                             capab, end,
1252                                             cred->req_conn_capab_proto[i],
1253                                             ports[j]))
1254                                         return 1;
1255                         }
1256                 }
1257         }
1258
1259         return 0;
1260 }
1261
1262
1263 static struct wpa_cred * interworking_credentials_available_roaming_consortium(
1264         struct wpa_supplicant *wpa_s, struct wpa_bss *bss, int ignore_bw,
1265         int *excluded)
1266 {
1267         struct wpa_cred *cred, *selected = NULL;
1268         const u8 *ie;
1269         int is_excluded = 0;
1270
1271         ie = wpa_bss_get_ie(bss, WLAN_EID_ROAMING_CONSORTIUM);
1272
1273         if (ie == NULL &&
1274             (bss->anqp == NULL || bss->anqp->roaming_consortium == NULL))
1275                 return NULL;
1276
1277         if (wpa_s->conf->cred == NULL)
1278                 return NULL;
1279
1280         for (cred = wpa_s->conf->cred; cred; cred = cred->next) {
1281                 if (cred->roaming_consortium_len == 0)
1282                         continue;
1283
1284                 if (!roaming_consortium_match(ie,
1285                                               bss->anqp ?
1286                                               bss->anqp->roaming_consortium :
1287                                               NULL,
1288                                               cred->roaming_consortium,
1289                                               cred->roaming_consortium_len))
1290                         continue;
1291
1292                 if (cred_no_required_oi_match(cred, bss))
1293                         continue;
1294                 if (!ignore_bw && cred_below_min_backhaul(wpa_s, cred, bss))
1295                         continue;
1296                 if (!ignore_bw && cred_over_max_bss_load(wpa_s, cred, bss))
1297                         continue;
1298                 if (!ignore_bw && cred_conn_capab_missing(wpa_s, cred, bss))
1299                         continue;
1300                 if (cred_excluded_ssid(cred, bss)) {
1301                         if (excluded == NULL)
1302                                 continue;
1303                         if (selected == NULL) {
1304                                 selected = cred;
1305                                 is_excluded = 1;
1306                         }
1307                 } else {
1308                         if (selected == NULL || is_excluded ||
1309                             cred_prio_cmp(selected, cred) < 0) {
1310                                 selected = cred;
1311                                 is_excluded = 0;
1312                         }
1313                 }
1314         }
1315
1316         if (excluded)
1317                 *excluded = is_excluded;
1318
1319         return selected;
1320 }
1321
1322
1323 static int interworking_set_eap_params(struct wpa_ssid *ssid,
1324                                        struct wpa_cred *cred, int ttls)
1325 {
1326         if (cred->eap_method) {
1327                 ttls = cred->eap_method->vendor == EAP_VENDOR_IETF &&
1328                         cred->eap_method->method == EAP_TYPE_TTLS;
1329
1330                 os_free(ssid->eap.eap_methods);
1331                 ssid->eap.eap_methods =
1332                         os_malloc(sizeof(struct eap_method_type) * 2);
1333                 if (ssid->eap.eap_methods == NULL)
1334                         return -1;
1335                 os_memcpy(ssid->eap.eap_methods, cred->eap_method,
1336                           sizeof(*cred->eap_method));
1337                 ssid->eap.eap_methods[1].vendor = EAP_VENDOR_IETF;
1338                 ssid->eap.eap_methods[1].method = EAP_TYPE_NONE;
1339         }
1340
1341         if (ttls && cred->username && cred->username[0]) {
1342                 const char *pos;
1343                 char *anon;
1344                 /* Use anonymous NAI in Phase 1 */
1345                 pos = os_strchr(cred->username, '@');
1346                 if (pos) {
1347                         size_t buflen = 9 + os_strlen(pos) + 1;
1348                         anon = os_malloc(buflen);
1349                         if (anon == NULL)
1350                                 return -1;
1351                         os_snprintf(anon, buflen, "anonymous%s", pos);
1352                 } else if (cred->realm) {
1353                         size_t buflen = 10 + os_strlen(cred->realm) + 1;
1354                         anon = os_malloc(buflen);
1355                         if (anon == NULL)
1356                                 return -1;
1357                         os_snprintf(anon, buflen, "anonymous@%s", cred->realm);
1358                 } else {
1359                         anon = os_strdup("anonymous");
1360                         if (anon == NULL)
1361                                 return -1;
1362                 }
1363                 if (wpa_config_set_quoted(ssid, "anonymous_identity", anon) <
1364                     0) {
1365                         os_free(anon);
1366                         return -1;
1367                 }
1368                 os_free(anon);
1369         }
1370
1371         if (cred->username && cred->username[0] &&
1372             wpa_config_set_quoted(ssid, "identity", cred->username) < 0)
1373                 return -1;
1374
1375         if (cred->password && cred->password[0]) {
1376                 if (cred->ext_password &&
1377                     wpa_config_set(ssid, "password", cred->password, 0) < 0)
1378                         return -1;
1379                 if (!cred->ext_password &&
1380                     wpa_config_set_quoted(ssid, "password", cred->password) <
1381                     0)
1382                         return -1;
1383         }
1384
1385         if (cred->client_cert && cred->client_cert[0] &&
1386             wpa_config_set_quoted(ssid, "client_cert", cred->client_cert) < 0)
1387                 return -1;
1388
1389 #ifdef ANDROID
1390         if (cred->private_key &&
1391             os_strncmp(cred->private_key, "keystore://", 11) == 0) {
1392                 /* Use OpenSSL engine configuration for Android keystore */
1393                 if (wpa_config_set_quoted(ssid, "engine_id", "keystore") < 0 ||
1394                     wpa_config_set_quoted(ssid, "key_id",
1395                                           cred->private_key + 11) < 0 ||
1396                     wpa_config_set(ssid, "engine", "1", 0) < 0)
1397                         return -1;
1398         } else
1399 #endif /* ANDROID */
1400         if (cred->private_key && cred->private_key[0] &&
1401             wpa_config_set_quoted(ssid, "private_key", cred->private_key) < 0)
1402                 return -1;
1403
1404         if (cred->private_key_passwd && cred->private_key_passwd[0] &&
1405             wpa_config_set_quoted(ssid, "private_key_passwd",
1406                                   cred->private_key_passwd) < 0)
1407                 return -1;
1408
1409         if (cred->phase1) {
1410                 os_free(ssid->eap.phase1);
1411                 ssid->eap.phase1 = os_strdup(cred->phase1);
1412         }
1413         if (cred->phase2) {
1414                 os_free(ssid->eap.phase2);
1415                 ssid->eap.phase2 = os_strdup(cred->phase2);
1416         }
1417
1418         if (cred->ca_cert && cred->ca_cert[0] &&
1419             wpa_config_set_quoted(ssid, "ca_cert", cred->ca_cert) < 0)
1420                 return -1;
1421
1422         if (cred->domain_suffix_match && cred->domain_suffix_match[0] &&
1423             wpa_config_set_quoted(ssid, "domain_suffix_match",
1424                                   cred->domain_suffix_match) < 0)
1425                 return -1;
1426
1427         ssid->eap.ocsp = cred->ocsp;
1428
1429         return 0;
1430 }
1431
1432
1433 static int interworking_connect_roaming_consortium(
1434         struct wpa_supplicant *wpa_s, struct wpa_cred *cred,
1435         struct wpa_bss *bss)
1436 {
1437         struct wpa_ssid *ssid;
1438
1439         wpa_printf(MSG_DEBUG, "Interworking: Connect with " MACSTR " based on "
1440                    "roaming consortium match", MAC2STR(bss->bssid));
1441
1442         if (already_connected(wpa_s, cred, bss)) {
1443                 wpa_msg(wpa_s, MSG_INFO, INTERWORKING_ALREADY_CONNECTED MACSTR,
1444                         MAC2STR(bss->bssid));
1445                 return 0;
1446         }
1447
1448         remove_duplicate_network(wpa_s, cred, bss);
1449
1450         ssid = wpa_config_add_network(wpa_s->conf);
1451         if (ssid == NULL)
1452                 return -1;
1453         ssid->parent_cred = cred;
1454         wpas_notify_network_added(wpa_s, ssid);
1455         wpa_config_set_network_defaults(ssid);
1456         ssid->priority = cred->priority;
1457         ssid->temporary = 1;
1458         ssid->ssid = os_zalloc(bss->ssid_len + 1);
1459         if (ssid->ssid == NULL)
1460                 goto fail;
1461         os_memcpy(ssid->ssid, bss->ssid, bss->ssid_len);
1462         ssid->ssid_len = bss->ssid_len;
1463
1464         if (interworking_set_hs20_params(wpa_s, ssid) < 0)
1465                 goto fail;
1466
1467         if (cred->eap_method == NULL) {
1468                 wpa_printf(MSG_DEBUG, "Interworking: No EAP method set for "
1469                            "credential using roaming consortium");
1470                 goto fail;
1471         }
1472
1473         if (interworking_set_eap_params(
1474                     ssid, cred,
1475                     cred->eap_method->vendor == EAP_VENDOR_IETF &&
1476                     cred->eap_method->method == EAP_TYPE_TTLS) < 0)
1477                 goto fail;
1478
1479         wpa_s->next_ssid = ssid;
1480         wpa_config_update_prio_list(wpa_s->conf);
1481         interworking_reconnect(wpa_s);
1482
1483         return 0;
1484
1485 fail:
1486         wpas_notify_network_removed(wpa_s, ssid);
1487         wpa_config_remove_network(wpa_s->conf, ssid->id);
1488         return -1;
1489 }
1490
1491
1492 static int interworking_connect_helper(struct wpa_supplicant *wpa_s,
1493                                        struct wpa_bss *bss, int allow_excluded)
1494 {
1495         struct wpa_cred *cred, *cred_rc, *cred_3gpp;
1496         struct wpa_ssid *ssid;
1497         struct nai_realm *realm;
1498         struct nai_realm_eap *eap = NULL;
1499         u16 count, i;
1500         char buf[100];
1501         int excluded = 0, *excl = allow_excluded ? &excluded : NULL;
1502
1503         if (wpa_s->conf->cred == NULL || bss == NULL)
1504                 return -1;
1505         if (disallowed_bssid(wpa_s, bss->bssid) ||
1506             disallowed_ssid(wpa_s, bss->ssid, bss->ssid_len)) {
1507                 wpa_printf(MSG_DEBUG, "Interworking: Reject connection to disallowed BSS "
1508                            MACSTR, MAC2STR(bss->bssid));
1509                 return -1;
1510         }
1511
1512         wpa_printf(MSG_DEBUG, "Interworking: Considering BSS " MACSTR
1513                    " for connection (allow_excluded=%d)",
1514                    MAC2STR(bss->bssid), allow_excluded);
1515
1516         if (!wpa_bss_get_ie(bss, WLAN_EID_RSN)) {
1517                 /*
1518                  * We currently support only HS 2.0 networks and those are
1519                  * required to use WPA2-Enterprise.
1520                  */
1521                 wpa_printf(MSG_DEBUG, "Interworking: Network does not use "
1522                            "RSN");
1523                 return -1;
1524         }
1525
1526         cred_rc = interworking_credentials_available_roaming_consortium(
1527                 wpa_s, bss, 0, excl);
1528         if (cred_rc) {
1529                 wpa_printf(MSG_DEBUG, "Interworking: Highest roaming "
1530                            "consortium matching credential priority %d "
1531                            "sp_priority %d",
1532                            cred_rc->priority, cred_rc->sp_priority);
1533                 if (allow_excluded && excl && !(*excl))
1534                         excl = NULL;
1535         }
1536
1537         cred = interworking_credentials_available_realm(wpa_s, bss, 0, excl);
1538         if (cred) {
1539                 wpa_printf(MSG_DEBUG, "Interworking: Highest NAI Realm list "
1540                            "matching credential priority %d sp_priority %d",
1541                            cred->priority, cred->sp_priority);
1542                 if (allow_excluded && excl && !(*excl))
1543                         excl = NULL;
1544         }
1545
1546         cred_3gpp = interworking_credentials_available_3gpp(wpa_s, bss, 0,
1547                                                             excl);
1548         if (cred_3gpp) {
1549                 wpa_printf(MSG_DEBUG, "Interworking: Highest 3GPP matching "
1550                            "credential priority %d sp_priority %d",
1551                            cred_3gpp->priority, cred_3gpp->sp_priority);
1552                 if (allow_excluded && excl && !(*excl))
1553                         excl = NULL;
1554         }
1555
1556         if (!cred_rc && !cred && !cred_3gpp) {
1557                 wpa_printf(MSG_DEBUG, "Interworking: No full credential matches - consider options without BW(etc.) limits");
1558                 cred_rc = interworking_credentials_available_roaming_consortium(
1559                         wpa_s, bss, 1, excl);
1560                 if (cred_rc) {
1561                         wpa_printf(MSG_DEBUG, "Interworking: Highest roaming "
1562                                    "consortium matching credential priority %d "
1563                                    "sp_priority %d (ignore BW)",
1564                                    cred_rc->priority, cred_rc->sp_priority);
1565                         if (allow_excluded && excl && !(*excl))
1566                                 excl = NULL;
1567                 }
1568
1569                 cred = interworking_credentials_available_realm(wpa_s, bss, 1,
1570                                                                 excl);
1571                 if (cred) {
1572                         wpa_printf(MSG_DEBUG, "Interworking: Highest NAI Realm "
1573                                    "list matching credential priority %d "
1574                                    "sp_priority %d (ignore BW)",
1575                                    cred->priority, cred->sp_priority);
1576                         if (allow_excluded && excl && !(*excl))
1577                                 excl = NULL;
1578                 }
1579
1580                 cred_3gpp = interworking_credentials_available_3gpp(wpa_s, bss,
1581                                                                     1, excl);
1582                 if (cred_3gpp) {
1583                         wpa_printf(MSG_DEBUG, "Interworking: Highest 3GPP "
1584                                    "matching credential priority %d "
1585                                    "sp_priority %d (ignore BW)",
1586                                    cred_3gpp->priority, cred_3gpp->sp_priority);
1587                         if (allow_excluded && excl && !(*excl))
1588                                 excl = NULL;
1589                 }
1590         }
1591
1592         if (cred_rc &&
1593             (cred == NULL || cred_prio_cmp(cred_rc, cred) >= 0) &&
1594             (cred_3gpp == NULL || cred_prio_cmp(cred_rc, cred_3gpp) >= 0))
1595                 return interworking_connect_roaming_consortium(wpa_s, cred_rc,
1596                                                                bss);
1597
1598         if (cred_3gpp &&
1599             (cred == NULL || cred_prio_cmp(cred_3gpp, cred) >= 0)) {
1600                 return interworking_connect_3gpp(wpa_s, cred_3gpp, bss);
1601         }
1602
1603         if (cred == NULL) {
1604                 wpa_printf(MSG_DEBUG, "Interworking: No matching credentials "
1605                            "found for " MACSTR, MAC2STR(bss->bssid));
1606                 return -1;
1607         }
1608
1609         realm = nai_realm_parse(bss->anqp ? bss->anqp->nai_realm : NULL,
1610                                 &count);
1611         if (realm == NULL) {
1612                 wpa_printf(MSG_DEBUG, "Interworking: Could not parse NAI "
1613                            "Realm list from " MACSTR, MAC2STR(bss->bssid));
1614                 return -1;
1615         }
1616
1617         for (i = 0; i < count; i++) {
1618                 if (!nai_realm_match(&realm[i], cred->realm))
1619                         continue;
1620                 eap = nai_realm_find_eap(cred, &realm[i]);
1621                 if (eap)
1622                         break;
1623         }
1624
1625         if (!eap) {
1626                 wpa_printf(MSG_DEBUG, "Interworking: No matching credentials "
1627                            "and EAP method found for " MACSTR,
1628                            MAC2STR(bss->bssid));
1629                 nai_realm_free(realm, count);
1630                 return -1;
1631         }
1632
1633         wpa_printf(MSG_DEBUG, "Interworking: Connect with " MACSTR,
1634                    MAC2STR(bss->bssid));
1635
1636         if (already_connected(wpa_s, cred, bss)) {
1637                 wpa_msg(wpa_s, MSG_INFO, INTERWORKING_ALREADY_CONNECTED MACSTR,
1638                         MAC2STR(bss->bssid));
1639                 nai_realm_free(realm, count);
1640                 return 0;
1641         }
1642
1643         remove_duplicate_network(wpa_s, cred, bss);
1644
1645         ssid = wpa_config_add_network(wpa_s->conf);
1646         if (ssid == NULL) {
1647                 nai_realm_free(realm, count);
1648                 return -1;
1649         }
1650         ssid->parent_cred = cred;
1651         wpas_notify_network_added(wpa_s, ssid);
1652         wpa_config_set_network_defaults(ssid);
1653         ssid->priority = cred->priority;
1654         ssid->temporary = 1;
1655         ssid->ssid = os_zalloc(bss->ssid_len + 1);
1656         if (ssid->ssid == NULL)
1657                 goto fail;
1658         os_memcpy(ssid->ssid, bss->ssid, bss->ssid_len);
1659         ssid->ssid_len = bss->ssid_len;
1660
1661         if (interworking_set_hs20_params(wpa_s, ssid) < 0)
1662                 goto fail;
1663
1664         if (wpa_config_set(ssid, "eap", eap_get_name(EAP_VENDOR_IETF,
1665                                                      eap->method), 0) < 0)
1666                 goto fail;
1667
1668         switch (eap->method) {
1669         case EAP_TYPE_TTLS:
1670                 if (eap->inner_method) {
1671                         os_snprintf(buf, sizeof(buf), "\"autheap=%s\"",
1672                                     eap_get_name(EAP_VENDOR_IETF,
1673                                                  eap->inner_method));
1674                         if (wpa_config_set(ssid, "phase2", buf, 0) < 0)
1675                                 goto fail;
1676                         break;
1677                 }
1678                 switch (eap->inner_non_eap) {
1679                 case NAI_REALM_INNER_NON_EAP_PAP:
1680                         if (wpa_config_set(ssid, "phase2", "\"auth=PAP\"", 0) <
1681                             0)
1682                                 goto fail;
1683                         break;
1684                 case NAI_REALM_INNER_NON_EAP_CHAP:
1685                         if (wpa_config_set(ssid, "phase2", "\"auth=CHAP\"", 0)
1686                             < 0)
1687                                 goto fail;
1688                         break;
1689                 case NAI_REALM_INNER_NON_EAP_MSCHAP:
1690                         if (wpa_config_set(ssid, "phase2", "\"auth=MSCHAP\"",
1691                                            0) < 0)
1692                                 goto fail;
1693                         break;
1694                 case NAI_REALM_INNER_NON_EAP_MSCHAPV2:
1695                         if (wpa_config_set(ssid, "phase2", "\"auth=MSCHAPV2\"",
1696                                            0) < 0)
1697                                 goto fail;
1698                         break;
1699                 default:
1700                         /* EAP params were not set - assume TTLS/MSCHAPv2 */
1701                         if (wpa_config_set(ssid, "phase2", "\"auth=MSCHAPV2\"",
1702                                            0) < 0)
1703                                 goto fail;
1704                         break;
1705                 }
1706                 break;
1707         case EAP_TYPE_PEAP:
1708         case EAP_TYPE_FAST:
1709                 if (wpa_config_set(ssid, "phase1", "\"fast_provisioning=2\"",
1710                                    0) < 0)
1711                         goto fail;
1712                 if (wpa_config_set(ssid, "pac_file",
1713                                    "\"blob://pac_interworking\"", 0) < 0)
1714                         goto fail;
1715                 os_snprintf(buf, sizeof(buf), "\"auth=%s\"",
1716                             eap_get_name(EAP_VENDOR_IETF,
1717                                          eap->inner_method ?
1718                                          eap->inner_method :
1719                                          EAP_TYPE_MSCHAPV2));
1720                 if (wpa_config_set(ssid, "phase2", buf, 0) < 0)
1721                         goto fail;
1722                 break;
1723         case EAP_TYPE_TLS:
1724                 break;
1725         }
1726
1727         if (interworking_set_eap_params(ssid, cred,
1728                                         eap->method == EAP_TYPE_TTLS) < 0)
1729                 goto fail;
1730
1731         nai_realm_free(realm, count);
1732
1733         wpa_s->next_ssid = ssid;
1734         wpa_config_update_prio_list(wpa_s->conf);
1735         interworking_reconnect(wpa_s);
1736
1737         return 0;
1738
1739 fail:
1740         wpas_notify_network_removed(wpa_s, ssid);
1741         wpa_config_remove_network(wpa_s->conf, ssid->id);
1742         nai_realm_free(realm, count);
1743         return -1;
1744 }
1745
1746
1747 int interworking_connect(struct wpa_supplicant *wpa_s, struct wpa_bss *bss)
1748 {
1749         return interworking_connect_helper(wpa_s, bss, 1);
1750 }
1751
1752
1753 #ifdef PCSC_FUNCS
1754 static int interworking_pcsc_read_imsi(struct wpa_supplicant *wpa_s)
1755 {
1756         size_t len;
1757
1758         if (wpa_s->imsi[0] && wpa_s->mnc_len)
1759                 return 0;
1760
1761         len = sizeof(wpa_s->imsi) - 1;
1762         if (scard_get_imsi(wpa_s->scard, wpa_s->imsi, &len)) {
1763                 scard_deinit(wpa_s->scard);
1764                 wpa_s->scard = NULL;
1765                 wpa_msg(wpa_s, MSG_ERROR, "Could not read IMSI");
1766                 return -1;
1767         }
1768         wpa_s->imsi[len] = '\0';
1769         wpa_s->mnc_len = scard_get_mnc_len(wpa_s->scard);
1770         wpa_printf(MSG_DEBUG, "SCARD: IMSI %s (MNC length %d)",
1771                    wpa_s->imsi, wpa_s->mnc_len);
1772
1773         return 0;
1774 }
1775 #endif /* PCSC_FUNCS */
1776
1777
1778 static struct wpa_cred * interworking_credentials_available_3gpp(
1779         struct wpa_supplicant *wpa_s, struct wpa_bss *bss, int ignore_bw,
1780         int *excluded)
1781 {
1782         struct wpa_cred *selected = NULL;
1783 #ifdef INTERWORKING_3GPP
1784         struct wpa_cred *cred;
1785         int ret;
1786         int is_excluded = 0;
1787
1788         if (bss->anqp == NULL || bss->anqp->anqp_3gpp == NULL)
1789                 return NULL;
1790
1791 #ifdef CONFIG_EAP_PROXY
1792         if (!wpa_s->imsi[0]) {
1793                 size_t len;
1794                 wpa_printf(MSG_DEBUG, "Interworking: IMSI not available - try to read again through eap_proxy");
1795                 wpa_s->mnc_len = eapol_sm_get_eap_proxy_imsi(wpa_s->eapol,
1796                                                              wpa_s->imsi,
1797                                                              &len);
1798                 if (wpa_s->mnc_len > 0) {
1799                         wpa_s->imsi[len] = '\0';
1800                         wpa_printf(MSG_DEBUG, "eap_proxy: IMSI %s (MNC length %d)",
1801                                    wpa_s->imsi, wpa_s->mnc_len);
1802                 } else {
1803                         wpa_printf(MSG_DEBUG, "eap_proxy: IMSI not available");
1804                 }
1805         }
1806 #endif /* CONFIG_EAP_PROXY */
1807
1808         for (cred = wpa_s->conf->cred; cred; cred = cred->next) {
1809                 char *sep;
1810                 const char *imsi;
1811                 int mnc_len;
1812                 char imsi_buf[16];
1813                 size_t msin_len;
1814
1815 #ifdef PCSC_FUNCS
1816                 if (cred->pcsc && wpa_s->scard) {
1817                         if (interworking_pcsc_read_imsi(wpa_s) < 0)
1818                                 continue;
1819                         imsi = wpa_s->imsi;
1820                         mnc_len = wpa_s->mnc_len;
1821                         goto compare;
1822                 }
1823 #endif /* PCSC_FUNCS */
1824 #ifdef CONFIG_EAP_PROXY
1825                 if (cred->pcsc && wpa_s->mnc_len > 0 && wpa_s->imsi[0]) {
1826                         imsi = wpa_s->imsi;
1827                         mnc_len = wpa_s->mnc_len;
1828                         goto compare;
1829                 }
1830 #endif /* CONFIG_EAP_PROXY */
1831
1832                 if (cred->imsi == NULL || !cred->imsi[0] ||
1833                     (!wpa_s->conf->external_sim &&
1834                      (cred->milenage == NULL || !cred->milenage[0])))
1835                         continue;
1836
1837                 sep = os_strchr(cred->imsi, '-');
1838                 if (sep == NULL ||
1839                     (sep - cred->imsi != 5 && sep - cred->imsi != 6))
1840                         continue;
1841                 mnc_len = sep - cred->imsi - 3;
1842                 os_memcpy(imsi_buf, cred->imsi, 3 + mnc_len);
1843                 sep++;
1844                 msin_len = os_strlen(cred->imsi);
1845                 if (3 + mnc_len + msin_len >= sizeof(imsi_buf) - 1)
1846                         msin_len = sizeof(imsi_buf) - 3 - mnc_len - 1;
1847                 os_memcpy(&imsi_buf[3 + mnc_len], sep, msin_len);
1848                 imsi_buf[3 + mnc_len + msin_len] = '\0';
1849                 imsi = imsi_buf;
1850
1851 #if defined(PCSC_FUNCS) || defined(CONFIG_EAP_PROXY)
1852         compare:
1853 #endif /* PCSC_FUNCS || CONFIG_EAP_PROXY */
1854                 wpa_printf(MSG_DEBUG, "Interworking: Parsing 3GPP info from "
1855                            MACSTR, MAC2STR(bss->bssid));
1856                 ret = plmn_id_match(bss->anqp->anqp_3gpp, imsi, mnc_len);
1857                 wpa_printf(MSG_DEBUG, "PLMN match %sfound", ret ? "" : "not ");
1858                 if (ret) {
1859                         if (cred_no_required_oi_match(cred, bss))
1860                                 continue;
1861                         if (!ignore_bw &&
1862                             cred_below_min_backhaul(wpa_s, cred, bss))
1863                                 continue;
1864                         if (!ignore_bw &&
1865                             cred_over_max_bss_load(wpa_s, cred, bss))
1866                                 continue;
1867                         if (!ignore_bw &&
1868                             cred_conn_capab_missing(wpa_s, cred, bss))
1869                                 continue;
1870                         if (cred_excluded_ssid(cred, bss)) {
1871                                 if (excluded == NULL)
1872                                         continue;
1873                                 if (selected == NULL) {
1874                                         selected = cred;
1875                                         is_excluded = 1;
1876                                 }
1877                         } else {
1878                                 if (selected == NULL || is_excluded ||
1879                                     cred_prio_cmp(selected, cred) < 0) {
1880                                         selected = cred;
1881                                         is_excluded = 0;
1882                                 }
1883                         }
1884                 }
1885         }
1886
1887         if (excluded)
1888                 *excluded = is_excluded;
1889 #endif /* INTERWORKING_3GPP */
1890         return selected;
1891 }
1892
1893
1894 static struct wpa_cred * interworking_credentials_available_realm(
1895         struct wpa_supplicant *wpa_s, struct wpa_bss *bss, int ignore_bw,
1896         int *excluded)
1897 {
1898         struct wpa_cred *cred, *selected = NULL;
1899         struct nai_realm *realm;
1900         u16 count, i;
1901         int is_excluded = 0;
1902
1903         if (bss->anqp == NULL || bss->anqp->nai_realm == NULL)
1904                 return NULL;
1905
1906         if (wpa_s->conf->cred == NULL)
1907                 return NULL;
1908
1909         wpa_printf(MSG_DEBUG, "Interworking: Parsing NAI Realm list from "
1910                    MACSTR, MAC2STR(bss->bssid));
1911         realm = nai_realm_parse(bss->anqp->nai_realm, &count);
1912         if (realm == NULL) {
1913                 wpa_printf(MSG_DEBUG, "Interworking: Could not parse NAI "
1914                            "Realm list from " MACSTR, MAC2STR(bss->bssid));
1915                 return NULL;
1916         }
1917
1918         for (cred = wpa_s->conf->cred; cred; cred = cred->next) {
1919                 if (cred->realm == NULL)
1920                         continue;
1921
1922                 for (i = 0; i < count; i++) {
1923                         if (!nai_realm_match(&realm[i], cred->realm))
1924                                 continue;
1925                         if (nai_realm_find_eap(cred, &realm[i])) {
1926                                 if (cred_no_required_oi_match(cred, bss))
1927                                         continue;
1928                                 if (!ignore_bw &&
1929                                     cred_below_min_backhaul(wpa_s, cred, bss))
1930                                         continue;
1931                                 if (!ignore_bw &&
1932                                     cred_over_max_bss_load(wpa_s, cred, bss))
1933                                         continue;
1934                                 if (!ignore_bw &&
1935                                     cred_conn_capab_missing(wpa_s, cred, bss))
1936                                         continue;
1937                                 if (cred_excluded_ssid(cred, bss)) {
1938                                         if (excluded == NULL)
1939                                                 continue;
1940                                         if (selected == NULL) {
1941                                                 selected = cred;
1942                                                 is_excluded = 1;
1943                                         }
1944                                 } else {
1945                                         if (selected == NULL || is_excluded ||
1946                                             cred_prio_cmp(selected, cred) < 0)
1947                                         {
1948                                                 selected = cred;
1949                                                 is_excluded = 0;
1950                                         }
1951                                 }
1952                                 break;
1953                         }
1954                 }
1955         }
1956
1957         nai_realm_free(realm, count);
1958
1959         if (excluded)
1960                 *excluded = is_excluded;
1961
1962         return selected;
1963 }
1964
1965
1966 static struct wpa_cred * interworking_credentials_available_helper(
1967         struct wpa_supplicant *wpa_s, struct wpa_bss *bss, int ignore_bw,
1968         int *excluded)
1969 {
1970         struct wpa_cred *cred, *cred2;
1971         int excluded1, excluded2;
1972
1973         if (disallowed_bssid(wpa_s, bss->bssid) ||
1974             disallowed_ssid(wpa_s, bss->ssid, bss->ssid_len)) {
1975                 wpa_printf(MSG_DEBUG, "Interworking: Ignore disallowed BSS "
1976                            MACSTR, MAC2STR(bss->bssid));
1977                 return NULL;
1978         }
1979
1980         cred = interworking_credentials_available_realm(wpa_s, bss, ignore_bw,
1981                                                         &excluded1);
1982         cred2 = interworking_credentials_available_3gpp(wpa_s, bss, ignore_bw,
1983                                                         &excluded2);
1984         if (cred && cred2 &&
1985             (cred_prio_cmp(cred2, cred) >= 0 || (!excluded2 && excluded1))) {
1986                 cred = cred2;
1987                 excluded1 = excluded2;
1988         }
1989         if (!cred) {
1990                 cred = cred2;
1991                 excluded1 = excluded2;
1992         }
1993
1994         cred2 = interworking_credentials_available_roaming_consortium(
1995                 wpa_s, bss, ignore_bw, &excluded2);
1996         if (cred && cred2 &&
1997             (cred_prio_cmp(cred2, cred) >= 0 || (!excluded2 && excluded1))) {
1998                 cred = cred2;
1999                 excluded1 = excluded2;
2000         }
2001         if (!cred) {
2002                 cred = cred2;
2003                 excluded1 = excluded2;
2004         }
2005
2006         if (excluded)
2007                 *excluded = excluded1;
2008         return cred;
2009 }
2010
2011
2012 static struct wpa_cred * interworking_credentials_available(
2013         struct wpa_supplicant *wpa_s, struct wpa_bss *bss, int *excluded)
2014 {
2015         struct wpa_cred *cred;
2016
2017         if (excluded)
2018                 *excluded = 0;
2019         cred = interworking_credentials_available_helper(wpa_s, bss, 0,
2020                                                          excluded);
2021         if (cred)
2022                 return cred;
2023         return interworking_credentials_available_helper(wpa_s, bss, 1,
2024                                                          excluded);
2025 }
2026
2027
2028 int domain_name_list_contains(struct wpabuf *domain_names,
2029                               const char *domain, int exact_match)
2030 {
2031         const u8 *pos, *end;
2032         size_t len;
2033
2034         len = os_strlen(domain);
2035         pos = wpabuf_head(domain_names);
2036         end = pos + wpabuf_len(domain_names);
2037
2038         while (pos + 1 < end) {
2039                 if (pos + 1 + pos[0] > end)
2040                         break;
2041
2042                 wpa_hexdump_ascii(MSG_DEBUG, "Interworking: AP domain name",
2043                                   pos + 1, pos[0]);
2044                 if (pos[0] == len &&
2045                     os_strncasecmp(domain, (const char *) (pos + 1), len) == 0)
2046                         return 1;
2047                 if (!exact_match && pos[0] > len && pos[pos[0] - len] == '.') {
2048                         const char *ap = (const char *) (pos + 1);
2049                         int offset = pos[0] - len;
2050                         if (os_strncasecmp(domain, ap + offset, len) == 0)
2051                                 return 1;
2052                 }
2053
2054                 pos += 1 + pos[0];
2055         }
2056
2057         return 0;
2058 }
2059
2060
2061 int interworking_home_sp_cred(struct wpa_supplicant *wpa_s,
2062                               struct wpa_cred *cred,
2063                               struct wpabuf *domain_names)
2064 {
2065         size_t i;
2066         int ret = -1;
2067 #ifdef INTERWORKING_3GPP
2068         char nai[100], *realm;
2069
2070         char *imsi = NULL;
2071         int mnc_len = 0;
2072         if (cred->imsi)
2073                 imsi = cred->imsi;
2074 #ifdef PCSC_FUNCS
2075         else if (cred->pcsc && wpa_s->scard) {
2076                 if (interworking_pcsc_read_imsi(wpa_s) < 0)
2077                         return -1;
2078                 imsi = wpa_s->imsi;
2079                 mnc_len = wpa_s->mnc_len;
2080         }
2081 #endif /* PCSC_FUNCS */
2082 #ifdef CONFIG_EAP_PROXY
2083         else if (cred->pcsc && wpa_s->mnc_len > 0 && wpa_s->imsi[0]) {
2084                 imsi = wpa_s->imsi;
2085                 mnc_len = wpa_s->mnc_len;
2086         }
2087 #endif /* CONFIG_EAP_PROXY */
2088         if (domain_names &&
2089             imsi && build_root_nai(nai, sizeof(nai), imsi, mnc_len, 0) == 0) {
2090                 realm = os_strchr(nai, '@');
2091                 if (realm)
2092                         realm++;
2093                 wpa_printf(MSG_DEBUG, "Interworking: Search for match "
2094                            "with SIM/USIM domain %s", realm);
2095                 if (realm &&
2096                     domain_name_list_contains(domain_names, realm, 1))
2097                         return 1;
2098                 if (realm)
2099                         ret = 0;
2100         }
2101 #endif /* INTERWORKING_3GPP */
2102
2103         if (domain_names == NULL || cred->domain == NULL)
2104                 return ret;
2105
2106         for (i = 0; i < cred->num_domain; i++) {
2107                 wpa_printf(MSG_DEBUG, "Interworking: Search for match with "
2108                            "home SP FQDN %s", cred->domain[i]);
2109                 if (domain_name_list_contains(domain_names, cred->domain[i], 1))
2110                         return 1;
2111         }
2112
2113         return 0;
2114 }
2115
2116
2117 static int interworking_home_sp(struct wpa_supplicant *wpa_s,
2118                                 struct wpabuf *domain_names)
2119 {
2120         struct wpa_cred *cred;
2121
2122         if (domain_names == NULL || wpa_s->conf->cred == NULL)
2123                 return -1;
2124
2125         for (cred = wpa_s->conf->cred; cred; cred = cred->next) {
2126                 int res = interworking_home_sp_cred(wpa_s, cred, domain_names);
2127                 if (res)
2128                         return res;
2129         }
2130
2131         return 0;
2132 }
2133
2134
2135 static int interworking_find_network_match(struct wpa_supplicant *wpa_s)
2136 {
2137         struct wpa_bss *bss;
2138         struct wpa_ssid *ssid;
2139
2140         dl_list_for_each(bss, &wpa_s->bss, struct wpa_bss, list) {
2141                 for (ssid = wpa_s->conf->ssid; ssid; ssid = ssid->next) {
2142                         if (wpas_network_disabled(wpa_s, ssid) ||
2143                             ssid->mode != WPAS_MODE_INFRA)
2144                                 continue;
2145                         if (ssid->ssid_len != bss->ssid_len ||
2146                             os_memcmp(ssid->ssid, bss->ssid, ssid->ssid_len) !=
2147                             0)
2148                                 continue;
2149                         /*
2150                          * TODO: Consider more accurate matching of security
2151                          * configuration similarly to what is done in events.c
2152                          */
2153                         return 1;
2154                 }
2155         }
2156
2157         return 0;
2158 }
2159
2160
2161 static int roaming_partner_match(struct wpa_supplicant *wpa_s,
2162                                  struct roaming_partner *partner,
2163                                  struct wpabuf *domain_names)
2164 {
2165         wpa_printf(MSG_DEBUG, "Interworking: Comparing roaming_partner info fqdn='%s' exact_match=%d priority=%u country='%s'",
2166                    partner->fqdn, partner->exact_match, partner->priority,
2167                    partner->country);
2168         wpa_hexdump_ascii(MSG_DEBUG, "Interworking: Domain names",
2169                           wpabuf_head(domain_names),
2170                           wpabuf_len(domain_names));
2171         if (!domain_name_list_contains(domain_names, partner->fqdn,
2172                                        partner->exact_match))
2173                 return 0;
2174         /* TODO: match Country */
2175         return 1;
2176 }
2177
2178
2179 static u8 roaming_prio(struct wpa_supplicant *wpa_s, struct wpa_cred *cred,
2180                        struct wpa_bss *bss)
2181 {
2182         size_t i;
2183
2184         if (bss->anqp == NULL || bss->anqp->domain_name == NULL) {
2185                 wpa_printf(MSG_DEBUG, "Interworking: No ANQP domain name info -> use default roaming partner priority 128");
2186                 return 128; /* cannot check preference with domain name */
2187         }
2188
2189         if (interworking_home_sp_cred(wpa_s, cred, bss->anqp->domain_name) > 0)
2190         {
2191                 wpa_printf(MSG_DEBUG, "Interworking: Determined to be home SP -> use maximum preference 0 as roaming partner priority");
2192                 return 0; /* max preference for home SP network */
2193         }
2194
2195         for (i = 0; i < cred->num_roaming_partner; i++) {
2196                 if (roaming_partner_match(wpa_s, &cred->roaming_partner[i],
2197                                           bss->anqp->domain_name)) {
2198                         wpa_printf(MSG_DEBUG, "Interworking: Roaming partner preference match - priority %u",
2199                                    cred->roaming_partner[i].priority);
2200                         return cred->roaming_partner[i].priority;
2201                 }
2202         }
2203
2204         wpa_printf(MSG_DEBUG, "Interworking: No roaming partner preference match - use default roaming partner priority 128");
2205         return 128;
2206 }
2207
2208
2209 static struct wpa_bss * pick_best_roaming_partner(struct wpa_supplicant *wpa_s,
2210                                                   struct wpa_bss *selected,
2211                                                   struct wpa_cred *cred)
2212 {
2213         struct wpa_bss *bss;
2214         u8 best_prio, prio;
2215         struct wpa_cred *cred2;
2216
2217         /*
2218          * Check if any other BSS is operated by a more preferred roaming
2219          * partner.
2220          */
2221
2222         best_prio = roaming_prio(wpa_s, cred, selected);
2223         wpa_printf(MSG_DEBUG, "Interworking: roaming_prio=%u for selected BSS "
2224                    MACSTR " (cred=%d)", best_prio, MAC2STR(selected->bssid),
2225                    cred->id);
2226
2227         dl_list_for_each(bss, &wpa_s->bss, struct wpa_bss, list) {
2228                 if (bss == selected)
2229                         continue;
2230                 cred2 = interworking_credentials_available(wpa_s, bss, NULL);
2231                 if (!cred2)
2232                         continue;
2233                 if (!wpa_bss_get_ie(bss, WLAN_EID_RSN))
2234                         continue;
2235                 prio = roaming_prio(wpa_s, cred2, bss);
2236                 wpa_printf(MSG_DEBUG, "Interworking: roaming_prio=%u for BSS "
2237                            MACSTR " (cred=%d)", prio, MAC2STR(bss->bssid),
2238                            cred2->id);
2239                 if (prio < best_prio) {
2240                         int bh1, bh2, load1, load2, conn1, conn2;
2241                         bh1 = cred_below_min_backhaul(wpa_s, cred, selected);
2242                         load1 = cred_over_max_bss_load(wpa_s, cred, selected);
2243                         conn1 = cred_conn_capab_missing(wpa_s, cred, selected);
2244                         bh2 = cred_below_min_backhaul(wpa_s, cred2, bss);
2245                         load2 = cred_over_max_bss_load(wpa_s, cred2, bss);
2246                         conn2 = cred_conn_capab_missing(wpa_s, cred2, bss);
2247                         wpa_printf(MSG_DEBUG, "Interworking: old: %d %d %d  new: %d %d %d",
2248                                    bh1, load1, conn1, bh2, load2, conn2);
2249                         if (bh1 || load1 || conn1 || !(bh2 || load2 || conn2)) {
2250                                 wpa_printf(MSG_DEBUG, "Interworking: Better roaming partner " MACSTR " selected", MAC2STR(bss->bssid));
2251                                 best_prio = prio;
2252                                 selected = bss;
2253                         }
2254                 }
2255         }
2256
2257         return selected;
2258 }
2259
2260
2261 static void interworking_select_network(struct wpa_supplicant *wpa_s)
2262 {
2263         struct wpa_bss *bss, *selected = NULL, *selected_home = NULL;
2264         struct wpa_bss *selected2 = NULL, *selected2_home = NULL;
2265         unsigned int count = 0;
2266         const char *type;
2267         int res;
2268         struct wpa_cred *cred, *selected_cred = NULL;
2269         struct wpa_cred *selected_home_cred = NULL;
2270         struct wpa_cred *selected2_cred = NULL;
2271         struct wpa_cred *selected2_home_cred = NULL;
2272
2273         wpa_s->network_select = 0;
2274
2275         wpa_printf(MSG_DEBUG, "Interworking: Select network (auto_select=%d)",
2276                    wpa_s->auto_select);
2277         dl_list_for_each(bss, &wpa_s->bss, struct wpa_bss, list) {
2278                 int excluded = 0;
2279                 int bh, bss_load, conn_capab;
2280                 cred = interworking_credentials_available(wpa_s, bss,
2281                                                           &excluded);
2282                 if (!cred)
2283                         continue;
2284                 if (!wpa_bss_get_ie(bss, WLAN_EID_RSN)) {
2285                         /*
2286                          * We currently support only HS 2.0 networks and those
2287                          * are required to use WPA2-Enterprise.
2288                          */
2289                         wpa_printf(MSG_DEBUG, "Interworking: Credential match "
2290                                    "with " MACSTR " but network does not use "
2291                                    "RSN", MAC2STR(bss->bssid));
2292                         continue;
2293                 }
2294                 if (!excluded)
2295                         count++;
2296                 res = interworking_home_sp(wpa_s, bss->anqp ?
2297                                            bss->anqp->domain_name : NULL);
2298                 if (res > 0)
2299                         type = "home";
2300                 else if (res == 0)
2301                         type = "roaming";
2302                 else
2303                         type = "unknown";
2304                 bh = cred_below_min_backhaul(wpa_s, cred, bss);
2305                 bss_load = cred_over_max_bss_load(wpa_s, cred, bss);
2306                 conn_capab = cred_conn_capab_missing(wpa_s, cred, bss);
2307                 wpa_msg(wpa_s, MSG_INFO, "%s" MACSTR " type=%s%s%s%s id=%d priority=%d sp_priority=%d",
2308                         excluded ? INTERWORKING_BLACKLISTED : INTERWORKING_AP,
2309                         MAC2STR(bss->bssid), type,
2310                         bh ? " below_min_backhaul=1" : "",
2311                         bss_load ? " over_max_bss_load=1" : "",
2312                         conn_capab ? " conn_capab_missing=1" : "",
2313                         cred->id, cred->priority, cred->sp_priority);
2314                 if (excluded)
2315                         continue;
2316                 if (wpa_s->auto_select ||
2317                     (wpa_s->conf->auto_interworking &&
2318                      wpa_s->auto_network_select)) {
2319                         if (bh || bss_load || conn_capab) {
2320                                 if (selected2_cred == NULL ||
2321                                     cred_prio_cmp(cred, selected2_cred) > 0) {
2322                                         wpa_printf(MSG_DEBUG, "Interworking: Mark as selected2");
2323                                         selected2 = bss;
2324                                         selected2_cred = cred;
2325                                 }
2326                                 if (res > 0 &&
2327                                     (selected2_home_cred == NULL ||
2328                                      cred_prio_cmp(cred, selected2_home_cred) >
2329                                      0)) {
2330                                         wpa_printf(MSG_DEBUG, "Interworking: Mark as selected2_home");
2331                                         selected2_home = bss;
2332                                         selected2_home_cred = cred;
2333                                 }
2334                         } else {
2335                                 if (selected_cred == NULL ||
2336                                     cred_prio_cmp(cred, selected_cred) > 0) {
2337                                         wpa_printf(MSG_DEBUG, "Interworking: Mark as selected");
2338                                         selected = bss;
2339                                         selected_cred = cred;
2340                                 }
2341                                 if (res > 0 &&
2342                                     (selected_home_cred == NULL ||
2343                                      cred_prio_cmp(cred, selected_home_cred) >
2344                                      0)) {
2345                                         wpa_printf(MSG_DEBUG, "Interworking: Mark as selected_home");
2346                                         selected_home = bss;
2347                                         selected_home_cred = cred;
2348                                 }
2349                         }
2350                 }
2351         }
2352
2353         if (selected_home && selected_home != selected &&
2354             selected_home_cred &&
2355             (selected_cred == NULL ||
2356              cred_prio_cmp(selected_home_cred, selected_cred) >= 0)) {
2357                 /* Prefer network operated by the Home SP */
2358                 wpa_printf(MSG_DEBUG, "Interworking: Overrided selected with selected_home");
2359                 selected = selected_home;
2360                 selected_cred = selected_home_cred;
2361         }
2362
2363         if (!selected) {
2364                 if (selected2_home) {
2365                         wpa_printf(MSG_DEBUG, "Interworking: Use home BSS with BW limit mismatch since no other network could be selected");
2366                         selected = selected2_home;
2367                         selected_cred = selected2_home_cred;
2368                 } else if (selected2) {
2369                         wpa_printf(MSG_DEBUG, "Interworking: Use visited BSS with BW limit mismatch since no other network could be selected");
2370                         selected = selected2;
2371                         selected_cred = selected2_cred;
2372                 }
2373         }
2374
2375         if (count == 0) {
2376                 /*
2377                  * No matching network was found based on configured
2378                  * credentials. Check whether any of the enabled network blocks
2379                  * have matching APs.
2380                  */
2381                 if (interworking_find_network_match(wpa_s)) {
2382                         wpa_printf(MSG_DEBUG, "Interworking: Possible BSS "
2383                                    "match for enabled network configurations");
2384                         if (wpa_s->auto_select)
2385                                 interworking_reconnect(wpa_s);
2386                         return;
2387                 }
2388
2389                 if (wpa_s->auto_network_select) {
2390                         wpa_printf(MSG_DEBUG, "Interworking: Continue "
2391                                    "scanning after ANQP fetch");
2392                         wpa_supplicant_req_scan(wpa_s, wpa_s->scan_interval,
2393                                                 0);
2394                         return;
2395                 }
2396
2397                 wpa_msg(wpa_s, MSG_INFO, INTERWORKING_NO_MATCH "No network "
2398                         "with matching credentials found");
2399         }
2400
2401         if (selected) {
2402                 wpa_printf(MSG_DEBUG, "Interworking: Selected " MACSTR,
2403                            MAC2STR(selected->bssid));
2404                 selected = pick_best_roaming_partner(wpa_s, selected,
2405                                                      selected_cred);
2406                 wpa_printf(MSG_DEBUG, "Interworking: Selected " MACSTR
2407                            " (after best roaming partner selection)",
2408                            MAC2STR(selected->bssid));
2409                 wpa_msg(wpa_s, MSG_INFO, INTERWORKING_SELECTED MACSTR,
2410                         MAC2STR(selected->bssid));
2411                 interworking_connect(wpa_s, selected);
2412         }
2413 }
2414
2415
2416 static struct wpa_bss_anqp *
2417 interworking_match_anqp_info(struct wpa_supplicant *wpa_s, struct wpa_bss *bss)
2418 {
2419         struct wpa_bss *other;
2420
2421         if (is_zero_ether_addr(bss->hessid))
2422                 return NULL; /* Cannot be in the same homegenous ESS */
2423
2424         dl_list_for_each(other, &wpa_s->bss, struct wpa_bss, list) {
2425                 if (other == bss)
2426                         continue;
2427                 if (other->anqp == NULL)
2428                         continue;
2429                 if (other->anqp->roaming_consortium == NULL &&
2430                     other->anqp->nai_realm == NULL &&
2431                     other->anqp->anqp_3gpp == NULL &&
2432                     other->anqp->domain_name == NULL)
2433                         continue;
2434                 if (!(other->flags & WPA_BSS_ANQP_FETCH_TRIED))
2435                         continue;
2436                 if (os_memcmp(bss->hessid, other->hessid, ETH_ALEN) != 0)
2437                         continue;
2438                 if (bss->ssid_len != other->ssid_len ||
2439                     os_memcmp(bss->ssid, other->ssid, bss->ssid_len) != 0)
2440                         continue;
2441
2442                 wpa_printf(MSG_DEBUG, "Interworking: Share ANQP data with "
2443                            "already fetched BSSID " MACSTR " and " MACSTR,
2444                            MAC2STR(other->bssid), MAC2STR(bss->bssid));
2445                 other->anqp->users++;
2446                 return other->anqp;
2447         }
2448
2449         return NULL;
2450 }
2451
2452
2453 static void interworking_next_anqp_fetch(struct wpa_supplicant *wpa_s)
2454 {
2455         struct wpa_bss *bss;
2456         int found = 0;
2457         const u8 *ie;
2458
2459         wpa_printf(MSG_DEBUG, "Interworking: next_anqp_fetch - "
2460                    "fetch_anqp_in_progress=%d fetch_osu_icon_in_progress=%d",
2461                    wpa_s->fetch_anqp_in_progress,
2462                    wpa_s->fetch_osu_icon_in_progress);
2463
2464         if (eloop_terminated() || !wpa_s->fetch_anqp_in_progress) {
2465                 wpa_printf(MSG_DEBUG, "Interworking: Stop next-ANQP-fetch");
2466                 return;
2467         }
2468
2469         if (wpa_s->fetch_osu_icon_in_progress) {
2470                 wpa_printf(MSG_DEBUG, "Interworking: Next icon (in progress)");
2471                 hs20_next_osu_icon(wpa_s);
2472                 return;
2473         }
2474
2475         dl_list_for_each(bss, &wpa_s->bss, struct wpa_bss, list) {
2476                 if (!(bss->caps & IEEE80211_CAP_ESS))
2477                         continue;
2478                 ie = wpa_bss_get_ie(bss, WLAN_EID_EXT_CAPAB);
2479                 if (ie == NULL || ie[1] < 4 || !(ie[5] & 0x80))
2480                         continue; /* AP does not support Interworking */
2481                 if (disallowed_bssid(wpa_s, bss->bssid) ||
2482                     disallowed_ssid(wpa_s, bss->ssid, bss->ssid_len))
2483                         continue; /* Disallowed BSS */
2484
2485                 if (!(bss->flags & WPA_BSS_ANQP_FETCH_TRIED)) {
2486                         if (bss->anqp == NULL) {
2487                                 bss->anqp = interworking_match_anqp_info(wpa_s,
2488                                                                          bss);
2489                                 if (bss->anqp) {
2490                                         /* Shared data already fetched */
2491                                         continue;
2492                                 }
2493                                 bss->anqp = wpa_bss_anqp_alloc();
2494                                 if (bss->anqp == NULL)
2495                                         break;
2496                         }
2497                         found++;
2498                         bss->flags |= WPA_BSS_ANQP_FETCH_TRIED;
2499                         wpa_msg(wpa_s, MSG_INFO, "Starting ANQP fetch for "
2500                                 MACSTR, MAC2STR(bss->bssid));
2501                         interworking_anqp_send_req(wpa_s, bss);
2502                         break;
2503                 }
2504         }
2505
2506         if (found == 0) {
2507                 if (wpa_s->fetch_osu_info) {
2508                         if (wpa_s->num_prov_found == 0 &&
2509                             wpa_s->num_osu_scans < 3) {
2510                                 wpa_printf(MSG_DEBUG, "HS 2.0: No OSU providers seen - try to scan again");
2511                                 hs20_start_osu_scan(wpa_s);
2512                                 return;
2513                         }
2514                         wpa_printf(MSG_DEBUG, "Interworking: Next icon");
2515                         hs20_osu_icon_fetch(wpa_s);
2516                         return;
2517                 }
2518                 wpa_msg(wpa_s, MSG_INFO, "ANQP fetch completed");
2519                 wpa_s->fetch_anqp_in_progress = 0;
2520                 if (wpa_s->network_select)
2521                         interworking_select_network(wpa_s);
2522         }
2523 }
2524
2525
2526 void interworking_start_fetch_anqp(struct wpa_supplicant *wpa_s)
2527 {
2528         struct wpa_bss *bss;
2529
2530         dl_list_for_each(bss, &wpa_s->bss, struct wpa_bss, list)
2531                 bss->flags &= ~WPA_BSS_ANQP_FETCH_TRIED;
2532
2533         wpa_s->fetch_anqp_in_progress = 1;
2534         interworking_next_anqp_fetch(wpa_s);
2535 }
2536
2537
2538 int interworking_fetch_anqp(struct wpa_supplicant *wpa_s)
2539 {
2540         if (wpa_s->fetch_anqp_in_progress || wpa_s->network_select)
2541                 return 0;
2542
2543         wpa_s->network_select = 0;
2544         wpa_s->fetch_all_anqp = 1;
2545         wpa_s->fetch_osu_info = 0;
2546
2547         interworking_start_fetch_anqp(wpa_s);
2548
2549         return 0;
2550 }
2551
2552
2553 void interworking_stop_fetch_anqp(struct wpa_supplicant *wpa_s)
2554 {
2555         if (!wpa_s->fetch_anqp_in_progress)
2556                 return;
2557
2558         wpa_s->fetch_anqp_in_progress = 0;
2559 }
2560
2561
2562 int anqp_send_req(struct wpa_supplicant *wpa_s, const u8 *dst,
2563                   u16 info_ids[], size_t num_ids, u32 subtypes)
2564 {
2565         struct wpabuf *buf;
2566         struct wpabuf *hs20_buf = NULL;
2567         int ret = 0;
2568         int freq;
2569         struct wpa_bss *bss;
2570         int res;
2571
2572         freq = wpa_s->assoc_freq;
2573         bss = wpa_bss_get_bssid(wpa_s, dst);
2574         if (bss) {
2575                 wpa_bss_anqp_unshare_alloc(bss);
2576                 freq = bss->freq;
2577         }
2578         if (freq <= 0)
2579                 return -1;
2580
2581         wpa_printf(MSG_DEBUG, "ANQP: Query Request to " MACSTR " for %u id(s)",
2582                    MAC2STR(dst), (unsigned int) num_ids);
2583
2584 #ifdef CONFIG_HS20
2585         if (subtypes != 0) {
2586                 hs20_buf = wpabuf_alloc(100);
2587                 if (hs20_buf == NULL)
2588                         return -1;
2589                 hs20_put_anqp_req(subtypes, NULL, 0, hs20_buf);
2590         }
2591 #endif /* CONFIG_HS20 */
2592
2593         buf = anqp_build_req(info_ids, num_ids, hs20_buf);
2594         wpabuf_free(hs20_buf);
2595         if (buf == NULL)
2596                 return -1;
2597
2598         res = gas_query_req(wpa_s->gas, dst, freq, buf, anqp_resp_cb, wpa_s);
2599         if (res < 0) {
2600                 wpa_printf(MSG_DEBUG, "ANQP: Failed to send Query Request");
2601                 wpabuf_free(buf);
2602                 ret = -1;
2603         } else
2604                 wpa_printf(MSG_DEBUG, "ANQP: Query started with dialog token "
2605                            "%u", res);
2606
2607         return ret;
2608 }
2609
2610
2611 static void interworking_parse_rx_anqp_resp(struct wpa_supplicant *wpa_s,
2612                                             struct wpa_bss *bss, const u8 *sa,
2613                                             u16 info_id,
2614                                             const u8 *data, size_t slen)
2615 {
2616         const u8 *pos = data;
2617         struct wpa_bss_anqp *anqp = NULL;
2618 #ifdef CONFIG_HS20
2619         u8 type;
2620 #endif /* CONFIG_HS20 */
2621
2622         if (bss)
2623                 anqp = bss->anqp;
2624
2625         switch (info_id) {
2626         case ANQP_CAPABILITY_LIST:
2627                 wpa_msg(wpa_s, MSG_INFO, "RX-ANQP " MACSTR
2628                         " ANQP Capability list", MAC2STR(sa));
2629                 break;
2630         case ANQP_VENUE_NAME:
2631                 wpa_msg(wpa_s, MSG_INFO, "RX-ANQP " MACSTR
2632                         " Venue Name", MAC2STR(sa));
2633                 wpa_hexdump_ascii(MSG_DEBUG, "ANQP: Venue Name", pos, slen);
2634                 if (anqp) {
2635                         wpabuf_free(anqp->venue_name);
2636                         anqp->venue_name = wpabuf_alloc_copy(pos, slen);
2637                 }
2638                 break;
2639         case ANQP_NETWORK_AUTH_TYPE:
2640                 wpa_msg(wpa_s, MSG_INFO, "RX-ANQP " MACSTR
2641                         " Network Authentication Type information",
2642                         MAC2STR(sa));
2643                 wpa_hexdump_ascii(MSG_DEBUG, "ANQP: Network Authentication "
2644                                   "Type", pos, slen);
2645                 if (anqp) {
2646                         wpabuf_free(anqp->network_auth_type);
2647                         anqp->network_auth_type = wpabuf_alloc_copy(pos, slen);
2648                 }
2649                 break;
2650         case ANQP_ROAMING_CONSORTIUM:
2651                 wpa_msg(wpa_s, MSG_INFO, "RX-ANQP " MACSTR
2652                         " Roaming Consortium list", MAC2STR(sa));
2653                 wpa_hexdump_ascii(MSG_DEBUG, "ANQP: Roaming Consortium",
2654                                   pos, slen);
2655                 if (anqp) {
2656                         wpabuf_free(anqp->roaming_consortium);
2657                         anqp->roaming_consortium = wpabuf_alloc_copy(pos, slen);
2658                 }
2659                 break;
2660         case ANQP_IP_ADDR_TYPE_AVAILABILITY:
2661                 wpa_msg(wpa_s, MSG_INFO, "RX-ANQP " MACSTR
2662                         " IP Address Type Availability information",
2663                         MAC2STR(sa));
2664                 wpa_hexdump(MSG_MSGDUMP, "ANQP: IP Address Availability",
2665                             pos, slen);
2666                 if (anqp) {
2667                         wpabuf_free(anqp->ip_addr_type_availability);
2668                         anqp->ip_addr_type_availability =
2669                                 wpabuf_alloc_copy(pos, slen);
2670                 }
2671                 break;
2672         case ANQP_NAI_REALM:
2673                 wpa_msg(wpa_s, MSG_INFO, "RX-ANQP " MACSTR
2674                         " NAI Realm list", MAC2STR(sa));
2675                 wpa_hexdump_ascii(MSG_DEBUG, "ANQP: NAI Realm", pos, slen);
2676                 if (anqp) {
2677                         wpabuf_free(anqp->nai_realm);
2678                         anqp->nai_realm = wpabuf_alloc_copy(pos, slen);
2679                 }
2680                 break;
2681         case ANQP_3GPP_CELLULAR_NETWORK:
2682                 wpa_msg(wpa_s, MSG_INFO, "RX-ANQP " MACSTR
2683                         " 3GPP Cellular Network information", MAC2STR(sa));
2684                 wpa_hexdump_ascii(MSG_DEBUG, "ANQP: 3GPP Cellular Network",
2685                                   pos, slen);
2686                 if (anqp) {
2687                         wpabuf_free(anqp->anqp_3gpp);
2688                         anqp->anqp_3gpp = wpabuf_alloc_copy(pos, slen);
2689                 }
2690                 break;
2691         case ANQP_DOMAIN_NAME:
2692                 wpa_msg(wpa_s, MSG_INFO, "RX-ANQP " MACSTR
2693                         " Domain Name list", MAC2STR(sa));
2694                 wpa_hexdump_ascii(MSG_MSGDUMP, "ANQP: Domain Name", pos, slen);
2695                 if (anqp) {
2696                         wpabuf_free(anqp->domain_name);
2697                         anqp->domain_name = wpabuf_alloc_copy(pos, slen);
2698                 }
2699                 break;
2700         case ANQP_VENDOR_SPECIFIC:
2701                 if (slen < 3)
2702                         return;
2703
2704                 switch (WPA_GET_BE24(pos)) {
2705 #ifdef CONFIG_HS20
2706                 case OUI_WFA:
2707                         pos += 3;
2708                         slen -= 3;
2709
2710                         if (slen < 1)
2711                                 return;
2712                         type = *pos++;
2713                         slen--;
2714
2715                         switch (type) {
2716                         case HS20_ANQP_OUI_TYPE:
2717                                 hs20_parse_rx_hs20_anqp_resp(wpa_s, sa, pos,
2718                                                              slen);
2719                                 break;
2720                         default:
2721                                 wpa_printf(MSG_DEBUG, "HS20: Unsupported ANQP "
2722                                            "vendor type %u", type);
2723                                 break;
2724                         }
2725                         break;
2726 #endif /* CONFIG_HS20 */
2727                 default:
2728                         wpa_printf(MSG_DEBUG, "Interworking: Unsupported "
2729                                    "vendor-specific ANQP OUI %06x",
2730                                    WPA_GET_BE24(pos));
2731                         return;
2732                 }
2733                 break;
2734         default:
2735                 wpa_printf(MSG_DEBUG, "Interworking: Unsupported ANQP Info ID "
2736                            "%u", info_id);
2737                 break;
2738         }
2739 }
2740
2741
2742 void anqp_resp_cb(void *ctx, const u8 *dst, u8 dialog_token,
2743                   enum gas_query_result result,
2744                   const struct wpabuf *adv_proto,
2745                   const struct wpabuf *resp, u16 status_code)
2746 {
2747         struct wpa_supplicant *wpa_s = ctx;
2748         const u8 *pos;
2749         const u8 *end;
2750         u16 info_id;
2751         u16 slen;
2752         struct wpa_bss *bss = NULL, *tmp;
2753
2754         wpa_printf(MSG_DEBUG, "Interworking: anqp_resp_cb dst=" MACSTR
2755                    " dialog_token=%u result=%d status_code=%u",
2756                    MAC2STR(dst), dialog_token, result, status_code);
2757         if (result != GAS_QUERY_SUCCESS) {
2758                 if (wpa_s->fetch_osu_icon_in_progress)
2759                         hs20_icon_fetch_failed(wpa_s);
2760                 return;
2761         }
2762
2763         pos = wpabuf_head(adv_proto);
2764         if (wpabuf_len(adv_proto) < 4 || pos[0] != WLAN_EID_ADV_PROTO ||
2765             pos[1] < 2 || pos[3] != ACCESS_NETWORK_QUERY_PROTOCOL) {
2766                 wpa_printf(MSG_DEBUG, "ANQP: Unexpected Advertisement "
2767                            "Protocol in response");
2768                 if (wpa_s->fetch_osu_icon_in_progress)
2769                         hs20_icon_fetch_failed(wpa_s);
2770                 return;
2771         }
2772
2773         /*
2774          * If possible, select the BSS entry based on which BSS entry was used
2775          * for the request. This can help in cases where multiple BSS entries
2776          * may exist for the same AP.
2777          */
2778         dl_list_for_each_reverse(tmp, &wpa_s->bss, struct wpa_bss, list) {
2779                 if (tmp == wpa_s->interworking_gas_bss &&
2780                     os_memcmp(tmp->bssid, dst, ETH_ALEN) == 0) {
2781                         bss = tmp;
2782                         break;
2783                 }
2784         }
2785         if (bss == NULL)
2786                 bss = wpa_bss_get_bssid(wpa_s, dst);
2787
2788         pos = wpabuf_head(resp);
2789         end = pos + wpabuf_len(resp);
2790
2791         while (pos < end) {
2792                 if (pos + 4 > end) {
2793                         wpa_printf(MSG_DEBUG, "ANQP: Invalid element");
2794                         break;
2795                 }
2796                 info_id = WPA_GET_LE16(pos);
2797                 pos += 2;
2798                 slen = WPA_GET_LE16(pos);
2799                 pos += 2;
2800                 if (pos + slen > end) {
2801                         wpa_printf(MSG_DEBUG, "ANQP: Invalid element length "
2802                                    "for Info ID %u", info_id);
2803                         break;
2804                 }
2805                 interworking_parse_rx_anqp_resp(wpa_s, bss, dst, info_id, pos,
2806                                                 slen);
2807                 pos += slen;
2808         }
2809
2810         hs20_notify_parse_done(wpa_s);
2811 }
2812
2813
2814 static void interworking_scan_res_handler(struct wpa_supplicant *wpa_s,
2815                                           struct wpa_scan_results *scan_res)
2816 {
2817         wpa_printf(MSG_DEBUG, "Interworking: Scan results available - start "
2818                    "ANQP fetch");
2819         interworking_start_fetch_anqp(wpa_s);
2820 }
2821
2822
2823 int interworking_select(struct wpa_supplicant *wpa_s, int auto_select,
2824                         int *freqs)
2825 {
2826         interworking_stop_fetch_anqp(wpa_s);
2827         wpa_s->network_select = 1;
2828         wpa_s->auto_network_select = 0;
2829         wpa_s->auto_select = !!auto_select;
2830         wpa_s->fetch_all_anqp = 0;
2831         wpa_s->fetch_osu_info = 0;
2832         wpa_printf(MSG_DEBUG, "Interworking: Start scan for network "
2833                    "selection");
2834         wpa_s->scan_res_handler = interworking_scan_res_handler;
2835         wpa_s->normal_scans = 0;
2836         wpa_s->scan_req = MANUAL_SCAN_REQ;
2837         os_free(wpa_s->manual_scan_freqs);
2838         wpa_s->manual_scan_freqs = freqs;
2839         wpa_s->after_wps = 0;
2840         wpa_s->known_wps_freq = 0;
2841         wpa_supplicant_req_scan(wpa_s, 0, 0);
2842
2843         return 0;
2844 }
2845
2846
2847 static void gas_resp_cb(void *ctx, const u8 *addr, u8 dialog_token,
2848                         enum gas_query_result result,
2849                         const struct wpabuf *adv_proto,
2850                         const struct wpabuf *resp, u16 status_code)
2851 {
2852         struct wpa_supplicant *wpa_s = ctx;
2853         struct wpabuf *n;
2854
2855         wpa_msg(wpa_s, MSG_INFO, GAS_RESPONSE_INFO "addr=" MACSTR
2856                 " dialog_token=%d status_code=%d resp_len=%d",
2857                 MAC2STR(addr), dialog_token, status_code,
2858                 resp ? (int) wpabuf_len(resp) : -1);
2859         if (!resp)
2860                 return;
2861
2862         n = wpabuf_dup(resp);
2863         if (n == NULL)
2864                 return;
2865         wpabuf_free(wpa_s->prev_gas_resp);
2866         wpa_s->prev_gas_resp = wpa_s->last_gas_resp;
2867         os_memcpy(wpa_s->prev_gas_addr, wpa_s->last_gas_addr, ETH_ALEN);
2868         wpa_s->prev_gas_dialog_token = wpa_s->last_gas_dialog_token;
2869         wpa_s->last_gas_resp = n;
2870         os_memcpy(wpa_s->last_gas_addr, addr, ETH_ALEN);
2871         wpa_s->last_gas_dialog_token = dialog_token;
2872 }
2873
2874
2875 int gas_send_request(struct wpa_supplicant *wpa_s, const u8 *dst,
2876                      const struct wpabuf *adv_proto,
2877                      const struct wpabuf *query)
2878 {
2879         struct wpabuf *buf;
2880         int ret = 0;
2881         int freq;
2882         struct wpa_bss *bss;
2883         int res;
2884         size_t len;
2885         u8 query_resp_len_limit = 0, pame_bi = 0;
2886
2887         freq = wpa_s->assoc_freq;
2888         bss = wpa_bss_get_bssid(wpa_s, dst);
2889         if (bss)
2890                 freq = bss->freq;
2891         if (freq <= 0)
2892                 return -1;
2893
2894         wpa_printf(MSG_DEBUG, "GAS request to " MACSTR " (freq %d MHz)",
2895                    MAC2STR(dst), freq);
2896         wpa_hexdump_buf(MSG_DEBUG, "Advertisement Protocol ID", adv_proto);
2897         wpa_hexdump_buf(MSG_DEBUG, "GAS Query", query);
2898
2899         len = 3 + wpabuf_len(adv_proto) + 2;
2900         if (query)
2901                 len += wpabuf_len(query);
2902         buf = gas_build_initial_req(0, len);
2903         if (buf == NULL)
2904                 return -1;
2905
2906         /* Advertisement Protocol IE */
2907         wpabuf_put_u8(buf, WLAN_EID_ADV_PROTO);
2908         wpabuf_put_u8(buf, 1 + wpabuf_len(adv_proto)); /* Length */
2909         wpabuf_put_u8(buf, (query_resp_len_limit & 0x7f) |
2910                       (pame_bi ? 0x80 : 0));
2911         wpabuf_put_buf(buf, adv_proto);
2912
2913         /* GAS Query */
2914         if (query) {
2915                 wpabuf_put_le16(buf, wpabuf_len(query));
2916                 wpabuf_put_buf(buf, query);
2917         } else
2918                 wpabuf_put_le16(buf, 0);
2919
2920         res = gas_query_req(wpa_s->gas, dst, freq, buf, gas_resp_cb, wpa_s);
2921         if (res < 0) {
2922                 wpa_printf(MSG_DEBUG, "GAS: Failed to send Query Request");
2923                 wpabuf_free(buf);
2924                 ret = -1;
2925         } else
2926                 wpa_printf(MSG_DEBUG, "GAS: Query started with dialog token "
2927                            "%u", res);
2928
2929         return ret;
2930 }