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