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