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