EAP-SIM DB: Return pseudonym username instead of structure with it
[mech_eap.git] / src / eap_server / eap_sim_db.c
1 /*
2  * hostapd / EAP-SIM database/authenticator gateway
3  * Copyright (c) 2005-2010, 2012, Jouni Malinen <j@w1.fi>
4  *
5  * This software may be distributed under the terms of the BSD license.
6  * See README for more details.
7  *
8  * This is an example implementation of the EAP-SIM/AKA database/authentication
9  * gateway interface that is using an external program as an SS7 gateway to
10  * GSM/UMTS authentication center (HLR/AuC). hlr_auc_gw is an example
11  * implementation of such a gateway program. This eap_sim_db.c takes care of
12  * EAP-SIM/AKA pseudonyms and re-auth identities. It can be used with different
13  * gateway implementations for HLR/AuC access. Alternatively, it can also be
14  * completely replaced if the in-memory database of pseudonyms/re-auth
15  * identities is not suitable for some cases.
16  */
17
18 #include "includes.h"
19 #include <sys/un.h>
20 #ifdef CONFIG_SQLITE
21 #include <sqlite3.h>
22 #endif /* CONFIG_SQLITE */
23
24 #include "common.h"
25 #include "crypto/random.h"
26 #include "eap_common/eap_sim_common.h"
27 #include "eap_server/eap_sim_db.h"
28 #include "eloop.h"
29
30 struct eap_sim_pseudonym {
31         struct eap_sim_pseudonym *next;
32         char *permanent; /* permanent username */
33         char *pseudonym; /* pseudonym username */
34 };
35
36 struct eap_sim_db_pending {
37         struct eap_sim_db_pending *next;
38         char imsi[20];
39         enum { PENDING, SUCCESS, FAILURE } state;
40         void *cb_session_ctx;
41         struct os_time timestamp;
42         int aka;
43         union {
44                 struct {
45                         u8 kc[EAP_SIM_MAX_CHAL][EAP_SIM_KC_LEN];
46                         u8 sres[EAP_SIM_MAX_CHAL][EAP_SIM_SRES_LEN];
47                         u8 rand[EAP_SIM_MAX_CHAL][GSM_RAND_LEN];
48                         int num_chal;
49                 } sim;
50                 struct {
51                         u8 rand[EAP_AKA_RAND_LEN];
52                         u8 autn[EAP_AKA_AUTN_LEN];
53                         u8 ik[EAP_AKA_IK_LEN];
54                         u8 ck[EAP_AKA_CK_LEN];
55                         u8 res[EAP_AKA_RES_MAX_LEN];
56                         size_t res_len;
57                 } aka;
58         } u;
59 };
60
61 struct eap_sim_db_data {
62         int sock;
63         char *fname;
64         char *local_sock;
65         void (*get_complete_cb)(void *ctx, void *session_ctx);
66         void *ctx;
67         struct eap_sim_pseudonym *pseudonyms;
68         struct eap_sim_reauth *reauths;
69         struct eap_sim_db_pending *pending;
70 #ifdef CONFIG_SQLITE
71         sqlite3 *sqlite_db;
72         char db_tmp_identity[100];
73         char db_tmp_pseudonym_str[100];
74         struct eap_sim_pseudonym db_tmp_pseudonym;
75         struct eap_sim_reauth db_tmp_reauth;
76 #endif /* CONFIG_SQLITE */
77 };
78
79
80 #ifdef CONFIG_SQLITE
81
82 static int db_table_exists(sqlite3 *db, const char *name)
83 {
84         char cmd[128];
85         os_snprintf(cmd, sizeof(cmd), "SELECT 1 FROM %s;", name);
86         return sqlite3_exec(db, cmd, NULL, NULL, NULL) == SQLITE_OK;
87 }
88
89
90 static int db_table_create_pseudonym(sqlite3 *db)
91 {
92         char *err = NULL;
93         const char *sql =
94                 "CREATE TABLE pseudonyms("
95                 "  permanent CHAR(21) PRIMARY KEY,"
96                 "  pseudonym CHAR(21) NOT NULL"
97                 ");";
98
99         wpa_printf(MSG_DEBUG, "EAP-SIM DB: Adding database table for "
100                    "pseudonym information");
101         if (sqlite3_exec(db, sql, NULL, NULL, &err) != SQLITE_OK) {
102                 wpa_printf(MSG_ERROR, "EAP-SIM DB: SQLite error: %s", err);
103                 sqlite3_free(err);
104                 return -1;
105         }
106
107         return 0;
108 }
109
110
111 static int db_table_create_reauth(sqlite3 *db)
112 {
113         char *err = NULL;
114         const char *sql =
115                 "CREATE TABLE reauth("
116                 "  permanent CHAR(21) PRIMARY KEY,"
117                 "  reauth_id CHAR(21) NOT NULL,"
118                 "  counter INTEGER,"
119                 "  mk CHAR(40),"
120                 "  k_encr CHAR(32),"
121                 "  k_aut CHAR(64),"
122                 "  k_re CHAR(64)"
123                 ");";
124
125         wpa_printf(MSG_DEBUG, "EAP-SIM DB: Adding database table for "
126                    "reauth information");
127         if (sqlite3_exec(db, sql, NULL, NULL, &err) != SQLITE_OK) {
128                 wpa_printf(MSG_ERROR, "EAP-SIM DB: SQLite error: %s", err);
129                 sqlite3_free(err);
130                 return -1;
131         }
132
133         return 0;
134 }
135
136
137 static sqlite3 * db_open(const char *db_file)
138 {
139         sqlite3 *db;
140
141         if (sqlite3_open(db_file, &db)) {
142                 wpa_printf(MSG_ERROR, "EAP-SIM DB: Failed to open database "
143                            "%s: %s", db_file, sqlite3_errmsg(db));
144                 sqlite3_close(db);
145                 return NULL;
146         }
147
148         if (!db_table_exists(db, "pseudonyms") &&
149             db_table_create_pseudonym(db) < 0) {
150                 sqlite3_close(db);
151                 return NULL;
152         }
153
154         if (!db_table_exists(db, "reauth") &&
155             db_table_create_reauth(db) < 0) {
156                 sqlite3_close(db);
157                 return NULL;
158         }
159
160         return db;
161 }
162
163
164 static int valid_db_string(const char *str)
165 {
166         const char *pos = str;
167         while (*pos) {
168                 if ((*pos < '0' || *pos > '9') &&
169                     (*pos < 'a' || *pos > 'f'))
170                         return 0;
171                 pos++;
172         }
173         return 1;
174 }
175
176
177 static int db_add_pseudonym(struct eap_sim_db_data *data,
178                             const char *permanent, char *pseudonym)
179 {
180         char cmd[128];
181         char *err = NULL;
182
183         if (!valid_db_string(permanent) || !valid_db_string(pseudonym)) {
184                 os_free(pseudonym);
185                 return -1;
186         }
187
188         os_snprintf(cmd, sizeof(cmd), "INSERT OR REPLACE INTO pseudonyms "
189                     "(permanent, pseudonym) VALUES ('%s', '%s');",
190                     permanent, pseudonym);
191         os_free(pseudonym);
192         if (sqlite3_exec(data->sqlite_db, cmd, NULL, NULL, &err) != SQLITE_OK)
193         {
194                 wpa_printf(MSG_ERROR, "EAP-SIM DB: SQLite error: %s", err);
195                 sqlite3_free(err);
196                 return -1;
197         }
198
199         return 0;
200 }
201
202
203 static int get_pseudonym_cb(void *ctx, int argc, char *argv[], char *col[])
204 {
205         struct eap_sim_db_data *data = ctx;
206         int i;
207
208         for (i = 0; i < argc; i++) {
209                 if (os_strcmp(col[i], "permanent") == 0 && argv[i]) {
210                         os_strlcpy(data->db_tmp_identity, argv[i],
211                                    sizeof(data->db_tmp_identity));
212                 }
213         }
214
215         return 0;
216 }
217
218
219 static char *
220 db_get_pseudonym(struct eap_sim_db_data *data, const char *pseudonym)
221 {
222         char cmd[128];
223
224         if (!valid_db_string(pseudonym))
225                 return NULL;
226         os_memset(&data->db_tmp_identity, 0, sizeof(data->db_tmp_identity));
227         os_snprintf(cmd, sizeof(cmd),
228                     "SELECT permanent FROM pseudonyms WHERE pseudonym='%s';",
229                     pseudonym);
230         if (sqlite3_exec(data->sqlite_db, cmd, get_pseudonym_cb, data, NULL) !=
231             SQLITE_OK)
232                 return NULL;
233         if (data->db_tmp_identity[0] == '\0')
234                 return NULL;
235         return data->db_tmp_identity;
236 }
237
238
239 static int db_add_reauth(struct eap_sim_db_data *data, const char *permanent,
240                          char *reauth_id, u16 counter, const u8 *mk,
241                          const u8 *k_encr, const u8 *k_aut, const u8 *k_re)
242 {
243         char cmd[2000], *pos, *end;
244         char *err = NULL;
245
246         if (!valid_db_string(permanent) || !valid_db_string(reauth_id)) {
247                 os_free(reauth_id);
248                 return -1;
249         }
250
251         pos = cmd;
252         end = pos + sizeof(cmd);
253         pos += os_snprintf(pos, end - pos, "INSERT OR REPLACE INTO reauth "
254                            "(permanent, reauth_id, counter%s%s%s%s) "
255                            "VALUES ('%s', '%s', %u",
256                            mk ? ", mk" : "",
257                            k_encr ? ", k_encr" : "",
258                            k_aut ? ", k_aut" : "",
259                            k_re ? ", k_re" : "",
260                            permanent, reauth_id, counter);
261         os_free(reauth_id);
262
263         if (mk) {
264                 pos += os_snprintf(pos, end - pos, ", '");
265                 pos += wpa_snprintf_hex(pos, end - pos, mk, EAP_SIM_MK_LEN);
266                 pos += os_snprintf(pos, end - pos, "'");
267         }
268
269         if (k_encr) {
270                 pos += os_snprintf(pos, end - pos, ", '");
271                 pos += wpa_snprintf_hex(pos, end - pos, k_encr,
272                                         EAP_SIM_K_ENCR_LEN);
273                 pos += os_snprintf(pos, end - pos, "'");
274         }
275
276         if (k_aut) {
277                 pos += os_snprintf(pos, end - pos, ", '");
278                 pos += wpa_snprintf_hex(pos, end - pos, k_aut,
279                                         EAP_AKA_PRIME_K_AUT_LEN);
280                 pos += os_snprintf(pos, end - pos, "'");
281         }
282
283         if (k_re) {
284                 pos += os_snprintf(pos, end - pos, ", '");
285                 pos += wpa_snprintf_hex(pos, end - pos, k_re,
286                                         EAP_AKA_PRIME_K_RE_LEN);
287                 pos += os_snprintf(pos, end - pos, "'");
288         }
289
290         os_snprintf(pos, end - pos, ");");
291
292         if (sqlite3_exec(data->sqlite_db, cmd, NULL, NULL, &err) != SQLITE_OK)
293         {
294                 wpa_printf(MSG_ERROR, "EAP-SIM DB: SQLite error: %s", err);
295                 sqlite3_free(err);
296                 return -1;
297         }
298
299         return 0;
300 }
301
302
303 static int get_reauth_cb(void *ctx, int argc, char *argv[], char *col[])
304 {
305         struct eap_sim_db_data *data = ctx;
306         int i;
307         struct eap_sim_reauth *reauth = &data->db_tmp_reauth;
308
309         for (i = 0; i < argc; i++) {
310                 if (os_strcmp(col[i], "permanent") == 0 && argv[i]) {
311                         os_strlcpy(data->db_tmp_identity, argv[i],
312                                    sizeof(data->db_tmp_identity));
313                         reauth->permanent = data->db_tmp_identity;
314                 } else if (os_strcmp(col[i], "counter") == 0 && argv[i]) {
315                         reauth->counter = atoi(argv[i]);
316                 } else if (os_strcmp(col[i], "mk") == 0 && argv[i]) {
317                         hexstr2bin(argv[i], reauth->mk, sizeof(reauth->mk));
318                 } else if (os_strcmp(col[i], "k_encr") == 0 && argv[i]) {
319                         hexstr2bin(argv[i], reauth->k_encr,
320                                    sizeof(reauth->k_encr));
321                 } else if (os_strcmp(col[i], "k_aut") == 0 && argv[i]) {
322                         hexstr2bin(argv[i], reauth->k_aut,
323                                    sizeof(reauth->k_aut));
324                 } else if (os_strcmp(col[i], "k_re") == 0 && argv[i]) {
325                         hexstr2bin(argv[i], reauth->k_re,
326                                    sizeof(reauth->k_re));
327                 }
328         }
329
330         return 0;
331 }
332
333
334 static struct eap_sim_reauth *
335 db_get_reauth(struct eap_sim_db_data *data, const char *reauth_id)
336 {
337         char cmd[256];
338
339         if (!valid_db_string(reauth_id))
340                 return NULL;
341         os_memset(&data->db_tmp_reauth, 0, sizeof(data->db_tmp_reauth));
342         os_strlcpy(data->db_tmp_pseudonym_str, reauth_id,
343                    sizeof(data->db_tmp_pseudonym_str));
344         data->db_tmp_reauth.reauth_id = data->db_tmp_pseudonym_str;
345         os_snprintf(cmd, sizeof(cmd),
346                     "SELECT * FROM reauth WHERE reauth_id='%s';", reauth_id);
347         if (sqlite3_exec(data->sqlite_db, cmd, get_reauth_cb, data, NULL) !=
348             SQLITE_OK)
349                 return NULL;
350         if (data->db_tmp_reauth.permanent == NULL)
351                 return NULL;
352         return &data->db_tmp_reauth;
353 }
354
355
356 static void db_remove_reauth(struct eap_sim_db_data *data,
357                              struct eap_sim_reauth *reauth)
358 {
359         char cmd[256];
360
361         if (!valid_db_string(reauth->permanent))
362                 return;
363         os_snprintf(cmd, sizeof(cmd),
364                     "DELETE FROM reauth WHERE permanent='%s';",
365                     reauth->permanent);
366         sqlite3_exec(data->sqlite_db, cmd, NULL, NULL, NULL);
367 }
368
369 #endif /* CONFIG_SQLITE */
370
371
372 static struct eap_sim_db_pending *
373 eap_sim_db_get_pending(struct eap_sim_db_data *data, const char *imsi, int aka)
374 {
375         struct eap_sim_db_pending *entry, *prev = NULL;
376
377         entry = data->pending;
378         while (entry) {
379                 if (entry->aka == aka && os_strcmp(entry->imsi, imsi) == 0) {
380                         if (prev)
381                                 prev->next = entry->next;
382                         else
383                                 data->pending = entry->next;
384                         break;
385                 }
386                 prev = entry;
387                 entry = entry->next;
388         }
389         return entry;
390 }
391
392
393 static void eap_sim_db_add_pending(struct eap_sim_db_data *data,
394                                    struct eap_sim_db_pending *entry)
395 {
396         entry->next = data->pending;
397         data->pending = entry;
398 }
399
400
401 static void eap_sim_db_sim_resp_auth(struct eap_sim_db_data *data,
402                                      const char *imsi, char *buf)
403 {
404         char *start, *end, *pos;
405         struct eap_sim_db_pending *entry;
406         int num_chal;
407
408         /*
409          * SIM-RESP-AUTH <IMSI> Kc(i):SRES(i):RAND(i) ...
410          * SIM-RESP-AUTH <IMSI> FAILURE
411          * (IMSI = ASCII string, Kc/SRES/RAND = hex string)
412          */
413
414         entry = eap_sim_db_get_pending(data, imsi, 0);
415         if (entry == NULL) {
416                 wpa_printf(MSG_DEBUG, "EAP-SIM DB: No pending entry for the "
417                            "received message found");
418                 return;
419         }
420
421         start = buf;
422         if (os_strncmp(start, "FAILURE", 7) == 0) {
423                 wpa_printf(MSG_DEBUG, "EAP-SIM DB: External server reported "
424                            "failure");
425                 entry->state = FAILURE;
426                 eap_sim_db_add_pending(data, entry);
427                 data->get_complete_cb(data->ctx, entry->cb_session_ctx);
428                 return;
429         }
430
431         num_chal = 0;
432         while (num_chal < EAP_SIM_MAX_CHAL) {
433                 end = os_strchr(start, ' ');
434                 if (end)
435                         *end = '\0';
436
437                 pos = os_strchr(start, ':');
438                 if (pos == NULL)
439                         goto parse_fail;
440                 *pos = '\0';
441                 if (hexstr2bin(start, entry->u.sim.kc[num_chal],
442                                EAP_SIM_KC_LEN))
443                         goto parse_fail;
444
445                 start = pos + 1;
446                 pos = os_strchr(start, ':');
447                 if (pos == NULL)
448                         goto parse_fail;
449                 *pos = '\0';
450                 if (hexstr2bin(start, entry->u.sim.sres[num_chal],
451                                EAP_SIM_SRES_LEN))
452                         goto parse_fail;
453
454                 start = pos + 1;
455                 if (hexstr2bin(start, entry->u.sim.rand[num_chal],
456                                GSM_RAND_LEN))
457                         goto parse_fail;
458
459                 num_chal++;
460                 if (end == NULL)
461                         break;
462                 else
463                         start = end + 1;
464         }
465         entry->u.sim.num_chal = num_chal;
466
467         entry->state = SUCCESS;
468         wpa_printf(MSG_DEBUG, "EAP-SIM DB: Authentication data parsed "
469                    "successfully - callback");
470         eap_sim_db_add_pending(data, entry);
471         data->get_complete_cb(data->ctx, entry->cb_session_ctx);
472         return;
473
474 parse_fail:
475         wpa_printf(MSG_DEBUG, "EAP-SIM DB: Failed to parse response string");
476         os_free(entry);
477 }
478
479
480 static void eap_sim_db_aka_resp_auth(struct eap_sim_db_data *data,
481                                      const char *imsi, char *buf)
482 {
483         char *start, *end;
484         struct eap_sim_db_pending *entry;
485
486         /*
487          * AKA-RESP-AUTH <IMSI> <RAND> <AUTN> <IK> <CK> <RES>
488          * AKA-RESP-AUTH <IMSI> FAILURE
489          * (IMSI = ASCII string, RAND/AUTN/IK/CK/RES = hex string)
490          */
491
492         entry = eap_sim_db_get_pending(data, imsi, 1);
493         if (entry == NULL) {
494                 wpa_printf(MSG_DEBUG, "EAP-SIM DB: No pending entry for the "
495                            "received message found");
496                 return;
497         }
498
499         start = buf;
500         if (os_strncmp(start, "FAILURE", 7) == 0) {
501                 wpa_printf(MSG_DEBUG, "EAP-SIM DB: External server reported "
502                            "failure");
503                 entry->state = FAILURE;
504                 eap_sim_db_add_pending(data, entry);
505                 data->get_complete_cb(data->ctx, entry->cb_session_ctx);
506                 return;
507         }
508
509         end = os_strchr(start, ' ');
510         if (end == NULL)
511                 goto parse_fail;
512         *end = '\0';
513         if (hexstr2bin(start, entry->u.aka.rand, EAP_AKA_RAND_LEN))
514                 goto parse_fail;
515
516         start = end + 1;
517         end = os_strchr(start, ' ');
518         if (end == NULL)
519                 goto parse_fail;
520         *end = '\0';
521         if (hexstr2bin(start, entry->u.aka.autn, EAP_AKA_AUTN_LEN))
522                 goto parse_fail;
523
524         start = end + 1;
525         end = os_strchr(start, ' ');
526         if (end == NULL)
527                 goto parse_fail;
528         *end = '\0';
529         if (hexstr2bin(start, entry->u.aka.ik, EAP_AKA_IK_LEN))
530                 goto parse_fail;
531
532         start = end + 1;
533         end = os_strchr(start, ' ');
534         if (end == NULL)
535                 goto parse_fail;
536         *end = '\0';
537         if (hexstr2bin(start, entry->u.aka.ck, EAP_AKA_CK_LEN))
538                 goto parse_fail;
539
540         start = end + 1;
541         end = os_strchr(start, ' ');
542         if (end)
543                 *end = '\0';
544         else {
545                 end = start;
546                 while (*end)
547                         end++;
548         }
549         entry->u.aka.res_len = (end - start) / 2;
550         if (entry->u.aka.res_len > EAP_AKA_RES_MAX_LEN) {
551                 wpa_printf(MSG_DEBUG, "EAP-SIM DB: Too long RES");
552                 entry->u.aka.res_len = 0;
553                 goto parse_fail;
554         }
555         if (hexstr2bin(start, entry->u.aka.res, entry->u.aka.res_len))
556                 goto parse_fail;
557
558         entry->state = SUCCESS;
559         wpa_printf(MSG_DEBUG, "EAP-SIM DB: Authentication data parsed "
560                    "successfully - callback");
561         eap_sim_db_add_pending(data, entry);
562         data->get_complete_cb(data->ctx, entry->cb_session_ctx);
563         return;
564
565 parse_fail:
566         wpa_printf(MSG_DEBUG, "EAP-SIM DB: Failed to parse response string");
567         os_free(entry);
568 }
569
570
571 static void eap_sim_db_receive(int sock, void *eloop_ctx, void *sock_ctx)
572 {
573         struct eap_sim_db_data *data = eloop_ctx;
574         char buf[1000], *pos, *cmd, *imsi;
575         int res;
576
577         res = recv(sock, buf, sizeof(buf), 0);
578         if (res < 0)
579                 return;
580         wpa_hexdump_ascii_key(MSG_MSGDUMP, "EAP-SIM DB: Received from an "
581                               "external source", (u8 *) buf, res);
582         if (res == 0)
583                 return;
584         if (res >= (int) sizeof(buf))
585                 res = sizeof(buf) - 1;
586         buf[res] = '\0';
587
588         if (data->get_complete_cb == NULL) {
589                 wpa_printf(MSG_DEBUG, "EAP-SIM DB: No get_complete_cb "
590                            "registered");
591                 return;
592         }
593
594         /* <cmd> <IMSI> ... */
595
596         cmd = buf;
597         pos = os_strchr(cmd, ' ');
598         if (pos == NULL)
599                 goto parse_fail;
600         *pos = '\0';
601         imsi = pos + 1;
602         pos = os_strchr(imsi, ' ');
603         if (pos == NULL)
604                 goto parse_fail;
605         *pos = '\0';
606         wpa_printf(MSG_DEBUG, "EAP-SIM DB: External response=%s for IMSI %s",
607                    cmd, imsi);
608
609         if (os_strcmp(cmd, "SIM-RESP-AUTH") == 0)
610                 eap_sim_db_sim_resp_auth(data, imsi, pos + 1);
611         else if (os_strcmp(cmd, "AKA-RESP-AUTH") == 0)
612                 eap_sim_db_aka_resp_auth(data, imsi, pos + 1);
613         else
614                 wpa_printf(MSG_INFO, "EAP-SIM DB: Unknown external response "
615                            "'%s'", cmd);
616         return;
617
618 parse_fail:
619         wpa_printf(MSG_DEBUG, "EAP-SIM DB: Failed to parse response string");
620 }
621
622
623 static int eap_sim_db_open_socket(struct eap_sim_db_data *data)
624 {
625         struct sockaddr_un addr;
626         static int counter = 0;
627
628         if (os_strncmp(data->fname, "unix:", 5) != 0)
629                 return -1;
630
631         data->sock = socket(PF_UNIX, SOCK_DGRAM, 0);
632         if (data->sock < 0) {
633                 perror("socket(eap_sim_db)");
634                 return -1;
635         }
636
637         os_memset(&addr, 0, sizeof(addr));
638         addr.sun_family = AF_UNIX;
639         os_snprintf(addr.sun_path, sizeof(addr.sun_path),
640                     "/tmp/eap_sim_db_%d-%d", getpid(), counter++);
641         os_free(data->local_sock);
642         data->local_sock = os_strdup(addr.sun_path);
643         if (bind(data->sock, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
644                 perror("bind(eap_sim_db)");
645                 close(data->sock);
646                 data->sock = -1;
647                 return -1;
648         }
649
650         os_memset(&addr, 0, sizeof(addr));
651         addr.sun_family = AF_UNIX;
652         os_strlcpy(addr.sun_path, data->fname + 5, sizeof(addr.sun_path));
653         if (connect(data->sock, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
654                 perror("connect(eap_sim_db)");
655                 wpa_hexdump_ascii(MSG_INFO, "HLR/AuC GW socket",
656                                   (u8 *) addr.sun_path,
657                                   os_strlen(addr.sun_path));
658                 close(data->sock);
659                 data->sock = -1;
660                 return -1;
661         }
662
663         eloop_register_read_sock(data->sock, eap_sim_db_receive, data, NULL);
664
665         return 0;
666 }
667
668
669 static void eap_sim_db_close_socket(struct eap_sim_db_data *data)
670 {
671         if (data->sock >= 0) {
672                 eloop_unregister_read_sock(data->sock);
673                 close(data->sock);
674                 data->sock = -1;
675         }
676         if (data->local_sock) {
677                 unlink(data->local_sock);
678                 os_free(data->local_sock);
679                 data->local_sock = NULL;
680         }
681 }
682
683
684 /**
685  * eap_sim_db_init - Initialize EAP-SIM DB / authentication gateway interface
686  * @config: Configuration data (e.g., file name)
687  * @get_complete_cb: Callback function for reporting availability of triplets
688  * @ctx: Context pointer for get_complete_cb
689  * Returns: Pointer to a private data structure or %NULL on failure
690  */
691 void * eap_sim_db_init(const char *config,
692                        void (*get_complete_cb)(void *ctx, void *session_ctx),
693                        void *ctx)
694 {
695         struct eap_sim_db_data *data;
696         char *pos;
697
698         data = os_zalloc(sizeof(*data));
699         if (data == NULL)
700                 return NULL;
701
702         data->sock = -1;
703         data->get_complete_cb = get_complete_cb;
704         data->ctx = ctx;
705         data->fname = os_strdup(config);
706         if (data->fname == NULL)
707                 goto fail;
708         pos = os_strstr(data->fname, " db=");
709         if (pos) {
710                 *pos = '\0';
711 #ifdef CONFIG_SQLITE
712                 pos += 4;
713                 data->sqlite_db = db_open(pos);
714                 if (data->sqlite_db == NULL)
715                         goto fail;
716 #endif /* CONFIG_SQLITE */
717         }
718
719         if (os_strncmp(data->fname, "unix:", 5) == 0) {
720                 if (eap_sim_db_open_socket(data)) {
721                         wpa_printf(MSG_DEBUG, "EAP-SIM DB: External database "
722                                    "connection not available - will retry "
723                                    "later");
724                 }
725         }
726
727         return data;
728
729 fail:
730         eap_sim_db_close_socket(data);
731         os_free(data->fname);
732         os_free(data);
733         return NULL;
734 }
735
736
737 static void eap_sim_db_free_pseudonym(struct eap_sim_pseudonym *p)
738 {
739         os_free(p->permanent);
740         os_free(p->pseudonym);
741         os_free(p);
742 }
743
744
745 static void eap_sim_db_free_reauth(struct eap_sim_reauth *r)
746 {
747         os_free(r->permanent);
748         os_free(r->reauth_id);
749         os_free(r);
750 }
751
752
753 /**
754  * eap_sim_db_deinit - Deinitialize EAP-SIM DB/authentication gw interface
755  * @priv: Private data pointer from eap_sim_db_init()
756  */
757 void eap_sim_db_deinit(void *priv)
758 {
759         struct eap_sim_db_data *data = priv;
760         struct eap_sim_pseudonym *p, *prev;
761         struct eap_sim_reauth *r, *prevr;
762         struct eap_sim_db_pending *pending, *prev_pending;
763
764 #ifdef CONFIG_SQLITE
765         if (data->sqlite_db) {
766                 sqlite3_close(data->sqlite_db);
767                 data->sqlite_db = NULL;
768         }
769 #endif /* CONFIG_SQLITE */
770
771         eap_sim_db_close_socket(data);
772         os_free(data->fname);
773
774         p = data->pseudonyms;
775         while (p) {
776                 prev = p;
777                 p = p->next;
778                 eap_sim_db_free_pseudonym(prev);
779         }
780
781         r = data->reauths;
782         while (r) {
783                 prevr = r;
784                 r = r->next;
785                 eap_sim_db_free_reauth(prevr);
786         }
787
788         pending = data->pending;
789         while (pending) {
790                 prev_pending = pending;
791                 pending = pending->next;
792                 os_free(prev_pending);
793         }
794
795         os_free(data);
796 }
797
798
799 static int eap_sim_db_send(struct eap_sim_db_data *data, const char *msg,
800                            size_t len)
801 {
802         int _errno = 0;
803
804         if (send(data->sock, msg, len, 0) < 0) {
805                 _errno = errno;
806                 perror("send[EAP-SIM DB UNIX]");
807         }
808
809         if (_errno == ENOTCONN || _errno == EDESTADDRREQ || _errno == EINVAL ||
810             _errno == ECONNREFUSED) {
811                 /* Try to reconnect */
812                 eap_sim_db_close_socket(data);
813                 if (eap_sim_db_open_socket(data) < 0)
814                         return -1;
815                 wpa_printf(MSG_DEBUG, "EAP-SIM DB: Reconnected to the "
816                            "external server");
817                 if (send(data->sock, msg, len, 0) < 0) {
818                         perror("send[EAP-SIM DB UNIX]");
819                         return -1;
820                 }
821         }
822
823         return 0;
824 }
825
826
827 static void eap_sim_db_expire_pending(struct eap_sim_db_data *data)
828 {
829         /* TODO: add limit for maximum length for pending list; remove latest
830          * (i.e., last) entry from the list if the limit is reached; could also
831          * use timeout to expire pending entries */
832 }
833
834
835 /**
836  * eap_sim_db_get_gsm_triplets - Get GSM triplets
837  * @priv: Private data pointer from eap_sim_db_init()
838  * @username: Permanent username (prefix | IMSI)
839  * @max_chal: Maximum number of triplets
840  * @_rand: Buffer for RAND values
841  * @kc: Buffer for Kc values
842  * @sres: Buffer for SRES values
843  * @cb_session_ctx: Session callback context for get_complete_cb()
844  * Returns: Number of triplets received (has to be less than or equal to
845  * max_chal), -1 (EAP_SIM_DB_FAILURE) on error (e.g., user not found), or
846  * -2 (EAP_SIM_DB_PENDING) if results are not yet available. In this case, the
847  * callback function registered with eap_sim_db_init() will be called once the
848  * results become available.
849  *
850  * When using an external server for GSM triplets, this function can always
851  * start a request and return EAP_SIM_DB_PENDING immediately if authentication
852  * triplets are not available. Once the triplets are received, callback
853  * function registered with eap_sim_db_init() is called to notify EAP state
854  * machine to reprocess the message. This eap_sim_db_get_gsm_triplets()
855  * function will then be called again and the newly received triplets will then
856  * be given to the caller.
857  */
858 int eap_sim_db_get_gsm_triplets(void *priv, const char *username, int max_chal,
859                                 u8 *_rand, u8 *kc, u8 *sres,
860                                 void *cb_session_ctx)
861 {
862         struct eap_sim_db_data *data = priv;
863         struct eap_sim_db_pending *entry;
864         int len, ret;
865         char msg[40];
866         const char *imsi;
867         size_t imsi_len;
868
869         if (username == NULL || username[0] != EAP_SIM_PERMANENT_PREFIX ||
870             username[1] == '\0' || os_strlen(username) > sizeof(entry->imsi)) {
871                 wpa_printf(MSG_DEBUG, "EAP-SIM DB: unexpected username '%s'",
872                            username);
873                 return EAP_SIM_DB_FAILURE;
874         }
875         imsi = username + 1;
876         wpa_printf(MSG_DEBUG, "EAP-SIM DB: Get GSM triplets for IMSI '%s'",
877                    imsi);
878
879         entry = eap_sim_db_get_pending(data, imsi, 0);
880         if (entry) {
881                 int num_chal;
882                 if (entry->state == FAILURE) {
883                         wpa_printf(MSG_DEBUG, "EAP-SIM DB: Pending entry -> "
884                                    "failure");
885                         os_free(entry);
886                         return EAP_SIM_DB_FAILURE;
887                 }
888
889                 if (entry->state == PENDING) {
890                         wpa_printf(MSG_DEBUG, "EAP-SIM DB: Pending entry -> "
891                                    "still pending");
892                         eap_sim_db_add_pending(data, entry);
893                         return EAP_SIM_DB_PENDING;
894                 }
895
896                 wpa_printf(MSG_DEBUG, "EAP-SIM DB: Pending entry -> "
897                            "%d challenges", entry->u.sim.num_chal);
898                 num_chal = entry->u.sim.num_chal;
899                 if (num_chal > max_chal)
900                         num_chal = max_chal;
901                 os_memcpy(_rand, entry->u.sim.rand, num_chal * GSM_RAND_LEN);
902                 os_memcpy(sres, entry->u.sim.sres,
903                           num_chal * EAP_SIM_SRES_LEN);
904                 os_memcpy(kc, entry->u.sim.kc, num_chal * EAP_SIM_KC_LEN);
905                 os_free(entry);
906                 return num_chal;
907         }
908
909         if (data->sock < 0) {
910                 if (eap_sim_db_open_socket(data) < 0)
911                         return EAP_SIM_DB_FAILURE;
912         }
913
914         imsi_len = os_strlen(imsi);
915         len = os_snprintf(msg, sizeof(msg), "SIM-REQ-AUTH ");
916         if (len < 0 || len + imsi_len >= sizeof(msg))
917                 return EAP_SIM_DB_FAILURE;
918         os_memcpy(msg + len, imsi, imsi_len);
919         len += imsi_len;
920         ret = os_snprintf(msg + len, sizeof(msg) - len, " %d", max_chal);
921         if (ret < 0 || (size_t) ret >= sizeof(msg) - len)
922                 return EAP_SIM_DB_FAILURE;
923         len += ret;
924
925         wpa_printf(MSG_DEBUG, "EAP-SIM DB: requesting SIM authentication "
926                    "data for IMSI '%s'", imsi);
927         if (eap_sim_db_send(data, msg, len) < 0)
928                 return EAP_SIM_DB_FAILURE;
929
930         entry = os_zalloc(sizeof(*entry));
931         if (entry == NULL)
932                 return EAP_SIM_DB_FAILURE;
933
934         os_get_time(&entry->timestamp);
935         os_strlcpy(entry->imsi, imsi, sizeof(entry->imsi));
936         entry->cb_session_ctx = cb_session_ctx;
937         entry->state = PENDING;
938         eap_sim_db_add_pending(data, entry);
939         eap_sim_db_expire_pending(data);
940
941         return EAP_SIM_DB_PENDING;
942 }
943
944
945 static const char *
946 eap_sim_db_get_pseudonym(struct eap_sim_db_data *data, const char *pseudonym)
947 {
948         struct eap_sim_pseudonym *p;
949
950         if (pseudonym[0] != EAP_SIM_PSEUDONYM_PREFIX &&
951             pseudonym[0] != EAP_AKA_PSEUDONYM_PREFIX &&
952             pseudonym[0] != EAP_AKA_PRIME_PSEUDONYM_PREFIX)
953                 return NULL;
954
955 #ifdef CONFIG_SQLITE
956         if (data->sqlite_db)
957                 return db_get_pseudonym(data, pseudonym);
958 #endif /* CONFIG_SQLITE */
959
960         p = data->pseudonyms;
961         while (p) {
962                 if (os_strcmp(p->pseudonym, pseudonym) == 0)
963                         return p->permanent;
964                 p = p->next;
965         }
966
967         return NULL;
968 }
969
970
971 static struct eap_sim_reauth *
972 eap_sim_db_get_reauth(struct eap_sim_db_data *data, const char *reauth_id)
973 {
974         struct eap_sim_reauth *r;
975
976         if (reauth_id[0] != EAP_SIM_REAUTH_ID_PREFIX &&
977             reauth_id[0] != EAP_AKA_REAUTH_ID_PREFIX &&
978             reauth_id[0] != EAP_AKA_PRIME_REAUTH_ID_PREFIX)
979                 return NULL;
980
981 #ifdef CONFIG_SQLITE
982         if (data->sqlite_db)
983                 return db_get_reauth(data, reauth_id);
984 #endif /* CONFIG_SQLITE */
985
986         r = data->reauths;
987         while (r) {
988                 if (os_strcmp(r->reauth_id, reauth_id) == 0)
989                         break;
990                 r = r->next;
991         }
992
993         return r;
994 }
995
996
997 static char * eap_sim_db_get_next(struct eap_sim_db_data *data, char prefix)
998 {
999         char *id, *pos, *end;
1000         u8 buf[10];
1001
1002         if (random_get_bytes(buf, sizeof(buf)))
1003                 return NULL;
1004         id = os_malloc(sizeof(buf) * 2 + 2);
1005         if (id == NULL)
1006                 return NULL;
1007
1008         pos = id;
1009         end = id + sizeof(buf) * 2 + 2;
1010         *pos++ = prefix;
1011         pos += wpa_snprintf_hex(pos, end - pos, buf, sizeof(buf));
1012         
1013         return id;
1014 }
1015
1016
1017 /**
1018  * eap_sim_db_get_next_pseudonym - EAP-SIM DB: Get next pseudonym
1019  * @priv: Private data pointer from eap_sim_db_init()
1020  * @method: EAP method (SIM/AKA/AKA')
1021  * Returns: Next pseudonym (allocated string) or %NULL on failure
1022  *
1023  * This function is used to generate a pseudonym for EAP-SIM. The returned
1024  * pseudonym is not added to database at this point; it will need to be added
1025  * with eap_sim_db_add_pseudonym() once the authentication has been completed
1026  * successfully. Caller is responsible for freeing the returned buffer.
1027  */
1028 char * eap_sim_db_get_next_pseudonym(void *priv, enum eap_sim_db_method method)
1029 {
1030         struct eap_sim_db_data *data = priv;
1031         char prefix = EAP_SIM_REAUTH_ID_PREFIX;
1032
1033         switch (method) {
1034         case EAP_SIM_DB_SIM:
1035                 prefix = EAP_SIM_PSEUDONYM_PREFIX;
1036                 break;
1037         case EAP_SIM_DB_AKA:
1038                 prefix = EAP_AKA_PSEUDONYM_PREFIX;
1039                 break;
1040         case EAP_SIM_DB_AKA_PRIME:
1041                 prefix = EAP_AKA_PRIME_PSEUDONYM_PREFIX;
1042                 break;
1043         }
1044
1045         return eap_sim_db_get_next(data, prefix);
1046 }
1047
1048
1049 /**
1050  * eap_sim_db_get_next_reauth_id - EAP-SIM DB: Get next reauth_id
1051  * @priv: Private data pointer from eap_sim_db_init()
1052  * @method: EAP method (SIM/AKA/AKA')
1053  * Returns: Next reauth_id (allocated string) or %NULL on failure
1054  *
1055  * This function is used to generate a fast re-authentication identity for
1056  * EAP-SIM. The returned reauth_id is not added to database at this point; it
1057  * will need to be added with eap_sim_db_add_reauth() once the authentication
1058  * has been completed successfully. Caller is responsible for freeing the
1059  * returned buffer.
1060  */
1061 char * eap_sim_db_get_next_reauth_id(void *priv, enum eap_sim_db_method method)
1062 {
1063         struct eap_sim_db_data *data = priv;
1064         char prefix = EAP_SIM_REAUTH_ID_PREFIX;
1065
1066         switch (method) {
1067         case EAP_SIM_DB_SIM:
1068                 prefix = EAP_SIM_REAUTH_ID_PREFIX;
1069                 break;
1070         case EAP_SIM_DB_AKA:
1071                 prefix = EAP_AKA_REAUTH_ID_PREFIX;
1072                 break;
1073         case EAP_SIM_DB_AKA_PRIME:
1074                 prefix = EAP_AKA_PRIME_REAUTH_ID_PREFIX;
1075                 break;
1076         }
1077
1078         return eap_sim_db_get_next(data, prefix);
1079 }
1080
1081
1082 /**
1083  * eap_sim_db_add_pseudonym - EAP-SIM DB: Add new pseudonym
1084  * @priv: Private data pointer from eap_sim_db_init()
1085  * @permanent: Permanent username
1086  * @pseudonym: Pseudonym for this user. This needs to be an allocated buffer,
1087  * e.g., return value from eap_sim_db_get_next_pseudonym(). Caller must not
1088  * free it.
1089  * Returns: 0 on success, -1 on failure
1090  *
1091  * This function adds a new pseudonym for EAP-SIM user. EAP-SIM DB is
1092  * responsible of freeing pseudonym buffer once it is not needed anymore.
1093  */
1094 int eap_sim_db_add_pseudonym(void *priv, const char *permanent,
1095                              char *pseudonym)
1096 {
1097         struct eap_sim_db_data *data = priv;
1098         struct eap_sim_pseudonym *p;
1099         wpa_printf(MSG_DEBUG, "EAP-SIM DB: Add pseudonym '%s' for permanent "
1100                    "username '%s'", pseudonym, permanent);
1101
1102         /* TODO: could store last two pseudonyms */
1103 #ifdef CONFIG_SQLITE
1104         if (data->sqlite_db)
1105                 return db_add_pseudonym(data, permanent, pseudonym);
1106 #endif /* CONFIG_SQLITE */
1107         for (p = data->pseudonyms; p; p = p->next) {
1108                 if (os_strcmp(permanent, p->permanent) == 0)
1109                         break;
1110         }
1111         if (p) {
1112                 wpa_printf(MSG_DEBUG, "EAP-SIM DB: Replacing previous "
1113                            "pseudonym: %s", p->pseudonym);
1114                 os_free(p->pseudonym);
1115                 p->pseudonym = pseudonym;
1116                 return 0;
1117         }
1118
1119         p = os_zalloc(sizeof(*p));
1120         if (p == NULL) {
1121                 os_free(pseudonym);
1122                 return -1;
1123         }
1124
1125         p->next = data->pseudonyms;
1126         p->permanent = os_strdup(permanent);
1127         if (p->permanent == NULL) {
1128                 os_free(p);
1129                 os_free(pseudonym);
1130                 return -1;
1131         }
1132         p->pseudonym = pseudonym;
1133         data->pseudonyms = p;
1134
1135         wpa_printf(MSG_DEBUG, "EAP-SIM DB: Added new pseudonym entry");
1136         return 0;
1137 }
1138
1139
1140 static struct eap_sim_reauth *
1141 eap_sim_db_add_reauth_data(struct eap_sim_db_data *data,
1142                            const char *permanent,
1143                            char *reauth_id, u16 counter)
1144 {
1145         struct eap_sim_reauth *r;
1146
1147         for (r = data->reauths; r; r = r->next) {
1148                 if (os_strcmp(r->permanent, permanent) == 0)
1149                         break;
1150         }
1151
1152         if (r) {
1153                 wpa_printf(MSG_DEBUG, "EAP-SIM DB: Replacing previous "
1154                            "reauth_id: %s", r->reauth_id);
1155                 os_free(r->reauth_id);
1156                 r->reauth_id = reauth_id;
1157         } else {
1158                 r = os_zalloc(sizeof(*r));
1159                 if (r == NULL) {
1160                         os_free(reauth_id);
1161                         return NULL;
1162                 }
1163
1164                 r->next = data->reauths;
1165                 r->permanent = os_strdup(permanent);
1166                 if (r->permanent == NULL) {
1167                         os_free(r);
1168                         os_free(reauth_id);
1169                         return NULL;
1170                 }
1171                 r->reauth_id = reauth_id;
1172                 data->reauths = r;
1173                 wpa_printf(MSG_DEBUG, "EAP-SIM DB: Added new reauth entry");
1174         }
1175
1176         r->counter = counter;
1177
1178         return r;
1179 }
1180
1181
1182 /**
1183  * eap_sim_db_add_reauth - EAP-SIM DB: Add new re-authentication entry
1184  * @priv: Private data pointer from eap_sim_db_init()
1185  * @permanent: Permanent username
1186  * @identity_len: Length of identity
1187  * @reauth_id: reauth_id for this user. This needs to be an allocated buffer,
1188  * e.g., return value from eap_sim_db_get_next_reauth_id(). Caller must not
1189  * free it.
1190  * @counter: AT_COUNTER value for fast re-authentication
1191  * @mk: 16-byte MK from the previous full authentication or %NULL
1192  * Returns: 0 on success, -1 on failure
1193  *
1194  * This function adds a new re-authentication entry for an EAP-SIM user.
1195  * EAP-SIM DB is responsible of freeing reauth_id buffer once it is not needed
1196  * anymore.
1197  */
1198 int eap_sim_db_add_reauth(void *priv, const char *permanent, char *reauth_id,
1199                           u16 counter, const u8 *mk)
1200 {
1201         struct eap_sim_db_data *data = priv;
1202         struct eap_sim_reauth *r;
1203
1204 #ifdef CONFIG_SQLITE
1205         if (data->sqlite_db)
1206                 return db_add_reauth(data, permanent, reauth_id, counter, mk,
1207                                      NULL, NULL, NULL);
1208 #endif /* CONFIG_SQLITE */
1209         r = eap_sim_db_add_reauth_data(data, permanent, reauth_id, counter);
1210         if (r == NULL)
1211                 return -1;
1212
1213         os_memcpy(r->mk, mk, EAP_SIM_MK_LEN);
1214
1215         return 0;
1216 }
1217
1218
1219 #ifdef EAP_SERVER_AKA_PRIME
1220 /**
1221  * eap_sim_db_add_reauth_prime - EAP-AKA' DB: Add new re-authentication entry
1222  * @priv: Private data pointer from eap_sim_db_init()
1223  * @permanent: Permanent username
1224  * @reauth_id: reauth_id for this user. This needs to be an allocated buffer,
1225  * e.g., return value from eap_sim_db_get_next_reauth_id(). Caller must not
1226  * free it.
1227  * @counter: AT_COUNTER value for fast re-authentication
1228  * @k_encr: K_encr from the previous full authentication
1229  * @k_aut: K_aut from the previous full authentication
1230  * @k_re: 32-byte K_re from the previous full authentication
1231  * Returns: 0 on success, -1 on failure
1232  *
1233  * This function adds a new re-authentication entry for an EAP-AKA' user.
1234  * EAP-SIM DB is responsible of freeing reauth_id buffer once it is not needed
1235  * anymore.
1236  */
1237 int eap_sim_db_add_reauth_prime(void *priv, const char *permanent,
1238                                 char *reauth_id, u16 counter, const u8 *k_encr,
1239                                 const u8 *k_aut, const u8 *k_re)
1240 {
1241         struct eap_sim_db_data *data = priv;
1242         struct eap_sim_reauth *r;
1243
1244         wpa_printf(MSG_DEBUG, "EAP-SIM DB: Add reauth_id '%s' for permanent "
1245                    "identity '%s'", reauth_id, permanent);
1246
1247 #ifdef CONFIG_SQLITE
1248         if (data->sqlite_db)
1249                 return db_add_reauth(data, permanent, reauth_id, counter, NULL,
1250                                      k_encr, k_aut, k_re);
1251 #endif /* CONFIG_SQLITE */
1252         r = eap_sim_db_add_reauth_data(data, permanent, reauth_id, counter);
1253         if (r == NULL)
1254                 return -1;
1255
1256         os_memcpy(r->k_encr, k_encr, EAP_SIM_K_ENCR_LEN);
1257         os_memcpy(r->k_aut, k_aut, EAP_AKA_PRIME_K_AUT_LEN);
1258         os_memcpy(r->k_re, k_re, EAP_AKA_PRIME_K_RE_LEN);
1259
1260         return 0;
1261 }
1262 #endif /* EAP_SERVER_AKA_PRIME */
1263
1264
1265 /**
1266  * eap_sim_db_get_permanent - EAP-SIM DB: Get permanent identity
1267  * @priv: Private data pointer from eap_sim_db_init()
1268  * @pseudonym: Pseudonym username
1269  * Returns: Pointer to permanent username or %NULL if not found
1270  */
1271 const char * eap_sim_db_get_permanent(void *priv, const char *pseudonym)
1272 {
1273         struct eap_sim_db_data *data = priv;
1274
1275         if (pseudonym == NULL)
1276                 return NULL;
1277
1278         return eap_sim_db_get_pseudonym(data, pseudonym);
1279 }
1280
1281
1282 /**
1283  * eap_sim_db_get_reauth_entry - EAP-SIM DB: Get re-authentication entry
1284  * @priv: Private data pointer from eap_sim_db_init()
1285  * @reauth_id: Fast re-authentication username
1286  * Returns: Pointer to the re-auth entry, or %NULL if not found
1287  */
1288 struct eap_sim_reauth *
1289 eap_sim_db_get_reauth_entry(void *priv, const char *reauth_id)
1290 {
1291         struct eap_sim_db_data *data = priv;
1292         struct eap_sim_reauth *r;
1293
1294         if (reauth_id == NULL)
1295                 return NULL;
1296         r = eap_sim_db_get_reauth(data, reauth_id);
1297         return r;
1298 }
1299
1300
1301 /**
1302  * eap_sim_db_remove_reauth - EAP-SIM DB: Remove re-authentication entry
1303  * @priv: Private data pointer from eap_sim_db_init()
1304  * @reauth: Pointer to re-authentication entry from
1305  * eap_sim_db_get_reauth_entry()
1306  */
1307 void eap_sim_db_remove_reauth(void *priv, struct eap_sim_reauth *reauth)
1308 {
1309         struct eap_sim_db_data *data = priv;
1310         struct eap_sim_reauth *r, *prev = NULL;
1311 #ifdef CONFIG_SQLITE
1312         if (data->sqlite_db) {
1313                 db_remove_reauth(data, reauth);
1314                 return;
1315         }
1316 #endif /* CONFIG_SQLITE */
1317         r = data->reauths;
1318         while (r) {
1319                 if (r == reauth) {
1320                         if (prev)
1321                                 prev->next = r->next;
1322                         else
1323                                 data->reauths = r->next;
1324                         eap_sim_db_free_reauth(r);
1325                         return;
1326                 }
1327                 prev = r;
1328                 r = r->next;
1329         }
1330 }
1331
1332
1333 /**
1334  * eap_sim_db_get_aka_auth - Get AKA authentication values
1335  * @priv: Private data pointer from eap_sim_db_init()
1336  * @username: Permanent username (prefix | IMSI)
1337  * @_rand: Buffer for RAND value
1338  * @autn: Buffer for AUTN value
1339  * @ik: Buffer for IK value
1340  * @ck: Buffer for CK value
1341  * @res: Buffer for RES value
1342  * @res_len: Buffer for RES length
1343  * @cb_session_ctx: Session callback context for get_complete_cb()
1344  * Returns: 0 on success, -1 (EAP_SIM_DB_FAILURE) on error (e.g., user not
1345  * found), or -2 (EAP_SIM_DB_PENDING) if results are not yet available. In this
1346  * case, the callback function registered with eap_sim_db_init() will be
1347  * called once the results become available.
1348  *
1349  * When using an external server for AKA authentication, this function can
1350  * always start a request and return EAP_SIM_DB_PENDING immediately if
1351  * authentication triplets are not available. Once the authentication data are
1352  * received, callback function registered with eap_sim_db_init() is called to
1353  * notify EAP state machine to reprocess the message. This
1354  * eap_sim_db_get_aka_auth() function will then be called again and the newly
1355  * received triplets will then be given to the caller.
1356  */
1357 int eap_sim_db_get_aka_auth(void *priv, const char *username, u8 *_rand,
1358                             u8 *autn, u8 *ik, u8 *ck, u8 *res, size_t *res_len,
1359                             void *cb_session_ctx)
1360 {
1361         struct eap_sim_db_data *data = priv;
1362         struct eap_sim_db_pending *entry;
1363         int len;
1364         char msg[40];
1365         const char *imsi;
1366         size_t imsi_len;
1367
1368         if (username == NULL ||
1369             (username[0] != EAP_AKA_PERMANENT_PREFIX &&
1370              username[0] != EAP_AKA_PRIME_PERMANENT_PREFIX) ||
1371             username[1] == '\0' || os_strlen(username) > sizeof(entry->imsi)) {
1372                 wpa_printf(MSG_DEBUG, "EAP-SIM DB: unexpected username '%s'",
1373                            username);
1374                 return EAP_SIM_DB_FAILURE;
1375         }
1376         imsi = username + 1;
1377         wpa_printf(MSG_DEBUG, "EAP-SIM DB: Get AKA auth for IMSI '%s'",
1378                    imsi);
1379
1380         entry = eap_sim_db_get_pending(data, imsi, 1);
1381         if (entry) {
1382                 if (entry->state == FAILURE) {
1383                         os_free(entry);
1384                         wpa_printf(MSG_DEBUG, "EAP-SIM DB: Failure");
1385                         return EAP_SIM_DB_FAILURE;
1386                 }
1387
1388                 if (entry->state == PENDING) {
1389                         eap_sim_db_add_pending(data, entry);
1390                         wpa_printf(MSG_DEBUG, "EAP-SIM DB: Pending");
1391                         return EAP_SIM_DB_PENDING;
1392                 }
1393
1394                 wpa_printf(MSG_DEBUG, "EAP-SIM DB: Returning successfully "
1395                            "received authentication data");
1396                 os_memcpy(_rand, entry->u.aka.rand, EAP_AKA_RAND_LEN);
1397                 os_memcpy(autn, entry->u.aka.autn, EAP_AKA_AUTN_LEN);
1398                 os_memcpy(ik, entry->u.aka.ik, EAP_AKA_IK_LEN);
1399                 os_memcpy(ck, entry->u.aka.ck, EAP_AKA_CK_LEN);
1400                 os_memcpy(res, entry->u.aka.res, EAP_AKA_RES_MAX_LEN);
1401                 *res_len = entry->u.aka.res_len;
1402                 os_free(entry);
1403                 return 0;
1404         }
1405
1406         if (data->sock < 0) {
1407                 if (eap_sim_db_open_socket(data) < 0)
1408                         return EAP_SIM_DB_FAILURE;
1409         }
1410
1411         imsi_len = os_strlen(imsi);
1412         len = os_snprintf(msg, sizeof(msg), "AKA-REQ-AUTH ");
1413         if (len < 0 || len + imsi_len >= sizeof(msg))
1414                 return EAP_SIM_DB_FAILURE;
1415         os_memcpy(msg + len, imsi, imsi_len);
1416         len += imsi_len;
1417
1418         wpa_printf(MSG_DEBUG, "EAP-SIM DB: requesting AKA authentication "
1419                     "data for IMSI '%s'", imsi);
1420         if (eap_sim_db_send(data, msg, len) < 0)
1421                 return EAP_SIM_DB_FAILURE;
1422
1423         entry = os_zalloc(sizeof(*entry));
1424         if (entry == NULL)
1425                 return EAP_SIM_DB_FAILURE;
1426
1427         os_get_time(&entry->timestamp);
1428         entry->aka = 1;
1429         os_strlcpy(entry->imsi, imsi, sizeof(entry->imsi));
1430         entry->cb_session_ctx = cb_session_ctx;
1431         entry->state = PENDING;
1432         eap_sim_db_add_pending(data, entry);
1433         eap_sim_db_expire_pending(data);
1434
1435         return EAP_SIM_DB_PENDING;
1436 }
1437
1438
1439 /**
1440  * eap_sim_db_resynchronize - Resynchronize AKA AUTN
1441  * @priv: Private data pointer from eap_sim_db_init()
1442  * @username: Permanent username
1443  * @auts: AUTS value from the peer
1444  * @_rand: RAND value used in the rejected message
1445  * Returns: 0 on success, -1 on failure
1446  *
1447  * This function is called when the peer reports synchronization failure in the
1448  * AUTN value by sending AUTS. The AUTS and RAND values should be sent to
1449  * HLR/AuC to allow it to resynchronize with the peer. After this,
1450  * eap_sim_db_get_aka_auth() will be called again to to fetch updated
1451  * RAND/AUTN values for the next challenge.
1452  */
1453 int eap_sim_db_resynchronize(void *priv, const char *username,
1454                              const u8 *auts, const u8 *_rand)
1455 {
1456         struct eap_sim_db_data *data = priv;
1457         const char *imsi;
1458         size_t imsi_len;
1459
1460         if (username == NULL ||
1461             (username[0] != EAP_AKA_PERMANENT_PREFIX &&
1462              username[0] != EAP_AKA_PRIME_PERMANENT_PREFIX) ||
1463             username[1] == '\0' || os_strlen(username) > 20) {
1464                 wpa_printf(MSG_DEBUG, "EAP-SIM DB: unexpected username '%s'",
1465                            username);
1466                 return -1;
1467         }
1468         imsi = username + 1;
1469         wpa_printf(MSG_DEBUG, "EAP-SIM DB: Get AKA auth for IMSI '%s'",
1470                    imsi);
1471
1472         if (data->sock >= 0) {
1473                 char msg[100];
1474                 int len, ret;
1475
1476                 imsi_len = os_strlen(imsi);
1477                 len = os_snprintf(msg, sizeof(msg), "AKA-AUTS ");
1478                 if (len < 0 || len + imsi_len >= sizeof(msg))
1479                         return -1;
1480                 os_memcpy(msg + len, imsi, imsi_len);
1481                 len += imsi_len;
1482
1483                 ret = os_snprintf(msg + len, sizeof(msg) - len, " ");
1484                 if (ret < 0 || (size_t) ret >= sizeof(msg) - len)
1485                         return -1;
1486                 len += ret;
1487                 len += wpa_snprintf_hex(msg + len, sizeof(msg) - len,
1488                                         auts, EAP_AKA_AUTS_LEN);
1489                 ret = os_snprintf(msg + len, sizeof(msg) - len, " ");
1490                 if (ret < 0 || (size_t) ret >= sizeof(msg) - len)
1491                         return -1;
1492                 len += ret;
1493                 len += wpa_snprintf_hex(msg + len, sizeof(msg) - len,
1494                                         _rand, EAP_AKA_RAND_LEN);
1495                 wpa_printf(MSG_DEBUG, "EAP-SIM DB: reporting AKA AUTS for "
1496                            "IMSI '%s'", imsi);
1497                 if (eap_sim_db_send(data, msg, len) < 0)
1498                         return -1;
1499         }
1500
1501         return 0;
1502 }
1503
1504
1505 /**
1506  * sim_get_username - Extract username from SIM identity
1507  * @identity: Identity
1508  * @identity_len: Identity length
1509  * Returns: Allocated buffer with the username part of the identity
1510  *
1511  * Caller is responsible for freeing the returned buffer with os_free().
1512  */
1513 char * sim_get_username(const u8 *identity, size_t identity_len)
1514 {
1515         char *username;
1516         size_t pos;
1517
1518         for (pos = 0; pos < identity_len; pos++) {
1519                 if (identity[pos] == '@' || identity[pos] == '\0')
1520                         break;
1521         }
1522
1523         username = os_malloc(pos + 1);
1524         if (username == NULL)
1525                 return NULL;
1526         os_memcpy(username, identity, pos);
1527         username[pos] = '\0';
1528
1529         return username;
1530 }