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