xref: /titanic_52/usr/src/lib/libipsecutil/common/ipsec_util.c (revision 455710d3fbabc22a8a307245b917b92d026a9879)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 #pragma ident	"%Z%%M%	%I%	%E% SMI"
27 
28 #include <unistd.h>
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <stdarg.h>
32 #include <sys/types.h>
33 #include <sys/stat.h>
34 #include <fcntl.h>
35 #include <sys/sysconf.h>
36 #include <strings.h>
37 #include <ctype.h>
38 #include <errno.h>
39 #include <sys/socket.h>
40 #include <netdb.h>
41 #include <netinet/in.h>
42 #include <arpa/inet.h>
43 #include <net/pfkeyv2.h>
44 #include <net/pfpolicy.h>
45 #include <libintl.h>
46 #include <setjmp.h>
47 #include <libgen.h>
48 #include <libscf.h>
49 
50 #include "ipsec_util.h"
51 #include "ikedoor.h"
52 
53 /*
54  * This file contains support functions that are shared by the ipsec
55  * utilities including ipseckey(1m) and ikeadm(1m).
56  */
57 
58 /* Set standard default/initial values for globals... */
59 boolean_t pflag = B_FALSE;	/* paranoid w.r.t. printing keying material */
60 boolean_t nflag = B_FALSE;	/* avoid nameservice? */
61 boolean_t interactive = B_FALSE;	/* util not running on cmdline */
62 boolean_t readfile = B_FALSE;	/* cmds are being read from a file */
63 uint_t	lineno = 0;		/* track location if reading cmds from file */
64 uint_t	lines_added = 0;
65 uint_t	lines_parsed = 0;
66 jmp_buf	env;		/* for error recovery in interactive/readfile modes */
67 char *my_fmri = NULL;
68 FILE *debugfile = stderr;
69 
70 /*
71  * Print errno and exit if cmdline or readfile, reset state if interactive
72  * The error string *what should be dgettext()'d before calling bail().
73  */
74 void
75 bail(char *what)
76 {
77 	if (errno != 0)
78 		warn(what);
79 	else
80 		warnx(dgettext(TEXT_DOMAIN, "Error: %s"), what);
81 	if (readfile) {
82 		return;
83 	}
84 	if (interactive && !readfile)
85 		longjmp(env, 2);
86 	EXIT_FATAL(NULL);
87 }
88 
89 /*
90  * Print caller-supplied variable-arg error msg, then exit if cmdline or
91  * readfile, or reset state if interactive.
92  */
93 /*PRINTFLIKE1*/
94 void
95 bail_msg(char *fmt, ...)
96 {
97 	va_list	ap;
98 	char	msgbuf[BUFSIZ];
99 
100 	va_start(ap, fmt);
101 	(void) vsnprintf(msgbuf, BUFSIZ, fmt, ap);
102 	va_end(ap);
103 	if (readfile)
104 		warnx(dgettext(TEXT_DOMAIN,
105 		    "ERROR on line %u:\n%s\n"), lineno,  msgbuf);
106 	else
107 		warnx(dgettext(TEXT_DOMAIN, "ERROR: %s\n"), msgbuf);
108 
109 	if (interactive && !readfile)
110 		longjmp(env, 1);
111 
112 	EXIT_FATAL(NULL);
113 }
114 
115 
116 /*
117  * dump_XXX functions produce ASCII output from various structures.
118  *
119  * Because certain errors need to do this to stderr, dump_XXX functions
120  * take a FILE pointer.
121  *
122  * If an error occured while writing to the specified file, these
123  * functions return -1, zero otherwise.
124  */
125 
126 int
127 dump_sockaddr(struct sockaddr *sa, uint8_t prefixlen, boolean_t addr_only,
128     FILE *where)
129 {
130 	struct sockaddr_in	*sin;
131 	struct sockaddr_in6	*sin6;
132 	char			*printable_addr, *protocol;
133 	uint8_t			*addrptr;
134 	/* Add 4 chars to hold '/nnn' for prefixes. */
135 	char			storage[INET6_ADDRSTRLEN + 4];
136 	uint16_t		port;
137 	boolean_t		unspec;
138 	struct hostent		*hp;
139 	int			getipnode_errno, addrlen;
140 
141 	switch (sa->sa_family) {
142 	case AF_INET:
143 		/* LINTED E_BAD_PTR_CAST_ALIGN */
144 		sin = (struct sockaddr_in *)sa;
145 		addrptr = (uint8_t *)&sin->sin_addr;
146 		port = sin->sin_port;
147 		protocol = "AF_INET";
148 		unspec = (sin->sin_addr.s_addr == 0);
149 		addrlen = sizeof (sin->sin_addr);
150 		break;
151 	case AF_INET6:
152 		/* LINTED E_BAD_PTR_CAST_ALIGN */
153 		sin6 = (struct sockaddr_in6 *)sa;
154 		addrptr = (uint8_t *)&sin6->sin6_addr;
155 		port = sin6->sin6_port;
156 		protocol = "AF_INET6";
157 		unspec = IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr);
158 		addrlen = sizeof (sin6->sin6_addr);
159 		break;
160 	default:
161 		return (0);
162 	}
163 
164 	if (inet_ntop(sa->sa_family, addrptr, storage, INET6_ADDRSTRLEN) ==
165 	    NULL) {
166 		printable_addr = dgettext(TEXT_DOMAIN, "Invalid IP address.");
167 	} else {
168 		char prefix[5];	/* "/nnn" with terminator. */
169 
170 		(void) snprintf(prefix, sizeof (prefix), "/%d", prefixlen);
171 		printable_addr = storage;
172 		if (prefixlen != 0) {
173 			(void) strlcat(printable_addr, prefix,
174 			    sizeof (storage));
175 		}
176 	}
177 	if (addr_only) {
178 		if (fprintf(where, "%s", printable_addr) < 0)
179 			return (-1);
180 	} else {
181 		if (fprintf(where, dgettext(TEXT_DOMAIN,
182 		    "%s: port %d, %s"), protocol,
183 		    ntohs(port), printable_addr) < 0)
184 			return (-1);
185 		if (!nflag) {
186 			/*
187 			 * Do AF_independent reverse hostname lookup here.
188 			 */
189 			if (unspec) {
190 				if (fprintf(where,
191 				    dgettext(TEXT_DOMAIN,
192 				    " <unspecified>")) < 0)
193 					return (-1);
194 			} else {
195 				hp = getipnodebyaddr((char *)addrptr, addrlen,
196 				    sa->sa_family, &getipnode_errno);
197 				if (hp != NULL) {
198 					if (fprintf(where,
199 					    " (%s)", hp->h_name) < 0)
200 						return (-1);
201 					freehostent(hp);
202 				} else {
203 					if (fprintf(where,
204 					    dgettext(TEXT_DOMAIN,
205 					    " <unknown>")) < 0)
206 						return (-1);
207 				}
208 			}
209 		}
210 		if (fputs(".\n", where) == EOF)
211 			return (-1);
212 	}
213 	return (0);
214 }
215 
216 /*
217  * Dump a key and bitlen
218  */
219 int
220 dump_key(uint8_t *keyp, uint_t bitlen, FILE *where)
221 {
222 	int	numbytes;
223 
224 	numbytes = SADB_1TO8(bitlen);
225 	/* The & 0x7 is to check for leftover bits. */
226 	if ((bitlen & 0x7) != 0)
227 		numbytes++;
228 	while (numbytes-- != 0) {
229 		if (pflag) {
230 			/* Print no keys if paranoid */
231 			if (fprintf(where, "XX") < 0)
232 				return (-1);
233 		} else {
234 			if (fprintf(where, "%02x", *keyp++) < 0)
235 				return (-1);
236 		}
237 	}
238 	if (fprintf(where, "/%u", bitlen) < 0)
239 		return (-1);
240 	return (0);
241 }
242 
243 /*
244  * Print an authentication or encryption algorithm
245  */
246 static int
247 dump_generic_alg(uint8_t alg_num, int proto_num, FILE *where)
248 {
249 	struct ipsecalgent *alg;
250 
251 	alg = getipsecalgbynum(alg_num, proto_num, NULL);
252 	if (alg == NULL) {
253 		if (fprintf(where, dgettext(TEXT_DOMAIN,
254 		    "<unknown %u>"), alg_num) < 0)
255 			return (-1);
256 		return (0);
257 	}
258 
259 	/*
260 	 * Special-case <none> for backward output compat.
261 	 * Assume that SADB_AALG_NONE == SADB_EALG_NONE.
262 	 */
263 	if (alg_num == SADB_AALG_NONE) {
264 		if (fputs(dgettext(TEXT_DOMAIN,
265 		    "<none>"), where) == EOF)
266 			return (-1);
267 	} else {
268 		if (fputs(alg->a_names[0], where) == EOF)
269 			return (-1);
270 	}
271 
272 	freeipsecalgent(alg);
273 	return (0);
274 }
275 
276 int
277 dump_aalg(uint8_t aalg, FILE *where)
278 {
279 	return (dump_generic_alg(aalg, IPSEC_PROTO_AH, where));
280 }
281 
282 int
283 dump_ealg(uint8_t ealg, FILE *where)
284 {
285 	return (dump_generic_alg(ealg, IPSEC_PROTO_ESP, where));
286 }
287 
288 /*
289  * Print an SADB_IDENTTYPE string
290  *
291  * Also return TRUE if the actual ident may be printed, FALSE if not.
292  *
293  * If rc is not NULL, set its value to -1 if an error occured while writing
294  * to the specified file, zero otherwise.
295  */
296 boolean_t
297 dump_sadb_idtype(uint8_t idtype, FILE *where, int *rc)
298 {
299 	boolean_t canprint = B_TRUE;
300 	int rc_val = 0;
301 
302 	switch (idtype) {
303 	case SADB_IDENTTYPE_PREFIX:
304 		if (fputs(dgettext(TEXT_DOMAIN, "prefix"), where) == EOF)
305 			rc_val = -1;
306 		break;
307 	case SADB_IDENTTYPE_FQDN:
308 		if (fputs(dgettext(TEXT_DOMAIN, "FQDN"), where) == EOF)
309 			rc_val = -1;
310 		break;
311 	case SADB_IDENTTYPE_USER_FQDN:
312 		if (fputs(dgettext(TEXT_DOMAIN,
313 		    "user-FQDN (mbox)"), where) == EOF)
314 			rc_val = -1;
315 		break;
316 	case SADB_X_IDENTTYPE_DN:
317 		if (fputs(dgettext(TEXT_DOMAIN, "ASN.1 DER Distinguished Name"),
318 		    where) == EOF)
319 			rc_val = -1;
320 		canprint = B_FALSE;
321 		break;
322 	case SADB_X_IDENTTYPE_GN:
323 		if (fputs(dgettext(TEXT_DOMAIN, "ASN.1 DER Generic Name"),
324 		    where) == EOF)
325 			rc_val = -1;
326 		canprint = B_FALSE;
327 		break;
328 	case SADB_X_IDENTTYPE_KEY_ID:
329 		if (fputs(dgettext(TEXT_DOMAIN, "Generic key id"),
330 		    where) == EOF)
331 			rc_val = -1;
332 		break;
333 	case SADB_X_IDENTTYPE_ADDR_RANGE:
334 		if (fputs(dgettext(TEXT_DOMAIN, "Address range"), where) == EOF)
335 			rc_val = -1;
336 		break;
337 	default:
338 		if (fprintf(where, dgettext(TEXT_DOMAIN,
339 		    "<unknown %u>"), idtype) < 0)
340 			rc_val = -1;
341 		break;
342 	}
343 
344 	if (rc != NULL)
345 		*rc = rc_val;
346 
347 	return (canprint);
348 }
349 
350 /*
351  * Slice an argv/argc vector from an interactive line or a read-file line.
352  */
353 static int
354 create_argv(char *ibuf, int *newargc, char ***thisargv)
355 {
356 	unsigned int argvlen = START_ARG;
357 	char **current;
358 	boolean_t firstchar = B_TRUE;
359 	boolean_t inquotes = B_FALSE;
360 
361 	*thisargv = malloc(sizeof (char *) * argvlen);
362 	if ((*thisargv) == NULL)
363 		return (MEMORY_ALLOCATION);
364 	current = *thisargv;
365 	*current = NULL;
366 
367 	for (; *ibuf != '\0'; ibuf++) {
368 		if (isspace(*ibuf)) {
369 			if (inquotes) {
370 				continue;
371 			}
372 			if (*current != NULL) {
373 				*ibuf = '\0';
374 				current++;
375 				if (*thisargv + argvlen == current) {
376 					/* Regrow ***thisargv. */
377 					if (argvlen == TOO_MANY_ARGS) {
378 						free(*thisargv);
379 						return (TOO_MANY_TOKENS);
380 					}
381 					/* Double the allocation. */
382 					current = realloc(*thisargv,
383 					    sizeof (char *) * (argvlen << 1));
384 					if (current == NULL) {
385 						free(*thisargv);
386 						return (MEMORY_ALLOCATION);
387 					}
388 					*thisargv = current;
389 					current += argvlen;
390 					argvlen <<= 1;	/* Double the size. */
391 				}
392 				*current = NULL;
393 			}
394 		} else {
395 			if (firstchar) {
396 				firstchar = B_FALSE;
397 				if (*ibuf == COMMENT_CHAR || *ibuf == '\n') {
398 					free(*thisargv);
399 					return (COMMENT_LINE);
400 				}
401 			}
402 			if (*ibuf == QUOTE_CHAR) {
403 				if (inquotes) {
404 					inquotes = B_FALSE;
405 					*ibuf = '\0';
406 				} else {
407 					inquotes = B_TRUE;
408 				}
409 				continue;
410 			}
411 			if (*current == NULL) {
412 				*current = ibuf;
413 				(*newargc)++;
414 			}
415 		}
416 	}
417 
418 	/*
419 	 * Tricky corner case...
420 	 * I've parsed _exactly_ the amount of args as I have space.  It
421 	 * won't return NULL-terminated, and bad things will happen to
422 	 * the caller.
423 	 */
424 	if (argvlen == *newargc) {
425 		current = realloc(*thisargv, sizeof (char *) * (argvlen + 1));
426 		if (current == NULL) {
427 			free(*thisargv);
428 			return (MEMORY_ALLOCATION);
429 		}
430 		*thisargv = current;
431 		current[argvlen] = NULL;
432 	}
433 
434 	return (SUCCESS);
435 }
436 
437 /*
438  * Enter a mode where commands are read from a file.  Treat stdin special.
439  */
440 void
441 do_interactive(FILE *infile, char *configfile, char *promptstring,
442     char *my_fmri, parse_cmdln_fn parseit)
443 {
444 	char		ibuf[IBUF_SIZE], holder[IBUF_SIZE];
445 	char		*hptr, **thisargv, *ebuf;
446 	int		thisargc;
447 	boolean_t	continue_in_progress = B_FALSE;
448 
449 	(void) setjmp(env);
450 
451 	ebuf = NULL;
452 	interactive = B_TRUE;
453 	bzero(ibuf, IBUF_SIZE);
454 
455 	if (infile == stdin) {
456 		(void) printf("%s", promptstring);
457 		(void) fflush(stdout);
458 	} else {
459 		readfile = B_TRUE;
460 	}
461 
462 	while (fgets(ibuf, IBUF_SIZE, infile) != NULL) {
463 		if (readfile)
464 			lineno++;
465 		thisargc = 0;
466 		thisargv = NULL;
467 
468 		/*
469 		 * Check byte IBUF_SIZE - 2, because byte IBUF_SIZE - 1 will
470 		 * be null-terminated because of fgets().
471 		 */
472 		if (ibuf[IBUF_SIZE - 2] != '\0') {
473 			ipsecutil_exit(SERVICE_FATAL, my_fmri, debugfile,
474 			    dgettext(TEXT_DOMAIN, "Line %d too big."), lineno);
475 		}
476 
477 		if (!continue_in_progress) {
478 			/* Use -2 because of \n from fgets. */
479 			if (ibuf[strlen(ibuf) - 2] == CONT_CHAR) {
480 				/*
481 				 * Can use strcpy here, I've checked the
482 				 * length already.
483 				 */
484 				(void) strcpy(holder, ibuf);
485 				hptr = &(holder[strlen(holder)]);
486 
487 				/* Remove the CONT_CHAR from the string. */
488 				hptr[-2] = ' ';
489 
490 				continue_in_progress = B_TRUE;
491 				bzero(ibuf, IBUF_SIZE);
492 				continue;
493 			}
494 		} else {
495 			/* Handle continuations... */
496 			(void) strncpy(hptr, ibuf,
497 			    (size_t)(&(holder[IBUF_SIZE]) - hptr));
498 			if (holder[IBUF_SIZE - 1] != '\0') {
499 				ipsecutil_exit(SERVICE_FATAL, my_fmri,
500 				    debugfile, dgettext(TEXT_DOMAIN,
501 				    "Command buffer overrun."));
502 			}
503 			/* Use - 2 because of \n from fgets. */
504 			if (hptr[strlen(hptr) - 2] == CONT_CHAR) {
505 				bzero(ibuf, IBUF_SIZE);
506 				hptr += strlen(hptr);
507 
508 				/* Remove the CONT_CHAR from the string. */
509 				hptr[-2] = ' ';
510 
511 				continue;
512 			} else {
513 				continue_in_progress = B_FALSE;
514 				/*
515 				 * I've already checked the length...
516 				 */
517 				(void) strcpy(ibuf, holder);
518 			}
519 		}
520 
521 		/*
522 		 * Just in case the command fails keep a copy of the
523 		 * command buffer for diagnostic output.
524 		 */
525 		if (readfile) {
526 			/*
527 			 * The error buffer needs to be big enough to
528 			 * hold the longest command string, plus
529 			 * some extra text, see below.
530 			 */
531 			ebuf = calloc((IBUF_SIZE * 2), sizeof (char));
532 			if (ebuf == NULL) {
533 				ipsecutil_exit(SERVICE_FATAL, my_fmri,
534 				    debugfile, dgettext(TEXT_DOMAIN,
535 				    "Memory allocation error."));
536 			} else {
537 				(void) snprintf(ebuf, (IBUF_SIZE * 2),
538 				    dgettext(TEXT_DOMAIN,
539 				    "Config file entry near line %u "
540 				    "caused error(s) or warnings:\n\n%s\n\n"),
541 				    lineno, ibuf);
542 			}
543 		}
544 
545 		switch (create_argv(ibuf, &thisargc, &thisargv)) {
546 		case TOO_MANY_TOKENS:
547 			ipsecutil_exit(SERVICE_BADCONF, my_fmri, debugfile,
548 			    dgettext(TEXT_DOMAIN, "Too many input tokens."));
549 			break;
550 		case MEMORY_ALLOCATION:
551 			ipsecutil_exit(SERVICE_BADCONF, my_fmri, debugfile,
552 			    dgettext(TEXT_DOMAIN, "Memory allocation error."));
553 			break;
554 		case COMMENT_LINE:
555 			/* Comment line. */
556 			free(ebuf);
557 			break;
558 		default:
559 			if (thisargc != 0) {
560 				lines_parsed++;
561 				/* ebuf consumed */
562 				parseit(thisargc, thisargv, ebuf, readfile);
563 			} else {
564 				free(ebuf);
565 			}
566 			free(thisargv);
567 			if (infile == stdin) {
568 				(void) printf("%s", promptstring);
569 				(void) fflush(stdout);
570 			}
571 			break;
572 		}
573 		bzero(ibuf, IBUF_SIZE);
574 	}
575 
576 	/*
577 	 * The following code is ipseckey specific. This should never be
578 	 * used by ikeadm which also calls this function because ikeadm
579 	 * only runs interactively. If this ever changes this code block
580 	 * sould be revisited.
581 	 */
582 	if (readfile) {
583 		if (lines_parsed != 0 && lines_added == 0) {
584 			ipsecutil_exit(SERVICE_BADCONF, my_fmri, debugfile,
585 			    dgettext(TEXT_DOMAIN, "Configuration file did not "
586 			    "contain any valid SAs"));
587 		}
588 
589 		/*
590 		 * There were errors. Putting the service in maintenance mode.
591 		 * When svc.startd(1M) allows services to degrade themselves,
592 		 * this should be revisited.
593 		 *
594 		 * If this function was called from a program running as a
595 		 * smf_method(5), print a warning message. Don't spew out the
596 		 * errors as these will end up in the smf(5) log file which is
597 		 * publically readable, the errors may contain sensitive
598 		 * information.
599 		 */
600 		if ((lines_added < lines_parsed) && (configfile != NULL)) {
601 			if (my_fmri != NULL) {
602 				ipsecutil_exit(SERVICE_BADCONF, my_fmri,
603 				    debugfile, dgettext(TEXT_DOMAIN,
604 				    "The configuration file contained %d "
605 				    "errors.\n"
606 				    "Manually check the configuration with:\n"
607 				    "ipseckey -c %s\n"
608 				    "Use svcadm(1M) to clear maintenance "
609 				    "condition when errors are resolved.\n"),
610 				    lines_parsed - lines_added, configfile);
611 			} else {
612 				EXIT_BADCONFIG(NULL);
613 			}
614 		} else {
615 			if (my_fmri != NULL)
616 				ipsecutil_exit(SERVICE_EXIT_OK, my_fmri,
617 				    debugfile, dgettext(TEXT_DOMAIN,
618 				    "%d actions successfully processed."),
619 				    lines_added);
620 		}
621 	} else {
622 		(void) putchar('\n');
623 		(void) fflush(stdout);
624 	}
625 	EXIT_OK(NULL);
626 }
627 
628 /*
629  * Functions to parse strings that represent a debug or privilege level.
630  * These functions are copied from main.c and door.c in usr.lib/in.iked/common.
631  * If this file evolves into a common library that may be used by in.iked
632  * as well as the usr.sbin utilities, those duplicate functions should be
633  * deleted.
634  *
635  * A privilege level may be represented by a simple keyword, corresponding
636  * to one of the possible levels.  A debug level may be represented by a
637  * series of keywords, separated by '+' or '-', indicating categories to
638  * be added or removed from the set of categories in the debug level.
639  * For example, +all-op corresponds to level 0xfffffffb (all flags except
640  * for D_OP set); while p1+p2+pfkey corresponds to level 0x38.  Note that
641  * the leading '+' is implicit; the first keyword in the list must be for
642  * a category that is to be added.
643  *
644  * These parsing functions make use of a local version of strtok, strtok_d,
645  * which includes an additional parameter, char *delim.  This param is filled
646  * in with the character which ends the returned token.  In other words,
647  * this version of strtok, in addition to returning the token, also returns
648  * the single character delimiter from the original string which marked the
649  * end of the token.
650  */
651 static char *
652 strtok_d(char *string, const char *sepset, char *delim)
653 {
654 	static char	*lasts;
655 	char		*q, *r;
656 
657 	/* first or subsequent call */
658 	if (string == NULL)
659 		string = lasts;
660 
661 	if (string == 0)		/* return if no tokens remaining */
662 		return (NULL);
663 
664 	q = string + strspn(string, sepset);	/* skip leading separators */
665 
666 	if (*q == '\0')			/* return if no tokens remaining */
667 		return (NULL);
668 
669 	if ((r = strpbrk(q, sepset)) == NULL) {		/* move past token */
670 		lasts = 0;	/* indicate that this is last token */
671 	} else {
672 		*delim = *r;	/* save delimitor */
673 		*r = '\0';
674 		lasts = r + 1;
675 	}
676 	return (q);
677 }
678 
679 static keywdtab_t	privtab[] = {
680 	{ IKE_PRIV_MINIMUM,	"base" },
681 	{ IKE_PRIV_MODKEYS,	"modkeys" },
682 	{ IKE_PRIV_KEYMAT,	"keymat" },
683 	{ IKE_PRIV_MINIMUM,	"0" },
684 };
685 
686 int
687 privstr2num(char *str)
688 {
689 	keywdtab_t	*pp;
690 	char		*endp;
691 	int		 priv;
692 
693 	for (pp = privtab; pp < A_END(privtab); pp++) {
694 		if (strcasecmp(str, pp->kw_str) == 0)
695 			return (pp->kw_tag);
696 	}
697 
698 	priv = strtol(str, &endp, 0);
699 	if (*endp == '\0')
700 		return (priv);
701 
702 	return (-1);
703 }
704 
705 static keywdtab_t	dbgtab[] = {
706 	{ D_CERT,	"cert" },
707 	{ D_KEY,	"key" },
708 	{ D_OP,		"op" },
709 	{ D_P1,		"p1" },
710 	{ D_P1,		"phase1" },
711 	{ D_P2,		"p2" },
712 	{ D_P2,		"phase2" },
713 	{ D_PFKEY,	"pfkey" },
714 	{ D_POL,	"pol" },
715 	{ D_POL,	"policy" },
716 	{ D_PROP,	"prop" },
717 	{ D_DOOR,	"door" },
718 	{ D_CONFIG,	"config" },
719 	{ D_ALL,	"all" },
720 	{ 0,		"0" },
721 };
722 
723 int
724 dbgstr2num(char *str)
725 {
726 	keywdtab_t	*dp;
727 
728 	for (dp = dbgtab; dp < A_END(dbgtab); dp++) {
729 		if (strcasecmp(str, dp->kw_str) == 0)
730 			return (dp->kw_tag);
731 	}
732 	return (D_INVALID);
733 }
734 
735 int
736 parsedbgopts(char *optarg)
737 {
738 	char	*argp, *endp, op, nextop;
739 	int	mask = 0, new;
740 
741 	mask = strtol(optarg, &endp, 0);
742 	if (*endp == '\0')
743 		return (mask);
744 
745 	op = optarg[0];
746 	if (op != '-')
747 		op = '+';
748 	argp = strtok_d(optarg, "+-", &nextop);
749 	do {
750 		new = dbgstr2num(argp);
751 		if (new == D_INVALID) {
752 			/* we encountered an invalid keywd */
753 			return (new);
754 		}
755 		if (op == '+') {
756 			mask |= new;
757 		} else {
758 			mask &= ~new;
759 		}
760 		op = nextop;
761 	} while ((argp = strtok_d(NULL, "+-", &nextop)) != NULL);
762 
763 	return (mask);
764 }
765 
766 
767 /*
768  * functions to manipulate the kmcookie-label mapping file
769  */
770 
771 /*
772  * Open, lockf, fdopen the given file, returning a FILE * on success,
773  * or NULL on failure.
774  */
775 FILE *
776 kmc_open_and_lock(char *name)
777 {
778 	int	fd, rtnerr;
779 	FILE	*fp;
780 
781 	if ((fd = open(name, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR)) < 0) {
782 		return (NULL);
783 	}
784 	if (lockf(fd, F_LOCK, 0) < 0) {
785 		return (NULL);
786 	}
787 	if ((fp = fdopen(fd, "a+")) == NULL) {
788 		return (NULL);
789 	}
790 	if (fseek(fp, 0, SEEK_SET) < 0) {
791 		/* save errno in case fclose changes it */
792 		rtnerr = errno;
793 		(void) fclose(fp);
794 		errno = rtnerr;
795 		return (NULL);
796 	}
797 	return (fp);
798 }
799 
800 /*
801  * Extract an integer cookie and string label from a line from the
802  * kmcookie-label file.  Return -1 on failure, 0 on success.
803  */
804 int
805 kmc_parse_line(char *line, int *cookie, char **label)
806 {
807 	char	*cookiestr;
808 
809 	*cookie = 0;
810 	*label = NULL;
811 
812 	cookiestr = strtok(line, " \t\n");
813 	if (cookiestr == NULL) {
814 		return (-1);
815 	}
816 
817 	/* Everything that follows, up to the newline, is the label. */
818 	*label = strtok(NULL, "\n");
819 	if (*label == NULL) {
820 		return (-1);
821 	}
822 
823 	*cookie = atoi(cookiestr);
824 	return (0);
825 }
826 
827 /*
828  * Insert a mapping into the file (if it's not already there), given the
829  * new label.  Return the assigned cookie, or -1 on error.
830  */
831 int
832 kmc_insert_mapping(char *label)
833 {
834 	FILE	*map;
835 	char	linebuf[MAXLINESIZE];
836 	char	*cur_label;
837 	int	max_cookie = 0, cur_cookie, rtn_cookie;
838 	int	rtnerr = 0;
839 	boolean_t	found = B_FALSE;
840 
841 	/* open and lock the file; will sleep until lock is available */
842 	if ((map = kmc_open_and_lock(KMCFILE)) == NULL) {
843 		/* kmc_open_and_lock() sets errno appropriately */
844 		return (-1);
845 	}
846 
847 	while (fgets(linebuf, sizeof (linebuf), map) != NULL) {
848 
849 		if (kmc_parse_line(linebuf, &cur_cookie, &cur_label) < 0) {
850 			rtnerr = EINVAL;
851 			goto error;
852 		}
853 
854 		if (cur_cookie > max_cookie)
855 			max_cookie = cur_cookie;
856 
857 		if ((!found) && (strcmp(cur_label, label) == 0)) {
858 			found = B_TRUE;
859 			rtn_cookie = cur_cookie;
860 		}
861 	}
862 
863 	if (!found) {
864 		rtn_cookie = ++max_cookie;
865 		if ((fprintf(map, "%u\t%s\n", rtn_cookie, label) < 0) ||
866 		    (fflush(map) < 0)) {
867 			rtnerr = errno;
868 			goto error;
869 		}
870 	}
871 	(void) fclose(map);
872 
873 	return (rtn_cookie);
874 
875 error:
876 	(void) fclose(map);
877 	errno = rtnerr;
878 	return (-1);
879 }
880 
881 /*
882  * Lookup the given cookie and return its corresponding label.  Return
883  * a pointer to the label on success, NULL on error (or if the label is
884  * not found).  Note that the returned label pointer points to a static
885  * string, so the label will be overwritten by a subsequent call to the
886  * function; the function is also not thread-safe as a result.
887  */
888 char *
889 kmc_lookup_by_cookie(int cookie)
890 {
891 	FILE		*map;
892 	static char	linebuf[MAXLINESIZE];
893 	char		*cur_label;
894 	int		cur_cookie;
895 
896 	if ((map = kmc_open_and_lock(KMCFILE)) == NULL) {
897 		return (NULL);
898 	}
899 
900 	while (fgets(linebuf, sizeof (linebuf), map) != NULL) {
901 
902 		if (kmc_parse_line(linebuf, &cur_cookie, &cur_label) < 0) {
903 			(void) fclose(map);
904 			return (NULL);
905 		}
906 
907 		if (cookie == cur_cookie) {
908 			(void) fclose(map);
909 			return (cur_label);
910 		}
911 	}
912 	(void) fclose(map);
913 
914 	return (NULL);
915 }
916 
917 /*
918  * Parse basic extension headers and return in the passed-in pointer vector.
919  * Return values include:
920  *
921  *	KGE_OK	Everything's nice and parsed out.
922  *		If there are no extensions, place NULL in extv[0].
923  *	KGE_DUP	There is a duplicate extension.
924  *		First instance in appropriate bin.  First duplicate in
925  *		extv[0].
926  *	KGE_UNK	Unknown extension type encountered.  extv[0] contains
927  *		unknown header.
928  *	KGE_LEN	Extension length error.
929  *	KGE_CHK	High-level reality check failed on specific extension.
930  *
931  * My apologies for some of the pointer arithmetic in here.  I'm thinking
932  * like an assembly programmer, yet trying to make the compiler happy.
933  */
934 int
935 spdsock_get_ext(spd_ext_t *extv[], spd_msg_t *basehdr, uint_t msgsize,
936     char *diag_buf, uint_t diag_buf_len)
937 {
938 	int i;
939 
940 	if (diag_buf != NULL)
941 		diag_buf[0] = '\0';
942 
943 	for (i = 1; i <= SPD_EXT_MAX; i++)
944 		extv[i] = NULL;
945 
946 	i = 0;
947 	/* Use extv[0] as the "current working pointer". */
948 
949 	extv[0] = (spd_ext_t *)(basehdr + 1);
950 	msgsize = SPD_64TO8(msgsize);
951 
952 	while ((char *)extv[0] < ((char *)basehdr + msgsize)) {
953 		/* Check for unknown headers. */
954 		i++;
955 
956 		if (extv[0]->spd_ext_type == 0 ||
957 		    extv[0]->spd_ext_type > SPD_EXT_MAX) {
958 			if (diag_buf != NULL) {
959 				(void) snprintf(diag_buf, diag_buf_len,
960 				    "spdsock ext 0x%X unknown: 0x%X",
961 				    i, extv[0]->spd_ext_type);
962 			}
963 			return (KGE_UNK);
964 		}
965 
966 		/*
967 		 * Check length.  Use uint64_t because extlen is in units
968 		 * of 64-bit words.  If length goes beyond the msgsize,
969 		 * return an error.  (Zero length also qualifies here.)
970 		 */
971 		if (extv[0]->spd_ext_len == 0 ||
972 		    (uint8_t *)((uint64_t *)extv[0] + extv[0]->spd_ext_len) >
973 		    (uint8_t *)((uint8_t *)basehdr + msgsize))
974 			return (KGE_LEN);
975 
976 		/* Check for redundant headers. */
977 		if (extv[extv[0]->spd_ext_type] != NULL)
978 			return (KGE_DUP);
979 
980 		/* If I make it here, assign the appropriate bin. */
981 		extv[extv[0]->spd_ext_type] = extv[0];
982 
983 		/* Advance pointer (See above for uint64_t ptr reasoning.) */
984 		extv[0] = (spd_ext_t *)
985 		    ((uint64_t *)extv[0] + extv[0]->spd_ext_len);
986 	}
987 
988 	/* Everything's cool. */
989 
990 	/*
991 	 * If extv[0] == NULL, then there are no extension headers in this
992 	 * message.  Ensure that this is the case.
993 	 */
994 	if (extv[0] == (spd_ext_t *)(basehdr + 1))
995 		extv[0] = NULL;
996 
997 	return (KGE_OK);
998 }
999 
1000 const char *
1001 spdsock_diag(int diagnostic)
1002 {
1003 	switch (diagnostic) {
1004 	case SPD_DIAGNOSTIC_NONE:
1005 		return (dgettext(TEXT_DOMAIN, "no error"));
1006 	case SPD_DIAGNOSTIC_UNKNOWN_EXT:
1007 		return (dgettext(TEXT_DOMAIN, "unknown extension"));
1008 	case SPD_DIAGNOSTIC_BAD_EXTLEN:
1009 		return (dgettext(TEXT_DOMAIN, "bad extension length"));
1010 	case SPD_DIAGNOSTIC_NO_RULE_EXT:
1011 		return (dgettext(TEXT_DOMAIN, "no rule extension"));
1012 	case SPD_DIAGNOSTIC_BAD_ADDR_LEN:
1013 		return (dgettext(TEXT_DOMAIN, "bad address len"));
1014 	case SPD_DIAGNOSTIC_MIXED_AF:
1015 		return (dgettext(TEXT_DOMAIN, "mixed address family"));
1016 	case SPD_DIAGNOSTIC_ADD_NO_MEM:
1017 		return (dgettext(TEXT_DOMAIN, "add: no memory"));
1018 	case SPD_DIAGNOSTIC_ADD_WRONG_ACT_COUNT:
1019 		return (dgettext(TEXT_DOMAIN, "add: wrong action count"));
1020 	case SPD_DIAGNOSTIC_ADD_BAD_TYPE:
1021 		return (dgettext(TEXT_DOMAIN, "add: bad type"));
1022 	case SPD_DIAGNOSTIC_ADD_BAD_FLAGS:
1023 		return (dgettext(TEXT_DOMAIN, "add: bad flags"));
1024 	case SPD_DIAGNOSTIC_ADD_INCON_FLAGS:
1025 		return (dgettext(TEXT_DOMAIN, "add: inconsistent flags"));
1026 	case SPD_DIAGNOSTIC_MALFORMED_LCLPORT:
1027 		return (dgettext(TEXT_DOMAIN, "malformed local port"));
1028 	case SPD_DIAGNOSTIC_DUPLICATE_LCLPORT:
1029 		return (dgettext(TEXT_DOMAIN, "duplicate local port"));
1030 	case SPD_DIAGNOSTIC_MALFORMED_REMPORT:
1031 		return (dgettext(TEXT_DOMAIN, "malformed remote port"));
1032 	case SPD_DIAGNOSTIC_DUPLICATE_REMPORT:
1033 		return (dgettext(TEXT_DOMAIN, "duplicate remote port"));
1034 	case SPD_DIAGNOSTIC_MALFORMED_PROTO:
1035 		return (dgettext(TEXT_DOMAIN, "malformed proto"));
1036 	case SPD_DIAGNOSTIC_DUPLICATE_PROTO:
1037 		return (dgettext(TEXT_DOMAIN, "duplicate proto"));
1038 	case SPD_DIAGNOSTIC_MALFORMED_LCLADDR:
1039 		return (dgettext(TEXT_DOMAIN, "malformed local address"));
1040 	case SPD_DIAGNOSTIC_DUPLICATE_LCLADDR:
1041 		return (dgettext(TEXT_DOMAIN, "duplicate local address"));
1042 	case SPD_DIAGNOSTIC_MALFORMED_REMADDR:
1043 		return (dgettext(TEXT_DOMAIN, "malformed remote address"));
1044 	case SPD_DIAGNOSTIC_DUPLICATE_REMADDR:
1045 		return (dgettext(TEXT_DOMAIN, "duplicate remote address"));
1046 	case SPD_DIAGNOSTIC_MALFORMED_ACTION:
1047 		return (dgettext(TEXT_DOMAIN, "malformed action"));
1048 	case SPD_DIAGNOSTIC_DUPLICATE_ACTION:
1049 		return (dgettext(TEXT_DOMAIN, "duplicate action"));
1050 	case SPD_DIAGNOSTIC_MALFORMED_RULE:
1051 		return (dgettext(TEXT_DOMAIN, "malformed rule"));
1052 	case SPD_DIAGNOSTIC_DUPLICATE_RULE:
1053 		return (dgettext(TEXT_DOMAIN, "duplicate rule"));
1054 	case SPD_DIAGNOSTIC_MALFORMED_RULESET:
1055 		return (dgettext(TEXT_DOMAIN, "malformed ruleset"));
1056 	case SPD_DIAGNOSTIC_DUPLICATE_RULESET:
1057 		return (dgettext(TEXT_DOMAIN, "duplicate ruleset"));
1058 	case SPD_DIAGNOSTIC_INVALID_RULE_INDEX:
1059 		return (dgettext(TEXT_DOMAIN, "invalid rule index"));
1060 	case SPD_DIAGNOSTIC_BAD_SPDID:
1061 		return (dgettext(TEXT_DOMAIN, "bad spdid"));
1062 	case SPD_DIAGNOSTIC_BAD_MSG_TYPE:
1063 		return (dgettext(TEXT_DOMAIN, "bad message type"));
1064 	case SPD_DIAGNOSTIC_UNSUPP_AH_ALG:
1065 		return (dgettext(TEXT_DOMAIN, "unsupported AH algorithm"));
1066 	case SPD_DIAGNOSTIC_UNSUPP_ESP_ENCR_ALG:
1067 		return (dgettext(TEXT_DOMAIN,
1068 		    "unsupported ESP encryption algorithm"));
1069 	case SPD_DIAGNOSTIC_UNSUPP_ESP_AUTH_ALG:
1070 		return (dgettext(TEXT_DOMAIN,
1071 		    "unsupported ESP authentication algorithm"));
1072 	case SPD_DIAGNOSTIC_UNSUPP_AH_KEYSIZE:
1073 		return (dgettext(TEXT_DOMAIN, "unsupported AH key size"));
1074 	case SPD_DIAGNOSTIC_UNSUPP_ESP_ENCR_KEYSIZE:
1075 		return (dgettext(TEXT_DOMAIN,
1076 		    "unsupported ESP encryption key size"));
1077 	case SPD_DIAGNOSTIC_UNSUPP_ESP_AUTH_KEYSIZE:
1078 		return (dgettext(TEXT_DOMAIN,
1079 		    "unsupported ESP authentication key size"));
1080 	case SPD_DIAGNOSTIC_NO_ACTION_EXT:
1081 		return (dgettext(TEXT_DOMAIN, "No ACTION extension"));
1082 	case SPD_DIAGNOSTIC_ALG_ID_RANGE:
1083 		return (dgettext(TEXT_DOMAIN, "invalid algorithm identifer"));
1084 	case SPD_DIAGNOSTIC_ALG_NUM_KEY_SIZES:
1085 		return (dgettext(TEXT_DOMAIN,
1086 		    "number of key sizes inconsistent"));
1087 	case SPD_DIAGNOSTIC_ALG_NUM_BLOCK_SIZES:
1088 		return (dgettext(TEXT_DOMAIN,
1089 		    "number of block sizes inconsistent"));
1090 	case SPD_DIAGNOSTIC_ALG_MECH_NAME_LEN:
1091 		return (dgettext(TEXT_DOMAIN, "invalid mechanism name length"));
1092 	case SPD_DIAGNOSTIC_NOT_GLOBAL_OP:
1093 		return (dgettext(TEXT_DOMAIN,
1094 		    "operation not applicable to all policies"));
1095 	case SPD_DIAGNOSTIC_NO_TUNNEL_SELECTORS:
1096 		return (dgettext(TEXT_DOMAIN,
1097 		    "using selectors on a transport-mode tunnel"));
1098 	default:
1099 		return (dgettext(TEXT_DOMAIN, "unknown diagnostic"));
1100 	}
1101 }
1102 
1103 /*
1104  * PF_KEY Diagnostic table.
1105  *
1106  * PF_KEY NOTE:  If you change pfkeyv2.h's SADB_X_DIAGNOSTIC_* space, this is
1107  * where you need to add new messages.
1108  */
1109 
1110 const char *
1111 keysock_diag(int diagnostic)
1112 {
1113 	switch (diagnostic) {
1114 	case SADB_X_DIAGNOSTIC_NONE:
1115 		return (dgettext(TEXT_DOMAIN, "No diagnostic"));
1116 	case SADB_X_DIAGNOSTIC_UNKNOWN_MSG:
1117 		return (dgettext(TEXT_DOMAIN, "Unknown message type"));
1118 	case SADB_X_DIAGNOSTIC_UNKNOWN_EXT:
1119 		return (dgettext(TEXT_DOMAIN, "Unknown extension type"));
1120 	case SADB_X_DIAGNOSTIC_BAD_EXTLEN:
1121 		return (dgettext(TEXT_DOMAIN, "Bad extension length"));
1122 	case SADB_X_DIAGNOSTIC_UNKNOWN_SATYPE:
1123 		return (dgettext(TEXT_DOMAIN,
1124 		    "Unknown Security Association type"));
1125 	case SADB_X_DIAGNOSTIC_SATYPE_NEEDED:
1126 		return (dgettext(TEXT_DOMAIN,
1127 		    "Specific Security Association type needed"));
1128 	case SADB_X_DIAGNOSTIC_NO_SADBS:
1129 		return (dgettext(TEXT_DOMAIN,
1130 		    "No Security Association Databases present"));
1131 	case SADB_X_DIAGNOSTIC_NO_EXT:
1132 		return (dgettext(TEXT_DOMAIN,
1133 		    "No extensions needed for message"));
1134 	case SADB_X_DIAGNOSTIC_BAD_SRC_AF:
1135 		return (dgettext(TEXT_DOMAIN, "Bad source address family"));
1136 	case SADB_X_DIAGNOSTIC_BAD_DST_AF:
1137 		return (dgettext(TEXT_DOMAIN,
1138 		    "Bad destination address family"));
1139 	case SADB_X_DIAGNOSTIC_BAD_PROXY_AF:
1140 		return (dgettext(TEXT_DOMAIN,
1141 		    "Bad inner-source address family"));
1142 	case SADB_X_DIAGNOSTIC_AF_MISMATCH:
1143 		return (dgettext(TEXT_DOMAIN,
1144 		    "Source/destination address family mismatch"));
1145 	case SADB_X_DIAGNOSTIC_BAD_SRC:
1146 		return (dgettext(TEXT_DOMAIN, "Bad source address value"));
1147 	case SADB_X_DIAGNOSTIC_BAD_DST:
1148 		return (dgettext(TEXT_DOMAIN, "Bad destination address value"));
1149 	case SADB_X_DIAGNOSTIC_ALLOC_HSERR:
1150 		return (dgettext(TEXT_DOMAIN,
1151 		    "Soft allocations limit more than hard limit"));
1152 	case SADB_X_DIAGNOSTIC_BYTES_HSERR:
1153 		return (dgettext(TEXT_DOMAIN,
1154 		    "Soft bytes limit more than hard limit"));
1155 	case SADB_X_DIAGNOSTIC_ADDTIME_HSERR:
1156 		return (dgettext(TEXT_DOMAIN, "Soft add expiration time later "
1157 		    "than hard expiration time"));
1158 	case SADB_X_DIAGNOSTIC_USETIME_HSERR:
1159 		return (dgettext(TEXT_DOMAIN, "Soft use expiration time later "
1160 		    "than hard expiration time"));
1161 	case SADB_X_DIAGNOSTIC_MISSING_SRC:
1162 		return (dgettext(TEXT_DOMAIN, "Missing source address"));
1163 	case SADB_X_DIAGNOSTIC_MISSING_DST:
1164 		return (dgettext(TEXT_DOMAIN, "Missing destination address"));
1165 	case SADB_X_DIAGNOSTIC_MISSING_SA:
1166 		return (dgettext(TEXT_DOMAIN, "Missing SA extension"));
1167 	case SADB_X_DIAGNOSTIC_MISSING_EKEY:
1168 		return (dgettext(TEXT_DOMAIN, "Missing encryption key"));
1169 	case SADB_X_DIAGNOSTIC_MISSING_AKEY:
1170 		return (dgettext(TEXT_DOMAIN, "Missing authentication key"));
1171 	case SADB_X_DIAGNOSTIC_MISSING_RANGE:
1172 		return (dgettext(TEXT_DOMAIN, "Missing SPI range"));
1173 	case SADB_X_DIAGNOSTIC_DUPLICATE_SRC:
1174 		return (dgettext(TEXT_DOMAIN, "Duplicate source address"));
1175 	case SADB_X_DIAGNOSTIC_DUPLICATE_DST:
1176 		return (dgettext(TEXT_DOMAIN, "Duplicate destination address"));
1177 	case SADB_X_DIAGNOSTIC_DUPLICATE_SA:
1178 		return (dgettext(TEXT_DOMAIN, "Duplicate SA extension"));
1179 	case SADB_X_DIAGNOSTIC_DUPLICATE_EKEY:
1180 		return (dgettext(TEXT_DOMAIN, "Duplicate encryption key"));
1181 	case SADB_X_DIAGNOSTIC_DUPLICATE_AKEY:
1182 		return (dgettext(TEXT_DOMAIN, "Duplicate authentication key"));
1183 	case SADB_X_DIAGNOSTIC_DUPLICATE_RANGE:
1184 		return (dgettext(TEXT_DOMAIN, "Duplicate SPI range"));
1185 	case SADB_X_DIAGNOSTIC_MALFORMED_SRC:
1186 		return (dgettext(TEXT_DOMAIN, "Malformed source address"));
1187 	case SADB_X_DIAGNOSTIC_MALFORMED_DST:
1188 		return (dgettext(TEXT_DOMAIN, "Malformed destination address"));
1189 	case SADB_X_DIAGNOSTIC_MALFORMED_SA:
1190 		return (dgettext(TEXT_DOMAIN, "Malformed SA extension"));
1191 	case SADB_X_DIAGNOSTIC_MALFORMED_EKEY:
1192 		return (dgettext(TEXT_DOMAIN, "Malformed encryption key"));
1193 	case SADB_X_DIAGNOSTIC_MALFORMED_AKEY:
1194 		return (dgettext(TEXT_DOMAIN, "Malformed authentication key"));
1195 	case SADB_X_DIAGNOSTIC_MALFORMED_RANGE:
1196 		return (dgettext(TEXT_DOMAIN, "Malformed SPI range"));
1197 	case SADB_X_DIAGNOSTIC_AKEY_PRESENT:
1198 		return (dgettext(TEXT_DOMAIN, "Authentication key not needed"));
1199 	case SADB_X_DIAGNOSTIC_EKEY_PRESENT:
1200 		return (dgettext(TEXT_DOMAIN, "Encryption key not needed"));
1201 	case SADB_X_DIAGNOSTIC_PROP_PRESENT:
1202 		return (dgettext(TEXT_DOMAIN, "Proposal extension not needed"));
1203 	case SADB_X_DIAGNOSTIC_SUPP_PRESENT:
1204 		return (dgettext(TEXT_DOMAIN,
1205 		    "Supported algorithms extension not needed"));
1206 	case SADB_X_DIAGNOSTIC_BAD_AALG:
1207 		return (dgettext(TEXT_DOMAIN,
1208 		    "Unsupported authentication algorithm"));
1209 	case SADB_X_DIAGNOSTIC_BAD_EALG:
1210 		return (dgettext(TEXT_DOMAIN,
1211 		    "Unsupported encryption algorithm"));
1212 	case SADB_X_DIAGNOSTIC_BAD_SAFLAGS:
1213 		return (dgettext(TEXT_DOMAIN, "Invalid SA flags"));
1214 	case SADB_X_DIAGNOSTIC_BAD_SASTATE:
1215 		return (dgettext(TEXT_DOMAIN, "Invalid SA state"));
1216 	case SADB_X_DIAGNOSTIC_BAD_AKEYBITS:
1217 		return (dgettext(TEXT_DOMAIN,
1218 		    "Bad number of authentication bits"));
1219 	case SADB_X_DIAGNOSTIC_BAD_EKEYBITS:
1220 		return (dgettext(TEXT_DOMAIN,
1221 		    "Bad number of encryption bits"));
1222 	case SADB_X_DIAGNOSTIC_ENCR_NOTSUPP:
1223 		return (dgettext(TEXT_DOMAIN,
1224 		    "Encryption not supported for this SA type"));
1225 	case SADB_X_DIAGNOSTIC_WEAK_EKEY:
1226 		return (dgettext(TEXT_DOMAIN, "Weak encryption key"));
1227 	case SADB_X_DIAGNOSTIC_WEAK_AKEY:
1228 		return (dgettext(TEXT_DOMAIN, "Weak authentication key"));
1229 	case SADB_X_DIAGNOSTIC_DUPLICATE_KMP:
1230 		return (dgettext(TEXT_DOMAIN,
1231 		    "Duplicate key management protocol"));
1232 	case SADB_X_DIAGNOSTIC_DUPLICATE_KMC:
1233 		return (dgettext(TEXT_DOMAIN,
1234 		    "Duplicate key management cookie"));
1235 	case SADB_X_DIAGNOSTIC_MISSING_NATT_LOC:
1236 		return (dgettext(TEXT_DOMAIN, "Missing NAT-T local address"));
1237 	case SADB_X_DIAGNOSTIC_MISSING_NATT_REM:
1238 		return (dgettext(TEXT_DOMAIN, "Missing NAT-T remote address"));
1239 	case SADB_X_DIAGNOSTIC_DUPLICATE_NATT_LOC:
1240 		return (dgettext(TEXT_DOMAIN, "Duplicate NAT-T local address"));
1241 	case SADB_X_DIAGNOSTIC_DUPLICATE_NATT_REM:
1242 		return (dgettext(TEXT_DOMAIN,
1243 		    "Duplicate NAT-T remote address"));
1244 	case SADB_X_DIAGNOSTIC_MALFORMED_NATT_LOC:
1245 		return (dgettext(TEXT_DOMAIN, "Malformed NAT-T local address"));
1246 	case SADB_X_DIAGNOSTIC_MALFORMED_NATT_REM:
1247 		return (dgettext(TEXT_DOMAIN,
1248 		    "Malformed NAT-T remote address"));
1249 	case SADB_X_DIAGNOSTIC_DUPLICATE_NATT_PORTS:
1250 		return (dgettext(TEXT_DOMAIN, "Duplicate NAT-T ports"));
1251 	case SADB_X_DIAGNOSTIC_MISSING_INNER_SRC:
1252 		return (dgettext(TEXT_DOMAIN, "Missing inner source address"));
1253 	case SADB_X_DIAGNOSTIC_MISSING_INNER_DST:
1254 		return (dgettext(TEXT_DOMAIN,
1255 		    "Missing inner destination address"));
1256 	case SADB_X_DIAGNOSTIC_DUPLICATE_INNER_SRC:
1257 		return (dgettext(TEXT_DOMAIN,
1258 		    "Duplicate inner source address"));
1259 	case SADB_X_DIAGNOSTIC_DUPLICATE_INNER_DST:
1260 		return (dgettext(TEXT_DOMAIN,
1261 		    "Duplicate inner destination address"));
1262 	case SADB_X_DIAGNOSTIC_MALFORMED_INNER_SRC:
1263 		return (dgettext(TEXT_DOMAIN,
1264 		    "Malformed inner source address"));
1265 	case SADB_X_DIAGNOSTIC_MALFORMED_INNER_DST:
1266 		return (dgettext(TEXT_DOMAIN,
1267 		    "Malformed inner destination address"));
1268 	case SADB_X_DIAGNOSTIC_PREFIX_INNER_SRC:
1269 		return (dgettext(TEXT_DOMAIN,
1270 		    "Invalid inner-source prefix length "));
1271 	case SADB_X_DIAGNOSTIC_PREFIX_INNER_DST:
1272 		return (dgettext(TEXT_DOMAIN,
1273 		    "Invalid inner-destination prefix length"));
1274 	case SADB_X_DIAGNOSTIC_BAD_INNER_DST_AF:
1275 		return (dgettext(TEXT_DOMAIN,
1276 		    "Bad inner-destination address family"));
1277 	case SADB_X_DIAGNOSTIC_INNER_AF_MISMATCH:
1278 		return (dgettext(TEXT_DOMAIN,
1279 		    "Inner source/destination address family mismatch"));
1280 	case SADB_X_DIAGNOSTIC_BAD_NATT_REM_AF:
1281 		return (dgettext(TEXT_DOMAIN,
1282 		    "Bad NAT-T remote address family"));
1283 	case SADB_X_DIAGNOSTIC_BAD_NATT_LOC_AF:
1284 		return (dgettext(TEXT_DOMAIN,
1285 		    "Bad NAT-T local address family"));
1286 	case SADB_X_DIAGNOSTIC_PROTO_MISMATCH:
1287 		return (dgettext(TEXT_DOMAIN,
1288 		    "Source/desination protocol mismatch"));
1289 	case SADB_X_DIAGNOSTIC_INNER_PROTO_MISMATCH:
1290 		return (dgettext(TEXT_DOMAIN,
1291 		    "Inner source/desination protocol mismatch"));
1292 	case SADB_X_DIAGNOSTIC_DUAL_PORT_SETS:
1293 		return (dgettext(TEXT_DOMAIN,
1294 		    "Both inner ports and outer ports are set"));
1295 	default:
1296 		return (dgettext(TEXT_DOMAIN, "Unknown diagnostic code"));
1297 	}
1298 }
1299 
1300 /*
1301  * Convert an IPv6 mask to a prefix len.  I assume all IPv6 masks are
1302  * contiguous, so I stop at the first zero bit!
1303  */
1304 int
1305 in_masktoprefix(uint8_t *mask, boolean_t is_v4mapped)
1306 {
1307 	int rc = 0;
1308 	uint8_t last;
1309 	int limit = IPV6_ABITS;
1310 
1311 	if (is_v4mapped) {
1312 		mask += ((IPV6_ABITS - IP_ABITS)/8);
1313 		limit = IP_ABITS;
1314 	}
1315 
1316 	while (*mask == 0xff) {
1317 		rc += 8;
1318 		if (rc == limit)
1319 			return (limit);
1320 		mask++;
1321 	}
1322 
1323 	last = *mask;
1324 	while (last != 0) {
1325 		rc++;
1326 		last = (last << 1) & 0xff;
1327 	}
1328 
1329 	return (rc);
1330 }
1331 
1332 /*
1333  * Expand the diagnostic code into a message.
1334  */
1335 void
1336 print_diagnostic(FILE *file, uint16_t diagnostic)
1337 {
1338 	/* Use two spaces so above strings can fit on the line. */
1339 	(void) fprintf(file, dgettext(TEXT_DOMAIN,
1340 	    "  Diagnostic code %u:  %s.\n"),
1341 	    diagnostic, keysock_diag(diagnostic));
1342 }
1343 
1344 /*
1345  * Prints the base PF_KEY message.
1346  */
1347 void
1348 print_sadb_msg(struct sadb_msg *samsg, time_t wallclock, boolean_t vflag)
1349 {
1350 	if (wallclock != 0)
1351 		printsatime(wallclock, dgettext(TEXT_DOMAIN,
1352 		    "%sTimestamp: %s\n"), "", NULL,
1353 		    vflag);
1354 
1355 	(void) printf(dgettext(TEXT_DOMAIN, "Base message (version %u) type "),
1356 	    samsg->sadb_msg_version);
1357 	switch (samsg->sadb_msg_type) {
1358 	case SADB_RESERVED:
1359 		(void) printf(dgettext(TEXT_DOMAIN,
1360 		    "RESERVED (warning: set to 0)"));
1361 		break;
1362 	case SADB_GETSPI:
1363 		(void) printf("GETSPI");
1364 		break;
1365 	case SADB_UPDATE:
1366 		(void) printf("UPDATE");
1367 		break;
1368 	case SADB_ADD:
1369 		(void) printf("ADD");
1370 		break;
1371 	case SADB_DELETE:
1372 		(void) printf("DELETE");
1373 		break;
1374 	case SADB_GET:
1375 		(void) printf("GET");
1376 		break;
1377 	case SADB_ACQUIRE:
1378 		(void) printf("ACQUIRE");
1379 		break;
1380 	case SADB_REGISTER:
1381 		(void) printf("REGISTER");
1382 		break;
1383 	case SADB_EXPIRE:
1384 		(void) printf("EXPIRE");
1385 		break;
1386 	case SADB_FLUSH:
1387 		(void) printf("FLUSH");
1388 		break;
1389 	case SADB_DUMP:
1390 		(void) printf("DUMP");
1391 		break;
1392 	case SADB_X_PROMISC:
1393 		(void) printf("X_PROMISC");
1394 		break;
1395 	case SADB_X_INVERSE_ACQUIRE:
1396 		(void) printf("X_INVERSE_ACQUIRE");
1397 		break;
1398 	default:
1399 		(void) printf(dgettext(TEXT_DOMAIN,
1400 		    "Unknown (%u)"), samsg->sadb_msg_type);
1401 		break;
1402 	}
1403 	(void) printf(dgettext(TEXT_DOMAIN, ", SA type "));
1404 
1405 	switch (samsg->sadb_msg_satype) {
1406 	case SADB_SATYPE_UNSPEC:
1407 		(void) printf(dgettext(TEXT_DOMAIN, "<unspecified/all>"));
1408 		break;
1409 	case SADB_SATYPE_AH:
1410 		(void) printf("AH");
1411 		break;
1412 	case SADB_SATYPE_ESP:
1413 		(void) printf("ESP");
1414 		break;
1415 	case SADB_SATYPE_RSVP:
1416 		(void) printf("RSVP");
1417 		break;
1418 	case SADB_SATYPE_OSPFV2:
1419 		(void) printf("OSPFv2");
1420 		break;
1421 	case SADB_SATYPE_RIPV2:
1422 		(void) printf("RIPv2");
1423 		break;
1424 	case SADB_SATYPE_MIP:
1425 		(void) printf(dgettext(TEXT_DOMAIN, "Mobile IP"));
1426 		break;
1427 	default:
1428 		(void) printf(dgettext(TEXT_DOMAIN,
1429 		    "<unknown %u>"), samsg->sadb_msg_satype);
1430 		break;
1431 	}
1432 
1433 	(void) printf(".\n");
1434 
1435 	if (samsg->sadb_msg_errno != 0) {
1436 		(void) printf(dgettext(TEXT_DOMAIN, "Error %s from PF_KEY.\n"),
1437 		    strerror(samsg->sadb_msg_errno));
1438 		print_diagnostic(stdout, samsg->sadb_x_msg_diagnostic);
1439 	}
1440 
1441 	(void) printf(dgettext(TEXT_DOMAIN,
1442 	    "Message length %u bytes, seq=%u, pid=%u.\n"),
1443 	    SADB_64TO8(samsg->sadb_msg_len), samsg->sadb_msg_seq,
1444 	    samsg->sadb_msg_pid);
1445 }
1446 
1447 /*
1448  * Print the SA extension for PF_KEY.
1449  */
1450 void
1451 print_sa(char *prefix, struct sadb_sa *assoc)
1452 {
1453 	if (assoc->sadb_sa_len != SADB_8TO64(sizeof (*assoc))) {
1454 		warnx(dgettext(TEXT_DOMAIN,
1455 		    "WARNING: SA info extension length (%u) is bad."),
1456 		    SADB_64TO8(assoc->sadb_sa_len));
1457 	}
1458 
1459 	(void) printf(dgettext(TEXT_DOMAIN,
1460 	    "%sSADB_ASSOC spi=0x%x, replay=%u, state="),
1461 	    prefix, ntohl(assoc->sadb_sa_spi), assoc->sadb_sa_replay);
1462 	switch (assoc->sadb_sa_state) {
1463 	case SADB_SASTATE_LARVAL:
1464 		(void) printf(dgettext(TEXT_DOMAIN, "LARVAL"));
1465 		break;
1466 	case SADB_SASTATE_MATURE:
1467 		(void) printf(dgettext(TEXT_DOMAIN, "MATURE"));
1468 		break;
1469 	case SADB_SASTATE_DYING:
1470 		(void) printf(dgettext(TEXT_DOMAIN, "DYING"));
1471 		break;
1472 	case SADB_SASTATE_DEAD:
1473 		(void) printf(dgettext(TEXT_DOMAIN, "DEAD"));
1474 		break;
1475 	default:
1476 		(void) printf(dgettext(TEXT_DOMAIN,
1477 		    "<unknown %u>"), assoc->sadb_sa_state);
1478 	}
1479 
1480 	if (assoc->sadb_sa_auth != SADB_AALG_NONE) {
1481 		(void) printf(dgettext(TEXT_DOMAIN,
1482 		    "\n%sAuthentication algorithm = "),
1483 		    prefix);
1484 		(void) dump_aalg(assoc->sadb_sa_auth, stdout);
1485 	}
1486 
1487 	if (assoc->sadb_sa_encrypt != SADB_EALG_NONE) {
1488 		(void) printf(dgettext(TEXT_DOMAIN,
1489 		    "\n%sEncryption algorithm = "), prefix);
1490 		(void) dump_ealg(assoc->sadb_sa_encrypt, stdout);
1491 	}
1492 
1493 	(void) printf(dgettext(TEXT_DOMAIN, "\n%sflags=0x%x < "), prefix,
1494 	    assoc->sadb_sa_flags);
1495 	if (assoc->sadb_sa_flags & SADB_SAFLAGS_PFS)
1496 		(void) printf("PFS ");
1497 	if (assoc->sadb_sa_flags & SADB_SAFLAGS_NOREPLAY)
1498 		(void) printf("NOREPLAY ");
1499 
1500 	/* BEGIN Solaris-specific flags. */
1501 	if (assoc->sadb_sa_flags & SADB_X_SAFLAGS_USED)
1502 		(void) printf("X_USED ");
1503 	if (assoc->sadb_sa_flags & SADB_X_SAFLAGS_UNIQUE)
1504 		(void) printf("X_UNIQUE ");
1505 	if (assoc->sadb_sa_flags & SADB_X_SAFLAGS_AALG1)
1506 		(void) printf("X_AALG1 ");
1507 	if (assoc->sadb_sa_flags & SADB_X_SAFLAGS_AALG2)
1508 		(void) printf("X_AALG2 ");
1509 	if (assoc->sadb_sa_flags & SADB_X_SAFLAGS_EALG1)
1510 		(void) printf("X_EALG1 ");
1511 	if (assoc->sadb_sa_flags & SADB_X_SAFLAGS_EALG2)
1512 		(void) printf("X_EALG2 ");
1513 	if (assoc->sadb_sa_flags & SADB_X_SAFLAGS_NATT_LOC)
1514 		(void) printf("X_NATT_LOC ");
1515 	if (assoc->sadb_sa_flags & SADB_X_SAFLAGS_NATT_REM)
1516 		(void) printf("X_NATT_REM ");
1517 	if (assoc->sadb_sa_flags & SADB_X_SAFLAGS_TUNNEL)
1518 		(void) printf("X_TUNNEL ");
1519 	/* END Solaris-specific flags. */
1520 
1521 	(void) printf(">\n");
1522 }
1523 
1524 void
1525 printsatime(int64_t lt, const char *msg, const char *pfx, const char *pfx2,
1526     boolean_t vflag)
1527 {
1528 	char tbuf[TBUF_SIZE]; /* For strftime() call. */
1529 	const char *tp = tbuf;
1530 	time_t t = lt;
1531 	struct tm res;
1532 
1533 	if (t != lt) {
1534 		if (lt > 0)
1535 			t = LONG_MAX;
1536 		else
1537 			t = LONG_MIN;
1538 	}
1539 
1540 	if (strftime(tbuf, TBUF_SIZE, NULL, localtime_r(&t, &res)) == 0)
1541 		tp = dgettext(TEXT_DOMAIN, "<time conversion failed>");
1542 	(void) printf(msg, pfx, tp);
1543 	if (vflag && (pfx2 != NULL))
1544 		(void) printf(dgettext(TEXT_DOMAIN,
1545 		    "%s\t(raw time value %llu)\n"), pfx2, lt);
1546 }
1547 
1548 /*
1549  * Print the SA lifetime information.  (An SADB_EXT_LIFETIME_* extension.)
1550  */
1551 void
1552 print_lifetimes(time_t wallclock, struct sadb_lifetime *current,
1553     struct sadb_lifetime *hard, struct sadb_lifetime *soft, boolean_t vflag)
1554 {
1555 	int64_t scratch;
1556 	char *soft_prefix = dgettext(TEXT_DOMAIN, "SLT: ");
1557 	char *hard_prefix = dgettext(TEXT_DOMAIN, "HLT: ");
1558 	char *current_prefix = dgettext(TEXT_DOMAIN, "CLT: ");
1559 
1560 	if (current != NULL &&
1561 	    current->sadb_lifetime_len != SADB_8TO64(sizeof (*current))) {
1562 		warnx(dgettext(TEXT_DOMAIN,
1563 		    "WARNING: CURRENT lifetime extension length (%u) is bad."),
1564 		    SADB_64TO8(current->sadb_lifetime_len));
1565 	}
1566 
1567 	if (hard != NULL &&
1568 	    hard->sadb_lifetime_len != SADB_8TO64(sizeof (*hard))) {
1569 		warnx(dgettext(TEXT_DOMAIN, "WARNING: HARD lifetime "
1570 		    "extension length (%u) is bad."),
1571 		    SADB_64TO8(hard->sadb_lifetime_len));
1572 	}
1573 
1574 	if (soft != NULL &&
1575 	    soft->sadb_lifetime_len != SADB_8TO64(sizeof (*soft))) {
1576 		warnx(dgettext(TEXT_DOMAIN, "WARNING: SOFT lifetime "
1577 		    "extension length (%u) is bad."),
1578 		    SADB_64TO8(soft->sadb_lifetime_len));
1579 	}
1580 
1581 	(void) printf(" LT: Lifetime information\n");
1582 
1583 	if (current != NULL) {
1584 		/* Express values as current values. */
1585 		(void) printf(dgettext(TEXT_DOMAIN,
1586 		    "%s%llu bytes protected, %u allocations used.\n"),
1587 		    current_prefix, current->sadb_lifetime_bytes,
1588 		    current->sadb_lifetime_allocations);
1589 		printsatime(current->sadb_lifetime_addtime,
1590 		    dgettext(TEXT_DOMAIN, "%sSA added at time %s\n"),
1591 		    current_prefix, current_prefix, vflag);
1592 		if (current->sadb_lifetime_usetime != 0) {
1593 			printsatime(current->sadb_lifetime_usetime,
1594 			    dgettext(TEXT_DOMAIN,
1595 			    "%sSA first used at time %s\n"),
1596 			    current_prefix, current_prefix, vflag);
1597 		}
1598 		printsatime(wallclock, dgettext(TEXT_DOMAIN,
1599 		    "%sTime now is %s\n"), current_prefix, current_prefix,
1600 		    vflag);
1601 	}
1602 
1603 	if (soft != NULL) {
1604 		(void) printf(dgettext(TEXT_DOMAIN,
1605 		    "%sSoft lifetime information:  "),
1606 		    soft_prefix);
1607 		(void) printf(dgettext(TEXT_DOMAIN,
1608 		    "%llu bytes of lifetime, %u "
1609 		    "allocations.\n"), soft->sadb_lifetime_bytes,
1610 		    soft->sadb_lifetime_allocations);
1611 		(void) printf(dgettext(TEXT_DOMAIN,
1612 		    "%s%llu seconds of post-add lifetime.\n"),
1613 		    soft_prefix, soft->sadb_lifetime_addtime);
1614 		(void) printf(dgettext(TEXT_DOMAIN,
1615 		    "%s%llu seconds of post-use lifetime.\n"),
1616 		    soft_prefix, soft->sadb_lifetime_usetime);
1617 		/* If possible, express values as time remaining. */
1618 		if (current != NULL) {
1619 			if (soft->sadb_lifetime_bytes != 0)
1620 				(void) printf(dgettext(TEXT_DOMAIN,
1621 				    "%s%llu more bytes can be protected.\n"),
1622 				    soft_prefix,
1623 				    (soft->sadb_lifetime_bytes >
1624 				    current->sadb_lifetime_bytes) ?
1625 				    (soft->sadb_lifetime_bytes -
1626 				    current->sadb_lifetime_bytes) : (0));
1627 			if (soft->sadb_lifetime_addtime != 0 ||
1628 			    (soft->sadb_lifetime_usetime != 0 &&
1629 			    current->sadb_lifetime_usetime != 0)) {
1630 				int64_t adddelta, usedelta;
1631 
1632 				if (soft->sadb_lifetime_addtime != 0) {
1633 					adddelta =
1634 					    current->sadb_lifetime_addtime +
1635 					    soft->sadb_lifetime_addtime -
1636 					    wallclock;
1637 				} else {
1638 					adddelta = TIME_MAX;
1639 				}
1640 
1641 				if (soft->sadb_lifetime_usetime != 0 &&
1642 				    current->sadb_lifetime_usetime != 0) {
1643 					usedelta =
1644 					    current->sadb_lifetime_usetime +
1645 					    soft->sadb_lifetime_usetime -
1646 					    wallclock;
1647 				} else {
1648 					usedelta = TIME_MAX;
1649 				}
1650 				(void) printf("%s", soft_prefix);
1651 				scratch = MIN(adddelta, usedelta);
1652 				if (scratch >= 0) {
1653 					(void) printf(dgettext(TEXT_DOMAIN,
1654 					    "Soft expiration occurs in %lld "
1655 					    "seconds, "), scratch);
1656 				} else {
1657 					(void) printf(dgettext(TEXT_DOMAIN,
1658 					    "Soft expiration occurred "));
1659 				}
1660 				scratch += wallclock;
1661 				printsatime(scratch, dgettext(TEXT_DOMAIN,
1662 				    "%sat %s.\n"), "", soft_prefix, vflag);
1663 			}
1664 		}
1665 	}
1666 
1667 	if (hard != NULL) {
1668 		(void) printf(dgettext(TEXT_DOMAIN,
1669 		    "%sHard lifetime information:  "), hard_prefix);
1670 		(void) printf(dgettext(TEXT_DOMAIN, "%llu bytes of lifetime, "
1671 		    "%u allocations.\n"), hard->sadb_lifetime_bytes,
1672 		    hard->sadb_lifetime_allocations);
1673 		(void) printf(dgettext(TEXT_DOMAIN,
1674 		    "%s%llu seconds of post-add lifetime.\n"),
1675 		    hard_prefix, hard->sadb_lifetime_addtime);
1676 		(void) printf(dgettext(TEXT_DOMAIN,
1677 		    "%s%llu seconds of post-use lifetime.\n"),
1678 		    hard_prefix, hard->sadb_lifetime_usetime);
1679 		/* If possible, express values as time remaining. */
1680 		if (current != NULL) {
1681 			if (hard->sadb_lifetime_bytes != 0)
1682 				(void) printf(dgettext(TEXT_DOMAIN,
1683 				    "%s%llu more bytes can be protected.\n"),
1684 				    hard_prefix,
1685 				    (hard->sadb_lifetime_bytes >
1686 				    current->sadb_lifetime_bytes) ?
1687 				    (hard->sadb_lifetime_bytes -
1688 				    current->sadb_lifetime_bytes) : (0));
1689 			if (hard->sadb_lifetime_addtime != 0 ||
1690 			    (hard->sadb_lifetime_usetime != 0 &&
1691 			    current->sadb_lifetime_usetime != 0)) {
1692 				int64_t adddelta, usedelta;
1693 
1694 				if (hard->sadb_lifetime_addtime != 0) {
1695 					adddelta =
1696 					    current->sadb_lifetime_addtime +
1697 					    hard->sadb_lifetime_addtime -
1698 					    wallclock;
1699 				} else {
1700 					adddelta = TIME_MAX;
1701 				}
1702 
1703 				if (hard->sadb_lifetime_usetime != 0 &&
1704 				    current->sadb_lifetime_usetime != 0) {
1705 					usedelta =
1706 					    current->sadb_lifetime_usetime +
1707 					    hard->sadb_lifetime_usetime -
1708 					    wallclock;
1709 				} else {
1710 					usedelta = TIME_MAX;
1711 				}
1712 				(void) printf("%s", hard_prefix);
1713 				scratch = MIN(adddelta, usedelta);
1714 				if (scratch >= 0) {
1715 					(void) printf(dgettext(TEXT_DOMAIN,
1716 					    "Hard expiration occurs in %lld "
1717 					    "seconds, "), scratch);
1718 				} else {
1719 					(void) printf(dgettext(TEXT_DOMAIN,
1720 					    "Hard expiration occured "));
1721 				}
1722 				scratch += wallclock;
1723 				printsatime(scratch, dgettext(TEXT_DOMAIN,
1724 				    "%sat %s.\n"), "", hard_prefix, vflag);
1725 			}
1726 		}
1727 	}
1728 }
1729 
1730 /*
1731  * Print an SADB_EXT_ADDRESS_* extension.
1732  */
1733 void
1734 print_address(char *prefix, struct sadb_address *addr)
1735 {
1736 	struct protoent *pe;
1737 
1738 	(void) printf("%s", prefix);
1739 	switch (addr->sadb_address_exttype) {
1740 	case SADB_EXT_ADDRESS_SRC:
1741 		(void) printf(dgettext(TEXT_DOMAIN, "Source address "));
1742 		break;
1743 	case SADB_X_EXT_ADDRESS_INNER_SRC:
1744 		(void) printf(dgettext(TEXT_DOMAIN, "Inner source address "));
1745 		break;
1746 	case SADB_EXT_ADDRESS_DST:
1747 		(void) printf(dgettext(TEXT_DOMAIN, "Destination address "));
1748 		break;
1749 	case SADB_X_EXT_ADDRESS_INNER_DST:
1750 		(void) printf(dgettext(TEXT_DOMAIN,
1751 		    "Inner destination address "));
1752 		break;
1753 	case SADB_X_EXT_ADDRESS_NATT_LOC:
1754 		(void) printf(dgettext(TEXT_DOMAIN, "NAT-T local address "));
1755 		break;
1756 	case SADB_X_EXT_ADDRESS_NATT_REM:
1757 		(void) printf(dgettext(TEXT_DOMAIN, "NAT-T remote address "));
1758 		break;
1759 	}
1760 
1761 	(void) printf(dgettext(TEXT_DOMAIN,
1762 	    "(proto=%d"), addr->sadb_address_proto);
1763 	if (!nflag) {
1764 		if (addr->sadb_address_proto == 0) {
1765 			(void) printf(dgettext(TEXT_DOMAIN, "/<unspecified>"));
1766 		} else if ((pe = getprotobynumber(addr->sadb_address_proto))
1767 		    != NULL) {
1768 			(void) printf("/%s", pe->p_name);
1769 		} else {
1770 			(void) printf(dgettext(TEXT_DOMAIN, "/<unknown>"));
1771 		}
1772 	}
1773 	(void) printf(dgettext(TEXT_DOMAIN, ")\n%s"), prefix);
1774 	(void) dump_sockaddr((struct sockaddr *)(addr + 1),
1775 	    addr->sadb_address_prefixlen, B_FALSE, stdout);
1776 }
1777 
1778 /*
1779  * Print an SADB_EXT_KEY extension.
1780  */
1781 void
1782 print_key(char *prefix, struct sadb_key *key)
1783 {
1784 	(void) printf("%s", prefix);
1785 
1786 	switch (key->sadb_key_exttype) {
1787 	case SADB_EXT_KEY_AUTH:
1788 		(void) printf(dgettext(TEXT_DOMAIN, "Authentication"));
1789 		break;
1790 	case SADB_EXT_KEY_ENCRYPT:
1791 		(void) printf(dgettext(TEXT_DOMAIN, "Encryption"));
1792 		break;
1793 	}
1794 
1795 	(void) printf(dgettext(TEXT_DOMAIN, " key.\n%s"), prefix);
1796 	(void) dump_key((uint8_t *)(key + 1), key->sadb_key_bits, stdout);
1797 	(void) putchar('\n');
1798 }
1799 
1800 /*
1801  * Print an SADB_EXT_IDENTITY_* extension.
1802  */
1803 void
1804 print_ident(char *prefix, struct sadb_ident *id)
1805 {
1806 	boolean_t canprint = B_TRUE;
1807 
1808 	(void) printf("%s", prefix);
1809 	switch (id->sadb_ident_exttype) {
1810 	case SADB_EXT_IDENTITY_SRC:
1811 		(void) printf(dgettext(TEXT_DOMAIN, "Source"));
1812 		break;
1813 	case SADB_EXT_IDENTITY_DST:
1814 		(void) printf(dgettext(TEXT_DOMAIN, "Destination"));
1815 		break;
1816 	}
1817 
1818 	(void) printf(dgettext(TEXT_DOMAIN,
1819 	    " identity, uid=%d, type "), id->sadb_ident_id);
1820 	canprint = dump_sadb_idtype(id->sadb_ident_type, stdout, NULL);
1821 	(void) printf("\n%s", prefix);
1822 	if (canprint)
1823 		(void) printf("%s\n", (char *)(id + 1));
1824 	else
1825 		(void) printf(dgettext(TEXT_DOMAIN, "<cannot print>\n"));
1826 }
1827 
1828 /*
1829  * Print an SADB_SENSITIVITY extension.
1830  */
1831 void
1832 print_sens(char *prefix, struct sadb_sens *sens)
1833 {
1834 	uint64_t *bitmap = (uint64_t *)(sens + 1);
1835 	int i;
1836 
1837 	(void) printf(
1838 	    dgettext(TEXT_DOMAIN,
1839 	    "%sSensitivity DPD %d, sens level=%d, integ level=%d\n"),
1840 	    prefix, sens->sadb_sens_dpd, sens->sadb_sens_sens_level,
1841 	    sens->sadb_sens_integ_level);
1842 	for (i = 0; sens->sadb_sens_sens_len-- > 0; i++, bitmap++)
1843 		(void) printf(
1844 		    dgettext(TEXT_DOMAIN,
1845 		    "%s Sensitivity BM extended word %d 0x%llx\n"), i, *bitmap);
1846 	for (i = 0; sens->sadb_sens_integ_len-- > 0; i++, bitmap++)
1847 		(void) printf(
1848 		    dgettext(TEXT_DOMAIN,
1849 		    "%s Integrity BM extended word %d 0x%llx\n"), i, *bitmap);
1850 }
1851 
1852 /*
1853  * Print an SADB_EXT_PROPOSAL extension.
1854  */
1855 void
1856 print_prop(char *prefix, struct sadb_prop *prop)
1857 {
1858 	struct sadb_comb *combs;
1859 	int i, numcombs;
1860 
1861 	(void) printf(dgettext(TEXT_DOMAIN,
1862 	    "%sProposal, replay counter = %u.\n"), prefix,
1863 	    prop->sadb_prop_replay);
1864 
1865 	numcombs = prop->sadb_prop_len - SADB_8TO64(sizeof (*prop));
1866 	numcombs /= SADB_8TO64(sizeof (*combs));
1867 
1868 	combs = (struct sadb_comb *)(prop + 1);
1869 
1870 	for (i = 0; i < numcombs; i++) {
1871 		(void) printf(dgettext(TEXT_DOMAIN,
1872 		    "%s Combination #%u "), prefix, i + 1);
1873 		if (combs[i].sadb_comb_auth != SADB_AALG_NONE) {
1874 			(void) printf(dgettext(TEXT_DOMAIN,
1875 			    "Authentication = "));
1876 			(void) dump_aalg(combs[i].sadb_comb_auth, stdout);
1877 			(void) printf(dgettext(TEXT_DOMAIN,
1878 			    "  minbits=%u, maxbits=%u.\n%s "),
1879 			    combs[i].sadb_comb_auth_minbits,
1880 			    combs[i].sadb_comb_auth_maxbits, prefix);
1881 		}
1882 
1883 		if (combs[i].sadb_comb_encrypt != SADB_EALG_NONE) {
1884 			(void) printf(dgettext(TEXT_DOMAIN, "Encryption = "));
1885 			(void) dump_ealg(combs[i].sadb_comb_encrypt, stdout);
1886 			(void) printf(dgettext(TEXT_DOMAIN,
1887 			    "  minbits=%u, maxbits=%u.\n%s "),
1888 			    combs[i].sadb_comb_encrypt_minbits,
1889 			    combs[i].sadb_comb_encrypt_maxbits, prefix);
1890 		}
1891 
1892 		(void) printf(dgettext(TEXT_DOMAIN, "HARD: "));
1893 		if (combs[i].sadb_comb_hard_allocations)
1894 			(void) printf(dgettext(TEXT_DOMAIN, "alloc=%u "),
1895 			    combs[i].sadb_comb_hard_allocations);
1896 		if (combs[i].sadb_comb_hard_bytes)
1897 			(void) printf(dgettext(TEXT_DOMAIN, "bytes=%llu "),
1898 			    combs[i].sadb_comb_hard_bytes);
1899 		if (combs[i].sadb_comb_hard_addtime)
1900 			(void) printf(dgettext(TEXT_DOMAIN,
1901 			    "post-add secs=%llu "),
1902 			    combs[i].sadb_comb_hard_addtime);
1903 		if (combs[i].sadb_comb_hard_usetime)
1904 			(void) printf(dgettext(TEXT_DOMAIN,
1905 			    "post-use secs=%llu"),
1906 			    combs[i].sadb_comb_hard_usetime);
1907 
1908 		(void) printf(dgettext(TEXT_DOMAIN, "\n%s SOFT: "), prefix);
1909 		if (combs[i].sadb_comb_soft_allocations)
1910 			(void) printf(dgettext(TEXT_DOMAIN, "alloc=%u "),
1911 			    combs[i].sadb_comb_soft_allocations);
1912 		if (combs[i].sadb_comb_soft_bytes)
1913 			(void) printf(dgettext(TEXT_DOMAIN, "bytes=%llu "),
1914 			    combs[i].sadb_comb_soft_bytes);
1915 		if (combs[i].sadb_comb_soft_addtime)
1916 			(void) printf(dgettext(TEXT_DOMAIN,
1917 			    "post-add secs=%llu "),
1918 			    combs[i].sadb_comb_soft_addtime);
1919 		if (combs[i].sadb_comb_soft_usetime)
1920 			(void) printf(dgettext(TEXT_DOMAIN,
1921 			    "post-use secs=%llu"),
1922 			    combs[i].sadb_comb_soft_usetime);
1923 		(void) putchar('\n');
1924 	}
1925 }
1926 
1927 /*
1928  * Print an extended proposal (SADB_X_EXT_EPROP).
1929  */
1930 void
1931 print_eprop(char *prefix, struct sadb_prop *eprop)
1932 {
1933 	uint64_t *sofar;
1934 	struct sadb_x_ecomb *ecomb;
1935 	struct sadb_x_algdesc *algdesc;
1936 	int i, j;
1937 
1938 	(void) printf(dgettext(TEXT_DOMAIN,
1939 	    "%sExtended Proposal, replay counter = %u, "), prefix,
1940 	    eprop->sadb_prop_replay);
1941 	(void) printf(dgettext(TEXT_DOMAIN, "number of combinations = %u.\n"),
1942 	    eprop->sadb_x_prop_numecombs);
1943 
1944 	sofar = (uint64_t *)(eprop + 1);
1945 	ecomb = (struct sadb_x_ecomb *)sofar;
1946 
1947 	for (i = 0; i < eprop->sadb_x_prop_numecombs; ) {
1948 		(void) printf(dgettext(TEXT_DOMAIN,
1949 		    "%s Extended combination #%u:\n"), prefix, ++i);
1950 
1951 		(void) printf(dgettext(TEXT_DOMAIN, "%s HARD: "), prefix);
1952 		(void) printf(dgettext(TEXT_DOMAIN, "alloc=%u, "),
1953 		    ecomb->sadb_x_ecomb_hard_allocations);
1954 		(void) printf(dgettext(TEXT_DOMAIN, "bytes=%llu, "),
1955 		    ecomb->sadb_x_ecomb_hard_bytes);
1956 		(void) printf(dgettext(TEXT_DOMAIN, "post-add secs=%llu, "),
1957 		    ecomb->sadb_x_ecomb_hard_addtime);
1958 		(void) printf(dgettext(TEXT_DOMAIN, "post-use secs=%llu\n"),
1959 		    ecomb->sadb_x_ecomb_hard_usetime);
1960 
1961 		(void) printf(dgettext(TEXT_DOMAIN, "%s SOFT: "), prefix);
1962 		(void) printf(dgettext(TEXT_DOMAIN, "alloc=%u, "),
1963 		    ecomb->sadb_x_ecomb_soft_allocations);
1964 		(void) printf(dgettext(TEXT_DOMAIN, "bytes=%llu, "),
1965 		    ecomb->sadb_x_ecomb_soft_bytes);
1966 		(void) printf(dgettext(TEXT_DOMAIN, "post-add secs=%llu, "),
1967 		    ecomb->sadb_x_ecomb_soft_addtime);
1968 		(void) printf(dgettext(TEXT_DOMAIN, "post-use secs=%llu\n"),
1969 		    ecomb->sadb_x_ecomb_soft_usetime);
1970 
1971 		sofar = (uint64_t *)(ecomb + 1);
1972 		algdesc = (struct sadb_x_algdesc *)sofar;
1973 
1974 		for (j = 0; j < ecomb->sadb_x_ecomb_numalgs; ) {
1975 			(void) printf(dgettext(TEXT_DOMAIN,
1976 			    "%s Alg #%u "), prefix, ++j);
1977 			switch (algdesc->sadb_x_algdesc_satype) {
1978 			case SADB_SATYPE_ESP:
1979 				(void) printf(dgettext(TEXT_DOMAIN,
1980 				    "for ESP "));
1981 				break;
1982 			case SADB_SATYPE_AH:
1983 				(void) printf(dgettext(TEXT_DOMAIN, "for AH "));
1984 				break;
1985 			default:
1986 				(void) printf(dgettext(TEXT_DOMAIN,
1987 				    "for satype=%d "),
1988 				    algdesc->sadb_x_algdesc_satype);
1989 			}
1990 			switch (algdesc->sadb_x_algdesc_algtype) {
1991 			case SADB_X_ALGTYPE_CRYPT:
1992 				(void) printf(dgettext(TEXT_DOMAIN,
1993 				    "Encryption = "));
1994 				(void) dump_ealg(algdesc->sadb_x_algdesc_alg,
1995 				    stdout);
1996 				break;
1997 			case SADB_X_ALGTYPE_AUTH:
1998 				(void) printf(dgettext(TEXT_DOMAIN,
1999 				    "Authentication = "));
2000 				(void) dump_aalg(algdesc->sadb_x_algdesc_alg,
2001 				    stdout);
2002 				break;
2003 			default:
2004 				(void) printf(dgettext(TEXT_DOMAIN,
2005 				    "algtype(%d) = alg(%d)"),
2006 				    algdesc->sadb_x_algdesc_algtype,
2007 				    algdesc->sadb_x_algdesc_alg);
2008 				break;
2009 			}
2010 
2011 			(void) printf(dgettext(TEXT_DOMAIN,
2012 			    "  minbits=%u, maxbits=%u.\n"),
2013 			    algdesc->sadb_x_algdesc_minbits,
2014 			    algdesc->sadb_x_algdesc_maxbits);
2015 
2016 			sofar = (uint64_t *)(++algdesc);
2017 		}
2018 		ecomb = (struct sadb_x_ecomb *)sofar;
2019 	}
2020 }
2021 
2022 /*
2023  * Print an SADB_EXT_SUPPORTED extension.
2024  */
2025 void
2026 print_supp(char *prefix, struct sadb_supported *supp)
2027 {
2028 	struct sadb_alg *algs;
2029 	int i, numalgs;
2030 
2031 	(void) printf(dgettext(TEXT_DOMAIN, "%sSupported "), prefix);
2032 	switch (supp->sadb_supported_exttype) {
2033 	case SADB_EXT_SUPPORTED_AUTH:
2034 		(void) printf(dgettext(TEXT_DOMAIN, "authentication"));
2035 		break;
2036 	case SADB_EXT_SUPPORTED_ENCRYPT:
2037 		(void) printf(dgettext(TEXT_DOMAIN, "encryption"));
2038 		break;
2039 	}
2040 	(void) printf(dgettext(TEXT_DOMAIN, " algorithms.\n"));
2041 
2042 	algs = (struct sadb_alg *)(supp + 1);
2043 	numalgs = supp->sadb_supported_len - SADB_8TO64(sizeof (*supp));
2044 	numalgs /= SADB_8TO64(sizeof (*algs));
2045 	for (i = 0; i < numalgs; i++) {
2046 		(void) printf("%s", prefix);
2047 		switch (supp->sadb_supported_exttype) {
2048 		case SADB_EXT_SUPPORTED_AUTH:
2049 			(void) dump_aalg(algs[i].sadb_alg_id, stdout);
2050 			break;
2051 		case SADB_EXT_SUPPORTED_ENCRYPT:
2052 			(void) dump_ealg(algs[i].sadb_alg_id, stdout);
2053 			break;
2054 		}
2055 		(void) printf(dgettext(TEXT_DOMAIN,
2056 		    " minbits=%u, maxbits=%u, ivlen=%u.\n"),
2057 		    algs[i].sadb_alg_minbits, algs[i].sadb_alg_maxbits,
2058 		    algs[i].sadb_alg_ivlen);
2059 	}
2060 }
2061 
2062 /*
2063  * Print an SADB_EXT_SPIRANGE extension.
2064  */
2065 void
2066 print_spirange(char *prefix, struct sadb_spirange *range)
2067 {
2068 	(void) printf(dgettext(TEXT_DOMAIN,
2069 	    "%sSPI Range, min=0x%x, max=0x%x\n"), prefix,
2070 	    htonl(range->sadb_spirange_min),
2071 	    htonl(range->sadb_spirange_max));
2072 }
2073 
2074 /*
2075  * Print an SADB_X_EXT_KM_COOKIE extension.
2076  */
2077 
2078 void
2079 print_kmc(char *prefix, struct sadb_x_kmc *kmc)
2080 {
2081 	char *cookie_label;
2082 
2083 	if ((cookie_label = kmc_lookup_by_cookie(kmc->sadb_x_kmc_cookie)) ==
2084 	    NULL)
2085 		cookie_label = dgettext(TEXT_DOMAIN, "<Label not found.>");
2086 
2087 	(void) printf(dgettext(TEXT_DOMAIN,
2088 	    "%sProtocol %u, cookie=\"%s\" (%u)\n"), prefix,
2089 	    kmc->sadb_x_kmc_proto, cookie_label, kmc->sadb_x_kmc_cookie);
2090 }
2091 
2092 /*
2093  * Take a PF_KEY message pointed to buffer and print it.  Useful for DUMP
2094  * and GET.
2095  */
2096 void
2097 print_samsg(uint64_t *buffer, boolean_t want_timestamp, boolean_t vflag)
2098 {
2099 	uint64_t *current;
2100 	struct sadb_msg *samsg = (struct sadb_msg *)buffer;
2101 	struct sadb_ext *ext;
2102 	struct sadb_lifetime *currentlt = NULL, *hardlt = NULL, *softlt = NULL;
2103 	int i;
2104 	time_t wallclock;
2105 
2106 	(void) time(&wallclock);
2107 
2108 	print_sadb_msg(samsg, want_timestamp ? wallclock : 0, vflag);
2109 	current = (uint64_t *)(samsg + 1);
2110 	while (current - buffer < samsg->sadb_msg_len) {
2111 		int lenbytes;
2112 
2113 		ext = (struct sadb_ext *)current;
2114 		lenbytes = SADB_64TO8(ext->sadb_ext_len);
2115 		switch (ext->sadb_ext_type) {
2116 		case SADB_EXT_SA:
2117 			print_sa(dgettext(TEXT_DOMAIN,
2118 			    "SA: "), (struct sadb_sa *)current);
2119 			break;
2120 		/*
2121 		 * Pluck out lifetimes and print them at the end.  This is
2122 		 * to show relative lifetimes.
2123 		 */
2124 		case SADB_EXT_LIFETIME_CURRENT:
2125 			currentlt = (struct sadb_lifetime *)current;
2126 			break;
2127 		case SADB_EXT_LIFETIME_HARD:
2128 			hardlt = (struct sadb_lifetime *)current;
2129 			break;
2130 		case SADB_EXT_LIFETIME_SOFT:
2131 			softlt = (struct sadb_lifetime *)current;
2132 			break;
2133 
2134 		case SADB_EXT_ADDRESS_SRC:
2135 			print_address(dgettext(TEXT_DOMAIN, "SRC: "),
2136 			    (struct sadb_address *)current);
2137 			break;
2138 		case SADB_X_EXT_ADDRESS_INNER_SRC:
2139 			print_address(dgettext(TEXT_DOMAIN, "INS: "),
2140 			    (struct sadb_address *)current);
2141 			break;
2142 		case SADB_EXT_ADDRESS_DST:
2143 			print_address(dgettext(TEXT_DOMAIN, "DST: "),
2144 			    (struct sadb_address *)current);
2145 			break;
2146 		case SADB_X_EXT_ADDRESS_INNER_DST:
2147 			print_address(dgettext(TEXT_DOMAIN, "IND: "),
2148 			    (struct sadb_address *)current);
2149 			break;
2150 		case SADB_EXT_KEY_AUTH:
2151 			print_key(dgettext(TEXT_DOMAIN,
2152 			    "AKY: "), (struct sadb_key *)current);
2153 			break;
2154 		case SADB_EXT_KEY_ENCRYPT:
2155 			print_key(dgettext(TEXT_DOMAIN,
2156 			    "EKY: "), (struct sadb_key *)current);
2157 			break;
2158 		case SADB_EXT_IDENTITY_SRC:
2159 			print_ident(dgettext(TEXT_DOMAIN, "SID: "),
2160 			    (struct sadb_ident *)current);
2161 			break;
2162 		case SADB_EXT_IDENTITY_DST:
2163 			print_ident(dgettext(TEXT_DOMAIN, "DID: "),
2164 			    (struct sadb_ident *)current);
2165 			break;
2166 		case SADB_EXT_SENSITIVITY:
2167 			print_sens(dgettext(TEXT_DOMAIN, "SNS: "),
2168 			    (struct sadb_sens *)current);
2169 			break;
2170 		case SADB_EXT_PROPOSAL:
2171 			print_prop(dgettext(TEXT_DOMAIN, "PRP: "),
2172 			    (struct sadb_prop *)current);
2173 			break;
2174 		case SADB_EXT_SUPPORTED_AUTH:
2175 			print_supp(dgettext(TEXT_DOMAIN, "SUA: "),
2176 			    (struct sadb_supported *)current);
2177 			break;
2178 		case SADB_EXT_SUPPORTED_ENCRYPT:
2179 			print_supp(dgettext(TEXT_DOMAIN, "SUE: "),
2180 			    (struct sadb_supported *)current);
2181 			break;
2182 		case SADB_EXT_SPIRANGE:
2183 			print_spirange(dgettext(TEXT_DOMAIN, "SPR: "),
2184 			    (struct sadb_spirange *)current);
2185 			break;
2186 		case SADB_X_EXT_EPROP:
2187 			print_eprop(dgettext(TEXT_DOMAIN, "EPR: "),
2188 			    (struct sadb_prop *)current);
2189 			break;
2190 		case SADB_X_EXT_KM_COOKIE:
2191 			print_kmc(dgettext(TEXT_DOMAIN, "KMC: "),
2192 			    (struct sadb_x_kmc *)current);
2193 			break;
2194 		case SADB_X_EXT_ADDRESS_NATT_REM:
2195 			print_address(dgettext(TEXT_DOMAIN, "NRM: "),
2196 			    (struct sadb_address *)current);
2197 			break;
2198 		case SADB_X_EXT_ADDRESS_NATT_LOC:
2199 			print_address(dgettext(TEXT_DOMAIN, "NLC: "),
2200 			    (struct sadb_address *)current);
2201 			break;
2202 		default:
2203 			(void) printf(dgettext(TEXT_DOMAIN,
2204 			    "UNK: Unknown ext. %d, len %d.\n"),
2205 			    ext->sadb_ext_type, lenbytes);
2206 			for (i = 0; i < ext->sadb_ext_len; i++)
2207 				(void) printf(dgettext(TEXT_DOMAIN,
2208 				    "UNK: 0x%llx\n"), ((uint64_t *)ext)[i]);
2209 			break;
2210 		}
2211 		current += (lenbytes == 0) ?
2212 		    SADB_8TO64(sizeof (struct sadb_ext)) : ext->sadb_ext_len;
2213 	}
2214 	/*
2215 	 * Print lifetimes NOW.
2216 	 */
2217 	if (currentlt != NULL || hardlt != NULL || softlt != NULL)
2218 		print_lifetimes(wallclock, currentlt, hardlt, softlt, vflag);
2219 
2220 	if (current - buffer != samsg->sadb_msg_len) {
2221 		warnx(dgettext(TEXT_DOMAIN, "WARNING: insufficient buffer "
2222 		    "space or corrupt message."));
2223 	}
2224 
2225 	(void) fflush(stdout);	/* Make sure our message is out there. */
2226 }
2227 
2228 /*
2229  * save_XXX functions are used when "saving" the SA tables to either a
2230  * file or standard output.  They use the dump_XXX functions where needed,
2231  * but mostly they use the rparseXXX functions.
2232  */
2233 
2234 /*
2235  * Print save information for a lifetime extension.
2236  *
2237  * NOTE : It saves the lifetime in absolute terms.  For example, if you
2238  * had a hard_usetime of 60 seconds, you'll save it as 60 seconds, even though
2239  * there may have been 59 seconds burned off the clock.
2240  */
2241 boolean_t
2242 save_lifetime(struct sadb_lifetime *lifetime, FILE *ofile)
2243 {
2244 	char *prefix;
2245 
2246 	prefix = (lifetime->sadb_lifetime_exttype == SADB_EXT_LIFETIME_SOFT) ?
2247 	    "soft" : "hard";
2248 
2249 	if (putc('\t', ofile) == EOF)
2250 		return (B_FALSE);
2251 
2252 	if (lifetime->sadb_lifetime_allocations != 0 && fprintf(ofile,
2253 	    "%s_alloc %u ", prefix, lifetime->sadb_lifetime_allocations) < 0)
2254 		return (B_FALSE);
2255 
2256 	if (lifetime->sadb_lifetime_bytes != 0 && fprintf(ofile,
2257 	    "%s_bytes %llu ", prefix, lifetime->sadb_lifetime_bytes) < 0)
2258 		return (B_FALSE);
2259 
2260 	if (lifetime->sadb_lifetime_addtime != 0 && fprintf(ofile,
2261 	    "%s_addtime %llu ", prefix, lifetime->sadb_lifetime_addtime) < 0)
2262 		return (B_FALSE);
2263 
2264 	if (lifetime->sadb_lifetime_usetime != 0 && fprintf(ofile,
2265 	    "%s_usetime %llu ", prefix, lifetime->sadb_lifetime_usetime) < 0)
2266 		return (B_FALSE);
2267 
2268 	return (B_TRUE);
2269 }
2270 
2271 /*
2272  * Print save information for an address extension.
2273  */
2274 boolean_t
2275 save_address(struct sadb_address *addr, FILE *ofile)
2276 {
2277 	char *printable_addr, buf[INET6_ADDRSTRLEN];
2278 	const char *prefix, *pprefix;
2279 	struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)(addr + 1);
2280 	struct sockaddr_in *sin = (struct sockaddr_in *)sin6;
2281 	int af = sin->sin_family;
2282 
2283 	/*
2284 	 * Address-family reality check.
2285 	 */
2286 	if (af != AF_INET6 && af != AF_INET)
2287 		return (B_FALSE);
2288 
2289 	switch (addr->sadb_address_exttype) {
2290 	case SADB_EXT_ADDRESS_SRC:
2291 		prefix = "src";
2292 		pprefix = "sport";
2293 		break;
2294 	case SADB_X_EXT_ADDRESS_INNER_SRC:
2295 		prefix = "isrc";
2296 		pprefix = "isport";
2297 		break;
2298 	case SADB_EXT_ADDRESS_DST:
2299 		prefix = "dst";
2300 		pprefix = "dport";
2301 		break;
2302 	case SADB_X_EXT_ADDRESS_INNER_DST:
2303 		prefix = "idst";
2304 		pprefix = "idport";
2305 		break;
2306 	case SADB_X_EXT_ADDRESS_NATT_LOC:
2307 		prefix = "nat_loc ";
2308 		pprefix = "nat_lport";
2309 		break;
2310 	case SADB_X_EXT_ADDRESS_NATT_REM:
2311 		prefix = "nat_rem ";
2312 		pprefix = "nat_rport";
2313 		break;
2314 	}
2315 
2316 	if (fprintf(ofile, "    %s ", prefix) < 0)
2317 		return (B_FALSE);
2318 
2319 	/*
2320 	 * Do not do address-to-name translation, given that we live in
2321 	 * an age of names that explode into many addresses.
2322 	 */
2323 	printable_addr = (char *)inet_ntop(af,
2324 	    (af == AF_INET) ? (char *)&sin->sin_addr : (char *)&sin6->sin6_addr,
2325 	    buf, sizeof (buf));
2326 	if (printable_addr == NULL)
2327 		printable_addr = "Invalid IP address.";
2328 	if (fprintf(ofile, "%s", printable_addr) < 0)
2329 		return (B_FALSE);
2330 	if (addr->sadb_address_prefixlen != 0 &&
2331 	    !((addr->sadb_address_prefixlen == 32 && af == AF_INET) ||
2332 	    (addr->sadb_address_prefixlen == 128 && af == AF_INET6))) {
2333 		if (fprintf(ofile, "/%d", addr->sadb_address_prefixlen) < 0)
2334 			return (B_FALSE);
2335 	}
2336 
2337 	/*
2338 	 * The port is in the same position for struct sockaddr_in and
2339 	 * struct sockaddr_in6.  We exploit that property here.
2340 	 */
2341 	if ((pprefix != NULL) && (sin->sin_port != 0))
2342 		(void) fprintf(ofile, " %s %d", pprefix, ntohs(sin->sin_port));
2343 
2344 	return (B_TRUE);
2345 }
2346 
2347 /*
2348  * Print save information for a key extension. Returns whether writing
2349  * to the specified output file was successful or not.
2350  */
2351 boolean_t
2352 save_key(struct sadb_key *key, FILE *ofile)
2353 {
2354 	char *prefix;
2355 
2356 	if (putc('\t', ofile) == EOF)
2357 		return (B_FALSE);
2358 
2359 	prefix = (key->sadb_key_exttype == SADB_EXT_KEY_AUTH) ? "auth" : "encr";
2360 
2361 	if (fprintf(ofile, "%skey ", prefix) < 0)
2362 		return (B_FALSE);
2363 
2364 	if (dump_key((uint8_t *)(key + 1), key->sadb_key_bits, ofile) == -1)
2365 		return (B_FALSE);
2366 
2367 	return (B_TRUE);
2368 }
2369 
2370 /*
2371  * Print save information for an identity extension.
2372  */
2373 boolean_t
2374 save_ident(struct sadb_ident *ident, FILE *ofile)
2375 {
2376 	char *prefix;
2377 
2378 	if (putc('\t', ofile) == EOF)
2379 		return (B_FALSE);
2380 
2381 	prefix = (ident->sadb_ident_exttype == SADB_EXT_IDENTITY_SRC) ? "src" :
2382 	    "dst";
2383 
2384 	if (fprintf(ofile, "%sidtype %s ", prefix,
2385 	    rparseidtype(ident->sadb_ident_type)) < 0)
2386 		return (B_FALSE);
2387 
2388 	if (ident->sadb_ident_type == SADB_X_IDENTTYPE_DN ||
2389 	    ident->sadb_ident_type == SADB_X_IDENTTYPE_GN) {
2390 		if (fprintf(ofile, dgettext(TEXT_DOMAIN,
2391 		    "<can-not-print>")) < 0)
2392 			return (B_FALSE);
2393 	} else {
2394 		if (fprintf(ofile, "%s", (char *)(ident + 1)) < 0)
2395 			return (B_FALSE);
2396 	}
2397 
2398 	return (B_TRUE);
2399 }
2400 
2401 /*
2402  * "Save" a security association to an output file.
2403  *
2404  * NOTE the lack of calls to dgettext() because I'm outputting parseable stuff.
2405  * ALSO NOTE that if you change keywords (see parsecmd()), you'll have to
2406  * change them here as well.
2407  */
2408 void
2409 save_assoc(uint64_t *buffer, FILE *ofile)
2410 {
2411 	int terrno;
2412 	int seen_proto = 0;
2413 	uint64_t *current;
2414 	struct sadb_address *addr;
2415 	struct sadb_msg *samsg = (struct sadb_msg *)buffer;
2416 	struct sadb_ext *ext;
2417 
2418 #define	tidyup() \
2419 	terrno = errno; (void) fclose(ofile); errno = terrno; \
2420 	interactive = B_FALSE
2421 
2422 #define	savenl() if (fputs(" \\\n", ofile) == EOF) \
2423 	{ bail(dgettext(TEXT_DOMAIN, "savenl")); }
2424 
2425 	if (fputs("# begin assoc\n", ofile) == EOF)
2426 		bail(dgettext(TEXT_DOMAIN,
2427 		    "save_assoc: Opening comment of SA"));
2428 	if (fprintf(ofile, "add %s ", rparsesatype(samsg->sadb_msg_satype)) < 0)
2429 		bail(dgettext(TEXT_DOMAIN, "save_assoc: First line of SA"));
2430 	savenl();
2431 
2432 	current = (uint64_t *)(samsg + 1);
2433 	while (current - buffer < samsg->sadb_msg_len) {
2434 		struct sadb_sa *assoc;
2435 
2436 		ext = (struct sadb_ext *)current;
2437 		switch (ext->sadb_ext_type) {
2438 		case SADB_EXT_SA:
2439 			assoc = (struct sadb_sa *)ext;
2440 			if (assoc->sadb_sa_state != SADB_SASTATE_MATURE) {
2441 				if (fprintf(ofile, "# WARNING: SA was dying "
2442 				    "or dead.\n") < 0) {
2443 					tidyup();
2444 					bail(dgettext(TEXT_DOMAIN,
2445 					    "save_assoc: fprintf not mature"));
2446 				}
2447 			}
2448 			if (fprintf(ofile, "    spi 0x%x ",
2449 			    ntohl(assoc->sadb_sa_spi)) < 0) {
2450 				tidyup();
2451 				bail(dgettext(TEXT_DOMAIN,
2452 				    "save_assoc: fprintf spi"));
2453 			}
2454 			if (assoc->sadb_sa_encrypt != SADB_EALG_NONE) {
2455 				if (fprintf(ofile, "encr_alg %s ",
2456 				    rparsealg(assoc->sadb_sa_encrypt,
2457 				    IPSEC_PROTO_ESP)) < 0) {
2458 					tidyup();
2459 					bail(dgettext(TEXT_DOMAIN,
2460 					    "save_assoc: fprintf encrypt"));
2461 				}
2462 			}
2463 			if (assoc->sadb_sa_auth != SADB_AALG_NONE) {
2464 				if (fprintf(ofile, "auth_alg %s ",
2465 				    rparsealg(assoc->sadb_sa_auth,
2466 				    IPSEC_PROTO_AH)) < 0) {
2467 					tidyup();
2468 					bail(dgettext(TEXT_DOMAIN,
2469 					    "save_assoc: fprintf auth"));
2470 				}
2471 			}
2472 			if (fprintf(ofile, "replay %d ",
2473 			    assoc->sadb_sa_replay) < 0) {
2474 				tidyup();
2475 				bail(dgettext(TEXT_DOMAIN,
2476 				    "save_assoc: fprintf replay"));
2477 			}
2478 			if (assoc->sadb_sa_flags & (SADB_X_SAFLAGS_NATT_LOC |
2479 			    SADB_X_SAFLAGS_NATT_REM)) {
2480 				if (fprintf(ofile, "encap udp") < 0) {
2481 					tidyup();
2482 					bail(dgettext(TEXT_DOMAIN,
2483 					    "save_assoc: fprintf encap"));
2484 				}
2485 			}
2486 			savenl();
2487 			break;
2488 		case SADB_EXT_LIFETIME_HARD:
2489 		case SADB_EXT_LIFETIME_SOFT:
2490 			if (!save_lifetime((struct sadb_lifetime *)ext,
2491 			    ofile)) {
2492 				tidyup();
2493 				bail(dgettext(TEXT_DOMAIN, "save_lifetime"));
2494 			}
2495 			savenl();
2496 			break;
2497 		case SADB_EXT_ADDRESS_SRC:
2498 		case SADB_EXT_ADDRESS_DST:
2499 		case SADB_X_EXT_ADDRESS_INNER_SRC:
2500 		case SADB_X_EXT_ADDRESS_INNER_DST:
2501 		case SADB_X_EXT_ADDRESS_NATT_REM:
2502 		case SADB_X_EXT_ADDRESS_NATT_LOC:
2503 			addr = (struct sadb_address *)ext;
2504 			if (!seen_proto && addr->sadb_address_proto) {
2505 				(void) fprintf(ofile, "    proto %d",
2506 				    addr->sadb_address_proto);
2507 				savenl();
2508 				seen_proto = 1;
2509 			}
2510 			if (!save_address(addr, ofile)) {
2511 				tidyup();
2512 				bail(dgettext(TEXT_DOMAIN, "save_address"));
2513 			}
2514 			savenl();
2515 			break;
2516 		case SADB_EXT_KEY_AUTH:
2517 		case SADB_EXT_KEY_ENCRYPT:
2518 			if (!save_key((struct sadb_key *)ext, ofile)) {
2519 				tidyup();
2520 				bail(dgettext(TEXT_DOMAIN, "save_address"));
2521 			}
2522 			savenl();
2523 			break;
2524 		case SADB_EXT_IDENTITY_SRC:
2525 		case SADB_EXT_IDENTITY_DST:
2526 			if (!save_ident((struct sadb_ident *)ext, ofile)) {
2527 				tidyup();
2528 				bail(dgettext(TEXT_DOMAIN, "save_address"));
2529 			}
2530 			savenl();
2531 			break;
2532 		case SADB_EXT_SENSITIVITY:
2533 		default:
2534 			/* Skip over irrelevant extensions. */
2535 			break;
2536 		}
2537 		current += ext->sadb_ext_len;
2538 	}
2539 
2540 	if (fputs(dgettext(TEXT_DOMAIN, "\n# end assoc\n\n"), ofile) == EOF) {
2541 		tidyup();
2542 		bail(dgettext(TEXT_DOMAIN, "save_assoc: last fputs"));
2543 	}
2544 }
2545 
2546 /*
2547  * Open the output file for the "save" command.
2548  */
2549 FILE *
2550 opensavefile(char *filename)
2551 {
2552 	int fd;
2553 	FILE *retval;
2554 	struct stat buf;
2555 
2556 	/*
2557 	 * If the user specifies "-" or doesn't give a filename, then
2558 	 * dump to stdout.  Make sure to document the dangers of files
2559 	 * that are NFS, directing your output to strange places, etc.
2560 	 */
2561 	if (filename == NULL || strcmp("-", filename) == 0)
2562 		return (stdout);
2563 
2564 	/*
2565 	 * open the file with the create bits set.  Since I check for
2566 	 * real UID == root in main(), I won't worry about the ownership
2567 	 * problem.
2568 	 */
2569 	fd = open(filename, O_WRONLY | O_EXCL | O_CREAT | O_TRUNC, S_IRUSR);
2570 	if (fd == -1) {
2571 		if (errno != EEXIST)
2572 			bail_msg("%s %s: %s", filename, dgettext(TEXT_DOMAIN,
2573 			    "open error"),
2574 			    strerror(errno));
2575 		fd = open(filename, O_WRONLY | O_TRUNC, 0);
2576 		if (fd == -1)
2577 			bail_msg("%s %s: %s", filename, dgettext(TEXT_DOMAIN,
2578 			    "open error"), strerror(errno));
2579 		if (fstat(fd, &buf) == -1) {
2580 			(void) close(fd);
2581 			bail_msg("%s fstat: %s", filename, strerror(errno));
2582 		}
2583 		if (S_ISREG(buf.st_mode) &&
2584 		    ((buf.st_mode & S_IAMB) != S_IRUSR)) {
2585 			warnx(dgettext(TEXT_DOMAIN,
2586 			    "WARNING: Save file already exists with "
2587 			    "permission %o."), buf.st_mode & S_IAMB);
2588 			warnx(dgettext(TEXT_DOMAIN,
2589 			    "Normal users may be able to read IPsec "
2590 			    "keying material."));
2591 		}
2592 	}
2593 
2594 	/* Okay, we have an FD.  Assign it to a stdio FILE pointer. */
2595 	retval = fdopen(fd, "w");
2596 	if (retval == NULL) {
2597 		(void) close(fd);
2598 		bail_msg("%s %s: %s", filename, dgettext(TEXT_DOMAIN,
2599 		    "fdopen error"), strerror(errno));
2600 	}
2601 	return (retval);
2602 }
2603 
2604 const char *
2605 do_inet_ntop(const void *addr, char *cp, size_t size)
2606 {
2607 	boolean_t isv4;
2608 	struct in6_addr *inaddr6 = (struct in6_addr *)addr;
2609 	struct in_addr inaddr;
2610 
2611 	if ((isv4 = IN6_IS_ADDR_V4MAPPED(inaddr6)) == B_TRUE) {
2612 		IN6_V4MAPPED_TO_INADDR(inaddr6, &inaddr);
2613 	}
2614 
2615 	return (inet_ntop(isv4 ? AF_INET : AF_INET6,
2616 	    isv4 ? (void *)&inaddr : inaddr6, cp, size));
2617 }
2618 
2619 char numprint[NBUF_SIZE];
2620 
2621 /*
2622  * Parse and reverse parse a specific SA type (AH, ESP, etc.).
2623  */
2624 static struct typetable {
2625 	char *type;
2626 	int token;
2627 } type_table[] = {
2628 	{"all", SADB_SATYPE_UNSPEC},
2629 	{"ah",  SADB_SATYPE_AH},
2630 	{"esp", SADB_SATYPE_ESP},
2631 	/* PF_KEY NOTE:  More to come if net/pfkeyv2.h gets updated. */
2632 	{NULL, 0}	/* Token value is irrelevant for this entry. */
2633 };
2634 
2635 char *
2636 rparsesatype(int type)
2637 {
2638 	struct typetable *tt = type_table;
2639 
2640 	while (tt->type != NULL && type != tt->token)
2641 		tt++;
2642 
2643 	if (tt->type == NULL) {
2644 		(void) snprintf(numprint, NBUF_SIZE, "%d", type);
2645 	} else {
2646 		return (tt->type);
2647 	}
2648 
2649 	return (numprint);
2650 }
2651 
2652 
2653 /*
2654  * Return a string containing the name of the specified numerical algorithm
2655  * identifier.
2656  */
2657 char *
2658 rparsealg(uint8_t alg, int proto_num)
2659 {
2660 	static struct ipsecalgent *holder = NULL; /* we're single-threaded */
2661 
2662 	if (holder != NULL)
2663 		freeipsecalgent(holder);
2664 
2665 	holder = getipsecalgbynum(alg, proto_num, NULL);
2666 	if (holder == NULL) {
2667 		(void) snprintf(numprint, NBUF_SIZE, "%d", alg);
2668 		return (numprint);
2669 	}
2670 
2671 	return (*(holder->a_names));
2672 }
2673 
2674 /*
2675  * Parse and reverse parse out a source/destination ID type.
2676  */
2677 static struct idtypes {
2678 	char *idtype;
2679 	uint8_t retval;
2680 } idtypes[] = {
2681 	{"prefix",	SADB_IDENTTYPE_PREFIX},
2682 	{"fqdn",	SADB_IDENTTYPE_FQDN},
2683 	{"domain",	SADB_IDENTTYPE_FQDN},
2684 	{"domainname",	SADB_IDENTTYPE_FQDN},
2685 	{"user_fqdn",	SADB_IDENTTYPE_USER_FQDN},
2686 	{"mailbox",	SADB_IDENTTYPE_USER_FQDN},
2687 	{"der_dn",	SADB_X_IDENTTYPE_DN},
2688 	{"der_gn",	SADB_X_IDENTTYPE_GN},
2689 	{NULL,		0}
2690 };
2691 
2692 char *
2693 rparseidtype(uint16_t type)
2694 {
2695 	struct idtypes *idp;
2696 
2697 	for (idp = idtypes; idp->idtype != NULL; idp++) {
2698 		if (type == idp->retval)
2699 			return (idp->idtype);
2700 	}
2701 
2702 	(void) snprintf(numprint, NBUF_SIZE, "%d", type);
2703 	return (numprint);
2704 }
2705 
2706 /*
2707  * This is a general purpose exit function, calling functions can specify an
2708  * error type. If the command calling this function was started by smf(5) the
2709  * error type could be used as a hint to the restarter. In the future this
2710  * function could be used to do something more intelligent with a process that
2711  * encounters an error.
2712  *
2713  * The function will handle an optional variable args error message, this
2714  * will be written to the error stream, typically a log file or stderr.
2715  */
2716 void
2717 ipsecutil_exit(exit_type_t type, char *fmri, FILE *fp, const char *fmt, ...)
2718 {
2719 	int exit_status;
2720 	va_list args;
2721 
2722 	if (fp == NULL)
2723 		fp = stderr;
2724 	if (fmt != NULL) {
2725 		va_start(args, fmt);
2726 		vwarnxfp(fp, fmt, args);
2727 		va_end(args);
2728 	}
2729 
2730 	if (fmri == NULL) {
2731 		/* Command being run directly from a shell. */
2732 		switch (type) {
2733 		case SERVICE_EXIT_OK:
2734 			exit_status = 0;
2735 			break;
2736 		case SERVICE_DEGRADE:
2737 			return;
2738 			break;
2739 		case SERVICE_BADPERM:
2740 		case SERVICE_BADCONF:
2741 		case SERVICE_MAINTAIN:
2742 		case SERVICE_DISABLE:
2743 		case SERVICE_FATAL:
2744 		case SERVICE_RESTART:
2745 			warnxfp(fp, "Fatal error - exiting.");
2746 			exit_status = 1;
2747 			break;
2748 		}
2749 	} else {
2750 		/* Command being run as a smf(5) method. */
2751 		switch (type) {
2752 		case SERVICE_EXIT_OK:
2753 			exit_status = SMF_EXIT_OK;
2754 			break;
2755 		case SERVICE_DEGRADE:
2756 			return;
2757 			break;
2758 		case SERVICE_BADPERM:
2759 			warnxfp(fp, dgettext(TEXT_DOMAIN,
2760 			    "Permission error with %s."), fmri);
2761 			exit_status = SMF_EXIT_ERR_PERM;
2762 			break;
2763 		case SERVICE_BADCONF:
2764 			warnxfp(fp, dgettext(TEXT_DOMAIN,
2765 			    "Bad configuration of service %s."), fmri);
2766 			exit_status = SMF_EXIT_ERR_FATAL;
2767 			break;
2768 		case SERVICE_MAINTAIN:
2769 			warnxfp(fp, dgettext(TEXT_DOMAIN,
2770 			    "Service %s needs maintenance."), fmri);
2771 			exit_status = SMF_EXIT_ERR_FATAL;
2772 			break;
2773 		case SERVICE_DISABLE:
2774 			exit_status = SMF_EXIT_ERR_FATAL;
2775 			break;
2776 		case SERVICE_FATAL:
2777 			warnxfp(fp, dgettext(TEXT_DOMAIN,
2778 			    "Service %s fatal error."), fmri);
2779 			exit_status = SMF_EXIT_ERR_FATAL;
2780 			break;
2781 		case SERVICE_RESTART:
2782 			exit_status = 1;
2783 			break;
2784 		}
2785 	}
2786 	(void) fflush(fp);
2787 	(void) fclose(fp);
2788 	exit(exit_status);
2789 }
2790