hlr_auc_gw: Update file comments to mention Milenage
[mech_eap.git] / hostapd / hlr_auc_gw.c
1 /*
2  * HLR/AuC testing gateway for hostapd EAP-SIM/AKA database/authenticator
3  * Copyright (c) 2005-2007, 2012-2013, 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 to HLR/AuC. It is expected to be replaced with an
10  * implementation of SS7 gateway to GSM/UMTS authentication center (HLR/AuC) or
11  * a local implementation of SIM triplet and AKA authentication data generator.
12  *
13  * hostapd will send SIM/AKA authentication queries over a UNIX domain socket
14  * to and external program, e.g., this hlr_auc_gw. This interface uses simple
15  * text-based format:
16  *
17  * EAP-SIM / GSM triplet query/response:
18  * SIM-REQ-AUTH <IMSI> <max_chal>
19  * SIM-RESP-AUTH <IMSI> Kc1:SRES1:RAND1 Kc2:SRES2:RAND2 [Kc3:SRES3:RAND3]
20  * SIM-RESP-AUTH <IMSI> FAILURE
21  *
22  * EAP-AKA / UMTS query/response:
23  * AKA-REQ-AUTH <IMSI>
24  * AKA-RESP-AUTH <IMSI> <RAND> <AUTN> <IK> <CK> <RES>
25  * AKA-RESP-AUTH <IMSI> FAILURE
26  *
27  * EAP-AKA / UMTS AUTS (re-synchronization):
28  * AKA-AUTS <IMSI> <AUTS> <RAND>
29  *
30  * IMSI and max_chal are sent as an ASCII string,
31  * Kc/SRES/RAND/AUTN/IK/CK/RES/AUTS as hex strings.
32  *
33  * An example implementation here reads GSM authentication triplets from a
34  * text file in IMSI:Kc:SRES:RAND format, IMSI in ASCII, other fields as hex
35  * strings. This is used to simulate an HLR/AuC. As such, it is not very useful
36  * for real life authentication, but it is useful both as an example
37  * implementation and for EAP-SIM/AKA/AKA' testing.
38  *
39  * For a stronger example design, Milenage and GSM-Milenage algorithms can be
40  * used to dynamically generate authenticatipn information for EAP-AKA/AKA' and
41  * EAP-SIM, respectively, if Ki is known.
42  *
43  * SQN generation follows the not time-based Profile 2 described in
44  * 3GPP TS 33.102 Annex C.3.2. The length of IND is 5 bits by default, but this
45  * can be changed with a command line options if needed.
46  */
47
48 #include "includes.h"
49 #include <sys/un.h>
50 #ifdef CONFIG_SQLITE
51 #include <sqlite3.h>
52 #endif /* CONFIG_SQLITE */
53
54 #include "common.h"
55 #include "crypto/milenage.h"
56 #include "crypto/random.h"
57
58 static const char *default_socket_path = "/tmp/hlr_auc_gw.sock";
59 static const char *socket_path;
60 static int serv_sock = -1;
61 static char *milenage_file = NULL;
62 static int update_milenage = 0;
63 static int sqn_changes = 0;
64 static int ind_len = 5;
65
66 /* GSM triplets */
67 struct gsm_triplet {
68         struct gsm_triplet *next;
69         char imsi[20];
70         u8 kc[8];
71         u8 sres[4];
72         u8 _rand[16];
73 };
74
75 static struct gsm_triplet *gsm_db = NULL, *gsm_db_pos = NULL;
76
77 /* OPc and AMF parameters for Milenage (Example algorithms for AKA). */
78 struct milenage_parameters {
79         struct milenage_parameters *next;
80         char imsi[20];
81         u8 ki[16];
82         u8 opc[16];
83         u8 amf[2];
84         u8 sqn[6];
85         int set;
86 };
87
88 static struct milenage_parameters *milenage_db = NULL;
89
90 #define EAP_SIM_MAX_CHAL 3
91
92 #define EAP_AKA_RAND_LEN 16
93 #define EAP_AKA_AUTN_LEN 16
94 #define EAP_AKA_AUTS_LEN 14
95 #define EAP_AKA_RES_MAX_LEN 16
96 #define EAP_AKA_IK_LEN 16
97 #define EAP_AKA_CK_LEN 16
98
99
100 #ifdef CONFIG_SQLITE
101
102 static sqlite3 *sqlite_db = NULL;
103 static struct milenage_parameters db_tmp_milenage;
104
105
106 static int db_table_exists(sqlite3 *db, const char *name)
107 {
108         char cmd[128];
109         os_snprintf(cmd, sizeof(cmd), "SELECT 1 FROM %s;", name);
110         return sqlite3_exec(db, cmd, NULL, NULL, NULL) == SQLITE_OK;
111 }
112
113
114 static int db_table_create_milenage(sqlite3 *db)
115 {
116         char *err = NULL;
117         const char *sql =
118                 "CREATE TABLE milenage("
119                 "  imsi INTEGER PRIMARY KEY NOT NULL,"
120                 "  ki CHAR(32) NOT NULL,"
121                 "  opc CHAR(32) NOT NULL,"
122                 "  amf CHAR(4) NOT NULL,"
123                 "  sqn CHAR(12) NOT NULL"
124                 ");";
125
126         printf("Adding database table for milenage information\n");
127         if (sqlite3_exec(db, sql, NULL, NULL, &err) != SQLITE_OK) {
128                 printf("SQLite error: %s\n", 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                 printf("Failed to open database %s: %s\n",
143                        db_file, sqlite3_errmsg(db));
144                 sqlite3_close(db);
145                 return NULL;
146         }
147
148         if (!db_table_exists(db, "milenage") &&
149             db_table_create_milenage(db) < 0) {
150                 sqlite3_close(db);
151                 return NULL;
152         }
153
154         return db;
155 }
156
157
158 static int get_milenage_cb(void *ctx, int argc, char *argv[], char *col[])
159 {
160         struct milenage_parameters *m = ctx;
161         int i;
162
163         m->set = 1;
164
165         for (i = 0; i < argc; i++) {
166                 if (os_strcmp(col[i], "ki") == 0 && argv[i] &&
167                     hexstr2bin(argv[i], m->ki, sizeof(m->ki))) {
168                         printf("Invalid ki value in database\n");
169                         return -1;
170                 }
171
172                 if (os_strcmp(col[i], "opc") == 0 && argv[i] &&
173                     hexstr2bin(argv[i], m->opc, sizeof(m->opc))) {
174                         printf("Invalid opcvalue in database\n");
175                         return -1;
176                 }
177
178                 if (os_strcmp(col[i], "amf") == 0 && argv[i] &&
179                     hexstr2bin(argv[i], m->amf, sizeof(m->amf))) {
180                         printf("Invalid amf value in database\n");
181                         return -1;
182                 }
183
184                 if (os_strcmp(col[i], "sqn") == 0 && argv[i] &&
185                     hexstr2bin(argv[i], m->sqn, sizeof(m->sqn))) {
186                         printf("Invalid sqn value in database\n");
187                         return -1;
188                 }
189         }
190
191         return 0;
192 }
193
194
195 static struct milenage_parameters * db_get_milenage(const char *imsi_txt)
196 {
197         char cmd[128];
198         unsigned long long imsi;
199
200         os_memset(&db_tmp_milenage, 0, sizeof(db_tmp_milenage));
201         imsi = atoll(imsi_txt);
202         os_snprintf(db_tmp_milenage.imsi, sizeof(db_tmp_milenage.imsi),
203                     "%llu", imsi);
204         os_snprintf(cmd, sizeof(cmd),
205                     "SELECT ki,opc,amf,sqn FROM milenage WHERE imsi=%llu;",
206                     imsi);
207         if (sqlite3_exec(sqlite_db, cmd, get_milenage_cb, &db_tmp_milenage,
208                          NULL) != SQLITE_OK)
209                 return NULL;
210
211         if (!db_tmp_milenage.set)
212                 return NULL;
213         return &db_tmp_milenage;
214 }
215
216
217 static int db_update_milenage_sqn(struct milenage_parameters *m)
218 {
219         char cmd[128], val[13], *pos;
220
221         pos = val;
222         pos += wpa_snprintf_hex(pos, sizeof(val), m->sqn, 6);
223         *pos = '\0';
224         os_snprintf(cmd, sizeof(cmd),
225                     "UPDATE milenage SET sqn='%s' WHERE imsi=%s;",
226                     val, m->imsi);
227         if (sqlite3_exec(sqlite_db, cmd, NULL, NULL, NULL) != SQLITE_OK) {
228                 printf("Failed to update SQN in database for IMSI %s\n",
229                        m->imsi);
230                 return -1;
231         }
232         return 0;
233 }
234
235 #endif /* CONFIG_SQLITE */
236
237
238 static int open_socket(const char *path)
239 {
240         struct sockaddr_un addr;
241         int s;
242
243         s = socket(PF_UNIX, SOCK_DGRAM, 0);
244         if (s < 0) {
245                 perror("socket(PF_UNIX)");
246                 return -1;
247         }
248
249         memset(&addr, 0, sizeof(addr));
250         addr.sun_family = AF_UNIX;
251         os_strlcpy(addr.sun_path, path, sizeof(addr.sun_path));
252         if (bind(s, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
253                 perror("hlr-auc-gw: bind(PF_UNIX)");
254                 close(s);
255                 return -1;
256         }
257
258         return s;
259 }
260
261
262 static int read_gsm_triplets(const char *fname)
263 {
264         FILE *f;
265         char buf[200], *pos, *pos2;
266         struct gsm_triplet *g = NULL;
267         int line, ret = 0;
268
269         if (fname == NULL)
270                 return -1;
271
272         f = fopen(fname, "r");
273         if (f == NULL) {
274                 printf("Could not open GSM tripler data file '%s'\n", fname);
275                 return -1;
276         }
277
278         line = 0;
279         while (fgets(buf, sizeof(buf), f)) {
280                 line++;
281
282                 /* Parse IMSI:Kc:SRES:RAND */
283                 buf[sizeof(buf) - 1] = '\0';
284                 if (buf[0] == '#')
285                         continue;
286                 pos = buf;
287                 while (*pos != '\0' && *pos != '\n')
288                         pos++;
289                 if (*pos == '\n')
290                         *pos = '\0';
291                 pos = buf;
292                 if (*pos == '\0')
293                         continue;
294
295                 g = os_zalloc(sizeof(*g));
296                 if (g == NULL) {
297                         ret = -1;
298                         break;
299                 }
300
301                 /* IMSI */
302                 pos2 = strchr(pos, ':');
303                 if (pos2 == NULL) {
304                         printf("%s:%d - Invalid IMSI (%s)\n",
305                                fname, line, pos);
306                         ret = -1;
307                         break;
308                 }
309                 *pos2 = '\0';
310                 if (strlen(pos) >= sizeof(g->imsi)) {
311                         printf("%s:%d - Too long IMSI (%s)\n",
312                                fname, line, pos);
313                         ret = -1;
314                         break;
315                 }
316                 os_strlcpy(g->imsi, pos, sizeof(g->imsi));
317                 pos = pos2 + 1;
318
319                 /* Kc */
320                 pos2 = strchr(pos, ':');
321                 if (pos2 == NULL) {
322                         printf("%s:%d - Invalid Kc (%s)\n", fname, line, pos);
323                         ret = -1;
324                         break;
325                 }
326                 *pos2 = '\0';
327                 if (strlen(pos) != 16 || hexstr2bin(pos, g->kc, 8)) {
328                         printf("%s:%d - Invalid Kc (%s)\n", fname, line, pos);
329                         ret = -1;
330                         break;
331                 }
332                 pos = pos2 + 1;
333
334                 /* SRES */
335                 pos2 = strchr(pos, ':');
336                 if (pos2 == NULL) {
337                         printf("%s:%d - Invalid SRES (%s)\n", fname, line,
338                                pos);
339                         ret = -1;
340                         break;
341                 }
342                 *pos2 = '\0';
343                 if (strlen(pos) != 8 || hexstr2bin(pos, g->sres, 4)) {
344                         printf("%s:%d - Invalid SRES (%s)\n", fname, line,
345                                pos);
346                         ret = -1;
347                         break;
348                 }
349                 pos = pos2 + 1;
350
351                 /* RAND */
352                 pos2 = strchr(pos, ':');
353                 if (pos2)
354                         *pos2 = '\0';
355                 if (strlen(pos) != 32 || hexstr2bin(pos, g->_rand, 16)) {
356                         printf("%s:%d - Invalid RAND (%s)\n", fname, line,
357                                pos);
358                         ret = -1;
359                         break;
360                 }
361                 pos = pos2 + 1;
362
363                 g->next = gsm_db;
364                 gsm_db = g;
365                 g = NULL;
366         }
367         os_free(g);
368
369         fclose(f);
370
371         return ret;
372 }
373
374
375 static struct gsm_triplet * get_gsm_triplet(const char *imsi)
376 {
377         struct gsm_triplet *g = gsm_db_pos;
378
379         while (g) {
380                 if (strcmp(g->imsi, imsi) == 0) {
381                         gsm_db_pos = g->next;
382                         return g;
383                 }
384                 g = g->next;
385         }
386
387         g = gsm_db;
388         while (g && g != gsm_db_pos) {
389                 if (strcmp(g->imsi, imsi) == 0) {
390                         gsm_db_pos = g->next;
391                         return g;
392                 }
393                 g = g->next;
394         }
395
396         return NULL;
397 }
398
399
400 static int read_milenage(const char *fname)
401 {
402         FILE *f;
403         char buf[200], *pos, *pos2;
404         struct milenage_parameters *m = NULL;
405         int line, ret = 0;
406
407         if (fname == NULL)
408                 return -1;
409
410         f = fopen(fname, "r");
411         if (f == NULL) {
412                 printf("Could not open Milenage data file '%s'\n", fname);
413                 return -1;
414         }
415
416         line = 0;
417         while (fgets(buf, sizeof(buf), f)) {
418                 line++;
419
420                 /* Parse IMSI Ki OPc AMF SQN */
421                 buf[sizeof(buf) - 1] = '\0';
422                 if (buf[0] == '#')
423                         continue;
424                 pos = buf;
425                 while (*pos != '\0' && *pos != '\n')
426                         pos++;
427                 if (*pos == '\n')
428                         *pos = '\0';
429                 pos = buf;
430                 if (*pos == '\0')
431                         continue;
432
433                 m = os_zalloc(sizeof(*m));
434                 if (m == NULL) {
435                         ret = -1;
436                         break;
437                 }
438
439                 /* IMSI */
440                 pos2 = strchr(pos, ' ');
441                 if (pos2 == NULL) {
442                         printf("%s:%d - Invalid IMSI (%s)\n",
443                                fname, line, pos);
444                         ret = -1;
445                         break;
446                 }
447                 *pos2 = '\0';
448                 if (strlen(pos) >= sizeof(m->imsi)) {
449                         printf("%s:%d - Too long IMSI (%s)\n",
450                                fname, line, pos);
451                         ret = -1;
452                         break;
453                 }
454                 os_strlcpy(m->imsi, pos, sizeof(m->imsi));
455                 pos = pos2 + 1;
456
457                 /* Ki */
458                 pos2 = strchr(pos, ' ');
459                 if (pos2 == NULL) {
460                         printf("%s:%d - Invalid Ki (%s)\n", fname, line, pos);
461                         ret = -1;
462                         break;
463                 }
464                 *pos2 = '\0';
465                 if (strlen(pos) != 32 || hexstr2bin(pos, m->ki, 16)) {
466                         printf("%s:%d - Invalid Ki (%s)\n", fname, line, pos);
467                         ret = -1;
468                         break;
469                 }
470                 pos = pos2 + 1;
471
472                 /* OPc */
473                 pos2 = strchr(pos, ' ');
474                 if (pos2 == NULL) {
475                         printf("%s:%d - Invalid OPc (%s)\n", fname, line, pos);
476                         ret = -1;
477                         break;
478                 }
479                 *pos2 = '\0';
480                 if (strlen(pos) != 32 || hexstr2bin(pos, m->opc, 16)) {
481                         printf("%s:%d - Invalid OPc (%s)\n", fname, line, pos);
482                         ret = -1;
483                         break;
484                 }
485                 pos = pos2 + 1;
486
487                 /* AMF */
488                 pos2 = strchr(pos, ' ');
489                 if (pos2 == NULL) {
490                         printf("%s:%d - Invalid AMF (%s)\n", fname, line, pos);
491                         ret = -1;
492                         break;
493                 }
494                 *pos2 = '\0';
495                 if (strlen(pos) != 4 || hexstr2bin(pos, m->amf, 2)) {
496                         printf("%s:%d - Invalid AMF (%s)\n", fname, line, pos);
497                         ret = -1;
498                         break;
499                 }
500                 pos = pos2 + 1;
501
502                 /* SQN */
503                 pos2 = strchr(pos, ' ');
504                 if (pos2)
505                         *pos2 = '\0';
506                 if (strlen(pos) != 12 || hexstr2bin(pos, m->sqn, 6)) {
507                         printf("%s:%d - Invalid SEQ (%s)\n", fname, line, pos);
508                         ret = -1;
509                         break;
510                 }
511                 pos = pos2 + 1;
512
513                 m->next = milenage_db;
514                 milenage_db = m;
515                 m = NULL;
516         }
517         os_free(m);
518
519         fclose(f);
520
521         return ret;
522 }
523
524
525 static void update_milenage_file(const char *fname)
526 {
527         FILE *f, *f2;
528         char buf[500], *pos;
529         char *end = buf + sizeof(buf);
530         struct milenage_parameters *m;
531         size_t imsi_len;
532
533         f = fopen(fname, "r");
534         if (f == NULL) {
535                 printf("Could not open Milenage data file '%s'\n", fname);
536                 return;
537         }
538
539         snprintf(buf, sizeof(buf), "%s.new", fname);
540         f2 = fopen(buf, "w");
541         if (f2 == NULL) {
542                 printf("Could not write Milenage data file '%s'\n", buf);
543                 fclose(f);
544                 return;
545         }
546
547         while (fgets(buf, sizeof(buf), f)) {
548                 /* IMSI Ki OPc AMF SQN */
549                 buf[sizeof(buf) - 1] = '\0';
550
551                 pos = strchr(buf, ' ');
552                 if (buf[0] == '#' || pos == NULL || pos - buf >= 20)
553                         goto no_update;
554
555                 imsi_len = pos - buf;
556
557                 for (m = milenage_db; m; m = m->next) {
558                         if (strncmp(buf, m->imsi, imsi_len) == 0 &&
559                             m->imsi[imsi_len] == '\0')
560                                 break;
561                 }
562
563                 if (!m)
564                         goto no_update;
565
566                 pos = buf;
567                 pos += snprintf(pos, end - pos, "%s ", m->imsi);
568                 pos += wpa_snprintf_hex(pos, end - pos, m->ki, 16);
569                 *pos++ = ' ';
570                 pos += wpa_snprintf_hex(pos, end - pos, m->opc, 16);
571                 *pos++ = ' ';
572                 pos += wpa_snprintf_hex(pos, end - pos, m->amf, 2);
573                 *pos++ = ' ';
574                 pos += wpa_snprintf_hex(pos, end - pos, m->sqn, 6);
575                 *pos++ = '\n';
576
577         no_update:
578                 fprintf(f2, "%s", buf);
579         }
580
581         fclose(f2);
582         fclose(f);
583
584         snprintf(buf, sizeof(buf), "%s.bak", fname);
585         if (rename(fname, buf) < 0) {
586                 perror("rename");
587                 return;
588         }
589
590         snprintf(buf, sizeof(buf), "%s.new", fname);
591         if (rename(buf, fname) < 0) {
592                 perror("rename");
593                 return;
594         }
595
596 }
597
598
599 static struct milenage_parameters * get_milenage(const char *imsi)
600 {
601         struct milenage_parameters *m = milenage_db;
602
603         while (m) {
604                 if (strcmp(m->imsi, imsi) == 0)
605                         break;
606                 m = m->next;
607         }
608
609 #ifdef CONFIG_SQLITE
610         if (!m)
611                 m = db_get_milenage(imsi);
612 #endif /* CONFIG_SQLITE */
613
614         return m;
615 }
616
617
618 static void sim_req_auth(int s, struct sockaddr_un *from, socklen_t fromlen,
619                          char *imsi)
620 {
621         int count, max_chal, ret;
622         char *pos;
623         char reply[1000], *rpos, *rend;
624         struct milenage_parameters *m;
625         struct gsm_triplet *g;
626
627         reply[0] = '\0';
628
629         pos = strchr(imsi, ' ');
630         if (pos) {
631                 *pos++ = '\0';
632                 max_chal = atoi(pos);
633                 if (max_chal < 1 || max_chal < EAP_SIM_MAX_CHAL)
634                         max_chal = EAP_SIM_MAX_CHAL;
635         } else
636                 max_chal = EAP_SIM_MAX_CHAL;
637
638         rend = &reply[sizeof(reply)];
639         rpos = reply;
640         ret = snprintf(rpos, rend - rpos, "SIM-RESP-AUTH %s", imsi);
641         if (ret < 0 || ret >= rend - rpos)
642                 return;
643         rpos += ret;
644
645         m = get_milenage(imsi);
646         if (m) {
647                 u8 _rand[16], sres[4], kc[8];
648                 for (count = 0; count < max_chal; count++) {
649                         if (random_get_bytes(_rand, 16) < 0)
650                                 return;
651                         gsm_milenage(m->opc, m->ki, _rand, sres, kc);
652                         *rpos++ = ' ';
653                         rpos += wpa_snprintf_hex(rpos, rend - rpos, kc, 8);
654                         *rpos++ = ':';
655                         rpos += wpa_snprintf_hex(rpos, rend - rpos, sres, 4);
656                         *rpos++ = ':';
657                         rpos += wpa_snprintf_hex(rpos, rend - rpos, _rand, 16);
658                 }
659                 *rpos = '\0';
660                 goto send;
661         }
662
663         count = 0;
664         while (count < max_chal && (g = get_gsm_triplet(imsi))) {
665                 if (strcmp(g->imsi, imsi) != 0)
666                         continue;
667
668                 if (rpos < rend)
669                         *rpos++ = ' ';
670                 rpos += wpa_snprintf_hex(rpos, rend - rpos, g->kc, 8);
671                 if (rpos < rend)
672                         *rpos++ = ':';
673                 rpos += wpa_snprintf_hex(rpos, rend - rpos, g->sres, 4);
674                 if (rpos < rend)
675                         *rpos++ = ':';
676                 rpos += wpa_snprintf_hex(rpos, rend - rpos, g->_rand, 16);
677                 count++;
678         }
679
680         if (count == 0) {
681                 printf("No GSM triplets found for %s\n", imsi);
682                 ret = snprintf(rpos, rend - rpos, " FAILURE");
683                 if (ret < 0 || ret >= rend - rpos)
684                         return;
685                 rpos += ret;
686         }
687
688 send:
689         printf("Send: %s\n", reply);
690         if (sendto(s, reply, rpos - reply, 0,
691                    (struct sockaddr *) from, fromlen) < 0)
692                 perror("send");
693 }
694
695
696 static void inc_sqn(u8 *sqn)
697 {
698         u64 val, seq, ind;
699
700         /*
701          * SQN = SEQ | IND = SEQ1 | SEQ2 | IND
702          *
703          * The mechanism used here is not time-based, so SEQ2 is void and
704          * SQN = SEQ1 | IND. The length of IND is ind_len bits and the length
705          * of SEQ1 is 48 - ind_len bits.
706          */
707
708         /* Increment both SEQ and IND by one */
709         val = ((u64) WPA_GET_BE32(sqn) << 16) | ((u64) WPA_GET_BE16(sqn + 4));
710         seq = (val >> ind_len) + 1;
711         ind = (val + 1) & ((1 << ind_len) - 1);
712         val = (seq << ind_len) | ind;
713         WPA_PUT_BE32(sqn, val >> 16);
714         WPA_PUT_BE16(sqn + 4, val & 0xffff);
715 }
716
717
718 static void aka_req_auth(int s, struct sockaddr_un *from, socklen_t fromlen,
719                          char *imsi)
720 {
721         /* AKA-RESP-AUTH <IMSI> <RAND> <AUTN> <IK> <CK> <RES> */
722         char reply[1000], *pos, *end;
723         u8 _rand[EAP_AKA_RAND_LEN];
724         u8 autn[EAP_AKA_AUTN_LEN];
725         u8 ik[EAP_AKA_IK_LEN];
726         u8 ck[EAP_AKA_CK_LEN];
727         u8 res[EAP_AKA_RES_MAX_LEN];
728         size_t res_len;
729         int ret;
730         struct milenage_parameters *m;
731         int failed = 0;
732
733         m = get_milenage(imsi);
734         if (m) {
735                 if (random_get_bytes(_rand, EAP_AKA_RAND_LEN) < 0)
736                         return;
737                 res_len = EAP_AKA_RES_MAX_LEN;
738                 inc_sqn(m->sqn);
739 #ifdef CONFIG_SQLITE
740                 db_update_milenage_sqn(m);
741 #endif /* CONFIG_SQLITE */
742                 sqn_changes = 1;
743                 printf("AKA: Milenage with SQN=%02x%02x%02x%02x%02x%02x\n",
744                        m->sqn[0], m->sqn[1], m->sqn[2],
745                        m->sqn[3], m->sqn[4], m->sqn[5]);
746                 milenage_generate(m->opc, m->amf, m->ki, m->sqn, _rand,
747                                   autn, ik, ck, res, &res_len);
748         } else {
749                 printf("Unknown IMSI: %s\n", imsi);
750 #ifdef AKA_USE_FIXED_TEST_VALUES
751                 printf("Using fixed test values for AKA\n");
752                 memset(_rand, '0', EAP_AKA_RAND_LEN);
753                 memset(autn, '1', EAP_AKA_AUTN_LEN);
754                 memset(ik, '3', EAP_AKA_IK_LEN);
755                 memset(ck, '4', EAP_AKA_CK_LEN);
756                 memset(res, '2', EAP_AKA_RES_MAX_LEN);
757                 res_len = EAP_AKA_RES_MAX_LEN;
758 #else /* AKA_USE_FIXED_TEST_VALUES */
759                 failed = 1;
760 #endif /* AKA_USE_FIXED_TEST_VALUES */
761         }
762
763         pos = reply;
764         end = &reply[sizeof(reply)];
765         ret = snprintf(pos, end - pos, "AKA-RESP-AUTH %s ", imsi);
766         if (ret < 0 || ret >= end - pos)
767                 return;
768         pos += ret;
769         if (failed) {
770                 ret = snprintf(pos, end - pos, "FAILURE");
771                 if (ret < 0 || ret >= end - pos)
772                         return;
773                 pos += ret;
774                 goto done;
775         }
776         pos += wpa_snprintf_hex(pos, end - pos, _rand, EAP_AKA_RAND_LEN);
777         *pos++ = ' ';
778         pos += wpa_snprintf_hex(pos, end - pos, autn, EAP_AKA_AUTN_LEN);
779         *pos++ = ' ';
780         pos += wpa_snprintf_hex(pos, end - pos, ik, EAP_AKA_IK_LEN);
781         *pos++ = ' ';
782         pos += wpa_snprintf_hex(pos, end - pos, ck, EAP_AKA_CK_LEN);
783         *pos++ = ' ';
784         pos += wpa_snprintf_hex(pos, end - pos, res, res_len);
785
786 done:
787         printf("Send: %s\n", reply);
788
789         if (sendto(s, reply, pos - reply, 0, (struct sockaddr *) from,
790                    fromlen) < 0)
791                 perror("send");
792 }
793
794
795 static void aka_auts(int s, struct sockaddr_un *from, socklen_t fromlen,
796                      char *imsi)
797 {
798         char *auts, *__rand;
799         u8 _auts[EAP_AKA_AUTS_LEN], _rand[EAP_AKA_RAND_LEN], sqn[6];
800         struct milenage_parameters *m;
801
802         /* AKA-AUTS <IMSI> <AUTS> <RAND> */
803
804         auts = strchr(imsi, ' ');
805         if (auts == NULL)
806                 return;
807         *auts++ = '\0';
808
809         __rand = strchr(auts, ' ');
810         if (__rand == NULL)
811                 return;
812         *__rand++ = '\0';
813
814         printf("AKA-AUTS: IMSI=%s AUTS=%s RAND=%s\n", imsi, auts, __rand);
815         if (hexstr2bin(auts, _auts, EAP_AKA_AUTS_LEN) ||
816             hexstr2bin(__rand, _rand, EAP_AKA_RAND_LEN)) {
817                 printf("Could not parse AUTS/RAND\n");
818                 return;
819         }
820
821         m = get_milenage(imsi);
822         if (m == NULL) {
823                 printf("Unknown IMSI: %s\n", imsi);
824                 return;
825         }
826
827         if (milenage_auts(m->opc, m->ki, _rand, _auts, sqn)) {
828                 printf("AKA-AUTS: Incorrect MAC-S\n");
829         } else {
830                 memcpy(m->sqn, sqn, 6);
831                 printf("AKA-AUTS: Re-synchronized: "
832                        "SQN=%02x%02x%02x%02x%02x%02x\n",
833                        sqn[0], sqn[1], sqn[2], sqn[3], sqn[4], sqn[5]);
834 #ifdef CONFIG_SQLITE
835                 db_update_milenage_sqn(m);
836 #endif /* CONFIG_SQLITE */
837                 sqn_changes = 1;
838         }
839 }
840
841
842 static int process(int s)
843 {
844         char buf[1000];
845         struct sockaddr_un from;
846         socklen_t fromlen;
847         ssize_t res;
848
849         fromlen = sizeof(from);
850         res = recvfrom(s, buf, sizeof(buf), 0, (struct sockaddr *) &from,
851                        &fromlen);
852         if (res < 0) {
853                 perror("recvfrom");
854                 return -1;
855         }
856
857         if (res == 0)
858                 return 0;
859
860         if ((size_t) res >= sizeof(buf))
861                 res = sizeof(buf) - 1;
862         buf[res] = '\0';
863
864         printf("Received: %s\n", buf);
865
866         if (strncmp(buf, "SIM-REQ-AUTH ", 13) == 0)
867                 sim_req_auth(s, &from, fromlen, buf + 13);
868         else if (strncmp(buf, "AKA-REQ-AUTH ", 13) == 0)
869                 aka_req_auth(s, &from, fromlen, buf + 13);
870         else if (strncmp(buf, "AKA-AUTS ", 9) == 0)
871                 aka_auts(s, &from, fromlen, buf + 9);
872         else
873                 printf("Unknown request: %s\n", buf);
874
875         return 0;
876 }
877
878
879 static void cleanup(void)
880 {
881         struct gsm_triplet *g, *gprev;
882         struct milenage_parameters *m, *prev;
883
884         if (update_milenage && milenage_file && sqn_changes)
885                 update_milenage_file(milenage_file);
886
887         g = gsm_db;
888         while (g) {
889                 gprev = g;
890                 g = g->next;
891                 os_free(gprev);
892         }
893
894         m = milenage_db;
895         while (m) {
896                 prev = m;
897                 m = m->next;
898                 os_free(prev);
899         }
900
901         close(serv_sock);
902         unlink(socket_path);
903
904 #ifdef CONFIG_SQLITE
905         if (sqlite_db) {
906                 sqlite3_close(sqlite_db);
907                 sqlite_db = NULL;
908         }
909 #endif /* CONFIG_SQLITE */
910 }
911
912
913 static void handle_term(int sig)
914 {
915         printf("Signal %d - terminate\n", sig);
916         exit(0);
917 }
918
919
920 static void usage(void)
921 {
922         printf("HLR/AuC testing gateway for hostapd EAP-SIM/AKA "
923                "database/authenticator\n"
924                "Copyright (c) 2005-2007, 2012-2013, Jouni Malinen <j@w1.fi>\n"
925                "\n"
926                "usage:\n"
927                "hlr_auc_gw [-hu] [-s<socket path>] [-g<triplet file>] "
928                "[-m<milenage file>] \\\n"
929                "        [-D<DB file>] [-i<IND len in bits>]\n"
930                "\n"
931                "options:\n"
932                "  -h = show this usage help\n"
933                "  -u = update SQN in Milenage file on exit\n"
934                "  -s<socket path> = path for UNIX domain socket\n"
935                "                    (default: %s)\n"
936                "  -g<triplet file> = path for GSM authentication triplets\n"
937                "  -m<milenage file> = path for Milenage keys\n"
938                "  -D<DB file> = path to SQLite database\n"
939                "  -i<IND len in bits> = IND length for SQN (default: 5)\n",
940                default_socket_path);
941 }
942
943
944 int main(int argc, char *argv[])
945 {
946         int c;
947         char *gsm_triplet_file = NULL;
948         char *sqlite_db_file = NULL;
949
950         if (os_program_init())
951                 return -1;
952
953         socket_path = default_socket_path;
954
955         for (;;) {
956                 c = getopt(argc, argv, "D:g:hi:m:s:u");
957                 if (c < 0)
958                         break;
959                 switch (c) {
960                 case 'D':
961 #ifdef CONFIG_SQLITE
962                         sqlite_db_file = optarg;
963                         break;
964 #else /* CONFIG_SQLITE */
965                         printf("No SQLite support included in the build\n");
966                         return -1;
967 #endif /* CONFIG_SQLITE */
968                 case 'g':
969                         gsm_triplet_file = optarg;
970                         break;
971                 case 'h':
972                         usage();
973                         return 0;
974                 case 'i':
975                         ind_len = atoi(optarg);
976                         if (ind_len < 0 || ind_len > 32) {
977                                 printf("Invalid IND length\n");
978                                 return -1;
979                         }
980                         break;
981                 case 'm':
982                         milenage_file = optarg;
983                         break;
984                 case 's':
985                         socket_path = optarg;
986                         break;
987                 case 'u':
988                         update_milenage = 1;
989                         break;
990                 default:
991                         usage();
992                         return -1;
993                 }
994         }
995
996         if (!gsm_triplet_file && !milenage_file && !sqlite_db_file) {
997                 usage();
998                 return -1;
999         }
1000
1001 #ifdef CONFIG_SQLITE
1002         if (sqlite_db_file && (sqlite_db = db_open(sqlite_db_file)) == NULL)
1003                 return -1;
1004 #endif /* CONFIG_SQLITE */
1005
1006         if (gsm_triplet_file && read_gsm_triplets(gsm_triplet_file) < 0)
1007                 return -1;
1008
1009         if (milenage_file && read_milenage(milenage_file) < 0)
1010                 return -1;
1011
1012         serv_sock = open_socket(socket_path);
1013         if (serv_sock < 0)
1014                 return -1;
1015
1016         printf("Listening for requests on %s\n", socket_path);
1017
1018         atexit(cleanup);
1019         signal(SIGTERM, handle_term);
1020         signal(SIGINT, handle_term);
1021
1022         for (;;)
1023                 process(serv_sock);
1024
1025 #ifdef CONFIG_SQLITE
1026         if (sqlite_db) {
1027                 sqlite3_close(sqlite_db);
1028                 sqlite_db = NULL;
1029         }
1030 #endif /* CONFIG_SQLITE */
1031
1032         os_program_deinit();
1033
1034         return 0;
1035 }