1 /*	$FreeBSD: stable/12/sbin/setkey/setkey.c 372090 2022-05-19 06:13:44Z eugen $	*/
2 /*	$KAME: setkey.c,v 1.28 2003/06/27 07:15:45 itojun Exp $	*/
3 
4 /*-
5  * SPDX-License-Identifier: BSD-3-Clause
6  *
7  * Copyright (C) 1995, 1996, 1997, 1998, and 1999 WIDE Project.
8  * All rights reserved.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. Neither the name of the project nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34 
35 #include <sys/types.h>
36 #include <sys/param.h>
37 #include <sys/linker.h>
38 #include <sys/module.h>
39 #include <sys/socket.h>
40 #include <sys/time.h>
41 #include <err.h>
42 #include <net/route.h>
43 #include <netinet/in.h>
44 #include <net/pfkeyv2.h>
45 #include <netipsec/keydb.h>
46 #include <netipsec/key_debug.h>
47 #include <netipsec/ipsec.h>
48 
49 #include <stdio.h>
50 #include <stdlib.h>
51 #include <limits.h>
52 #include <string.h>
53 #include <ctype.h>
54 #include <unistd.h>
55 #include <errno.h>
56 #include <netdb.h>
57 
58 #include "libpfkey.h"
59 
60 void usage(void);
61 int main(int, char **);
62 int get_supported(void);
63 void sendkeyshort(u_int, uint8_t);
64 void promisc(void);
65 int sendkeymsg(char *, size_t);
66 int postproc(struct sadb_msg *, int);
67 const char *numstr(int);
68 void shortdump_hdr(void);
69 void shortdump(struct sadb_msg *);
70 static void printdate(void);
71 static int32_t gmt2local(time_t);
72 static int modload(const char *name);
73 
74 #define MODE_SCRIPT	1
75 #define MODE_CMDDUMP	2
76 #define MODE_CMDFLUSH	3
77 #define MODE_PROMISC	4
78 
79 int so;
80 
81 int f_forever = 0;
82 int f_all = 0;
83 int f_verbose = 0;
84 int f_mode = 0;
85 int f_cmddump = 0;
86 int f_policy = 0;
87 int f_hexdump = 0;
88 int f_tflag = 0;
89 int f_scope = 0;
90 static time_t thiszone;
91 
92 extern int lineno;
93 
94 extern int parse(FILE **);
95 
96 void
usage()97 usage()
98 {
99 
100 	printf("usage: setkey [-v] -c\n");
101 	printf("       setkey [-v] -f filename\n");
102 	printf("       setkey [-Pagltv] -D\n");
103 	printf("       setkey [-Pv] -F\n");
104 	printf("       setkey [-h] -x\n");
105 	exit(1);
106 }
107 
108 static int
modload(const char * name)109 modload(const char *name)
110 {
111 	if (modfind(name) < 0)
112 		if (kldload(name) < 0 || modfind(name) < 0) {
113 			warn("%s: module not found", name);
114 			return 0;
115 	}
116 	return 1;
117 }
118 
119 int
main(ac,av)120 main(ac, av)
121 	int ac;
122 	char **av;
123 {
124 	FILE *fp = stdin;
125 	int c;
126 
127 	if (ac == 1) {
128 		usage();
129 		/* NOTREACHED */
130 	}
131 
132 	thiszone = gmt2local(0);
133 
134 	while ((c = getopt(ac, av, "acdf:ghltvxDFP")) != -1) {
135 		switch (c) {
136 		case 'c':
137 			f_mode = MODE_SCRIPT;
138 			fp = stdin;
139 			break;
140 		case 'f':
141 			f_mode = MODE_SCRIPT;
142 			if ((fp = fopen(optarg, "r")) == NULL) {
143 				err(-1, "fopen");
144 				/*NOTREACHED*/
145 			}
146 			break;
147 		case 'D':
148 			f_mode = MODE_CMDDUMP;
149 			break;
150 		case 'F':
151 			f_mode = MODE_CMDFLUSH;
152 			break;
153 		case 'a':
154 			f_all = 1;
155 			break;
156 		case 'l':
157 			f_forever = 1;
158 			break;
159 		case 'h':
160 			f_hexdump = 1;
161 			break;
162 		case 'x':
163 			f_mode = MODE_PROMISC;
164 			f_tflag++;
165 			break;
166 		case 'P':
167 			f_policy = 1;
168 			break;
169 		case 'g': /* global */
170 			f_scope |= IPSEC_POLICYSCOPE_GLOBAL;
171 			break;
172 		case 't': /* tunnel */
173 			f_scope |= IPSEC_POLICYSCOPE_IFNET;
174 			break;
175 		case 'v':
176 			f_verbose = 1;
177 			break;
178 		default:
179 			usage();
180 			/*NOTREACHED*/
181 		}
182 	}
183 
184 	modload("ipsec");
185 	so = pfkey_open();
186 	if (so < 0) {
187 		perror("pfkey_open");
188 		exit(1);
189 	}
190 
191 	switch (f_mode) {
192 	case MODE_CMDDUMP:
193 		sendkeyshort(f_policy ? SADB_X_SPDDUMP: SADB_DUMP,
194 		    f_policy ? f_scope: SADB_SATYPE_UNSPEC);
195 		break;
196 	case MODE_CMDFLUSH:
197 		sendkeyshort(f_policy ? SADB_X_SPDFLUSH: SADB_FLUSH,
198 		    SADB_SATYPE_UNSPEC);
199 		break;
200 	case MODE_SCRIPT:
201 		if (get_supported() < 0) {
202 			errx(-1, "%s", ipsec_strerror());
203 			/*NOTREACHED*/
204 		}
205 		if (parse(&fp))
206 			exit (1);
207 		break;
208 	case MODE_PROMISC:
209 		promisc();
210 		/*NOTREACHED*/
211 	default:
212 		usage();
213 		/*NOTREACHED*/
214 	}
215 
216 	exit(0);
217 }
218 
219 int
get_supported()220 get_supported()
221 {
222 
223 	if (pfkey_send_register(so, SADB_SATYPE_UNSPEC) < 0)
224 		return -1;
225 
226 	if (pfkey_recv_register(so) < 0)
227 		return -1;
228 
229 	return 0;
230 }
231 
232 void
sendkeyshort(u_int type,uint8_t satype)233 sendkeyshort(u_int type, uint8_t satype)
234 {
235 	struct sadb_msg msg;
236 
237 	msg.sadb_msg_version = PF_KEY_V2;
238 	msg.sadb_msg_type = type;
239 	msg.sadb_msg_errno = 0;
240 	msg.sadb_msg_satype = satype;
241 	msg.sadb_msg_len = PFKEY_UNIT64(sizeof(msg));
242 	msg.sadb_msg_reserved = 0;
243 	msg.sadb_msg_seq = 0;
244 	msg.sadb_msg_pid = getpid();
245 
246 	sendkeymsg((char *)&msg, sizeof(msg));
247 
248 	return;
249 }
250 
251 void
promisc()252 promisc()
253 {
254 	struct sadb_msg msg;
255 	u_char rbuf[1024 * 32];	/* XXX: Enough ? Should I do MSG_PEEK ? */
256 	ssize_t l;
257 
258 	msg.sadb_msg_version = PF_KEY_V2;
259 	msg.sadb_msg_type = SADB_X_PROMISC;
260 	msg.sadb_msg_errno = 0;
261 	msg.sadb_msg_satype = 1;
262 	msg.sadb_msg_len = PFKEY_UNIT64(sizeof(msg));
263 	msg.sadb_msg_reserved = 0;
264 	msg.sadb_msg_seq = 0;
265 	msg.sadb_msg_pid = getpid();
266 
267 	if ((l = send(so, &msg, sizeof(msg), 0)) < 0) {
268 		err(1, "send");
269 		/*NOTREACHED*/
270 	}
271 
272 	while (1) {
273 		struct sadb_msg *base;
274 
275 		if ((l = recv(so, rbuf, sizeof(*base), MSG_PEEK)) < 0) {
276 			err(1, "recv");
277 			/*NOTREACHED*/
278 		}
279 
280 		if (l != sizeof(*base))
281 			continue;
282 
283 		base = (struct sadb_msg *)rbuf;
284 		if ((l = recv(so, rbuf, PFKEY_UNUNIT64(base->sadb_msg_len),
285 				0)) < 0) {
286 			err(1, "recv");
287 			/*NOTREACHED*/
288 		}
289 		printdate();
290 		if (f_hexdump) {
291 			int i;
292 			for (i = 0; i < l; i++) {
293 				if (i % 16 == 0)
294 					printf("%08x: ", i);
295 				printf("%02x ", rbuf[i] & 0xff);
296 				if (i % 16 == 15)
297 					printf("\n");
298 			}
299 			if (l % 16)
300 				printf("\n");
301 		}
302 		/* adjust base pointer for promisc mode */
303 		if (base->sadb_msg_type == SADB_X_PROMISC) {
304 			if ((ssize_t)sizeof(*base) < l)
305 				base++;
306 			else
307 				base = NULL;
308 		}
309 		if (base) {
310 			kdebug_sadb(base);
311 			printf("\n");
312 			fflush(stdout);
313 		}
314 	}
315 }
316 
317 int
sendkeymsg(buf,len)318 sendkeymsg(buf, len)
319 	char *buf;
320 	size_t len;
321 {
322 	u_char rbuf[1024 * 32];	/* XXX: Enough ? Should I do MSG_PEEK ? */
323 	ssize_t l;
324 	struct sadb_msg *msg;
325 
326     {
327 	struct timeval tv;
328 	tv.tv_sec = 1;
329 	tv.tv_usec = 0;
330 	if (setsockopt(so, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)) < 0) {
331 		perror("setsockopt");
332 		goto end;
333 	}
334     }
335 
336 	if (f_forever)
337 		shortdump_hdr();
338 again:
339 	if (f_verbose) {
340 		kdebug_sadb((struct sadb_msg *)buf);
341 		printf("\n");
342 	}
343 	if (f_hexdump) {
344 		int i;
345 		for (i = 0; i < len; i++) {
346 			if (i % 16 == 0)
347 				printf("%08x: ", i);
348 			printf("%02x ", buf[i] & 0xff);
349 			if (i % 16 == 15)
350 				printf("\n");
351 		}
352 		if (len % 16)
353 			printf("\n");
354 	}
355 
356 	if ((l = send(so, buf, len, 0)) < 0) {
357 		perror("send");
358 		goto end;
359 	}
360 
361 	msg = (struct sadb_msg *)rbuf;
362 	do {
363 		if ((l = recv(so, rbuf, sizeof(rbuf), 0)) < 0) {
364 			perror("recv");
365 			goto end;
366 		}
367 
368 		if (PFKEY_UNUNIT64(msg->sadb_msg_len) != l) {
369 			warnx("invalid keymsg length");
370 			break;
371 		}
372 
373 		if (f_verbose) {
374 			kdebug_sadb((struct sadb_msg *)rbuf);
375 			printf("\n");
376 		}
377 		if (postproc(msg, l) < 0)
378 			break;
379 	} while (msg->sadb_msg_errno || msg->sadb_msg_seq);
380 
381 	if (f_forever) {
382 		fflush(stdout);
383 		sleep(1);
384 		goto again;
385 	}
386 
387 end:
388 	return(0);
389 }
390 
391 int
postproc(msg,len)392 postproc(msg, len)
393 	struct sadb_msg *msg;
394 	int len;
395 {
396 
397 	if (msg->sadb_msg_errno != 0) {
398 		char inf[80];
399 		const char *errmsg = NULL;
400 
401 		if (f_mode == MODE_SCRIPT)
402 			snprintf(inf, sizeof(inf), "The result of line %d: ", lineno);
403 		else
404 			inf[0] = '\0';
405 
406 		switch (msg->sadb_msg_errno) {
407 		case ENOENT:
408 			switch (msg->sadb_msg_type) {
409 			case SADB_DELETE:
410 			case SADB_GET:
411 			case SADB_X_SPDDELETE:
412 				errmsg = "No entry";
413 				break;
414 			case SADB_DUMP:
415 				errmsg = "No SAD entries";
416 				break;
417 			case SADB_X_SPDDUMP:
418 				errmsg = "No SPD entries";
419 				break;
420 			}
421 			break;
422 		default:
423 			errmsg = strerror(msg->sadb_msg_errno);
424 		}
425 		printf("%s%s.\n", inf, errmsg);
426 		return(-1);
427 	}
428 
429 	switch (msg->sadb_msg_type) {
430 	case SADB_GET:
431 		pfkey_sadump(msg);
432 		break;
433 
434 	case SADB_DUMP:
435 		/* filter out DEAD SAs */
436 		if (!f_all) {
437 			caddr_t mhp[SADB_EXT_MAX + 1];
438 			struct sadb_sa *sa;
439 			pfkey_align(msg, mhp);
440 			pfkey_check(mhp);
441 			if ((sa = (struct sadb_sa *)mhp[SADB_EXT_SA]) != NULL) {
442 				if (sa->sadb_sa_state == SADB_SASTATE_DEAD)
443 					break;
444 			}
445 		}
446 		if (f_forever)
447 			shortdump(msg);
448 		else
449 			pfkey_sadump(msg);
450 		msg = (struct sadb_msg *)((caddr_t)msg +
451 				     PFKEY_UNUNIT64(msg->sadb_msg_len));
452 		if (f_verbose) {
453 			kdebug_sadb((struct sadb_msg *)msg);
454 			printf("\n");
455 		}
456 		break;
457 
458 	case SADB_X_SPDDUMP:
459 		pfkey_spdump(msg);
460 		if (msg->sadb_msg_seq == 0) break;
461 		msg = (struct sadb_msg *)((caddr_t)msg +
462 				     PFKEY_UNUNIT64(msg->sadb_msg_len));
463 		if (f_verbose) {
464 			kdebug_sadb((struct sadb_msg *)msg);
465 			printf("\n");
466 		}
467 		break;
468 	}
469 
470 	return(0);
471 }
472 
473 /*------------------------------------------------------------*/
474 static const char *satype[] = {
475 	NULL, NULL, "ah", "esp"
476 };
477 static const char *sastate[] = {
478 	"L", "M", "D", "d"
479 };
480 static const char *ipproto[] = {
481 /*0*/	"ip", "icmp", "igmp", "ggp", "ip4",
482 	NULL, "tcp", NULL, "egp", NULL,
483 /*10*/	NULL, NULL, NULL, NULL, NULL,
484 	NULL, NULL, "udp", NULL, NULL,
485 /*20*/	NULL, NULL, "idp", NULL, NULL,
486 	NULL, NULL, NULL, NULL, "tp",
487 /*30*/	NULL, NULL, NULL, NULL, NULL,
488 	NULL, NULL, NULL, NULL, NULL,
489 /*40*/	NULL, "ip6", NULL, "rt6", "frag6",
490 	NULL, "rsvp", "gre", NULL, NULL,
491 /*50*/	"esp", "ah", NULL, NULL, NULL,
492 	NULL, NULL, NULL, "icmp6", "none",
493 /*60*/	"dst6",
494 };
495 
496 #define STR_OR_ID(x, tab) \
497 	(((x) < sizeof(tab)/sizeof(tab[0]) && tab[(x)])	? tab[(x)] : numstr(x))
498 
499 const char *
numstr(x)500 numstr(x)
501 	int x;
502 {
503 	static char buf[20];
504 	snprintf(buf, sizeof(buf), "#%d", x);
505 	return buf;
506 }
507 
508 void
shortdump_hdr()509 shortdump_hdr()
510 {
511 	printf("%-4s %-3s %-1s %-8s %-7s %s -> %s\n",
512 		"time", "p", "s", "spi", "ltime", "src", "dst");
513 }
514 
515 void
shortdump(msg)516 shortdump(msg)
517 	struct sadb_msg *msg;
518 {
519 	caddr_t mhp[SADB_EXT_MAX + 1];
520 	char buf[NI_MAXHOST], pbuf[NI_MAXSERV];
521 	struct sadb_sa *sa;
522 	struct sadb_address *saddr;
523 	struct sadb_lifetime *lts, *lth, *ltc;
524 	struct sockaddr *s;
525 	u_int t;
526 	time_t cur = time(0);
527 
528 	pfkey_align(msg, mhp);
529 	pfkey_check(mhp);
530 
531 	printf("%02lu%02lu", (u_long)(cur % 3600) / 60, (u_long)(cur % 60));
532 
533 	printf(" %-3s", STR_OR_ID(msg->sadb_msg_satype, satype));
534 
535 	if ((sa = (struct sadb_sa *)mhp[SADB_EXT_SA]) != NULL) {
536 		printf(" %-1s", STR_OR_ID(sa->sadb_sa_state, sastate));
537 		printf(" %08x", (u_int32_t)ntohl(sa->sadb_sa_spi));
538 	} else
539 		printf("%-1s %-8s", "?", "?");
540 
541 	lts = (struct sadb_lifetime *)mhp[SADB_EXT_LIFETIME_SOFT];
542 	lth = (struct sadb_lifetime *)mhp[SADB_EXT_LIFETIME_HARD];
543 	ltc = (struct sadb_lifetime *)mhp[SADB_EXT_LIFETIME_CURRENT];
544 	if (lts && lth && ltc) {
545 		if (ltc->sadb_lifetime_addtime == 0)
546 			t = (u_long)0;
547 		else
548 			t = (u_long)(cur - ltc->sadb_lifetime_addtime);
549 		if (t >= 1000)
550 			strlcpy(buf, " big/", sizeof(buf));
551 		else
552 			snprintf(buf, sizeof(buf), " %3lu/", (u_long)t);
553 		printf("%s", buf);
554 
555 		t = (u_long)lth->sadb_lifetime_addtime;
556 		if (t >= 1000)
557 			strlcpy(buf, "big", sizeof(buf));
558 		else
559 			snprintf(buf, sizeof(buf), "%-3lu", (u_long)t);
560 		printf("%s", buf);
561 	} else
562 		printf(" ??\?/???");	/* backslash to avoid trigraph ??/ */
563 
564 	printf(" ");
565 
566 	if ((saddr = (struct sadb_address *)mhp[SADB_EXT_ADDRESS_SRC]) != NULL) {
567 		if (saddr->sadb_address_proto)
568 			printf("%s ", STR_OR_ID(saddr->sadb_address_proto, ipproto));
569 		s = (struct sockaddr *)(saddr + 1);
570 		getnameinfo(s, s->sa_len, buf, sizeof(buf),
571 			pbuf, sizeof(pbuf), NI_NUMERICHOST|NI_NUMERICSERV);
572 		if (strcmp(pbuf, "0") != 0)
573 			printf("%s[%s]", buf, pbuf);
574 		else
575 			printf("%s", buf);
576 	} else
577 		printf("?");
578 
579 	printf(" -> ");
580 
581 	if ((saddr = (struct sadb_address *)mhp[SADB_EXT_ADDRESS_DST]) != NULL) {
582 		if (saddr->sadb_address_proto)
583 			printf("%s ", STR_OR_ID(saddr->sadb_address_proto, ipproto));
584 
585 		s = (struct sockaddr *)(saddr + 1);
586 		getnameinfo(s, s->sa_len, buf, sizeof(buf),
587 			pbuf, sizeof(pbuf), NI_NUMERICHOST|NI_NUMERICSERV);
588 		if (strcmp(pbuf, "0") != 0)
589 			printf("%s[%s]", buf, pbuf);
590 		else
591 			printf("%s", buf);
592 	} else
593 		printf("?");
594 
595 	printf("\n");
596 }
597 
598 /* From: tcpdump(1):gmt2local.c and util.c */
599 /*
600  * Print the timestamp
601  */
602 static void
printdate()603 printdate()
604 {
605 	struct timeval tp;
606 	int s;
607 
608 	if (gettimeofday(&tp, NULL) == -1) {
609 		perror("gettimeofday");
610 		return;
611 	}
612 
613 	if (f_tflag == 1) {
614 		/* Default */
615 		s = (tp.tv_sec + thiszone ) % 86400;
616 		(void)printf("%02d:%02d:%02d.%06u ",
617 		    s / 3600, (s % 3600) / 60, s % 60, (u_int32_t)tp.tv_usec);
618 	} else if (f_tflag > 1) {
619 		/* Unix timeval style */
620 		(void)printf("%u.%06u ",
621 		    (u_int32_t)tp.tv_sec, (u_int32_t)tp.tv_usec);
622 	}
623 
624 	printf("\n");
625 }
626 
627 /*
628  * Returns the difference between gmt and local time in seconds.
629  * Use gmtime() and localtime() to keep things simple.
630  */
631 int32_t
gmt2local(time_t t)632 gmt2local(time_t t)
633 {
634 	register int dt, dir;
635 	register struct tm *gmt, *loc;
636 	struct tm sgmt;
637 
638 	if (t == 0)
639 		t = time(NULL);
640 	gmt = &sgmt;
641 	*gmt = *gmtime(&t);
642 	loc = localtime(&t);
643 	dt = (loc->tm_hour - gmt->tm_hour) * 60 * 60 +
644 	    (loc->tm_min - gmt->tm_min) * 60;
645 
646 	/*
647 	 * If the year or julian day is different, we span 00:00 GMT
648 	 * and must add or subtract a day. Check the year first to
649 	 * avoid problems when the julian day wraps.
650 	 */
651 	dir = loc->tm_year - gmt->tm_year;
652 	if (dir == 0)
653 		dir = loc->tm_yday - gmt->tm_yday;
654 	dt += dir * 24 * 60 * 60;
655 
656 	return (dt);
657 }
658