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