hostapd: remove version tag from directory
[dragonfly.git] / contrib / hostapd / eap_sim_db.c
1 /*
2  * hostapd / EAP-SIM database/authenticator gateway
3  * Copyright (c) 2005-2006, Jouni Malinen <j@w1.fi>
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License version 2 as
7  * published by the Free Software Foundation.
8  *
9  * Alternatively, this software may be distributed under the terms of BSD
10  * license.
11  *
12  * See README and COPYING for more details.
13  *
14  * This is an example implementation of the EAP-SIM/AKA database/authentication
15  * gateway interface that is using an external program as an SS7 gateway to
16  * GSM/UMTS authentication center (HLR/AuC). hlr_auc_gw is an example
17  * implementation of such a gateway program. This eap_sim_db.c takes care of
18  * EAP-SIM/AKA pseudonyms and re-auth identities. It can be used with different
19  * gateway implementations for HLR/AuC access. Alternatively, it can also be
20  * completely replaced if the in-memory database of pseudonyms/re-auth
21  * identities is not suitable for some cases.
22  */
23
24 #include "includes.h"
25 #include <sys/un.h>
26
27 #include "common.h"
28 #include "eap_sim_common.h"
29 #include "eap_sim_db.h"
30 #include "eloop.h"
31
32 struct eap_sim_pseudonym {
33         struct eap_sim_pseudonym *next;
34         u8 *identity;
35         size_t identity_len;
36         char *pseudonym;
37 };
38
39 struct eap_sim_db_pending {
40         struct eap_sim_db_pending *next;
41         u8 imsi[20];
42         size_t imsi_len;
43         enum { PENDING, SUCCESS, FAILURE } state;
44         void *cb_session_ctx;
45         struct os_time timestamp;
46         int aka;
47         union {
48                 struct {
49                         u8 kc[EAP_SIM_MAX_CHAL][EAP_SIM_KC_LEN];
50                         u8 sres[EAP_SIM_MAX_CHAL][EAP_SIM_SRES_LEN];
51                         u8 rand[EAP_SIM_MAX_CHAL][GSM_RAND_LEN];
52                         int num_chal;
53                 } sim;
54                 struct {
55                         u8 rand[EAP_AKA_RAND_LEN];
56                         u8 autn[EAP_AKA_AUTN_LEN];
57                         u8 ik[EAP_AKA_IK_LEN];
58                         u8 ck[EAP_AKA_CK_LEN];
59                         u8 res[EAP_AKA_RES_MAX_LEN];
60                         size_t res_len;
61                 } aka;
62         } u;
63 };
64
65 struct eap_sim_db_data {
66         int sock;
67         char *fname;
68         char *local_sock;
69         void (*get_complete_cb)(void *ctx, void *session_ctx);
70         void *ctx;
71         struct eap_sim_pseudonym *pseudonyms;
72         struct eap_sim_reauth *reauths;
73         struct eap_sim_db_pending *pending;
74 };
75
76
77 static struct eap_sim_db_pending *
78 eap_sim_db_get_pending(struct eap_sim_db_data *data, const u8 *imsi,
79                        size_t imsi_len, int aka)
80 {
81         struct eap_sim_db_pending *entry, *prev = NULL;
82
83         entry = data->pending;
84         while (entry) {
85                 if (entry->aka == aka && entry->imsi_len == imsi_len &&
86                     memcmp(entry->imsi, imsi, imsi_len) == 0) {
87                         if (prev)
88                                 prev->next = entry->next;
89                         else
90                                 data->pending = entry->next;
91                         break;
92                 }
93                 prev = entry;
94                 entry = entry->next;
95         }
96         return entry;
97 }
98
99
100 static void eap_sim_db_add_pending(struct eap_sim_db_data *data,
101                                    struct eap_sim_db_pending *entry)
102 {
103         entry->next = data->pending;
104         data->pending = entry;
105 }
106
107
108 static void eap_sim_db_sim_resp_auth(struct eap_sim_db_data *data,
109                                      const char *imsi, char *buf)
110 {
111         char *start, *end, *pos;
112         struct eap_sim_db_pending *entry;
113         int num_chal;
114
115         /*
116          * SIM-RESP-AUTH <IMSI> Kc(i):SRES(i):RAND(i) ...
117          * SIM-RESP-AUTH <IMSI> FAILURE
118          * (IMSI = ASCII string, Kc/SRES/RAND = hex string)
119          */
120
121         entry = eap_sim_db_get_pending(data, (u8 *) imsi, strlen(imsi), 0);
122         if (entry == NULL) {
123                 wpa_printf(MSG_DEBUG, "EAP-SIM DB: No pending entry for the "
124                            "received message found");
125                 return;
126         }
127
128         start = buf;
129         if (strncmp(start, "FAILURE", 7) == 0) {
130                 wpa_printf(MSG_DEBUG, "EAP-SIM DB: External server reported "
131                            "failure");
132                 entry->state = FAILURE;
133                 eap_sim_db_add_pending(data, entry);
134                 data->get_complete_cb(data->ctx, entry->cb_session_ctx);
135                 return;
136         }
137
138         num_chal = 0;
139         while (num_chal < EAP_SIM_MAX_CHAL) {
140                 end = strchr(start, ' ');
141                 if (end)
142                         *end = '\0';
143
144                 pos = strchr(start, ':');
145                 if (pos == NULL)
146                         goto parse_fail;
147                 *pos = '\0';
148                 if (hexstr2bin(start, entry->u.sim.kc[num_chal],
149                                EAP_SIM_KC_LEN))
150                         goto parse_fail;
151
152                 start = pos + 1;
153                 pos = strchr(start, ':');
154                 if (pos == NULL)
155                         goto parse_fail;
156                 *pos = '\0';
157                 if (hexstr2bin(start, entry->u.sim.sres[num_chal],
158                                EAP_SIM_SRES_LEN))
159                         goto parse_fail;
160
161                 start = pos + 1;
162                 if (hexstr2bin(start, entry->u.sim.rand[num_chal],
163                                GSM_RAND_LEN))
164                         goto parse_fail;
165
166                 num_chal++;
167                 if (end == NULL)
168                         break;
169                 else
170                         start = end + 1;
171         }
172         entry->u.sim.num_chal = num_chal;
173
174         entry->state = SUCCESS;
175         wpa_printf(MSG_DEBUG, "EAP-SIM DB: Authentication data parsed "
176                    "successfully - callback");
177         eap_sim_db_add_pending(data, entry);
178         data->get_complete_cb(data->ctx, entry->cb_session_ctx);
179         return;
180
181 parse_fail:
182         wpa_printf(MSG_DEBUG, "EAP-SIM DB: Failed to parse response string");
183         free(entry);
184 }
185
186
187 static void eap_sim_db_aka_resp_auth(struct eap_sim_db_data *data,
188                                      const char *imsi, char *buf)
189 {
190         char *start, *end;
191         struct eap_sim_db_pending *entry;
192
193         /*
194          * AKA-RESP-AUTH <IMSI> <RAND> <AUTN> <IK> <CK> <RES>
195          * AKA-RESP-AUTH <IMSI> FAILURE
196          * (IMSI = ASCII string, RAND/AUTN/IK/CK/RES = hex string)
197          */
198
199         entry = eap_sim_db_get_pending(data, (u8 *) imsi, strlen(imsi), 1);
200         if (entry == NULL) {
201                 wpa_printf(MSG_DEBUG, "EAP-SIM DB: No pending entry for the "
202                            "received message found");
203                 return;
204         }
205
206         start = buf;
207         if (strncmp(start, "FAILURE", 7) == 0) {
208                 wpa_printf(MSG_DEBUG, "EAP-SIM DB: External server reported "
209                            "failure");
210                 entry->state = FAILURE;
211                 eap_sim_db_add_pending(data, entry);
212                 data->get_complete_cb(data->ctx, entry->cb_session_ctx);
213                 return;
214         }
215
216         end = strchr(start, ' ');
217         if (end == NULL)
218                 goto parse_fail;
219         *end = '\0';
220         if (hexstr2bin(start, entry->u.aka.rand, EAP_AKA_RAND_LEN))
221                 goto parse_fail;
222
223         start = end + 1;
224         end = strchr(start, ' ');
225         if (end == NULL)
226                 goto parse_fail;
227         *end = '\0';
228         if (hexstr2bin(start, entry->u.aka.autn, EAP_AKA_AUTN_LEN))
229                 goto parse_fail;
230
231         start = end + 1;
232         end = strchr(start, ' ');
233         if (end == NULL)
234                 goto parse_fail;
235         *end = '\0';
236         if (hexstr2bin(start, entry->u.aka.ik, EAP_AKA_IK_LEN))
237                 goto parse_fail;
238
239         start = end + 1;
240         end = strchr(start, ' ');
241         if (end == NULL)
242                 goto parse_fail;
243         *end = '\0';
244         if (hexstr2bin(start, entry->u.aka.ck, EAP_AKA_CK_LEN))
245                 goto parse_fail;
246
247         start = end + 1;
248         end = strchr(start, ' ');
249         if (end)
250                 *end = '\0';
251         else {
252                 end = start;
253                 while (*end)
254                         end++;
255         }
256         entry->u.aka.res_len = (end - start) / 2;
257         if (entry->u.aka.res_len > EAP_AKA_RES_MAX_LEN) {
258                 wpa_printf(MSG_DEBUG, "EAP-SIM DB: Too long RES");
259                 entry->u.aka.res_len = 0;
260                 goto parse_fail;
261         }
262         if (hexstr2bin(start, entry->u.aka.res, entry->u.aka.res_len))
263                 goto parse_fail;
264
265         entry->state = SUCCESS;
266         wpa_printf(MSG_DEBUG, "EAP-SIM DB: Authentication data parsed "
267                    "successfully - callback");
268         eap_sim_db_add_pending(data, entry);
269         data->get_complete_cb(data->ctx, entry->cb_session_ctx);
270         return;
271
272 parse_fail:
273         wpa_printf(MSG_DEBUG, "EAP-SIM DB: Failed to parse response string");
274         free(entry);
275 }
276
277
278 static void eap_sim_db_receive(int sock, void *eloop_ctx, void *sock_ctx)
279 {
280         struct eap_sim_db_data *data = eloop_ctx;
281         char buf[1000], *pos, *cmd, *imsi;
282         int res;
283
284         res = recv(sock, buf, sizeof(buf), 0);
285         if (res < 0)
286                 return;
287         wpa_hexdump_ascii_key(MSG_MSGDUMP, "EAP-SIM DB: Received from an "
288                               "external source", (u8 *) buf, res);
289         if (res == 0)
290                 return;
291         if (res >= (int) sizeof(buf))
292                 res = sizeof(buf) - 1;
293         buf[res] = '\0';
294
295         if (data->get_complete_cb == NULL) {
296                 wpa_printf(MSG_DEBUG, "EAP-SIM DB: No get_complete_cb "
297                            "registered");
298                 return;
299         }
300
301         /* <cmd> <IMSI> ... */
302
303         cmd = buf;
304         pos = strchr(cmd, ' ');
305         if (pos == NULL)
306                 goto parse_fail;
307         *pos = '\0';
308         imsi = pos + 1;
309         pos = strchr(imsi, ' ');
310         if (pos == NULL)
311                 goto parse_fail;
312         *pos = '\0';
313         wpa_printf(MSG_DEBUG, "EAP-SIM DB: External response=%s for IMSI %s",
314                    cmd, imsi);
315
316         if (strcmp(cmd, "SIM-RESP-AUTH") == 0)
317                 eap_sim_db_sim_resp_auth(data, imsi, pos + 1);
318         else if (strcmp(cmd, "AKA-RESP-AUTH") == 0)
319                 eap_sim_db_aka_resp_auth(data, imsi, pos + 1);
320         else
321                 wpa_printf(MSG_INFO, "EAP-SIM DB: Unknown external response "
322                            "'%s'", cmd);
323         return;
324
325 parse_fail:
326         wpa_printf(MSG_DEBUG, "EAP-SIM DB: Failed to parse response string");
327 }
328
329
330 static int eap_sim_db_open_socket(struct eap_sim_db_data *data)
331 {
332         struct sockaddr_un addr;
333         static int counter = 0;
334
335         if (strncmp(data->fname, "unix:", 5) != 0)
336                 return -1;
337
338         data->sock = socket(PF_UNIX, SOCK_DGRAM, 0);
339         if (data->sock < 0) {
340                 perror("socket(eap_sim_db)");
341                 return -1;
342         }
343
344         memset(&addr, 0, sizeof(addr));
345         addr.sun_family = AF_UNIX;
346         snprintf(addr.sun_path, sizeof(addr.sun_path),
347                  "/tmp/eap_sim_db_%d-%d", getpid(), counter++);
348         data->local_sock = strdup(addr.sun_path);
349         if (bind(data->sock, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
350                 perror("bind(eap_sim_db)");
351                 close(data->sock);
352                 data->sock = -1;
353                 return -1;
354         }
355
356         memset(&addr, 0, sizeof(addr));
357         addr.sun_family = AF_UNIX;
358         snprintf(addr.sun_path, sizeof(addr.sun_path), "%s", data->fname + 5);
359         if (connect(data->sock, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
360                 perror("connect(eap_sim_db)");
361                 wpa_hexdump_ascii(MSG_INFO, "HLR/AuC GW socket",
362                                   (u8 *) addr.sun_path, strlen(addr.sun_path));
363                 close(data->sock);
364                 data->sock = -1;
365                 return -1;
366         }
367
368         eloop_register_read_sock(data->sock, eap_sim_db_receive, data, NULL);
369
370         return 0;
371 }
372
373
374 static void eap_sim_db_close_socket(struct eap_sim_db_data *data)
375 {
376         if (data->sock >= 0) {
377                 eloop_unregister_read_sock(data->sock);
378                 close(data->sock);
379                 data->sock = -1;
380         }
381         if (data->local_sock) {
382                 unlink(data->local_sock);
383                 free(data->local_sock);
384                 data->local_sock = NULL;
385         }
386 }
387
388
389 /**
390  * eap_sim_db_init - Initialize EAP-SIM DB / authentication gateway interface
391  * @config: Configuration data (e.g., file name)
392  * @get_complete_cb: Callback function for reporting availability of triplets
393  * @ctx: Context pointer for get_complete_cb
394  * Returns: Pointer to a private data structure or %NULL on failure
395  */
396 void * eap_sim_db_init(const char *config,
397                        void (*get_complete_cb)(void *ctx, void *session_ctx),
398                        void *ctx)
399 {
400         struct eap_sim_db_data *data;
401
402         data = wpa_zalloc(sizeof(*data));
403         if (data == NULL)
404                 return NULL;
405
406         data->sock = -1;
407         data->get_complete_cb = get_complete_cb;
408         data->ctx = ctx;
409         data->fname = strdup(config);
410         if (data->fname == NULL)
411                 goto fail;
412
413         if (strncmp(data->fname, "unix:", 5) == 0) {
414                 if (eap_sim_db_open_socket(data))
415                         goto fail;
416         }
417
418         return data;
419
420 fail:
421         eap_sim_db_close_socket(data);
422         free(data->fname);
423         free(data);
424         return NULL;
425 }
426
427
428 static void eap_sim_db_free_pseudonym(struct eap_sim_pseudonym *p)
429 {
430         free(p->identity);
431         free(p->pseudonym);
432         free(p);
433 }
434
435
436 static void eap_sim_db_free_reauth(struct eap_sim_reauth *r)
437 {
438         free(r->identity);
439         free(r->reauth_id);
440         free(r);
441 }
442
443
444 /**
445  * eap_sim_db_deinit - Deinitialize EAP-SIM DB/authentication gw interface
446  * @priv: Private data pointer from eap_sim_db_init()
447  */
448 void eap_sim_db_deinit(void *priv)
449 {
450         struct eap_sim_db_data *data = priv;
451         struct eap_sim_pseudonym *p, *prev;
452         struct eap_sim_reauth *r, *prevr;
453         struct eap_sim_db_pending *pending, *prev_pending;
454
455         eap_sim_db_close_socket(data);
456         free(data->fname);
457
458         p = data->pseudonyms;
459         while (p) {
460                 prev = p;
461                 p = p->next;
462                 eap_sim_db_free_pseudonym(prev);
463         }
464
465         r = data->reauths;
466         while (r) {
467                 prevr = r;
468                 r = r->next;
469                 eap_sim_db_free_reauth(prevr);
470         }
471
472         pending = data->pending;
473         while (pending) {
474                 prev_pending = pending;
475                 pending = pending->next;
476                 free(prev_pending);
477         }
478
479         free(data);
480 }
481
482
483 static int eap_sim_db_send(struct eap_sim_db_data *data, const char *msg,
484                            size_t len)
485 {
486         int _errno = 0;
487
488         if (send(data->sock, msg, len, 0) < 0) {
489                 _errno = errno;
490                 perror("send[EAP-SIM DB UNIX]");
491         }
492
493         if (_errno == ENOTCONN || _errno == EDESTADDRREQ || _errno == EINVAL ||
494             _errno == ECONNREFUSED) {
495                 /* Try to reconnect */
496                 eap_sim_db_close_socket(data);
497                 if (eap_sim_db_open_socket(data) < 0)
498                         return -1;
499                 wpa_printf(MSG_DEBUG, "EAP-SIM DB: Reconnected to the "
500                            "external server");
501                 if (send(data->sock, msg, len, 0) < 0) {
502                         perror("send[EAP-SIM DB UNIX]");
503                         return -1;
504                 }
505         }
506
507         return 0;
508 }
509
510
511 static void eap_sim_db_expire_pending(struct eap_sim_db_data *data)
512 {
513         /* TODO: add limit for maximum length for pending list; remove latest
514          * (i.e., last) entry from the list if the limit is reached; could also
515          * use timeout to expire pending entries */
516 }
517
518
519 /**
520  * eap_sim_db_get_gsm_triplets - Get GSM triplets
521  * @priv: Private data pointer from eap_sim_db_init()
522  * @identity: User name identity
523  * @identity_len: Length of identity in bytes
524  * @max_chal: Maximum number of triplets
525  * @_rand: Buffer for RAND values
526  * @kc: Buffer for Kc values
527  * @sres: Buffer for SRES values
528  * @cb_session_ctx: Session callback context for get_complete_cb()
529  * Returns: Number of triplets received (has to be less than or equal to
530  * max_chal), -1 (EAP_SIM_DB_FAILURE) on error (e.g., user not found), or
531  * -2 (EAP_SIM_DB_PENDING) if results are not yet available. In this case, the
532  * callback function registered with eap_sim_db_init() will be called once the
533  * results become available.
534  *
535  * In most cases, the user name is '1' | IMSI, i.e., 1 followed by the IMSI in
536  * ASCII format.
537  *
538  * When using an external server for GSM triplets, this function can always
539  * start a request and return EAP_SIM_DB_PENDING immediately if authentication
540  * triplets are not available. Once the triplets are received, callback
541  * function registered with eap_sim_db_init() is called to notify EAP state
542  * machine to reprocess the message. This eap_sim_db_get_gsm_triplets()
543  * function will then be called again and the newly received triplets will then
544  * be given to the caller.
545  */
546 int eap_sim_db_get_gsm_triplets(void *priv, const u8 *identity,
547                                 size_t identity_len, int max_chal,
548                                 u8 *_rand, u8 *kc, u8 *sres,
549                                 void *cb_session_ctx)
550 {
551         struct eap_sim_db_data *data = priv;
552         struct eap_sim_db_pending *entry;
553         int len, ret;
554         size_t i;
555         char msg[40];
556
557         if (identity_len < 2 || identity[0] != EAP_SIM_PERMANENT_PREFIX ||
558             identity_len + 1 > sizeof(entry->imsi)) {
559                 wpa_hexdump_ascii(MSG_DEBUG, "EAP-SIM DB: unexpected identity",
560                                   identity, identity_len);
561                 return EAP_SIM_DB_FAILURE;
562         }
563         identity++;
564         identity_len--;
565         for (i = 0; i < identity_len; i++) {
566                 if (identity[i] == '@') {
567                         identity_len = i;
568                         break;
569                 }
570         }
571         wpa_hexdump_ascii(MSG_DEBUG, "EAP-SIM DB: Get GSM triplets for IMSI",
572                           identity, identity_len);
573
574         entry = eap_sim_db_get_pending(data, identity, identity_len, 0);
575         if (entry) {
576                 int num_chal;
577                 if (entry->state == FAILURE) {
578                         wpa_printf(MSG_DEBUG, "EAP-SIM DB: Pending entry -> "
579                                    "failure");
580                         free(entry);
581                         return EAP_SIM_DB_FAILURE;
582                 }
583
584                 if (entry->state == PENDING) {
585                         wpa_printf(MSG_DEBUG, "EAP-SIM DB: Pending entry -> "
586                                    "still pending");
587                         eap_sim_db_add_pending(data, entry);
588                         return EAP_SIM_DB_PENDING;
589                 }
590
591                 wpa_printf(MSG_DEBUG, "EAP-SIM DB: Pending entry -> "
592                            "%d challenges", entry->u.sim.num_chal);
593                 num_chal = entry->u.sim.num_chal;
594                 if (num_chal > max_chal)
595                         num_chal = max_chal;
596                 memcpy(_rand, entry->u.sim.rand, num_chal * GSM_RAND_LEN);
597                 memcpy(sres, entry->u.sim.sres, num_chal * EAP_SIM_SRES_LEN);
598                 memcpy(kc, entry->u.sim.kc, num_chal * EAP_SIM_KC_LEN);
599                 free(entry);
600                 return num_chal;
601         }
602
603         if (data->sock < 0) {
604                 if (eap_sim_db_open_socket(data) < 0)
605                         return EAP_SIM_DB_FAILURE;
606         }
607
608         len = snprintf(msg, sizeof(msg), "SIM-REQ-AUTH ");
609         if (len < 0 || len + identity_len >= sizeof(msg))
610                 return EAP_SIM_DB_FAILURE;
611         memcpy(msg + len, identity, identity_len);
612         len += identity_len;
613         ret = snprintf(msg + len, sizeof(msg) - len, " %d", max_chal);
614         if (ret < 0 || (size_t) ret >= sizeof(msg) - len)
615                 return EAP_SIM_DB_FAILURE;
616         len += ret;
617
618         wpa_hexdump(MSG_DEBUG, "EAP-SIM DB: requesting SIM authentication "
619                     "data for IMSI", identity, identity_len);
620         if (eap_sim_db_send(data, msg, len) < 0)
621                 return EAP_SIM_DB_FAILURE;
622
623         entry = wpa_zalloc(sizeof(*entry));
624         if (entry == NULL)
625                 return EAP_SIM_DB_FAILURE;
626
627         os_get_time(&entry->timestamp);
628         memcpy(entry->imsi, identity, identity_len);
629         entry->imsi_len = identity_len;
630         entry->cb_session_ctx = cb_session_ctx;
631         entry->state = PENDING;
632         eap_sim_db_add_pending(data, entry);
633         eap_sim_db_expire_pending(data);
634
635         return EAP_SIM_DB_PENDING;
636 }
637
638
639 static struct eap_sim_pseudonym *
640 eap_sim_db_get_pseudonym(struct eap_sim_db_data *data, const u8 *identity,
641                          size_t identity_len)
642 {
643         char *pseudonym;
644         size_t len;
645         struct eap_sim_pseudonym *p;
646
647         if (identity_len == 0 ||
648             (identity[0] != EAP_SIM_PSEUDONYM_PREFIX &&
649              identity[0] != EAP_AKA_PSEUDONYM_PREFIX))
650                 return NULL;
651
652         /* Remove possible realm from identity */
653         len = 0;
654         while (len < identity_len) {
655                 if (identity[len] == '@')
656                         break;
657                 len++;
658         }
659
660         pseudonym = malloc(len + 1);
661         if (pseudonym == NULL)
662                 return NULL;
663         memcpy(pseudonym, identity, len);
664         pseudonym[len] = '\0';
665
666         p = data->pseudonyms;
667         while (p) {
668                 if (strcmp(p->pseudonym, pseudonym) == 0)
669                         break;
670                 p = p->next;
671         }
672
673         free(pseudonym);
674
675         return p;
676 }
677
678
679 static struct eap_sim_pseudonym *
680 eap_sim_db_get_pseudonym_id(struct eap_sim_db_data *data, const u8 *identity,
681                             size_t identity_len)
682 {
683         struct eap_sim_pseudonym *p;
684
685         if (identity_len == 0 ||
686             (identity[0] != EAP_SIM_PERMANENT_PREFIX &&
687              identity[0] != EAP_AKA_PERMANENT_PREFIX))
688                 return NULL;
689
690         p = data->pseudonyms;
691         while (p) {
692                 if (identity_len == p->identity_len &&
693                     memcmp(p->identity, identity, identity_len) == 0)
694                         break;
695                 p = p->next;
696         }
697
698         return p;
699 }
700
701
702 static struct eap_sim_reauth *
703 eap_sim_db_get_reauth(struct eap_sim_db_data *data, const u8 *identity,
704                       size_t identity_len)
705 {
706         char *reauth_id;
707         size_t len;
708         struct eap_sim_reauth *r;
709
710         if (identity_len == 0 ||
711             (identity[0] != EAP_SIM_REAUTH_ID_PREFIX &&
712              identity[0] != EAP_AKA_REAUTH_ID_PREFIX))
713                 return NULL;
714
715         /* Remove possible realm from identity */
716         len = 0;
717         while (len < identity_len) {
718                 if (identity[len] == '@')
719                         break;
720                 len++;
721         }
722
723         reauth_id = malloc(len + 1);
724         if (reauth_id == NULL)
725                 return NULL;
726         memcpy(reauth_id, identity, len);
727         reauth_id[len] = '\0';
728
729         r = data->reauths;
730         while (r) {
731                 if (strcmp(r->reauth_id, reauth_id) == 0)
732                         break;
733                 r = r->next;
734         }
735
736         free(reauth_id);
737
738         return r;
739 }
740
741
742 static struct eap_sim_reauth *
743 eap_sim_db_get_reauth_id(struct eap_sim_db_data *data, const u8 *identity,
744                          size_t identity_len)
745 {
746         struct eap_sim_pseudonym *p;
747         struct eap_sim_reauth *r;
748
749         if (identity_len == 0)
750                 return NULL;
751
752         p = eap_sim_db_get_pseudonym(data, identity, identity_len);
753         if (p == NULL)
754                 p = eap_sim_db_get_pseudonym_id(data, identity, identity_len);
755         if (p) {
756                 identity = p->identity;
757                 identity_len = p->identity_len;
758         }
759
760         r = data->reauths;
761         while (r) {
762                 if (identity_len == r->identity_len &&
763                     memcmp(r->identity, identity, identity_len) == 0)
764                         break;
765                 r = r->next;
766         }
767
768         return r;
769 }
770
771
772 /**
773  * eap_sim_db_identity_known - Verify whether the given identity is known
774  * @priv: Private data pointer from eap_sim_db_init()
775  * @identity: User name identity
776  * @identity_len: Length of identity in bytes 
777  * Returns: 0 if the user is found or -1 on failure
778  *
779  * In most cases, the user name is ['0','1'] | IMSI, i.e., 1 followed by the
780  * IMSI in ASCII format, ['2','3'] | pseudonym, or ['4','5'] | reauth_id.
781  */
782 int eap_sim_db_identity_known(void *priv, const u8 *identity,
783                               size_t identity_len)
784 {
785         struct eap_sim_db_data *data = priv;
786
787         if (identity == NULL || identity_len < 2)
788                 return -1;
789
790         if (identity[0] == EAP_SIM_PSEUDONYM_PREFIX ||
791             identity[0] == EAP_AKA_PSEUDONYM_PREFIX) {
792                 struct eap_sim_pseudonym *p =
793                         eap_sim_db_get_pseudonym(data, identity, identity_len);
794                 return p ? 0 : -1;
795         }
796
797         if (identity[0] == EAP_SIM_REAUTH_ID_PREFIX ||
798             identity[0] == EAP_AKA_REAUTH_ID_PREFIX) {
799                 struct eap_sim_reauth *r =
800                         eap_sim_db_get_reauth(data, identity, identity_len);
801                 return r ? 0 : -1;
802         }
803
804         if (identity[0] != EAP_SIM_PERMANENT_PREFIX &&
805             identity[0] != EAP_AKA_PERMANENT_PREFIX) {
806                 /* Unknown identity prefix */
807                 return -1;
808         }
809
810         /* TODO: Should consider asking HLR/AuC gateway whether this permanent
811          * identity is known. If it is, EAP-SIM/AKA can skip identity request.
812          * In case of EAP-AKA, this would reduce number of needed round-trips.
813          * Ideally, this would be done with one wait, i.e., just request
814          * authentication data and store it for the next use. This would then
815          * need to use similar pending-request functionality as the normal
816          * request for authentication data at later phase.
817          */
818         return -1;
819 }
820
821
822 static char * eap_sim_db_get_next(struct eap_sim_db_data *data, char prefix)
823 {
824         char *id, *pos, *end;
825         u8 buf[10];
826
827         if (hostapd_get_rand(buf, sizeof(buf)))
828                 return NULL;
829         id = malloc(sizeof(buf) * 2 + 2);
830         if (id == NULL)
831                 return NULL;
832
833         pos = id;
834         end = id + sizeof(buf) * 2 + 2;
835         *pos++ = prefix;
836         pos += wpa_snprintf_hex(pos, end - pos, buf, sizeof(buf));
837         
838         return id;
839 }
840
841
842 /**
843  * eap_sim_db_get_next_pseudonym - EAP-SIM DB: Get next pseudonym
844  * @priv: Private data pointer from eap_sim_db_init()
845  * @aka: Using EAP-AKA instead of EAP-SIM
846  * Returns: Next pseudonym (allocated string) or %NULL on failure
847  *
848  * This function is used to generate a pseudonym for EAP-SIM. The returned
849  * pseudonym is not added to database at this point; it will need to be added
850  * with eap_sim_db_add_pseudonym() once the authentication has been completed
851  * successfully. Caller is responsible for freeing the returned buffer.
852  */
853 char * eap_sim_db_get_next_pseudonym(void *priv, int aka)
854 {
855         struct eap_sim_db_data *data = priv;
856         return eap_sim_db_get_next(data, aka ? EAP_AKA_PSEUDONYM_PREFIX :
857                                    EAP_SIM_PSEUDONYM_PREFIX);
858 }
859
860
861 /**
862  * eap_sim_db_get_next_reauth_id - EAP-SIM DB: Get next reauth_id
863  * @priv: Private data pointer from eap_sim_db_init()
864  * @aka: Using EAP-AKA instead of EAP-SIM
865  * Returns: Next reauth_id (allocated string) or %NULL on failure
866  *
867  * This function is used to generate a fast re-authentication identity for
868  * EAP-SIM. The returned reauth_id is not added to database at this point; it
869  * will need to be added with eap_sim_db_add_reauth() once the authentication
870  * has been completed successfully. Caller is responsible for freeing the
871  * returned buffer.
872  */
873 char * eap_sim_db_get_next_reauth_id(void *priv, int aka)
874 {
875         struct eap_sim_db_data *data = priv;
876         return eap_sim_db_get_next(data, aka ? EAP_AKA_REAUTH_ID_PREFIX :
877                                    EAP_SIM_REAUTH_ID_PREFIX);
878 }
879
880
881 /**
882  * eap_sim_db_add_pseudonym - EAP-SIM DB: Add new pseudonym
883  * @priv: Private data pointer from eap_sim_db_init()
884  * @identity: Identity of the user (may be permanent identity or pseudonym)
885  * @identity_len: Length of identity
886  * @pseudonym: Pseudonym for this user. This needs to be an allocated buffer,
887  * e.g., return value from eap_sim_db_get_next_pseudonym(). Caller must not
888  * free it.
889  * Returns: 0 on success, -1 on failure
890  *
891  * This function adds a new pseudonym for EAP-SIM user. EAP-SIM DB is
892  * responsible of freeing pseudonym buffer once it is not needed anymore.
893  */
894 int eap_sim_db_add_pseudonym(void *priv, const u8 *identity,
895                              size_t identity_len, char *pseudonym)
896 {
897         struct eap_sim_db_data *data = priv;
898         struct eap_sim_pseudonym *p;
899         wpa_hexdump_ascii(MSG_DEBUG, "EAP-SIM DB: Add pseudonym for identity",
900                           identity, identity_len);
901         wpa_printf(MSG_DEBUG, "EAP-SIM DB: Pseudonym: %s", pseudonym);
902
903         /* TODO: could store last two pseudonyms */
904         p = eap_sim_db_get_pseudonym(data, identity, identity_len);
905         if (p == NULL)
906                 p = eap_sim_db_get_pseudonym_id(data, identity, identity_len);
907
908         if (p) {
909                 wpa_printf(MSG_DEBUG, "EAP-SIM DB: Replacing previous "
910                            "pseudonym: %s", p->pseudonym);
911                 free(p->pseudonym);
912                 p->pseudonym = pseudonym;
913                 return 0;
914         }
915
916         p = wpa_zalloc(sizeof(*p));
917         if (p == NULL) {
918                 free(pseudonym);
919                 return -1;
920         }
921
922         p->next = data->pseudonyms;
923         p->identity = malloc(identity_len);
924         if (p->identity == NULL) {
925                 free(p);
926                 free(pseudonym);
927                 return -1;
928         }
929         memcpy(p->identity, identity, identity_len);
930         p->identity_len = identity_len;
931         p->pseudonym = pseudonym;
932         data->pseudonyms = p;
933
934         wpa_printf(MSG_DEBUG, "EAP-SIM DB: Added new pseudonym entry");
935         return 0;
936 }
937
938
939 /**
940  * eap_sim_db_add_reauth - EAP-SIM DB: Add new re-authentication entry
941  * @priv: Private data pointer from eap_sim_db_init()
942  * @identity: Identity of the user (may be permanent identity or pseudonym)
943  * @identity_len: Length of identity
944  * @reauth_id: reauth_id for this user. This needs to be an allocated buffer,
945  * e.g., return value from eap_sim_db_get_next_reauth_id(). Caller must not
946  * free it.
947  * @mk: 16-byte MK from the previous full authentication
948  * Returns: 0 on success, -1 on failure
949  *
950  * This function adds a new re-authentication entry for an EAP-SIM user.
951  * EAP-SIM DB is responsible of freeing reauth_id buffer once it is not needed
952  * anymore.
953  */
954 int eap_sim_db_add_reauth(void *priv, const u8 *identity,
955                           size_t identity_len, char *reauth_id, u16 counter,
956                           const u8 *mk)
957 {
958         struct eap_sim_db_data *data = priv;
959         struct eap_sim_reauth *r;
960         wpa_hexdump_ascii(MSG_DEBUG, "EAP-SIM DB: Add reauth_id for identity",
961                           identity, identity_len);
962         wpa_printf(MSG_DEBUG, "EAP-SIM DB: reauth_id: %s", reauth_id);
963
964         r = eap_sim_db_get_reauth(data, identity, identity_len);
965         if (r == NULL)
966                 r = eap_sim_db_get_reauth_id(data, identity, identity_len);
967
968         if (r) {
969                 wpa_printf(MSG_DEBUG, "EAP-SIM DB: Replacing previous "
970                            "reauth_id: %s", r->reauth_id);
971                 free(r->reauth_id);
972                 r->reauth_id = reauth_id;
973         } else {
974                 r = wpa_zalloc(sizeof(*r));
975                 if (r == NULL) {
976                         free(reauth_id);
977                         return -1;
978                 }
979
980                 r->next = data->reauths;
981                 r->identity = malloc(identity_len);
982                 if (r->identity == NULL) {
983                         free(r);
984                         free(reauth_id);
985                         return -1;
986                 }
987                 memcpy(r->identity, identity, identity_len);
988                 r->identity_len = identity_len;
989                 r->reauth_id = reauth_id;
990                 data->reauths = r;
991                 wpa_printf(MSG_DEBUG, "EAP-SIM DB: Added new reauth entry");
992         }
993
994         r->counter = counter;
995         memcpy(r->mk, mk, EAP_SIM_MK_LEN);
996
997         return 0;
998 }
999
1000
1001 /**
1002  * eap_sim_db_get_permanent - EAP-SIM DB: Get permanent identity
1003  * @priv: Private data pointer from eap_sim_db_init()
1004  * @identity: Identity of the user (may be permanent identity or pseudonym)
1005  * @identity_len: Length of identity
1006  * @len: Buffer for length of the returned permanent identity
1007  * Returns: Pointer to the permanent identity, or %NULL if not found
1008  */
1009 const u8 * eap_sim_db_get_permanent(void *priv, const u8 *identity,
1010                                     size_t identity_len, size_t *len)
1011 {
1012         struct eap_sim_db_data *data = priv;
1013         struct eap_sim_pseudonym *p;
1014
1015         if (identity == NULL)
1016                 return NULL;
1017
1018         p = eap_sim_db_get_pseudonym(data, identity, identity_len);
1019         if (p == NULL)
1020                 p = eap_sim_db_get_pseudonym_id(data, identity, identity_len);
1021         if (p == NULL)
1022                 return NULL;
1023
1024         *len = p->identity_len;
1025         return p->identity;
1026 }
1027
1028
1029 /**
1030  * eap_sim_db_get_reauth_entry - EAP-SIM DB: Get re-authentication entry
1031  * @priv: Private data pointer from eap_sim_db_init()
1032  * @identity: Identity of the user (may be permanent identity, pseudonym, or
1033  * reauth_id)
1034  * @identity_len: Length of identity
1035  * @len: Buffer for length of the returned permanent identity
1036  * Returns: Pointer to the re-auth entry, or %NULL if not found
1037  */
1038 struct eap_sim_reauth *
1039 eap_sim_db_get_reauth_entry(void *priv, const u8 *identity,
1040                             size_t identity_len)
1041 {
1042         struct eap_sim_db_data *data = priv;
1043         struct eap_sim_reauth *r;
1044
1045         if (identity == NULL)
1046                 return NULL;
1047         r = eap_sim_db_get_reauth(data, identity, identity_len);
1048         if (r == NULL)
1049                 r = eap_sim_db_get_reauth_id(data, identity, identity_len);
1050         return r;
1051 }
1052
1053
1054 /**
1055  * eap_sim_db_remove_reauth - EAP-SIM DB: Remove re-authentication entry
1056  * @priv: Private data pointer from eap_sim_db_init()
1057  * @reauth: Pointer to re-authentication entry from
1058  * eap_sim_db_get_reauth_entry()
1059  */
1060 void eap_sim_db_remove_reauth(void *priv, struct eap_sim_reauth *reauth)
1061 {
1062         struct eap_sim_db_data *data = priv;
1063         struct eap_sim_reauth *r, *prev = NULL;
1064         r = data->reauths;
1065         while (r) {
1066                 if (r == reauth) {
1067                         if (prev)
1068                                 prev->next = r->next;
1069                         else
1070                                 data->reauths = r->next;
1071                         eap_sim_db_free_reauth(r);
1072                         return;
1073                 }
1074                 prev = r;
1075                 r = r->next;
1076         }
1077 }
1078
1079
1080 /**
1081  * eap_sim_db_get_aka_auth - Get AKA authentication values
1082  * @priv: Private data pointer from eap_sim_db_init()
1083  * @identity: User name identity
1084  * @identity_len: Length of identity in bytes
1085  * @_rand: Buffer for RAND value
1086  * @autn: Buffer for AUTN value
1087  * @ik: Buffer for IK value
1088  * @ck: Buffer for CK value
1089  * @res: Buffer for RES value
1090  * @res_len: Buffer for RES length
1091  * @cb_session_ctx: Session callback context for get_complete_cb()
1092  * Returns: 0 on success, -1 (EAP_SIM_DB_FAILURE) on error (e.g., user not
1093  * found), or -2 (EAP_SIM_DB_PENDING) if results are not yet available. In this
1094  * case, the callback function registered with eap_sim_db_init() will be
1095  * called once the results become available.
1096  *
1097  * In most cases, the user name is '0' | IMSI, i.e., 0 followed by the IMSI in
1098  * ASCII format.
1099  *
1100  * When using an external server for AKA authentication, this function can
1101  * always start a request and return EAP_SIM_DB_PENDING immediately if
1102  * authentication triplets are not available. Once the authentication data are
1103  * received, callback function registered with eap_sim_db_init() is called to
1104  * notify EAP state machine to reprocess the message. This
1105  * eap_sim_db_get_aka_auth() function will then be called again and the newly
1106  * received triplets will then be given to the caller.
1107  */
1108 int eap_sim_db_get_aka_auth(void *priv, const u8 *identity,
1109                             size_t identity_len, u8 *_rand, u8 *autn, u8 *ik,
1110                             u8 *ck, u8 *res, size_t *res_len,
1111                             void *cb_session_ctx)
1112 {
1113         struct eap_sim_db_data *data = priv;
1114         struct eap_sim_db_pending *entry;
1115         int len;
1116         size_t i;
1117         char msg[40];
1118
1119         if (identity_len < 2 || identity == NULL ||
1120             identity[0] != EAP_AKA_PERMANENT_PREFIX ||
1121             identity_len + 1 > sizeof(entry->imsi)) {
1122                 wpa_hexdump_ascii(MSG_DEBUG, "EAP-SIM DB: unexpected identity",
1123                                   identity, identity_len);
1124                 return EAP_SIM_DB_FAILURE;
1125         }
1126         identity++;
1127         identity_len--;
1128         for (i = 0; i < identity_len; i++) {
1129                 if (identity[i] == '@') {
1130                         identity_len = i;
1131                         break;
1132                 }
1133         }
1134         wpa_hexdump_ascii(MSG_DEBUG, "EAP-SIM DB: Get AKA auth for IMSI",
1135                           identity, identity_len);
1136
1137         entry = eap_sim_db_get_pending(data, identity, identity_len, 1);
1138         if (entry) {
1139                 if (entry->state == FAILURE) {
1140                         free(entry);
1141                         wpa_printf(MSG_DEBUG, "EAP-SIM DB: Failure");
1142                         return EAP_SIM_DB_FAILURE;
1143                 }
1144
1145                 if (entry->state == PENDING) {
1146                         eap_sim_db_add_pending(data, entry);
1147                         wpa_printf(MSG_DEBUG, "EAP-SIM DB: Pending");
1148                         return EAP_SIM_DB_PENDING;
1149                 }
1150
1151                 wpa_printf(MSG_DEBUG, "EAP-SIM DB: Returning successfully "
1152                            "received authentication data");
1153                 memcpy(_rand, entry->u.aka.rand, EAP_AKA_RAND_LEN);
1154                 memcpy(autn, entry->u.aka.autn, EAP_AKA_AUTN_LEN);
1155                 memcpy(ik, entry->u.aka.ik, EAP_AKA_IK_LEN);
1156                 memcpy(ck, entry->u.aka.ck, EAP_AKA_CK_LEN);
1157                 memcpy(res, entry->u.aka.res, EAP_AKA_RES_MAX_LEN);
1158                 *res_len = entry->u.aka.res_len;
1159                 free(entry);
1160                 return 0;
1161         }
1162
1163         if (data->sock < 0) {
1164                 if (eap_sim_db_open_socket(data) < 0)
1165                         return EAP_SIM_DB_FAILURE;
1166         }
1167
1168         len = snprintf(msg, sizeof(msg), "AKA-REQ-AUTH ");
1169         if (len < 0 || len + identity_len >= sizeof(msg))
1170                 return EAP_SIM_DB_FAILURE;
1171         memcpy(msg + len, identity, identity_len);
1172         len += identity_len;
1173
1174         wpa_hexdump(MSG_DEBUG, "EAP-SIM DB: requesting AKA authentication "
1175                     "data for IMSI", identity, identity_len);
1176         if (eap_sim_db_send(data, msg, len) < 0)
1177                 return EAP_SIM_DB_FAILURE;
1178
1179         entry = wpa_zalloc(sizeof(*entry));
1180         if (entry == NULL)
1181                 return EAP_SIM_DB_FAILURE;
1182
1183         os_get_time(&entry->timestamp);
1184         entry->aka = 1;
1185         memcpy(entry->imsi, identity, identity_len);
1186         entry->imsi_len = identity_len;
1187         entry->cb_session_ctx = cb_session_ctx;
1188         entry->state = PENDING;
1189         eap_sim_db_add_pending(data, entry);
1190         eap_sim_db_expire_pending(data);
1191
1192         return EAP_SIM_DB_PENDING;
1193 }
1194
1195
1196 /**
1197  * eap_sim_db_resynchronize - Resynchronize AKA AUTN
1198  * @priv: Private data pointer from eap_sim_db_init()
1199  * @identity: User name identity
1200  * @identity_len: Length of identity in bytes
1201  * @auts: AUTS value from the peer
1202  * @_rand: RAND value used in the rejected message
1203  * Returns: 0 on success, -1 on failure
1204  *
1205  * This function is called when the peer reports synchronization failure in the
1206  * AUTN value by sending AUTS. The AUTS and RAND values should be sent to
1207  * HLR/AuC to allow it to resynchronize with the peer. After this,
1208  * eap_sim_db_get_aka_auth() will be called again to to fetch updated
1209  * RAND/AUTN values for the next challenge.
1210  */
1211 int eap_sim_db_resynchronize(void *priv, const u8 *identity,
1212                              size_t identity_len, const u8 *auts,
1213                              const u8 *_rand)
1214 {
1215         struct eap_sim_db_data *data = priv;
1216
1217         if (identity_len < 2 || identity[0] != EAP_AKA_PERMANENT_PREFIX ||
1218             identity_len > 20) {
1219                 wpa_hexdump_ascii(MSG_DEBUG, "EAP-SIM DB: unexpected identity",
1220                                   identity, identity_len);
1221                 return -1;
1222         }
1223
1224         if (data->sock >= 0) {
1225                 char msg[100];
1226                 int len, ret;
1227
1228                 len = snprintf(msg, sizeof(msg), "AKA-AUTS ");
1229                 if (len < 0 || len + identity_len - 1 >= sizeof(msg))
1230                         return -1;
1231                 memcpy(msg + len, identity + 1, identity_len - 1);
1232                 len += identity_len - 1;
1233
1234                 ret = snprintf(msg + len, sizeof(msg) - len, " ");
1235                 if (ret < 0 || (size_t) ret >= sizeof(msg) - len)
1236                         return -1;
1237                 len += ret;
1238                 len += wpa_snprintf_hex(msg + len, sizeof(msg) - len,
1239                                         auts, EAP_AKA_AUTS_LEN);
1240                 ret = snprintf(msg + len, sizeof(msg) - len, " ");
1241                 if (ret < 0 || (size_t) ret >= sizeof(msg) - len)
1242                         return -1;
1243                 len += ret;
1244                 len += wpa_snprintf_hex(msg + len, sizeof(msg) - len,
1245                                         _rand, EAP_AKA_RAND_LEN);
1246                 wpa_hexdump(MSG_DEBUG, "EAP-SIM DB: reporting AKA AUTS for "
1247                             "IMSI", identity + 1, identity_len - 1);
1248                 if (eap_sim_db_send(data, msg, len) < 0)
1249                         return -1;
1250         }
1251
1252         return 0;
1253 }