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