Interworking: Init scard when a credential requires SIM access
[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 static struct wpa_cred * interworking_credentials_available_3gpp(
1754         struct wpa_supplicant *wpa_s, struct wpa_bss *bss, int ignore_bw,
1755         int *excluded)
1756 {
1757         struct wpa_cred *selected = NULL;
1758 #ifdef INTERWORKING_3GPP
1759         struct wpa_cred *cred;
1760         int ret;
1761         int is_excluded = 0;
1762
1763         if (bss->anqp == NULL || bss->anqp->anqp_3gpp == NULL)
1764                 return NULL;
1765
1766 #ifdef CONFIG_EAP_PROXY
1767         if (!wpa_s->imsi[0]) {
1768                 size_t len;
1769                 wpa_printf(MSG_DEBUG, "Interworking: IMSI not available - try to read again through eap_proxy");
1770                 wpa_s->mnc_len = eapol_sm_get_eap_proxy_imsi(wpa_s->eapol,
1771                                                              wpa_s->imsi,
1772                                                              &len);
1773                 if (wpa_s->mnc_len > 0) {
1774                         wpa_s->imsi[len] = '\0';
1775                         wpa_printf(MSG_DEBUG, "eap_proxy: IMSI %s (MNC length %d)",
1776                                    wpa_s->imsi, wpa_s->mnc_len);
1777                 } else {
1778                         wpa_printf(MSG_DEBUG, "eap_proxy: IMSI not available");
1779                 }
1780         }
1781 #endif /* CONFIG_EAP_PROXY */
1782
1783         for (cred = wpa_s->conf->cred; cred; cred = cred->next) {
1784                 char *sep;
1785                 const char *imsi;
1786                 int mnc_len;
1787                 char imsi_buf[16];
1788                 size_t msin_len;
1789
1790 #ifdef PCSC_FUNCS
1791                 if (cred->pcsc && wpa_s->conf->pcsc_reader && wpa_s->scard &&
1792                     wpa_s->imsi[0]) {
1793                         imsi = wpa_s->imsi;
1794                         mnc_len = wpa_s->mnc_len;
1795                         goto compare;
1796                 }
1797 #endif /* PCSC_FUNCS */
1798 #ifdef CONFIG_EAP_PROXY
1799                 if (cred->pcsc && wpa_s->mnc_len > 0 && wpa_s->imsi[0]) {
1800                         imsi = wpa_s->imsi;
1801                         mnc_len = wpa_s->mnc_len;
1802                         goto compare;
1803                 }
1804 #endif /* CONFIG_EAP_PROXY */
1805
1806                 if (cred->imsi == NULL || !cred->imsi[0] ||
1807                     (!wpa_s->conf->external_sim &&
1808                      (cred->milenage == NULL || !cred->milenage[0])))
1809                         continue;
1810
1811                 sep = os_strchr(cred->imsi, '-');
1812                 if (sep == NULL ||
1813                     (sep - cred->imsi != 5 && sep - cred->imsi != 6))
1814                         continue;
1815                 mnc_len = sep - cred->imsi - 3;
1816                 os_memcpy(imsi_buf, cred->imsi, 3 + mnc_len);
1817                 sep++;
1818                 msin_len = os_strlen(cred->imsi);
1819                 if (3 + mnc_len + msin_len >= sizeof(imsi_buf) - 1)
1820                         msin_len = sizeof(imsi_buf) - 3 - mnc_len - 1;
1821                 os_memcpy(&imsi_buf[3 + mnc_len], sep, msin_len);
1822                 imsi_buf[3 + mnc_len + msin_len] = '\0';
1823                 imsi = imsi_buf;
1824
1825 #if defined(PCSC_FUNCS) || defined(CONFIG_EAP_PROXY)
1826         compare:
1827 #endif /* PCSC_FUNCS || CONFIG_EAP_PROXY */
1828                 wpa_printf(MSG_DEBUG, "Interworking: Parsing 3GPP info from "
1829                            MACSTR, MAC2STR(bss->bssid));
1830                 ret = plmn_id_match(bss->anqp->anqp_3gpp, imsi, mnc_len);
1831                 wpa_printf(MSG_DEBUG, "PLMN match %sfound", ret ? "" : "not ");
1832                 if (ret) {
1833                         if (cred_no_required_oi_match(cred, bss))
1834                                 continue;
1835                         if (!ignore_bw &&
1836                             cred_below_min_backhaul(wpa_s, cred, bss))
1837                                 continue;
1838                         if (!ignore_bw &&
1839                             cred_over_max_bss_load(wpa_s, cred, bss))
1840                                 continue;
1841                         if (!ignore_bw &&
1842                             cred_conn_capab_missing(wpa_s, cred, bss))
1843                                 continue;
1844                         if (cred_excluded_ssid(cred, bss)) {
1845                                 if (excluded == NULL)
1846                                         continue;
1847                                 if (selected == NULL) {
1848                                         selected = cred;
1849                                         is_excluded = 1;
1850                                 }
1851                         } else {
1852                                 if (selected == NULL || is_excluded ||
1853                                     cred_prio_cmp(selected, cred) < 0) {
1854                                         selected = cred;
1855                                         is_excluded = 0;
1856                                 }
1857                         }
1858                 }
1859         }
1860
1861         if (excluded)
1862                 *excluded = is_excluded;
1863 #endif /* INTERWORKING_3GPP */
1864         return selected;
1865 }
1866
1867
1868 static struct wpa_cred * interworking_credentials_available_realm(
1869         struct wpa_supplicant *wpa_s, struct wpa_bss *bss, int ignore_bw,
1870         int *excluded)
1871 {
1872         struct wpa_cred *cred, *selected = NULL;
1873         struct nai_realm *realm;
1874         u16 count, i;
1875         int is_excluded = 0;
1876
1877         if (bss->anqp == NULL || bss->anqp->nai_realm == NULL)
1878                 return NULL;
1879
1880         if (wpa_s->conf->cred == NULL)
1881                 return NULL;
1882
1883         wpa_printf(MSG_DEBUG, "Interworking: Parsing NAI Realm list from "
1884                    MACSTR, MAC2STR(bss->bssid));
1885         realm = nai_realm_parse(bss->anqp->nai_realm, &count);
1886         if (realm == NULL) {
1887                 wpa_printf(MSG_DEBUG, "Interworking: Could not parse NAI "
1888                            "Realm list from " MACSTR, MAC2STR(bss->bssid));
1889                 return NULL;
1890         }
1891
1892         for (cred = wpa_s->conf->cred; cred; cred = cred->next) {
1893                 if (cred->realm == NULL)
1894                         continue;
1895
1896                 for (i = 0; i < count; i++) {
1897                         if (!nai_realm_match(&realm[i], cred->realm))
1898                                 continue;
1899                         if (nai_realm_find_eap(cred, &realm[i])) {
1900                                 if (cred_no_required_oi_match(cred, bss))
1901                                         continue;
1902                                 if (!ignore_bw &&
1903                                     cred_below_min_backhaul(wpa_s, cred, bss))
1904                                         continue;
1905                                 if (!ignore_bw &&
1906                                     cred_over_max_bss_load(wpa_s, cred, bss))
1907                                         continue;
1908                                 if (!ignore_bw &&
1909                                     cred_conn_capab_missing(wpa_s, cred, bss))
1910                                         continue;
1911                                 if (cred_excluded_ssid(cred, bss)) {
1912                                         if (excluded == NULL)
1913                                                 continue;
1914                                         if (selected == NULL) {
1915                                                 selected = cred;
1916                                                 is_excluded = 1;
1917                                         }
1918                                 } else {
1919                                         if (selected == NULL || is_excluded ||
1920                                             cred_prio_cmp(selected, cred) < 0)
1921                                         {
1922                                                 selected = cred;
1923                                                 is_excluded = 0;
1924                                         }
1925                                 }
1926                                 break;
1927                         }
1928                 }
1929         }
1930
1931         nai_realm_free(realm, count);
1932
1933         if (excluded)
1934                 *excluded = is_excluded;
1935
1936         return selected;
1937 }
1938
1939
1940 static struct wpa_cred * interworking_credentials_available_helper(
1941         struct wpa_supplicant *wpa_s, struct wpa_bss *bss, int ignore_bw,
1942         int *excluded)
1943 {
1944         struct wpa_cred *cred, *cred2;
1945         int excluded1, excluded2;
1946
1947         if (disallowed_bssid(wpa_s, bss->bssid) ||
1948             disallowed_ssid(wpa_s, bss->ssid, bss->ssid_len)) {
1949                 wpa_printf(MSG_DEBUG, "Interworking: Ignore disallowed BSS "
1950                            MACSTR, MAC2STR(bss->bssid));
1951                 return NULL;
1952         }
1953
1954         cred = interworking_credentials_available_realm(wpa_s, bss, ignore_bw,
1955                                                         &excluded1);
1956         cred2 = interworking_credentials_available_3gpp(wpa_s, bss, ignore_bw,
1957                                                         &excluded2);
1958         if (cred && cred2 &&
1959             (cred_prio_cmp(cred2, cred) >= 0 || (!excluded2 && excluded1))) {
1960                 cred = cred2;
1961                 excluded1 = excluded2;
1962         }
1963         if (!cred) {
1964                 cred = cred2;
1965                 excluded1 = excluded2;
1966         }
1967
1968         cred2 = interworking_credentials_available_roaming_consortium(
1969                 wpa_s, bss, ignore_bw, &excluded2);
1970         if (cred && cred2 &&
1971             (cred_prio_cmp(cred2, cred) >= 0 || (!excluded2 && excluded1))) {
1972                 cred = cred2;
1973                 excluded1 = excluded2;
1974         }
1975         if (!cred) {
1976                 cred = cred2;
1977                 excluded1 = excluded2;
1978         }
1979
1980         if (excluded)
1981                 *excluded = excluded1;
1982         return cred;
1983 }
1984
1985
1986 static struct wpa_cred * interworking_credentials_available(
1987         struct wpa_supplicant *wpa_s, struct wpa_bss *bss, int *excluded)
1988 {
1989         struct wpa_cred *cred;
1990
1991         if (excluded)
1992                 *excluded = 0;
1993         cred = interworking_credentials_available_helper(wpa_s, bss, 0,
1994                                                          excluded);
1995         if (cred)
1996                 return cred;
1997         return interworking_credentials_available_helper(wpa_s, bss, 1,
1998                                                          excluded);
1999 }
2000
2001
2002 int domain_name_list_contains(struct wpabuf *domain_names,
2003                               const char *domain, int exact_match)
2004 {
2005         const u8 *pos, *end;
2006         size_t len;
2007
2008         len = os_strlen(domain);
2009         pos = wpabuf_head(domain_names);
2010         end = pos + wpabuf_len(domain_names);
2011
2012         while (pos + 1 < end) {
2013                 if (pos + 1 + pos[0] > end)
2014                         break;
2015
2016                 wpa_hexdump_ascii(MSG_DEBUG, "Interworking: AP domain name",
2017                                   pos + 1, pos[0]);
2018                 if (pos[0] == len &&
2019                     os_strncasecmp(domain, (const char *) (pos + 1), len) == 0)
2020                         return 1;
2021                 if (!exact_match && pos[0] > len && pos[pos[0] - len] == '.') {
2022                         const char *ap = (const char *) (pos + 1);
2023                         int offset = pos[0] - len;
2024                         if (os_strncasecmp(domain, ap + offset, len) == 0)
2025                                 return 1;
2026                 }
2027
2028                 pos += 1 + pos[0];
2029         }
2030
2031         return 0;
2032 }
2033
2034
2035 int interworking_home_sp_cred(struct wpa_supplicant *wpa_s,
2036                               struct wpa_cred *cred,
2037                               struct wpabuf *domain_names)
2038 {
2039         size_t i;
2040         int ret = -1;
2041 #ifdef INTERWORKING_3GPP
2042         char nai[100], *realm;
2043
2044         char *imsi = NULL;
2045         int mnc_len = 0;
2046         if (cred->imsi)
2047                 imsi = cred->imsi;
2048 #ifdef PCSC_FUNCS
2049         else if (cred->pcsc && wpa_s->conf->pcsc_reader &&
2050                  wpa_s->scard && wpa_s->imsi[0]) {
2051                 imsi = wpa_s->imsi;
2052                 mnc_len = wpa_s->mnc_len;
2053         }
2054 #endif /* PCSC_FUNCS */
2055 #ifdef CONFIG_EAP_PROXY
2056         else if (cred->pcsc && wpa_s->mnc_len > 0 && wpa_s->imsi[0]) {
2057                 imsi = wpa_s->imsi;
2058                 mnc_len = wpa_s->mnc_len;
2059         }
2060 #endif /* CONFIG_EAP_PROXY */
2061         if (domain_names &&
2062             imsi && build_root_nai(nai, sizeof(nai), imsi, mnc_len, 0) == 0) {
2063                 realm = os_strchr(nai, '@');
2064                 if (realm)
2065                         realm++;
2066                 wpa_printf(MSG_DEBUG, "Interworking: Search for match "
2067                            "with SIM/USIM domain %s", realm);
2068                 if (realm &&
2069                     domain_name_list_contains(domain_names, realm, 1))
2070                         return 1;
2071                 if (realm)
2072                         ret = 0;
2073         }
2074 #endif /* INTERWORKING_3GPP */
2075
2076         if (domain_names == NULL || cred->domain == NULL)
2077                 return ret;
2078
2079         for (i = 0; i < cred->num_domain; i++) {
2080                 wpa_printf(MSG_DEBUG, "Interworking: Search for match with "
2081                            "home SP FQDN %s", cred->domain[i]);
2082                 if (domain_name_list_contains(domain_names, cred->domain[i], 1))
2083                         return 1;
2084         }
2085
2086         return 0;
2087 }
2088
2089
2090 static int interworking_home_sp(struct wpa_supplicant *wpa_s,
2091                                 struct wpabuf *domain_names)
2092 {
2093         struct wpa_cred *cred;
2094
2095         if (domain_names == NULL || wpa_s->conf->cred == NULL)
2096                 return -1;
2097
2098         for (cred = wpa_s->conf->cred; cred; cred = cred->next) {
2099                 int res = interworking_home_sp_cred(wpa_s, cred, domain_names);
2100                 if (res)
2101                         return res;
2102         }
2103
2104         return 0;
2105 }
2106
2107
2108 static int interworking_find_network_match(struct wpa_supplicant *wpa_s)
2109 {
2110         struct wpa_bss *bss;
2111         struct wpa_ssid *ssid;
2112
2113         dl_list_for_each(bss, &wpa_s->bss, struct wpa_bss, list) {
2114                 for (ssid = wpa_s->conf->ssid; ssid; ssid = ssid->next) {
2115                         if (wpas_network_disabled(wpa_s, ssid) ||
2116                             ssid->mode != WPAS_MODE_INFRA)
2117                                 continue;
2118                         if (ssid->ssid_len != bss->ssid_len ||
2119                             os_memcmp(ssid->ssid, bss->ssid, ssid->ssid_len) !=
2120                             0)
2121                                 continue;
2122                         /*
2123                          * TODO: Consider more accurate matching of security
2124                          * configuration similarly to what is done in events.c
2125                          */
2126                         return 1;
2127                 }
2128         }
2129
2130         return 0;
2131 }
2132
2133
2134 static int roaming_partner_match(struct wpa_supplicant *wpa_s,
2135                                  struct roaming_partner *partner,
2136                                  struct wpabuf *domain_names)
2137 {
2138         wpa_printf(MSG_DEBUG, "Interworking: Comparing roaming_partner info fqdn='%s' exact_match=%d priority=%u country='%s'",
2139                    partner->fqdn, partner->exact_match, partner->priority,
2140                    partner->country);
2141         wpa_hexdump_ascii(MSG_DEBUG, "Interworking: Domain names",
2142                           wpabuf_head(domain_names),
2143                           wpabuf_len(domain_names));
2144         if (!domain_name_list_contains(domain_names, partner->fqdn,
2145                                        partner->exact_match))
2146                 return 0;
2147         /* TODO: match Country */
2148         return 1;
2149 }
2150
2151
2152 static u8 roaming_prio(struct wpa_supplicant *wpa_s, struct wpa_cred *cred,
2153                        struct wpa_bss *bss)
2154 {
2155         size_t i;
2156
2157         if (bss->anqp == NULL || bss->anqp->domain_name == NULL) {
2158                 wpa_printf(MSG_DEBUG, "Interworking: No ANQP domain name info -> use default roaming partner priority 128");
2159                 return 128; /* cannot check preference with domain name */
2160         }
2161
2162         if (interworking_home_sp_cred(wpa_s, cred, bss->anqp->domain_name) > 0)
2163         {
2164                 wpa_printf(MSG_DEBUG, "Interworking: Determined to be home SP -> use maximum preference 0 as roaming partner priority");
2165                 return 0; /* max preference for home SP network */
2166         }
2167
2168         for (i = 0; i < cred->num_roaming_partner; i++) {
2169                 if (roaming_partner_match(wpa_s, &cred->roaming_partner[i],
2170                                           bss->anqp->domain_name)) {
2171                         wpa_printf(MSG_DEBUG, "Interworking: Roaming partner preference match - priority %u",
2172                                    cred->roaming_partner[i].priority);
2173                         return cred->roaming_partner[i].priority;
2174                 }
2175         }
2176
2177         wpa_printf(MSG_DEBUG, "Interworking: No roaming partner preference match - use default roaming partner priority 128");
2178         return 128;
2179 }
2180
2181
2182 static struct wpa_bss * pick_best_roaming_partner(struct wpa_supplicant *wpa_s,
2183                                                   struct wpa_bss *selected,
2184                                                   struct wpa_cred *cred)
2185 {
2186         struct wpa_bss *bss;
2187         u8 best_prio, prio;
2188         struct wpa_cred *cred2;
2189
2190         /*
2191          * Check if any other BSS is operated by a more preferred roaming
2192          * partner.
2193          */
2194
2195         best_prio = roaming_prio(wpa_s, cred, selected);
2196         wpa_printf(MSG_DEBUG, "Interworking: roaming_prio=%u for selected BSS "
2197                    MACSTR " (cred=%d)", best_prio, MAC2STR(selected->bssid),
2198                    cred->id);
2199
2200         dl_list_for_each(bss, &wpa_s->bss, struct wpa_bss, list) {
2201                 if (bss == selected)
2202                         continue;
2203                 cred2 = interworking_credentials_available(wpa_s, bss, NULL);
2204                 if (!cred2)
2205                         continue;
2206                 if (!wpa_bss_get_ie(bss, WLAN_EID_RSN))
2207                         continue;
2208                 prio = roaming_prio(wpa_s, cred2, bss);
2209                 wpa_printf(MSG_DEBUG, "Interworking: roaming_prio=%u for BSS "
2210                            MACSTR " (cred=%d)", prio, MAC2STR(bss->bssid),
2211                            cred2->id);
2212                 if (prio < best_prio) {
2213                         int bh1, bh2, load1, load2, conn1, conn2;
2214                         bh1 = cred_below_min_backhaul(wpa_s, cred, selected);
2215                         load1 = cred_over_max_bss_load(wpa_s, cred, selected);
2216                         conn1 = cred_conn_capab_missing(wpa_s, cred, selected);
2217                         bh2 = cred_below_min_backhaul(wpa_s, cred2, bss);
2218                         load2 = cred_over_max_bss_load(wpa_s, cred2, bss);
2219                         conn2 = cred_conn_capab_missing(wpa_s, cred2, bss);
2220                         wpa_printf(MSG_DEBUG, "Interworking: old: %d %d %d  new: %d %d %d",
2221                                    bh1, load1, conn1, bh2, load2, conn2);
2222                         if (bh1 || load1 || conn1 || !(bh2 || load2 || conn2)) {
2223                                 wpa_printf(MSG_DEBUG, "Interworking: Better roaming partner " MACSTR " selected", MAC2STR(bss->bssid));
2224                                 best_prio = prio;
2225                                 selected = bss;
2226                         }
2227                 }
2228         }
2229
2230         return selected;
2231 }
2232
2233
2234 static void interworking_select_network(struct wpa_supplicant *wpa_s)
2235 {
2236         struct wpa_bss *bss, *selected = NULL, *selected_home = NULL;
2237         struct wpa_bss *selected2 = NULL, *selected2_home = NULL;
2238         unsigned int count = 0;
2239         const char *type;
2240         int res;
2241         struct wpa_cred *cred, *selected_cred = NULL;
2242         struct wpa_cred *selected_home_cred = NULL;
2243         struct wpa_cred *selected2_cred = NULL;
2244         struct wpa_cred *selected2_home_cred = NULL;
2245
2246         wpa_s->network_select = 0;
2247
2248         wpa_printf(MSG_DEBUG, "Interworking: Select network (auto_select=%d)",
2249                    wpa_s->auto_select);
2250         dl_list_for_each(bss, &wpa_s->bss, struct wpa_bss, list) {
2251                 int excluded = 0;
2252                 int bh, bss_load, conn_capab;
2253                 cred = interworking_credentials_available(wpa_s, bss,
2254                                                           &excluded);
2255                 if (!cred)
2256                         continue;
2257                 if (!wpa_bss_get_ie(bss, WLAN_EID_RSN)) {
2258                         /*
2259                          * We currently support only HS 2.0 networks and those
2260                          * are required to use WPA2-Enterprise.
2261                          */
2262                         wpa_printf(MSG_DEBUG, "Interworking: Credential match "
2263                                    "with " MACSTR " but network does not use "
2264                                    "RSN", MAC2STR(bss->bssid));
2265                         continue;
2266                 }
2267                 if (!excluded)
2268                         count++;
2269                 res = interworking_home_sp(wpa_s, bss->anqp ?
2270                                            bss->anqp->domain_name : NULL);
2271                 if (res > 0)
2272                         type = "home";
2273                 else if (res == 0)
2274                         type = "roaming";
2275                 else
2276                         type = "unknown";
2277                 bh = cred_below_min_backhaul(wpa_s, cred, bss);
2278                 bss_load = cred_over_max_bss_load(wpa_s, cred, bss);
2279                 conn_capab = cred_conn_capab_missing(wpa_s, cred, bss);
2280                 wpa_msg(wpa_s, MSG_INFO, "%s" MACSTR " type=%s%s%s%s id=%d priority=%d sp_priority=%d",
2281                         excluded ? INTERWORKING_BLACKLISTED : INTERWORKING_AP,
2282                         MAC2STR(bss->bssid), type,
2283                         bh ? " below_min_backhaul=1" : "",
2284                         bss_load ? " over_max_bss_load=1" : "",
2285                         conn_capab ? " conn_capab_missing=1" : "",
2286                         cred->id, cred->priority, cred->sp_priority);
2287                 if (excluded)
2288                         continue;
2289                 if (wpa_s->auto_select ||
2290                     (wpa_s->conf->auto_interworking &&
2291                      wpa_s->auto_network_select)) {
2292                         if (bh || bss_load || conn_capab) {
2293                                 if (selected2_cred == NULL ||
2294                                     cred_prio_cmp(cred, selected2_cred) > 0) {
2295                                         wpa_printf(MSG_DEBUG, "Interworking: Mark as selected2");
2296                                         selected2 = bss;
2297                                         selected2_cred = cred;
2298                                 }
2299                                 if (res > 0 &&
2300                                     (selected2_home_cred == NULL ||
2301                                      cred_prio_cmp(cred, selected2_home_cred) >
2302                                      0)) {
2303                                         wpa_printf(MSG_DEBUG, "Interworking: Mark as selected2_home");
2304                                         selected2_home = bss;
2305                                         selected2_home_cred = cred;
2306                                 }
2307                         } else {
2308                                 if (selected_cred == NULL ||
2309                                     cred_prio_cmp(cred, selected_cred) > 0) {
2310                                         wpa_printf(MSG_DEBUG, "Interworking: Mark as selected");
2311                                         selected = bss;
2312                                         selected_cred = cred;
2313                                 }
2314                                 if (res > 0 &&
2315                                     (selected_home_cred == NULL ||
2316                                      cred_prio_cmp(cred, selected_home_cred) >
2317                                      0)) {
2318                                         wpa_printf(MSG_DEBUG, "Interworking: Mark as selected_home");
2319                                         selected_home = bss;
2320                                         selected_home_cred = cred;
2321                                 }
2322                         }
2323                 }
2324         }
2325
2326         if (selected_home && selected_home != selected &&
2327             selected_home_cred &&
2328             (selected_cred == NULL ||
2329              cred_prio_cmp(selected_home_cred, selected_cred) >= 0)) {
2330                 /* Prefer network operated by the Home SP */
2331                 wpa_printf(MSG_DEBUG, "Interworking: Overrided selected with selected_home");
2332                 selected = selected_home;
2333                 selected_cred = selected_home_cred;
2334         }
2335
2336         if (!selected) {
2337                 if (selected2_home) {
2338                         wpa_printf(MSG_DEBUG, "Interworking: Use home BSS with BW limit mismatch since no other network could be selected");
2339                         selected = selected2_home;
2340                         selected_cred = selected2_home_cred;
2341                 } else if (selected2) {
2342                         wpa_printf(MSG_DEBUG, "Interworking: Use visited BSS with BW limit mismatch since no other network could be selected");
2343                         selected = selected2;
2344                         selected_cred = selected2_cred;
2345                 }
2346         }
2347
2348         if (count == 0) {
2349                 /*
2350                  * No matching network was found based on configured
2351                  * credentials. Check whether any of the enabled network blocks
2352                  * have matching APs.
2353                  */
2354                 if (interworking_find_network_match(wpa_s)) {
2355                         wpa_printf(MSG_DEBUG, "Interworking: Possible BSS "
2356                                    "match for enabled network configurations");
2357                         if (wpa_s->auto_select)
2358                                 interworking_reconnect(wpa_s);
2359                         return;
2360                 }
2361
2362                 if (wpa_s->auto_network_select) {
2363                         wpa_printf(MSG_DEBUG, "Interworking: Continue "
2364                                    "scanning after ANQP fetch");
2365                         wpa_supplicant_req_scan(wpa_s, wpa_s->scan_interval,
2366                                                 0);
2367                         return;
2368                 }
2369
2370                 wpa_msg(wpa_s, MSG_INFO, INTERWORKING_NO_MATCH "No network "
2371                         "with matching credentials found");
2372         }
2373
2374         if (selected) {
2375                 wpa_printf(MSG_DEBUG, "Interworking: Selected " MACSTR,
2376                            MAC2STR(selected->bssid));
2377                 selected = pick_best_roaming_partner(wpa_s, selected,
2378                                                      selected_cred);
2379                 wpa_printf(MSG_DEBUG, "Interworking: Selected " MACSTR
2380                            " (after best roaming partner selection)",
2381                            MAC2STR(selected->bssid));
2382                 wpa_msg(wpa_s, MSG_INFO, INTERWORKING_SELECTED MACSTR,
2383                         MAC2STR(selected->bssid));
2384                 interworking_connect(wpa_s, selected);
2385         }
2386 }
2387
2388
2389 static struct wpa_bss_anqp *
2390 interworking_match_anqp_info(struct wpa_supplicant *wpa_s, struct wpa_bss *bss)
2391 {
2392         struct wpa_bss *other;
2393
2394         if (is_zero_ether_addr(bss->hessid))
2395                 return NULL; /* Cannot be in the same homegenous ESS */
2396
2397         dl_list_for_each(other, &wpa_s->bss, struct wpa_bss, list) {
2398                 if (other == bss)
2399                         continue;
2400                 if (other->anqp == NULL)
2401                         continue;
2402                 if (other->anqp->roaming_consortium == NULL &&
2403                     other->anqp->nai_realm == NULL &&
2404                     other->anqp->anqp_3gpp == NULL &&
2405                     other->anqp->domain_name == NULL)
2406                         continue;
2407                 if (!(other->flags & WPA_BSS_ANQP_FETCH_TRIED))
2408                         continue;
2409                 if (os_memcmp(bss->hessid, other->hessid, ETH_ALEN) != 0)
2410                         continue;
2411                 if (bss->ssid_len != other->ssid_len ||
2412                     os_memcmp(bss->ssid, other->ssid, bss->ssid_len) != 0)
2413                         continue;
2414
2415                 wpa_printf(MSG_DEBUG, "Interworking: Share ANQP data with "
2416                            "already fetched BSSID " MACSTR " and " MACSTR,
2417                            MAC2STR(other->bssid), MAC2STR(bss->bssid));
2418                 other->anqp->users++;
2419                 return other->anqp;
2420         }
2421
2422         return NULL;
2423 }
2424
2425
2426 static void interworking_next_anqp_fetch(struct wpa_supplicant *wpa_s)
2427 {
2428         struct wpa_bss *bss;
2429         int found = 0;
2430         const u8 *ie;
2431
2432         wpa_printf(MSG_DEBUG, "Interworking: next_anqp_fetch - "
2433                    "fetch_anqp_in_progress=%d fetch_osu_icon_in_progress=%d",
2434                    wpa_s->fetch_anqp_in_progress,
2435                    wpa_s->fetch_osu_icon_in_progress);
2436
2437         if (eloop_terminated() || !wpa_s->fetch_anqp_in_progress) {
2438                 wpa_printf(MSG_DEBUG, "Interworking: Stop next-ANQP-fetch");
2439                 return;
2440         }
2441
2442         if (wpa_s->fetch_osu_icon_in_progress) {
2443                 wpa_printf(MSG_DEBUG, "Interworking: Next icon (in progress)");
2444                 hs20_next_osu_icon(wpa_s);
2445                 return;
2446         }
2447
2448         dl_list_for_each(bss, &wpa_s->bss, struct wpa_bss, list) {
2449                 if (!(bss->caps & IEEE80211_CAP_ESS))
2450                         continue;
2451                 ie = wpa_bss_get_ie(bss, WLAN_EID_EXT_CAPAB);
2452                 if (ie == NULL || ie[1] < 4 || !(ie[5] & 0x80))
2453                         continue; /* AP does not support Interworking */
2454                 if (disallowed_bssid(wpa_s, bss->bssid) ||
2455                     disallowed_ssid(wpa_s, bss->ssid, bss->ssid_len))
2456                         continue; /* Disallowed BSS */
2457
2458                 if (!(bss->flags & WPA_BSS_ANQP_FETCH_TRIED)) {
2459                         if (bss->anqp == NULL) {
2460                                 bss->anqp = interworking_match_anqp_info(wpa_s,
2461                                                                          bss);
2462                                 if (bss->anqp) {
2463                                         /* Shared data already fetched */
2464                                         continue;
2465                                 }
2466                                 bss->anqp = wpa_bss_anqp_alloc();
2467                                 if (bss->anqp == NULL)
2468                                         break;
2469                         }
2470                         found++;
2471                         bss->flags |= WPA_BSS_ANQP_FETCH_TRIED;
2472                         wpa_msg(wpa_s, MSG_INFO, "Starting ANQP fetch for "
2473                                 MACSTR, MAC2STR(bss->bssid));
2474                         interworking_anqp_send_req(wpa_s, bss);
2475                         break;
2476                 }
2477         }
2478
2479         if (found == 0) {
2480                 if (wpa_s->fetch_osu_info) {
2481                         if (wpa_s->num_prov_found == 0 &&
2482                             wpa_s->num_osu_scans < 3) {
2483                                 wpa_printf(MSG_DEBUG, "HS 2.0: No OSU providers seen - try to scan again");
2484                                 hs20_start_osu_scan(wpa_s);
2485                                 return;
2486                         }
2487                         wpa_printf(MSG_DEBUG, "Interworking: Next icon");
2488                         hs20_osu_icon_fetch(wpa_s);
2489                         return;
2490                 }
2491                 wpa_msg(wpa_s, MSG_INFO, "ANQP fetch completed");
2492                 wpa_s->fetch_anqp_in_progress = 0;
2493                 if (wpa_s->network_select)
2494                         interworking_select_network(wpa_s);
2495         }
2496 }
2497
2498
2499 void interworking_start_fetch_anqp(struct wpa_supplicant *wpa_s)
2500 {
2501         struct wpa_bss *bss;
2502
2503         dl_list_for_each(bss, &wpa_s->bss, struct wpa_bss, list)
2504                 bss->flags &= ~WPA_BSS_ANQP_FETCH_TRIED;
2505
2506         wpa_s->fetch_anqp_in_progress = 1;
2507         interworking_next_anqp_fetch(wpa_s);
2508 }
2509
2510
2511 int interworking_fetch_anqp(struct wpa_supplicant *wpa_s)
2512 {
2513         if (wpa_s->fetch_anqp_in_progress || wpa_s->network_select)
2514                 return 0;
2515
2516         wpa_s->network_select = 0;
2517         wpa_s->fetch_all_anqp = 1;
2518         wpa_s->fetch_osu_info = 0;
2519
2520         interworking_start_fetch_anqp(wpa_s);
2521
2522         return 0;
2523 }
2524
2525
2526 void interworking_stop_fetch_anqp(struct wpa_supplicant *wpa_s)
2527 {
2528         if (!wpa_s->fetch_anqp_in_progress)
2529                 return;
2530
2531         wpa_s->fetch_anqp_in_progress = 0;
2532 }
2533
2534
2535 int anqp_send_req(struct wpa_supplicant *wpa_s, const u8 *dst,
2536                   u16 info_ids[], size_t num_ids, u32 subtypes)
2537 {
2538         struct wpabuf *buf;
2539         struct wpabuf *hs20_buf = NULL;
2540         int ret = 0;
2541         int freq;
2542         struct wpa_bss *bss;
2543         int res;
2544
2545         freq = wpa_s->assoc_freq;
2546         bss = wpa_bss_get_bssid(wpa_s, dst);
2547         if (bss) {
2548                 wpa_bss_anqp_unshare_alloc(bss);
2549                 freq = bss->freq;
2550         }
2551         if (freq <= 0)
2552                 return -1;
2553
2554         wpa_printf(MSG_DEBUG, "ANQP: Query Request to " MACSTR " for %u id(s)",
2555                    MAC2STR(dst), (unsigned int) num_ids);
2556
2557 #ifdef CONFIG_HS20
2558         if (subtypes != 0) {
2559                 hs20_buf = wpabuf_alloc(100);
2560                 if (hs20_buf == NULL)
2561                         return -1;
2562                 hs20_put_anqp_req(subtypes, NULL, 0, hs20_buf);
2563         }
2564 #endif /* CONFIG_HS20 */
2565
2566         buf = anqp_build_req(info_ids, num_ids, hs20_buf);
2567         wpabuf_free(hs20_buf);
2568         if (buf == NULL)
2569                 return -1;
2570
2571         res = gas_query_req(wpa_s->gas, dst, freq, buf, anqp_resp_cb, wpa_s);
2572         if (res < 0) {
2573                 wpa_printf(MSG_DEBUG, "ANQP: Failed to send Query Request");
2574                 wpabuf_free(buf);
2575                 ret = -1;
2576         } else
2577                 wpa_printf(MSG_DEBUG, "ANQP: Query started with dialog token "
2578                            "%u", res);
2579
2580         return ret;
2581 }
2582
2583
2584 static void interworking_parse_rx_anqp_resp(struct wpa_supplicant *wpa_s,
2585                                             struct wpa_bss *bss, const u8 *sa,
2586                                             u16 info_id,
2587                                             const u8 *data, size_t slen)
2588 {
2589         const u8 *pos = data;
2590         struct wpa_bss_anqp *anqp = NULL;
2591 #ifdef CONFIG_HS20
2592         u8 type;
2593 #endif /* CONFIG_HS20 */
2594
2595         if (bss)
2596                 anqp = bss->anqp;
2597
2598         switch (info_id) {
2599         case ANQP_CAPABILITY_LIST:
2600                 wpa_msg(wpa_s, MSG_INFO, "RX-ANQP " MACSTR
2601                         " ANQP Capability list", MAC2STR(sa));
2602                 break;
2603         case ANQP_VENUE_NAME:
2604                 wpa_msg(wpa_s, MSG_INFO, "RX-ANQP " MACSTR
2605                         " Venue Name", MAC2STR(sa));
2606                 wpa_hexdump_ascii(MSG_DEBUG, "ANQP: Venue Name", pos, slen);
2607                 if (anqp) {
2608                         wpabuf_free(anqp->venue_name);
2609                         anqp->venue_name = wpabuf_alloc_copy(pos, slen);
2610                 }
2611                 break;
2612         case ANQP_NETWORK_AUTH_TYPE:
2613                 wpa_msg(wpa_s, MSG_INFO, "RX-ANQP " MACSTR
2614                         " Network Authentication Type information",
2615                         MAC2STR(sa));
2616                 wpa_hexdump_ascii(MSG_DEBUG, "ANQP: Network Authentication "
2617                                   "Type", pos, slen);
2618                 if (anqp) {
2619                         wpabuf_free(anqp->network_auth_type);
2620                         anqp->network_auth_type = wpabuf_alloc_copy(pos, slen);
2621                 }
2622                 break;
2623         case ANQP_ROAMING_CONSORTIUM:
2624                 wpa_msg(wpa_s, MSG_INFO, "RX-ANQP " MACSTR
2625                         " Roaming Consortium list", MAC2STR(sa));
2626                 wpa_hexdump_ascii(MSG_DEBUG, "ANQP: Roaming Consortium",
2627                                   pos, slen);
2628                 if (anqp) {
2629                         wpabuf_free(anqp->roaming_consortium);
2630                         anqp->roaming_consortium = wpabuf_alloc_copy(pos, slen);
2631                 }
2632                 break;
2633         case ANQP_IP_ADDR_TYPE_AVAILABILITY:
2634                 wpa_msg(wpa_s, MSG_INFO, "RX-ANQP " MACSTR
2635                         " IP Address Type Availability information",
2636                         MAC2STR(sa));
2637                 wpa_hexdump(MSG_MSGDUMP, "ANQP: IP Address Availability",
2638                             pos, slen);
2639                 if (anqp) {
2640                         wpabuf_free(anqp->ip_addr_type_availability);
2641                         anqp->ip_addr_type_availability =
2642                                 wpabuf_alloc_copy(pos, slen);
2643                 }
2644                 break;
2645         case ANQP_NAI_REALM:
2646                 wpa_msg(wpa_s, MSG_INFO, "RX-ANQP " MACSTR
2647                         " NAI Realm list", MAC2STR(sa));
2648                 wpa_hexdump_ascii(MSG_DEBUG, "ANQP: NAI Realm", pos, slen);
2649                 if (anqp) {
2650                         wpabuf_free(anqp->nai_realm);
2651                         anqp->nai_realm = wpabuf_alloc_copy(pos, slen);
2652                 }
2653                 break;
2654         case ANQP_3GPP_CELLULAR_NETWORK:
2655                 wpa_msg(wpa_s, MSG_INFO, "RX-ANQP " MACSTR
2656                         " 3GPP Cellular Network information", MAC2STR(sa));
2657                 wpa_hexdump_ascii(MSG_DEBUG, "ANQP: 3GPP Cellular Network",
2658                                   pos, slen);
2659                 if (anqp) {
2660                         wpabuf_free(anqp->anqp_3gpp);
2661                         anqp->anqp_3gpp = wpabuf_alloc_copy(pos, slen);
2662                 }
2663                 break;
2664         case ANQP_DOMAIN_NAME:
2665                 wpa_msg(wpa_s, MSG_INFO, "RX-ANQP " MACSTR
2666                         " Domain Name list", MAC2STR(sa));
2667                 wpa_hexdump_ascii(MSG_MSGDUMP, "ANQP: Domain Name", pos, slen);
2668                 if (anqp) {
2669                         wpabuf_free(anqp->domain_name);
2670                         anqp->domain_name = wpabuf_alloc_copy(pos, slen);
2671                 }
2672                 break;
2673         case ANQP_VENDOR_SPECIFIC:
2674                 if (slen < 3)
2675                         return;
2676
2677                 switch (WPA_GET_BE24(pos)) {
2678 #ifdef CONFIG_HS20
2679                 case OUI_WFA:
2680                         pos += 3;
2681                         slen -= 3;
2682
2683                         if (slen < 1)
2684                                 return;
2685                         type = *pos++;
2686                         slen--;
2687
2688                         switch (type) {
2689                         case HS20_ANQP_OUI_TYPE:
2690                                 hs20_parse_rx_hs20_anqp_resp(wpa_s, sa, pos,
2691                                                              slen);
2692                                 break;
2693                         default:
2694                                 wpa_printf(MSG_DEBUG, "HS20: Unsupported ANQP "
2695                                            "vendor type %u", type);
2696                                 break;
2697                         }
2698                         break;
2699 #endif /* CONFIG_HS20 */
2700                 default:
2701                         wpa_printf(MSG_DEBUG, "Interworking: Unsupported "
2702                                    "vendor-specific ANQP OUI %06x",
2703                                    WPA_GET_BE24(pos));
2704                         return;
2705                 }
2706                 break;
2707         default:
2708                 wpa_printf(MSG_DEBUG, "Interworking: Unsupported ANQP Info ID "
2709                            "%u", info_id);
2710                 break;
2711         }
2712 }
2713
2714
2715 void anqp_resp_cb(void *ctx, const u8 *dst, u8 dialog_token,
2716                   enum gas_query_result result,
2717                   const struct wpabuf *adv_proto,
2718                   const struct wpabuf *resp, u16 status_code)
2719 {
2720         struct wpa_supplicant *wpa_s = ctx;
2721         const u8 *pos;
2722         const u8 *end;
2723         u16 info_id;
2724         u16 slen;
2725         struct wpa_bss *bss = NULL, *tmp;
2726
2727         wpa_printf(MSG_DEBUG, "Interworking: anqp_resp_cb dst=" MACSTR
2728                    " dialog_token=%u result=%d status_code=%u",
2729                    MAC2STR(dst), dialog_token, result, status_code);
2730         if (result != GAS_QUERY_SUCCESS) {
2731                 if (wpa_s->fetch_osu_icon_in_progress)
2732                         hs20_icon_fetch_failed(wpa_s);
2733                 return;
2734         }
2735
2736         pos = wpabuf_head(adv_proto);
2737         if (wpabuf_len(adv_proto) < 4 || pos[0] != WLAN_EID_ADV_PROTO ||
2738             pos[1] < 2 || pos[3] != ACCESS_NETWORK_QUERY_PROTOCOL) {
2739                 wpa_printf(MSG_DEBUG, "ANQP: Unexpected Advertisement "
2740                            "Protocol in response");
2741                 if (wpa_s->fetch_osu_icon_in_progress)
2742                         hs20_icon_fetch_failed(wpa_s);
2743                 return;
2744         }
2745
2746         /*
2747          * If possible, select the BSS entry based on which BSS entry was used
2748          * for the request. This can help in cases where multiple BSS entries
2749          * may exist for the same AP.
2750          */
2751         dl_list_for_each_reverse(tmp, &wpa_s->bss, struct wpa_bss, list) {
2752                 if (tmp == wpa_s->interworking_gas_bss &&
2753                     os_memcmp(tmp->bssid, dst, ETH_ALEN) == 0) {
2754                         bss = tmp;
2755                         break;
2756                 }
2757         }
2758         if (bss == NULL)
2759                 bss = wpa_bss_get_bssid(wpa_s, dst);
2760
2761         pos = wpabuf_head(resp);
2762         end = pos + wpabuf_len(resp);
2763
2764         while (pos < end) {
2765                 if (pos + 4 > end) {
2766                         wpa_printf(MSG_DEBUG, "ANQP: Invalid element");
2767                         break;
2768                 }
2769                 info_id = WPA_GET_LE16(pos);
2770                 pos += 2;
2771                 slen = WPA_GET_LE16(pos);
2772                 pos += 2;
2773                 if (pos + slen > end) {
2774                         wpa_printf(MSG_DEBUG, "ANQP: Invalid element length "
2775                                    "for Info ID %u", info_id);
2776                         break;
2777                 }
2778                 interworking_parse_rx_anqp_resp(wpa_s, bss, dst, info_id, pos,
2779                                                 slen);
2780                 pos += slen;
2781         }
2782
2783         hs20_notify_parse_done(wpa_s);
2784 }
2785
2786
2787 static void interworking_scan_res_handler(struct wpa_supplicant *wpa_s,
2788                                           struct wpa_scan_results *scan_res)
2789 {
2790         wpa_printf(MSG_DEBUG, "Interworking: Scan results available - start "
2791                    "ANQP fetch");
2792         interworking_start_fetch_anqp(wpa_s);
2793 }
2794
2795
2796 int interworking_select(struct wpa_supplicant *wpa_s, int auto_select,
2797                         int *freqs)
2798 {
2799         interworking_stop_fetch_anqp(wpa_s);
2800         wpa_s->network_select = 1;
2801         wpa_s->auto_network_select = 0;
2802         wpa_s->auto_select = !!auto_select;
2803         wpa_s->fetch_all_anqp = 0;
2804         wpa_s->fetch_osu_info = 0;
2805         wpa_printf(MSG_DEBUG, "Interworking: Start scan for network "
2806                    "selection");
2807         wpa_s->scan_res_handler = interworking_scan_res_handler;
2808         wpa_s->normal_scans = 0;
2809         wpa_s->scan_req = MANUAL_SCAN_REQ;
2810         os_free(wpa_s->manual_scan_freqs);
2811         wpa_s->manual_scan_freqs = freqs;
2812         wpa_s->after_wps = 0;
2813         wpa_s->known_wps_freq = 0;
2814         wpa_supplicant_req_scan(wpa_s, 0, 0);
2815
2816         return 0;
2817 }
2818
2819
2820 static void gas_resp_cb(void *ctx, const u8 *addr, u8 dialog_token,
2821                         enum gas_query_result result,
2822                         const struct wpabuf *adv_proto,
2823                         const struct wpabuf *resp, u16 status_code)
2824 {
2825         struct wpa_supplicant *wpa_s = ctx;
2826         struct wpabuf *n;
2827
2828         wpa_msg(wpa_s, MSG_INFO, GAS_RESPONSE_INFO "addr=" MACSTR
2829                 " dialog_token=%d status_code=%d resp_len=%d",
2830                 MAC2STR(addr), dialog_token, status_code,
2831                 resp ? (int) wpabuf_len(resp) : -1);
2832         if (!resp)
2833                 return;
2834
2835         n = wpabuf_dup(resp);
2836         if (n == NULL)
2837                 return;
2838         wpabuf_free(wpa_s->prev_gas_resp);
2839         wpa_s->prev_gas_resp = wpa_s->last_gas_resp;
2840         os_memcpy(wpa_s->prev_gas_addr, wpa_s->last_gas_addr, ETH_ALEN);
2841         wpa_s->prev_gas_dialog_token = wpa_s->last_gas_dialog_token;
2842         wpa_s->last_gas_resp = n;
2843         os_memcpy(wpa_s->last_gas_addr, addr, ETH_ALEN);
2844         wpa_s->last_gas_dialog_token = dialog_token;
2845 }
2846
2847
2848 int gas_send_request(struct wpa_supplicant *wpa_s, const u8 *dst,
2849                      const struct wpabuf *adv_proto,
2850                      const struct wpabuf *query)
2851 {
2852         struct wpabuf *buf;
2853         int ret = 0;
2854         int freq;
2855         struct wpa_bss *bss;
2856         int res;
2857         size_t len;
2858         u8 query_resp_len_limit = 0, pame_bi = 0;
2859
2860         freq = wpa_s->assoc_freq;
2861         bss = wpa_bss_get_bssid(wpa_s, dst);
2862         if (bss)
2863                 freq = bss->freq;
2864         if (freq <= 0)
2865                 return -1;
2866
2867         wpa_printf(MSG_DEBUG, "GAS request to " MACSTR " (freq %d MHz)",
2868                    MAC2STR(dst), freq);
2869         wpa_hexdump_buf(MSG_DEBUG, "Advertisement Protocol ID", adv_proto);
2870         wpa_hexdump_buf(MSG_DEBUG, "GAS Query", query);
2871
2872         len = 3 + wpabuf_len(adv_proto) + 2;
2873         if (query)
2874                 len += wpabuf_len(query);
2875         buf = gas_build_initial_req(0, len);
2876         if (buf == NULL)
2877                 return -1;
2878
2879         /* Advertisement Protocol IE */
2880         wpabuf_put_u8(buf, WLAN_EID_ADV_PROTO);
2881         wpabuf_put_u8(buf, 1 + wpabuf_len(adv_proto)); /* Length */
2882         wpabuf_put_u8(buf, (query_resp_len_limit & 0x7f) |
2883                       (pame_bi ? 0x80 : 0));
2884         wpabuf_put_buf(buf, adv_proto);
2885
2886         /* GAS Query */
2887         if (query) {
2888                 wpabuf_put_le16(buf, wpabuf_len(query));
2889                 wpabuf_put_buf(buf, query);
2890         } else
2891                 wpabuf_put_le16(buf, 0);
2892
2893         res = gas_query_req(wpa_s->gas, dst, freq, buf, gas_resp_cb, wpa_s);
2894         if (res < 0) {
2895                 wpa_printf(MSG_DEBUG, "GAS: Failed to send Query Request");
2896                 wpabuf_free(buf);
2897                 ret = -1;
2898         } else
2899                 wpa_printf(MSG_DEBUG, "GAS: Query started with dialog token "
2900                            "%u", res);
2901
2902         return ret;
2903 }