xref: /illumos-gate/usr/src/lib/libipsecutil/common/ipsec_util.c (revision 8119dad84d6416f13557b0ba8e2aaf9064cbcfd3)
1 /*
2  *
3  * CDDL HEADER START
4  *
5  * The contents of this file are subject to the terms of the
6  * Common Development and Distribution License (the "License").
7  * You may not use this file except in compliance with the License.
8  *
9  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10  * or http://www.opensolaris.org/os/licensing.
11  * See the License for the specific language governing permissions
12  * and limitations under the License.
13  *
14  * When distributing Covered Code, include this CDDL HEADER in each
15  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16  * If applicable, add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your own identifying
18  * information: Portions Copyright [yyyy] [name of copyright owner]
19  *
20  * CDDL HEADER END
21  */
22 /*
23  * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  * Copyright 2012 Milan Juri. All rights reserved.
26  * Copyright 2018 Joyent, Inc.
27  * Copyright 2018 OmniOS Community Edition (OmniOSce) Association.
28  * Copyright 2024 Oxide Computer Company
29  */
30 
31 #include <unistd.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <stdarg.h>
35 #include <sys/types.h>
36 #include <sys/stat.h>
37 #include <fcntl.h>
38 #include <sys/sysconf.h>
39 #include <strings.h>
40 #include <ctype.h>
41 #include <errno.h>
42 #include <sys/socket.h>
43 #include <netdb.h>
44 #include <netinet/in.h>
45 #include <arpa/inet.h>
46 #include <net/pfkeyv2.h>
47 #include <net/pfpolicy.h>
48 #include <libintl.h>
49 #include <setjmp.h>
50 #include <libgen.h>
51 #include <libscf.h>
52 #include <kmfapi.h>
53 #include <ber_der.h>
54 
55 #include "ipsec_util.h"
56 #include "ikedoor.h"
57 
58 /*
59  * This file contains support functions that are shared by the ipsec
60  * utilities and daemons including ipseckey(8), ikeadm(8) and in.iked(8).
61  */
62 
63 
64 #define	EFD(file) (((file) == stdout) ? stderr : (file))
65 
66 /* Limits for interactive mode. */
67 #define	MAX_LINE_LEN	IBUF_SIZE
68 #define	MAX_CMD_HIST	64000	/* in bytes */
69 
70 /* Set standard default/initial values for globals... */
71 boolean_t pflag = B_FALSE;	/* paranoid w.r.t. printing keying material */
72 boolean_t nflag = B_FALSE;	/* avoid nameservice? */
73 boolean_t interactive = B_FALSE;	/* util not running on cmdline */
74 boolean_t readfile = B_FALSE;	/* cmds are being read from a file */
75 uint_t	lineno = 0;		/* track location if reading cmds from file */
76 uint_t	lines_added = 0;
77 uint_t	lines_parsed = 0;
78 jmp_buf	env;		/* for error recovery in interactive/readfile modes */
79 char *my_fmri = NULL;
80 FILE *debugfile = stderr;
81 static GetLine *gl = NULL;	/* for interactive mode */
82 
83 /*
84  * Print errno and exit if cmdline or readfile, reset state if interactive
85  * The error string *what should be dgettext()'d before calling bail().
86  */
87 void
88 bail(char *what)
89 {
90 	if (errno != 0)
91 		warn(what);
92 	else
93 		warnx(dgettext(TEXT_DOMAIN, "Error: %s"), what);
94 	if (readfile) {
95 		return;
96 	}
97 	if (interactive && !readfile)
98 		longjmp(env, 2);
99 	EXIT_FATAL(NULL);
100 }
101 
102 /*
103  * Print caller-supplied variable-arg error msg, then exit if cmdline or
104  * readfile, or reset state if interactive.
105  */
106 /*PRINTFLIKE1*/
107 void
108 bail_msg(char *fmt, ...)
109 {
110 	va_list	ap;
111 	char	msgbuf[BUFSIZ];
112 
113 	va_start(ap, fmt);
114 	(void) vsnprintf(msgbuf, BUFSIZ, fmt, ap);
115 	va_end(ap);
116 	if (readfile)
117 		warnx(dgettext(TEXT_DOMAIN,
118 		    "ERROR on line %u:\n%s\n"), lineno,  msgbuf);
119 	else
120 		warnx(dgettext(TEXT_DOMAIN, "ERROR: %s\n"), msgbuf);
121 
122 	if (interactive && !readfile)
123 		longjmp(env, 1);
124 
125 	EXIT_FATAL(NULL);
126 }
127 
128 /*
129  * bytecnt2str() wrapper. Zeroes out the input buffer and if the number
130  * of bytes to be converted is more than 1K, it will produce readable string
131  * in parentheses, store it in the original buffer and return the pointer to it.
132  * Maximum length of the returned string is 14 characters (not including
133  * the terminating zero).
134  */
135 char *
136 bytecnt2out(uint64_t num, char *buf, size_t bufsiz, int flags)
137 {
138 	char *str;
139 
140 	(void) memset(buf, '\0', bufsiz);
141 
142 	if (num > 1024) {
143 		/* Return empty string in case of out-of-memory. */
144 		if ((str = malloc(bufsiz)) == NULL)
145 			return (buf);
146 
147 		(void) bytecnt2str(num, str, bufsiz);
148 		/* Detect overflow. */
149 		if (strlen(str) == 0) {
150 			free(str);
151 			return (buf);
152 		}
153 
154 		/* Emit nothing in case of overflow. */
155 		if (snprintf(buf, bufsiz, "%s(%sB)%s",
156 		    flags & SPC_BEGIN ? " " : "", str,
157 		    flags & SPC_END ? " " : "") >= bufsiz)
158 			(void) memset(buf, '\0', bufsiz);
159 
160 		free(str);
161 	}
162 
163 	return (buf);
164 }
165 
166 /*
167  * Convert 64-bit number to human readable string. Useful mainly for the
168  * byte lifetime counters. Returns pointer to the user supplied buffer.
169  * Able to convert up to Exabytes. Maximum length of the string produced
170  * is 9 characters (not counting the terminating zero).
171  */
172 char *
173 bytecnt2str(uint64_t num, char *buf, size_t buflen)
174 {
175 	uint64_t n = num;
176 	char u;
177 	int index = 0;
178 
179 	while (n >= 1024) {
180 		n /= 1024;
181 		index++;
182 	}
183 
184 	/* The field has all units this function can represent. */
185 	u = " KMGTPE"[index];
186 
187 	if (index == 0) {
188 		/* Less than 1K */
189 		if (snprintf(buf, buflen, "%llu ", num) >= buflen)
190 			(void) memset(buf, '\0', buflen);
191 	} else {
192 		/* Otherwise display 2 precision digits. */
193 		if (snprintf(buf, buflen, "%.2f %c",
194 		    (double)num / (1ULL << index * 10), u) >= buflen)
195 			(void) memset(buf, '\0', buflen);
196 	}
197 
198 	return (buf);
199 }
200 
201 /*
202  * secs2str() wrapper. Zeroes out the input buffer and if the number of
203  * seconds to be converted is more than minute, it will produce readable
204  * string in parentheses, store it in the original buffer and return the
205  * pointer to it.
206  */
207 char *
208 secs2out(unsigned int secs, char *buf, int bufsiz, int flags)
209 {
210 	char *str;
211 
212 	(void) memset(buf, '\0', bufsiz);
213 
214 	if (secs > 60) {
215 		/* Return empty string in case of out-of-memory. */
216 		if ((str = malloc(bufsiz)) == NULL)
217 			return (buf);
218 
219 		(void) secs2str(secs, str, bufsiz);
220 		/* Detect overflow. */
221 		if (strlen(str) == 0) {
222 			free(str);
223 			return (buf);
224 		}
225 
226 		/* Emit nothing in case of overflow. */
227 		if (snprintf(buf, bufsiz, "%s(%s)%s",
228 		    flags & SPC_BEGIN ? " " : "", str,
229 		    flags & SPC_END ? " " : "") >= bufsiz)
230 			(void) memset(buf, '\0', bufsiz);
231 
232 		free(str);
233 	}
234 
235 	return (buf);
236 }
237 
238 /*
239  * Convert number of seconds to human readable string. Useful mainly for
240  * the lifetime counters. Returns pointer to the user supplied buffer.
241  * Able to convert up to days.
242  */
243 char *
244 secs2str(unsigned int secs, char *buf, int bufsiz)
245 {
246 	double val = secs;
247 	char *unit = "second";
248 
249 	if (val >= 24*60*60) {
250 		val /= 86400;
251 		unit = "day";
252 	} else if (val >= 60*60) {
253 		val /= 60*60;
254 		unit = "hour";
255 	} else if (val >= 60) {
256 		val /= 60;
257 		unit = "minute";
258 	}
259 
260 	/* Emit nothing in case of overflow. */
261 	if (snprintf(buf, bufsiz, "%.2f %s%s", val, unit,
262 	    val >= 2 ? "s" : "") >= bufsiz)
263 		(void) memset(buf, '\0', bufsiz);
264 
265 	return (buf);
266 }
267 
268 /*
269  * dump_XXX functions produce ASCII output from various structures.
270  *
271  * Because certain errors need to do this to stderr, dump_XXX functions
272  * take a FILE pointer.
273  *
274  * If an error occured while writing to the specified file, these
275  * functions return -1, zero otherwise.
276  */
277 
278 int
279 dump_sockaddr(struct sockaddr *sa, uint8_t prefixlen, boolean_t addr_only,
280     FILE *where, boolean_t ignore_nss)
281 {
282 	struct sockaddr_in	*sin;
283 	struct sockaddr_in6	*sin6;
284 	char			*printable_addr, *protocol;
285 	uint8_t			*addrptr;
286 	/* Add 4 chars to hold '/nnn' for prefixes. */
287 	char			storage[INET6_ADDRSTRLEN + 4];
288 	uint16_t		port;
289 	boolean_t		unspec;
290 	struct hostent		*hp;
291 	int			getipnode_errno, addrlen;
292 
293 	switch (sa->sa_family) {
294 	case AF_INET:
295 		/* LINTED E_BAD_PTR_CAST_ALIGN */
296 		sin = (struct sockaddr_in *)sa;
297 		addrptr = (uint8_t *)&sin->sin_addr;
298 		port = sin->sin_port;
299 		protocol = "AF_INET";
300 		unspec = (sin->sin_addr.s_addr == 0);
301 		addrlen = sizeof (sin->sin_addr);
302 		break;
303 	case AF_INET6:
304 		/* LINTED E_BAD_PTR_CAST_ALIGN */
305 		sin6 = (struct sockaddr_in6 *)sa;
306 		addrptr = (uint8_t *)&sin6->sin6_addr;
307 		port = sin6->sin6_port;
308 		protocol = "AF_INET6";
309 		unspec = IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr);
310 		addrlen = sizeof (sin6->sin6_addr);
311 		break;
312 	default:
313 		return (0);
314 	}
315 
316 	if (inet_ntop(sa->sa_family, addrptr, storage, INET6_ADDRSTRLEN) ==
317 	    NULL) {
318 		printable_addr = dgettext(TEXT_DOMAIN, "Invalid IP address.");
319 	} else {
320 		char prefix[5];	/* "/nnn" with terminator. */
321 
322 		(void) snprintf(prefix, sizeof (prefix), "/%d", prefixlen);
323 		printable_addr = storage;
324 		if (prefixlen != 0) {
325 			(void) strlcat(printable_addr, prefix,
326 			    sizeof (storage));
327 		}
328 	}
329 	if (addr_only) {
330 		if (fprintf(where, "%s", printable_addr) < 0)
331 			return (-1);
332 	} else {
333 		if (fprintf(where, dgettext(TEXT_DOMAIN,
334 		    "%s: port %d, %s"), protocol,
335 		    ntohs(port), printable_addr) < 0)
336 			return (-1);
337 		if (ignore_nss == B_FALSE) {
338 			/*
339 			 * Do AF_independent reverse hostname lookup here.
340 			 */
341 			if (unspec) {
342 				if (fprintf(where,
343 				    dgettext(TEXT_DOMAIN,
344 				    " <unspecified>")) < 0)
345 					return (-1);
346 			} else {
347 				hp = getipnodebyaddr((char *)addrptr, addrlen,
348 				    sa->sa_family, &getipnode_errno);
349 				if (hp != NULL) {
350 					if (fprintf(where,
351 					    " (%s)", hp->h_name) < 0)
352 						return (-1);
353 					freehostent(hp);
354 				} else {
355 					if (fprintf(where,
356 					    dgettext(TEXT_DOMAIN,
357 					    " <unknown>")) < 0)
358 						return (-1);
359 				}
360 			}
361 		}
362 		if (fputs(".\n", where) == EOF)
363 			return (-1);
364 	}
365 	return (0);
366 }
367 
368 /*
369  * Dump a key, any salt and bitlen.
370  * The key is made up of a stream of bits. If the algorithm requires a salt
371  * value, this will also be part of the dumped key. The last "saltbits" of the
372  * key string, reading left to right will be the salt value. To make it easier
373  * to see which bits make up the key, the salt value is enclosed in []'s.
374  * This function can also be called when ipseckey(8) -s is run, this "saves"
375  * the SAs, including the key to a file. When this is the case, the []'s are
376  * not printed.
377  *
378  * The implementation allows the kernel to be told about the length of the salt
379  * in whole bytes only. If this changes, this function will need to be updated.
380  */
381 int
382 dump_key(uint8_t *keyp, uint_t bitlen, uint_t saltbits, FILE *where,
383     boolean_t separate_salt)
384 {
385 	int	numbytes, saltbytes;
386 
387 	numbytes = SADB_1TO8(bitlen);
388 	saltbytes = SADB_1TO8(saltbits);
389 	numbytes += saltbytes;
390 
391 	/* The & 0x7 is to check for leftover bits. */
392 	if ((bitlen & 0x7) != 0)
393 		numbytes++;
394 
395 	while (numbytes-- != 0) {
396 		if (pflag) {
397 			/* Print no keys if paranoid */
398 			if (fprintf(where, "XX") < 0)
399 				return (-1);
400 		} else {
401 			if (fprintf(where, "%02x", *keyp++) < 0)
402 				return (-1);
403 		}
404 		if (separate_salt && saltbytes != 0 &&
405 		    numbytes == saltbytes) {
406 			if (fprintf(where, "[") < 0)
407 				return (-1);
408 		}
409 	}
410 
411 	if (separate_salt && saltbits != 0) {
412 		if (fprintf(where, "]/%u+%u", bitlen, saltbits) < 0)
413 			return (-1);
414 	} else {
415 		if (fprintf(where, "/%u", bitlen + saltbits) < 0)
416 			return (-1);
417 	}
418 
419 	return (0);
420 }
421 
422 int
423 dump_keystr(uint8_t *keystr, uint_t bitlen, FILE *where)
424 {
425 	size_t keylen;
426 	uint_t i;
427 
428 	/* There should be no leftover bits for a key string */
429 	if ((bitlen & 0x7) != 0)
430 		return (-1);
431 
432 	keylen = SADB_1TO8(bitlen);
433 
434 	for (i = 0; i < keylen; i++) {
435 		if (pflag)
436 			(void) fprintf(where, "XX");
437 		else if (isprint(keystr[i]))
438 			(void) fprintf(where, "%c", keystr[i]);
439 		else
440 			(void) fprintf(where, "\\x%x", keystr[i]);
441 	}
442 
443 	return (0);
444 }
445 
446 
447 static struct tcpsigalg {
448 	uint8_t ta_value;
449 	const char *ta_name;
450 } tcpalgs[] = {
451 	{ .ta_name = "md5", .ta_value = SADB_AALG_MD5 }
452 };
453 
454 uint8_t
455 gettcpsigalgbyname(const char *name)
456 {
457 	uint_t i;
458 
459 	for (i = 0; i < ARRAY_SIZE(tcpalgs); i++) {
460 		if (strcmp(name, tcpalgs[i].ta_name) == 0)
461 			return (tcpalgs[i].ta_value);
462 	}
463 	return (0);
464 }
465 
466 const char *
467 gettcpsigalgbynum(uint8_t num)
468 {
469 	uint_t i;
470 
471 	for (i = 0; i < ARRAY_SIZE(tcpalgs); i++) {
472 		if (num == tcpalgs[i].ta_value)
473 			return (tcpalgs[i].ta_name);
474 	}
475 	return (NULL);
476 }
477 
478 /*
479  * Print an authentication or encryption algorithm
480  */
481 static int
482 dump_generic_alg(uint8_t alg_num, int proto_num, FILE *where)
483 {
484 	struct ipsecalgent *alg;
485 
486 	alg = getipsecalgbynum(alg_num, proto_num, NULL);
487 	if (alg == NULL) {
488 		if (fprintf(where, dgettext(TEXT_DOMAIN,
489 		    "<unknown %u>"), alg_num) < 0)
490 			return (-1);
491 		return (0);
492 	}
493 
494 	/*
495 	 * Special-case <none> for backward output compat.
496 	 * Assume that SADB_AALG_NONE == SADB_EALG_NONE.
497 	 */
498 	if (alg_num == SADB_AALG_NONE) {
499 		if (fputs(dgettext(TEXT_DOMAIN,
500 		    "<none>"), where) == EOF)
501 			return (-1);
502 	} else {
503 		if (fputs(alg->a_names[0], where) == EOF)
504 			return (-1);
505 	}
506 
507 	freeipsecalgent(alg);
508 	return (0);
509 }
510 
511 int
512 dump_aalg(uint8_t aalg, FILE *where)
513 {
514 	return (dump_generic_alg(aalg, IPSEC_PROTO_AH, where));
515 }
516 
517 int
518 dump_ealg(uint8_t ealg, FILE *where)
519 {
520 	return (dump_generic_alg(ealg, IPSEC_PROTO_ESP, where));
521 }
522 
523 int
524 dump_tcpsigalg(uint8_t aalg, FILE *where)
525 {
526 	const char *name = gettcpsigalgbynum(aalg);
527 
528 	if (name == NULL) {
529 		if (fprintf(where, dgettext(TEXT_DOMAIN,
530 		    "<unknown %u>"), aalg) < 0) {
531 			return (-1);
532 		}
533 		return (0);
534 	}
535 
536 	if (fputs(name, where) == EOF)
537 		return (-1);
538 
539 	return (0);
540 }
541 
542 /*
543  * Print an SADB_IDENTTYPE string
544  *
545  * Also return TRUE if the actual ident may be printed, FALSE if not.
546  *
547  * If rc is not NULL, set its value to -1 if an error occured while writing
548  * to the specified file, zero otherwise.
549  */
550 boolean_t
551 dump_sadb_idtype(uint8_t idtype, FILE *where, int *rc)
552 {
553 	boolean_t canprint = B_TRUE;
554 	int rc_val = 0;
555 
556 	switch (idtype) {
557 	case SADB_IDENTTYPE_PREFIX:
558 		if (fputs(dgettext(TEXT_DOMAIN, "prefix"), where) == EOF)
559 			rc_val = -1;
560 		break;
561 	case SADB_IDENTTYPE_FQDN:
562 		if (fputs(dgettext(TEXT_DOMAIN, "FQDN"), where) == EOF)
563 			rc_val = -1;
564 		break;
565 	case SADB_IDENTTYPE_USER_FQDN:
566 		if (fputs(dgettext(TEXT_DOMAIN,
567 		    "user-FQDN (mbox)"), where) == EOF)
568 			rc_val = -1;
569 		break;
570 	case SADB_X_IDENTTYPE_DN:
571 		if (fputs(dgettext(TEXT_DOMAIN, "ASN.1 DER Distinguished Name"),
572 		    where) == EOF)
573 			rc_val = -1;
574 		canprint = B_FALSE;
575 		break;
576 	case SADB_X_IDENTTYPE_GN:
577 		if (fputs(dgettext(TEXT_DOMAIN, "ASN.1 DER Generic Name"),
578 		    where) == EOF)
579 			rc_val = -1;
580 		canprint = B_FALSE;
581 		break;
582 	case SADB_X_IDENTTYPE_KEY_ID:
583 		if (fputs(dgettext(TEXT_DOMAIN, "Generic key id"),
584 		    where) == EOF)
585 			rc_val = -1;
586 		break;
587 	case SADB_X_IDENTTYPE_ADDR_RANGE:
588 		if (fputs(dgettext(TEXT_DOMAIN, "Address range"), where) == EOF)
589 			rc_val = -1;
590 		break;
591 	default:
592 		if (fprintf(where, dgettext(TEXT_DOMAIN,
593 		    "<unknown %u>"), idtype) < 0)
594 			rc_val = -1;
595 		break;
596 	}
597 
598 	if (rc != NULL)
599 		*rc = rc_val;
600 
601 	return (canprint);
602 }
603 
604 /*
605  * Slice an argv/argc vector from an interactive line or a read-file line.
606  */
607 static int
608 create_argv(char *ibuf, int *newargc, char ***thisargv)
609 {
610 	unsigned int argvlen = START_ARG;
611 	char **current;
612 	boolean_t firstchar = B_TRUE;
613 	boolean_t inquotes = B_FALSE;
614 
615 	*thisargv = malloc(sizeof (char *) * argvlen);
616 	if ((*thisargv) == NULL)
617 		return (MEMORY_ALLOCATION);
618 	current = *thisargv;
619 	*current = NULL;
620 
621 	for (; *ibuf != '\0'; ibuf++) {
622 		if (isspace(*ibuf)) {
623 			if (inquotes) {
624 				continue;
625 			}
626 			if (*current != NULL) {
627 				*ibuf = '\0';
628 				current++;
629 				if (*thisargv + argvlen == current) {
630 					/* Regrow ***thisargv. */
631 					if (argvlen == TOO_MANY_ARGS) {
632 						free(*thisargv);
633 						return (TOO_MANY_TOKENS);
634 					}
635 					/* Double the allocation. */
636 					current = realloc(*thisargv,
637 					    sizeof (char *) * (argvlen << 1));
638 					if (current == NULL) {
639 						free(*thisargv);
640 						return (MEMORY_ALLOCATION);
641 					}
642 					*thisargv = current;
643 					current += argvlen;
644 					argvlen <<= 1;	/* Double the size. */
645 				}
646 				*current = NULL;
647 			}
648 		} else {
649 			if (firstchar) {
650 				firstchar = B_FALSE;
651 				if (*ibuf == COMMENT_CHAR || *ibuf == '\n') {
652 					free(*thisargv);
653 					return (COMMENT_LINE);
654 				}
655 			}
656 			if (*ibuf == QUOTE_CHAR) {
657 				if (inquotes) {
658 					inquotes = B_FALSE;
659 					*ibuf = '\0';
660 				} else {
661 					inquotes = B_TRUE;
662 				}
663 				continue;
664 			}
665 			if (*current == NULL) {
666 				*current = ibuf;
667 				(*newargc)++;
668 			}
669 		}
670 	}
671 
672 	/*
673 	 * Tricky corner case...
674 	 * I've parsed _exactly_ the amount of args as I have space.  It
675 	 * won't return NULL-terminated, and bad things will happen to
676 	 * the caller.
677 	 */
678 	if (argvlen == *newargc) {
679 		current = realloc(*thisargv, sizeof (char *) * (argvlen + 1));
680 		if (current == NULL) {
681 			free(*thisargv);
682 			return (MEMORY_ALLOCATION);
683 		}
684 		*thisargv = current;
685 		current[argvlen] = NULL;
686 	}
687 
688 	return (SUCCESS);
689 }
690 
691 /*
692  * init interactive mode if needed and not yet initialized
693  */
694 static void
695 init_interactive(FILE *infile, CplMatchFn *match_fn)
696 {
697 	if (infile == stdin) {
698 		if (gl == NULL) {
699 			if ((gl = new_GetLine(MAX_LINE_LEN,
700 			    MAX_CMD_HIST)) == NULL)
701 				errx(1, dgettext(TEXT_DOMAIN,
702 				    "tecla initialization failed"));
703 
704 			if (gl_customize_completion(gl, NULL,
705 			    match_fn) != 0) {
706 				(void) del_GetLine(gl);
707 				errx(1, dgettext(TEXT_DOMAIN,
708 				    "tab completion failed to initialize"));
709 			}
710 
711 			/*
712 			 * In interactive mode we only want to terminate
713 			 * when explicitly requested (e.g. by a command).
714 			 */
715 			(void) sigset(SIGINT, SIG_IGN);
716 		}
717 	} else {
718 		readfile = B_TRUE;
719 	}
720 }
721 
722 /*
723  * free tecla data structure
724  */
725 static void
726 fini_interactive(void)
727 {
728 	if (gl != NULL)
729 		(void) del_GetLine(gl);
730 }
731 
732 /*
733  * Get single input line, wrapping around interactive and non-interactive
734  * mode.
735  */
736 static char *
737 do_getstr(FILE *infile, char *prompt, char *ibuf, size_t ibuf_size)
738 {
739 	char	*line;
740 
741 	if (infile != stdin)
742 		return (fgets(ibuf, ibuf_size, infile));
743 
744 	/*
745 	 * If the user hits ^C then we want to catch it and
746 	 * start over.  If the user hits EOF then we want to
747 	 * bail out.
748 	 */
749 once_again:
750 	line = gl_get_line(gl, prompt, NULL, -1);
751 	if (gl_return_status(gl) == GLR_SIGNAL) {
752 		gl_abandon_line(gl);
753 		goto once_again;
754 	} else if (gl_return_status(gl) == GLR_ERROR) {
755 		gl_abandon_line(gl);
756 		errx(1, dgettext(TEXT_DOMAIN, "Error reading terminal: %s\n"),
757 		    gl_error_message(gl, NULL, 0));
758 	} else {
759 		if (line != NULL) {
760 			if (strlcpy(ibuf, line, ibuf_size) >= ibuf_size)
761 				warnx(dgettext(TEXT_DOMAIN,
762 				    "Line too long (max=%d chars)"),
763 				    ibuf_size);
764 			line = ibuf;
765 		}
766 	}
767 
768 	return (line);
769 }
770 
771 /*
772  * Enter a mode where commands are read from a file.  Treat stdin special.
773  */
774 void
775 do_interactive(FILE *infile, char *configfile, char *promptstring,
776     char *my_fmri, parse_cmdln_fn parseit, CplMatchFn *match_fn)
777 {
778 	char		ibuf[IBUF_SIZE], holder[IBUF_SIZE];
779 	char		*volatile hptr, **thisargv, *ebuf;
780 	int		thisargc;
781 	volatile boolean_t	continue_in_progress = B_FALSE;
782 	char		*s;
783 
784 	(void) setjmp(env);
785 
786 	ebuf = NULL;
787 	interactive = B_TRUE;
788 	bzero(ibuf, IBUF_SIZE);
789 
790 	/* panics for us */
791 	init_interactive(infile, match_fn);
792 
793 	while ((s = do_getstr(infile, promptstring, ibuf, IBUF_SIZE)) != NULL) {
794 		if (readfile)
795 			lineno++;
796 		thisargc = 0;
797 		thisargv = NULL;
798 
799 		/*
800 		 * Check byte IBUF_SIZE - 2, because byte IBUF_SIZE - 1 will
801 		 * be null-terminated because of fgets().
802 		 */
803 		if (ibuf[IBUF_SIZE - 2] != '\0') {
804 			if (infile == stdin) {
805 				/* do_getstr() issued a warning already */
806 				bzero(ibuf, IBUF_SIZE);
807 				continue;
808 			} else {
809 				ipsecutil_exit(SERVICE_FATAL, my_fmri,
810 				    debugfile, dgettext(TEXT_DOMAIN,
811 				    "Line %d too big."), lineno);
812 			}
813 		}
814 
815 		if (!continue_in_progress) {
816 			/* Use -2 because of \n from fgets. */
817 			if (ibuf[strlen(ibuf) - 2] == CONT_CHAR) {
818 				/*
819 				 * Can use strcpy here, I've checked the
820 				 * length already.
821 				 */
822 				(void) strcpy(holder, ibuf);
823 				hptr = &(holder[strlen(holder)]);
824 
825 				/* Remove the CONT_CHAR from the string. */
826 				hptr[-2] = ' ';
827 
828 				continue_in_progress = B_TRUE;
829 				bzero(ibuf, IBUF_SIZE);
830 				continue;
831 			}
832 		} else {
833 			/* Handle continuations... */
834 			(void) strncpy(hptr, ibuf,
835 			    (size_t)(&(holder[IBUF_SIZE]) - hptr));
836 			if (holder[IBUF_SIZE - 1] != '\0') {
837 				ipsecutil_exit(SERVICE_FATAL, my_fmri,
838 				    debugfile, dgettext(TEXT_DOMAIN,
839 				    "Command buffer overrun."));
840 			}
841 			/* Use - 2 because of \n from fgets. */
842 			if (hptr[strlen(hptr) - 2] == CONT_CHAR) {
843 				bzero(ibuf, IBUF_SIZE);
844 				hptr += strlen(hptr);
845 
846 				/* Remove the CONT_CHAR from the string. */
847 				hptr[-2] = ' ';
848 
849 				continue;
850 			} else {
851 				continue_in_progress = B_FALSE;
852 				/*
853 				 * I've already checked the length...
854 				 */
855 				(void) strcpy(ibuf, holder);
856 			}
857 		}
858 
859 		/*
860 		 * Just in case the command fails keep a copy of the
861 		 * command buffer for diagnostic output.
862 		 */
863 		if (readfile) {
864 			/*
865 			 * The error buffer needs to be big enough to
866 			 * hold the longest command string, plus
867 			 * some extra text, see below.
868 			 */
869 			ebuf = calloc((IBUF_SIZE * 2), sizeof (char));
870 			if (ebuf == NULL) {
871 				ipsecutil_exit(SERVICE_FATAL, my_fmri,
872 				    debugfile, dgettext(TEXT_DOMAIN,
873 				    "Memory allocation error."));
874 			} else {
875 				(void) snprintf(ebuf, (IBUF_SIZE * 2),
876 				    dgettext(TEXT_DOMAIN,
877 				    "Config file entry near line %u "
878 				    "caused error(s) or warnings:\n\n%s\n\n"),
879 				    lineno, ibuf);
880 			}
881 		}
882 
883 		switch (create_argv(ibuf, &thisargc, &thisargv)) {
884 		case TOO_MANY_TOKENS:
885 			ipsecutil_exit(SERVICE_BADCONF, my_fmri, debugfile,
886 			    dgettext(TEXT_DOMAIN, "Too many input tokens."));
887 			break;
888 		case MEMORY_ALLOCATION:
889 			ipsecutil_exit(SERVICE_BADCONF, my_fmri, debugfile,
890 			    dgettext(TEXT_DOMAIN, "Memory allocation error."));
891 			break;
892 		case COMMENT_LINE:
893 			/* Comment line. */
894 			free(ebuf);
895 			break;
896 		default:
897 			if (thisargc != 0) {
898 				lines_parsed++;
899 				/* ebuf consumed */
900 				parseit(thisargc, thisargv, ebuf, readfile);
901 			} else {
902 				free(ebuf);
903 			}
904 			free(thisargv);
905 			if (infile == stdin) {
906 				(void) printf("%s", promptstring);
907 				(void) fflush(stdout);
908 			}
909 			break;
910 		}
911 		bzero(ibuf, IBUF_SIZE);
912 	}
913 
914 	/*
915 	 * The following code is ipseckey specific. This should never be
916 	 * used by ikeadm which also calls this function because ikeadm
917 	 * only runs interactively. If this ever changes this code block
918 	 * sould be revisited.
919 	 */
920 	if (readfile) {
921 		if (lines_parsed != 0 && lines_added == 0) {
922 			ipsecutil_exit(SERVICE_BADCONF, my_fmri, debugfile,
923 			    dgettext(TEXT_DOMAIN, "Configuration file did not "
924 			    "contain any valid SAs"));
925 		}
926 
927 		/*
928 		 * There were errors. Putting the service in maintenance mode.
929 		 * When svc.startd(8) allows services to degrade themselves,
930 		 * this should be revisited.
931 		 *
932 		 * If this function was called from a program running as a
933 		 * smf_method(7), print a warning message. Don't spew out the
934 		 * errors as these will end up in the smf(7) log file which is
935 		 * publically readable, the errors may contain sensitive
936 		 * information.
937 		 */
938 		if ((lines_added < lines_parsed) && (configfile != NULL)) {
939 			if (my_fmri != NULL) {
940 				ipsecutil_exit(SERVICE_BADCONF, my_fmri,
941 				    debugfile, dgettext(TEXT_DOMAIN,
942 				    "The configuration file contained %d "
943 				    "errors.\n"
944 				    "Manually check the configuration with:\n"
945 				    "ipseckey -c %s\n"
946 				    "Use svcadm(8) to clear maintenance "
947 				    "condition when errors are resolved.\n"),
948 				    lines_parsed - lines_added, configfile);
949 			} else {
950 				EXIT_BADCONFIG(NULL);
951 			}
952 		} else {
953 			if (my_fmri != NULL)
954 				ipsecutil_exit(SERVICE_EXIT_OK, my_fmri,
955 				    debugfile, dgettext(TEXT_DOMAIN,
956 				    "%d actions successfully processed."),
957 				    lines_added);
958 		}
959 	} else {
960 		/* no newline upon Ctrl-D */
961 		if (s != NULL)
962 			(void) putchar('\n');
963 		(void) fflush(stdout);
964 	}
965 
966 	fini_interactive();
967 
968 	EXIT_OK(NULL);
969 }
970 
971 /*
972  * Functions to parse strings that represent a debug or privilege level.
973  * These functions are copied from main.c and door.c in usr.lib/in.iked/common.
974  * If this file evolves into a common library that may be used by in.iked
975  * as well as the usr.sbin utilities, those duplicate functions should be
976  * deleted.
977  *
978  * A privilege level may be represented by a simple keyword, corresponding
979  * to one of the possible levels.  A debug level may be represented by a
980  * series of keywords, separated by '+' or '-', indicating categories to
981  * be added or removed from the set of categories in the debug level.
982  * For example, +all-op corresponds to level 0xfffffffb (all flags except
983  * for D_OP set); while p1+p2+pfkey corresponds to level 0x38.  Note that
984  * the leading '+' is implicit; the first keyword in the list must be for
985  * a category that is to be added.
986  *
987  * These parsing functions make use of a local version of strtok, strtok_d,
988  * which includes an additional parameter, char *delim.  This param is filled
989  * in with the character which ends the returned token.  In other words,
990  * this version of strtok, in addition to returning the token, also returns
991  * the single character delimiter from the original string which marked the
992  * end of the token.
993  */
994 static char *
995 strtok_d(char *string, const char *sepset, char *delim)
996 {
997 	static char	*lasts;
998 	char		*q, *r;
999 
1000 	/* first or subsequent call */
1001 	if (string == NULL)
1002 		string = lasts;
1003 
1004 	if (string == 0)		/* return if no tokens remaining */
1005 		return (NULL);
1006 
1007 	q = string + strspn(string, sepset);	/* skip leading separators */
1008 
1009 	if (*q == '\0')			/* return if no tokens remaining */
1010 		return (NULL);
1011 
1012 	if ((r = strpbrk(q, sepset)) == NULL) {		/* move past token */
1013 		lasts = 0;	/* indicate that this is last token */
1014 	} else {
1015 		*delim = *r;	/* save delimitor */
1016 		*r = '\0';
1017 		lasts = r + 1;
1018 	}
1019 	return (q);
1020 }
1021 
1022 static keywdtab_t	privtab[] = {
1023 	{ IKE_PRIV_MINIMUM,	"base" },
1024 	{ IKE_PRIV_MODKEYS,	"modkeys" },
1025 	{ IKE_PRIV_KEYMAT,	"keymat" },
1026 	{ IKE_PRIV_MINIMUM,	"0" },
1027 };
1028 
1029 int
1030 privstr2num(char *str)
1031 {
1032 	keywdtab_t	*pp;
1033 	char		*endp;
1034 	int		 priv;
1035 
1036 	for (pp = privtab; pp < A_END(privtab); pp++) {
1037 		if (strcasecmp(str, pp->kw_str) == 0)
1038 			return (pp->kw_tag);
1039 	}
1040 
1041 	priv = strtol(str, &endp, 0);
1042 	if (*endp == '\0')
1043 		return (priv);
1044 
1045 	return (-1);
1046 }
1047 
1048 static keywdtab_t	dbgtab[] = {
1049 	{ D_CERT,	"cert" },
1050 	{ D_KEY,	"key" },
1051 	{ D_OP,		"op" },
1052 	{ D_P1,		"p1" },
1053 	{ D_P1,		"phase1" },
1054 	{ D_P2,		"p2" },
1055 	{ D_P2,		"phase2" },
1056 	{ D_PFKEY,	"pfkey" },
1057 	{ D_POL,	"pol" },
1058 	{ D_POL,	"policy" },
1059 	{ D_PROP,	"prop" },
1060 	{ D_DOOR,	"door" },
1061 	{ D_CONFIG,	"config" },
1062 	{ D_LABEL,	"label" },
1063 	{ D_ALL,	"all" },
1064 	{ 0,		"0" },
1065 };
1066 
1067 int
1068 dbgstr2num(char *str)
1069 {
1070 	keywdtab_t	*dp;
1071 
1072 	for (dp = dbgtab; dp < A_END(dbgtab); dp++) {
1073 		if (strcasecmp(str, dp->kw_str) == 0)
1074 			return (dp->kw_tag);
1075 	}
1076 	return (D_INVALID);
1077 }
1078 
1079 int
1080 parsedbgopts(char *optarg)
1081 {
1082 	char	*argp, *endp, op, nextop;
1083 	int	mask = 0, new;
1084 
1085 	mask = strtol(optarg, &endp, 0);
1086 	if (*endp == '\0')
1087 		return (mask);
1088 
1089 	op = optarg[0];
1090 	if (op != '-')
1091 		op = '+';
1092 	argp = strtok_d(optarg, "+-", &nextop);
1093 	do {
1094 		new = dbgstr2num(argp);
1095 		if (new == D_INVALID) {
1096 			/* we encountered an invalid keywd */
1097 			return (new);
1098 		}
1099 		if (op == '+') {
1100 			mask |= new;
1101 		} else {
1102 			mask &= ~new;
1103 		}
1104 		op = nextop;
1105 	} while ((argp = strtok_d(NULL, "+-", &nextop)) != NULL);
1106 
1107 	return (mask);
1108 }
1109 
1110 
1111 /*
1112  * functions to manipulate the kmcookie-label mapping file
1113  */
1114 
1115 /*
1116  * Open, lockf, fdopen the given file, returning a FILE * on success,
1117  * or NULL on failure.
1118  */
1119 FILE *
1120 kmc_open_and_lock(char *name)
1121 {
1122 	int	fd, rtnerr;
1123 	FILE	*fp;
1124 
1125 	if ((fd = open(name, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR)) < 0) {
1126 		return (NULL);
1127 	}
1128 	if (lockf(fd, F_LOCK, 0) < 0) {
1129 		return (NULL);
1130 	}
1131 	if ((fp = fdopen(fd, "a+")) == NULL) {
1132 		return (NULL);
1133 	}
1134 	if (fseek(fp, 0, SEEK_SET) < 0) {
1135 		/* save errno in case fclose changes it */
1136 		rtnerr = errno;
1137 		(void) fclose(fp);
1138 		errno = rtnerr;
1139 		return (NULL);
1140 	}
1141 	return (fp);
1142 }
1143 
1144 /*
1145  * Extract an integer cookie and string label from a line from the
1146  * kmcookie-label file.  Return -1 on failure, 0 on success.
1147  */
1148 int
1149 kmc_parse_line(char *line, int *cookie, char **label)
1150 {
1151 	char	*cookiestr;
1152 
1153 	*cookie = 0;
1154 	*label = NULL;
1155 
1156 	cookiestr = strtok(line, " \t\n");
1157 	if (cookiestr == NULL) {
1158 		return (-1);
1159 	}
1160 
1161 	/* Everything that follows, up to the newline, is the label. */
1162 	*label = strtok(NULL, "\n");
1163 	if (*label == NULL) {
1164 		return (-1);
1165 	}
1166 
1167 	*cookie = atoi(cookiestr);
1168 	return (0);
1169 }
1170 
1171 /*
1172  * Insert a mapping into the file (if it's not already there), given the
1173  * new label.  Return the assigned cookie, or -1 on error.
1174  */
1175 int
1176 kmc_insert_mapping(char *label)
1177 {
1178 	FILE	*map;
1179 	char	linebuf[IBUF_SIZE];
1180 	char	*cur_label;
1181 	int	max_cookie = 0, cur_cookie, rtn_cookie;
1182 	int	rtnerr = 0;
1183 	boolean_t	found = B_FALSE;
1184 
1185 	/* open and lock the file; will sleep until lock is available */
1186 	if ((map = kmc_open_and_lock(KMCFILE)) == NULL) {
1187 		/* kmc_open_and_lock() sets errno appropriately */
1188 		return (-1);
1189 	}
1190 
1191 	while (fgets(linebuf, sizeof (linebuf), map) != NULL) {
1192 
1193 		/* Skip blank lines, which often come near EOF. */
1194 		if (strlen(linebuf) == 0)
1195 			continue;
1196 
1197 		if (kmc_parse_line(linebuf, &cur_cookie, &cur_label) < 0) {
1198 			rtnerr = EINVAL;
1199 			goto error;
1200 		}
1201 
1202 		if (cur_cookie > max_cookie)
1203 			max_cookie = cur_cookie;
1204 
1205 		if ((!found) && (strcmp(cur_label, label) == 0)) {
1206 			found = B_TRUE;
1207 			rtn_cookie = cur_cookie;
1208 		}
1209 	}
1210 
1211 	if (!found) {
1212 		rtn_cookie = ++max_cookie;
1213 		if ((fprintf(map, "%u\t%s\n", rtn_cookie, label) < 0) ||
1214 		    (fflush(map) < 0)) {
1215 			rtnerr = errno;
1216 			goto error;
1217 		}
1218 	}
1219 	(void) fclose(map);
1220 
1221 	return (rtn_cookie);
1222 
1223 error:
1224 	(void) fclose(map);
1225 	errno = rtnerr;
1226 	return (-1);
1227 }
1228 
1229 /*
1230  * Lookup the given cookie and return its corresponding label.  Return
1231  * a pointer to the label on success, NULL on error (or if the label is
1232  * not found).  Note that the returned label pointer points to a static
1233  * string, so the label will be overwritten by a subsequent call to the
1234  * function; the function is also not thread-safe as a result.
1235  *
1236  * Because this is possibly publically exported, do not change its name,
1237  * but this is for all intents and purposes an IKEv1/in.iked function.
1238  */
1239 char *
1240 kmc_lookup_by_cookie(int cookie)
1241 {
1242 	FILE		*map;
1243 	static char	linebuf[IBUF_SIZE];
1244 	char		*cur_label;
1245 	int		cur_cookie;
1246 
1247 	if ((map = kmc_open_and_lock(KMCFILE)) == NULL) {
1248 		return (NULL);
1249 	}
1250 
1251 	while (fgets(linebuf, sizeof (linebuf), map) != NULL) {
1252 
1253 		if (kmc_parse_line(linebuf, &cur_cookie, &cur_label) < 0) {
1254 			(void) fclose(map);
1255 			return (NULL);
1256 		}
1257 
1258 		if (cookie == cur_cookie) {
1259 			(void) fclose(map);
1260 			return (cur_label);
1261 		}
1262 	}
1263 	(void) fclose(map);
1264 
1265 	return (NULL);
1266 }
1267 
1268 /*
1269  * Parse basic extension headers and return in the passed-in pointer vector.
1270  * Return values include:
1271  *
1272  *	KGE_OK	Everything's nice and parsed out.
1273  *		If there are no extensions, place NULL in extv[0].
1274  *	KGE_DUP	There is a duplicate extension.
1275  *		First instance in appropriate bin.  First duplicate in
1276  *		extv[0].
1277  *	KGE_UNK	Unknown extension type encountered.  extv[0] contains
1278  *		unknown header.
1279  *	KGE_LEN	Extension length error.
1280  *	KGE_CHK	High-level reality check failed on specific extension.
1281  *
1282  * My apologies for some of the pointer arithmetic in here.  I'm thinking
1283  * like an assembly programmer, yet trying to make the compiler happy.
1284  */
1285 int
1286 spdsock_get_ext(spd_ext_t *extv[], spd_msg_t *basehdr, uint_t msgsize,
1287     char *diag_buf, uint_t diag_buf_len)
1288 {
1289 	int i;
1290 
1291 	if (diag_buf != NULL)
1292 		diag_buf[0] = '\0';
1293 
1294 	for (i = 1; i <= SPD_EXT_MAX; i++)
1295 		extv[i] = NULL;
1296 
1297 	i = 0;
1298 	/* Use extv[0] as the "current working pointer". */
1299 
1300 	extv[0] = (spd_ext_t *)(basehdr + 1);
1301 	msgsize = SPD_64TO8(msgsize);
1302 
1303 	while ((char *)extv[0] < ((char *)basehdr + msgsize)) {
1304 		/* Check for unknown headers. */
1305 		i++;
1306 		if (extv[0]->spd_ext_type == 0 ||
1307 		    extv[0]->spd_ext_type > SPD_EXT_MAX) {
1308 			if (diag_buf != NULL) {
1309 				(void) snprintf(diag_buf, diag_buf_len,
1310 				    "spdsock ext 0x%X unknown: 0x%X",
1311 				    i, extv[0]->spd_ext_type);
1312 			}
1313 			return (KGE_UNK);
1314 		}
1315 
1316 		/*
1317 		 * Check length.  Use uint64_t because extlen is in units
1318 		 * of 64-bit words.  If length goes beyond the msgsize,
1319 		 * return an error.  (Zero length also qualifies here.)
1320 		 */
1321 		if (extv[0]->spd_ext_len == 0 ||
1322 		    (uint8_t *)((uint64_t *)extv[0] + extv[0]->spd_ext_len) >
1323 		    (uint8_t *)((uint8_t *)basehdr + msgsize))
1324 			return (KGE_LEN);
1325 
1326 		/* Check for redundant headers. */
1327 		if (extv[extv[0]->spd_ext_type] != NULL)
1328 			return (KGE_DUP);
1329 
1330 		/* If I make it here, assign the appropriate bin. */
1331 		extv[extv[0]->spd_ext_type] = extv[0];
1332 
1333 		/* Advance pointer (See above for uint64_t ptr reasoning.) */
1334 		extv[0] = (spd_ext_t *)
1335 		    ((uint64_t *)extv[0] + extv[0]->spd_ext_len);
1336 	}
1337 
1338 	/* Everything's cool. */
1339 
1340 	/*
1341 	 * If extv[0] == NULL, then there are no extension headers in this
1342 	 * message.  Ensure that this is the case.
1343 	 */
1344 	if (extv[0] == (spd_ext_t *)(basehdr + 1))
1345 		extv[0] = NULL;
1346 
1347 	return (KGE_OK);
1348 }
1349 
1350 const char *
1351 spdsock_diag(int diagnostic)
1352 {
1353 	switch (diagnostic) {
1354 	case SPD_DIAGNOSTIC_NONE:
1355 		return (dgettext(TEXT_DOMAIN, "no error"));
1356 	case SPD_DIAGNOSTIC_UNKNOWN_EXT:
1357 		return (dgettext(TEXT_DOMAIN, "unknown extension"));
1358 	case SPD_DIAGNOSTIC_BAD_EXTLEN:
1359 		return (dgettext(TEXT_DOMAIN, "bad extension length"));
1360 	case SPD_DIAGNOSTIC_NO_RULE_EXT:
1361 		return (dgettext(TEXT_DOMAIN, "no rule extension"));
1362 	case SPD_DIAGNOSTIC_BAD_ADDR_LEN:
1363 		return (dgettext(TEXT_DOMAIN, "bad address len"));
1364 	case SPD_DIAGNOSTIC_MIXED_AF:
1365 		return (dgettext(TEXT_DOMAIN, "mixed address family"));
1366 	case SPD_DIAGNOSTIC_ADD_NO_MEM:
1367 		return (dgettext(TEXT_DOMAIN, "add: no memory"));
1368 	case SPD_DIAGNOSTIC_ADD_WRONG_ACT_COUNT:
1369 		return (dgettext(TEXT_DOMAIN, "add: wrong action count"));
1370 	case SPD_DIAGNOSTIC_ADD_BAD_TYPE:
1371 		return (dgettext(TEXT_DOMAIN, "add: bad type"));
1372 	case SPD_DIAGNOSTIC_ADD_BAD_FLAGS:
1373 		return (dgettext(TEXT_DOMAIN, "add: bad flags"));
1374 	case SPD_DIAGNOSTIC_ADD_INCON_FLAGS:
1375 		return (dgettext(TEXT_DOMAIN, "add: inconsistent flags"));
1376 	case SPD_DIAGNOSTIC_MALFORMED_LCLPORT:
1377 		return (dgettext(TEXT_DOMAIN, "malformed local port"));
1378 	case SPD_DIAGNOSTIC_DUPLICATE_LCLPORT:
1379 		return (dgettext(TEXT_DOMAIN, "duplicate local port"));
1380 	case SPD_DIAGNOSTIC_MALFORMED_REMPORT:
1381 		return (dgettext(TEXT_DOMAIN, "malformed remote port"));
1382 	case SPD_DIAGNOSTIC_DUPLICATE_REMPORT:
1383 		return (dgettext(TEXT_DOMAIN, "duplicate remote port"));
1384 	case SPD_DIAGNOSTIC_MALFORMED_PROTO:
1385 		return (dgettext(TEXT_DOMAIN, "malformed proto"));
1386 	case SPD_DIAGNOSTIC_DUPLICATE_PROTO:
1387 		return (dgettext(TEXT_DOMAIN, "duplicate proto"));
1388 	case SPD_DIAGNOSTIC_MALFORMED_LCLADDR:
1389 		return (dgettext(TEXT_DOMAIN, "malformed local address"));
1390 	case SPD_DIAGNOSTIC_DUPLICATE_LCLADDR:
1391 		return (dgettext(TEXT_DOMAIN, "duplicate local address"));
1392 	case SPD_DIAGNOSTIC_MALFORMED_REMADDR:
1393 		return (dgettext(TEXT_DOMAIN, "malformed remote address"));
1394 	case SPD_DIAGNOSTIC_DUPLICATE_REMADDR:
1395 		return (dgettext(TEXT_DOMAIN, "duplicate remote address"));
1396 	case SPD_DIAGNOSTIC_MALFORMED_ACTION:
1397 		return (dgettext(TEXT_DOMAIN, "malformed action"));
1398 	case SPD_DIAGNOSTIC_DUPLICATE_ACTION:
1399 		return (dgettext(TEXT_DOMAIN, "duplicate action"));
1400 	case SPD_DIAGNOSTIC_MALFORMED_RULE:
1401 		return (dgettext(TEXT_DOMAIN, "malformed rule"));
1402 	case SPD_DIAGNOSTIC_DUPLICATE_RULE:
1403 		return (dgettext(TEXT_DOMAIN, "duplicate rule"));
1404 	case SPD_DIAGNOSTIC_MALFORMED_RULESET:
1405 		return (dgettext(TEXT_DOMAIN, "malformed ruleset"));
1406 	case SPD_DIAGNOSTIC_DUPLICATE_RULESET:
1407 		return (dgettext(TEXT_DOMAIN, "duplicate ruleset"));
1408 	case SPD_DIAGNOSTIC_INVALID_RULE_INDEX:
1409 		return (dgettext(TEXT_DOMAIN, "invalid rule index"));
1410 	case SPD_DIAGNOSTIC_BAD_SPDID:
1411 		return (dgettext(TEXT_DOMAIN, "bad spdid"));
1412 	case SPD_DIAGNOSTIC_BAD_MSG_TYPE:
1413 		return (dgettext(TEXT_DOMAIN, "bad message type"));
1414 	case SPD_DIAGNOSTIC_UNSUPP_AH_ALG:
1415 		return (dgettext(TEXT_DOMAIN, "unsupported AH algorithm"));
1416 	case SPD_DIAGNOSTIC_UNSUPP_ESP_ENCR_ALG:
1417 		return (dgettext(TEXT_DOMAIN,
1418 		    "unsupported ESP encryption algorithm"));
1419 	case SPD_DIAGNOSTIC_UNSUPP_ESP_AUTH_ALG:
1420 		return (dgettext(TEXT_DOMAIN,
1421 		    "unsupported ESP authentication algorithm"));
1422 	case SPD_DIAGNOSTIC_UNSUPP_AH_KEYSIZE:
1423 		return (dgettext(TEXT_DOMAIN, "unsupported AH key size"));
1424 	case SPD_DIAGNOSTIC_UNSUPP_ESP_ENCR_KEYSIZE:
1425 		return (dgettext(TEXT_DOMAIN,
1426 		    "unsupported ESP encryption key size"));
1427 	case SPD_DIAGNOSTIC_UNSUPP_ESP_AUTH_KEYSIZE:
1428 		return (dgettext(TEXT_DOMAIN,
1429 		    "unsupported ESP authentication key size"));
1430 	case SPD_DIAGNOSTIC_NO_ACTION_EXT:
1431 		return (dgettext(TEXT_DOMAIN, "No ACTION extension"));
1432 	case SPD_DIAGNOSTIC_ALG_ID_RANGE:
1433 		return (dgettext(TEXT_DOMAIN, "invalid algorithm identifer"));
1434 	case SPD_DIAGNOSTIC_ALG_NUM_KEY_SIZES:
1435 		return (dgettext(TEXT_DOMAIN,
1436 		    "number of key sizes inconsistent"));
1437 	case SPD_DIAGNOSTIC_ALG_NUM_BLOCK_SIZES:
1438 		return (dgettext(TEXT_DOMAIN,
1439 		    "number of block sizes inconsistent"));
1440 	case SPD_DIAGNOSTIC_ALG_MECH_NAME_LEN:
1441 		return (dgettext(TEXT_DOMAIN, "invalid mechanism name length"));
1442 	case SPD_DIAGNOSTIC_NOT_GLOBAL_OP:
1443 		return (dgettext(TEXT_DOMAIN,
1444 		    "operation not applicable to all policies"));
1445 	case SPD_DIAGNOSTIC_NO_TUNNEL_SELECTORS:
1446 		return (dgettext(TEXT_DOMAIN,
1447 		    "using selectors on a transport-mode tunnel"));
1448 	default:
1449 		return (dgettext(TEXT_DOMAIN, "unknown diagnostic"));
1450 	}
1451 }
1452 
1453 /*
1454  * PF_KEY Diagnostic table.
1455  *
1456  * PF_KEY NOTE:  If you change pfkeyv2.h's SADB_X_DIAGNOSTIC_* space, this is
1457  * where you need to add new messages.
1458  */
1459 
1460 const char *
1461 keysock_diag(int diagnostic)
1462 {
1463 	switch (diagnostic) {
1464 	case SADB_X_DIAGNOSTIC_NONE:
1465 		return (dgettext(TEXT_DOMAIN, "No diagnostic"));
1466 	case SADB_X_DIAGNOSTIC_UNKNOWN_MSG:
1467 		return (dgettext(TEXT_DOMAIN, "Unknown message type"));
1468 	case SADB_X_DIAGNOSTIC_UNKNOWN_EXT:
1469 		return (dgettext(TEXT_DOMAIN, "Unknown extension type"));
1470 	case SADB_X_DIAGNOSTIC_BAD_EXTLEN:
1471 		return (dgettext(TEXT_DOMAIN, "Bad extension length"));
1472 	case SADB_X_DIAGNOSTIC_UNKNOWN_SATYPE:
1473 		return (dgettext(TEXT_DOMAIN,
1474 		    "Unknown Security Association type"));
1475 	case SADB_X_DIAGNOSTIC_SATYPE_NEEDED:
1476 		return (dgettext(TEXT_DOMAIN,
1477 		    "Specific Security Association type needed"));
1478 	case SADB_X_DIAGNOSTIC_NO_SADBS:
1479 		return (dgettext(TEXT_DOMAIN,
1480 		    "No Security Association Databases present"));
1481 	case SADB_X_DIAGNOSTIC_NO_EXT:
1482 		return (dgettext(TEXT_DOMAIN,
1483 		    "No extensions needed for message"));
1484 	case SADB_X_DIAGNOSTIC_BAD_SRC_AF:
1485 		return (dgettext(TEXT_DOMAIN, "Bad source address family"));
1486 	case SADB_X_DIAGNOSTIC_BAD_DST_AF:
1487 		return (dgettext(TEXT_DOMAIN,
1488 		    "Bad destination address family"));
1489 	case SADB_X_DIAGNOSTIC_BAD_PROXY_AF:
1490 		return (dgettext(TEXT_DOMAIN,
1491 		    "Bad inner-source address family"));
1492 	case SADB_X_DIAGNOSTIC_AF_MISMATCH:
1493 		return (dgettext(TEXT_DOMAIN,
1494 		    "Source/destination address family mismatch"));
1495 	case SADB_X_DIAGNOSTIC_BAD_SRC:
1496 		return (dgettext(TEXT_DOMAIN, "Bad source address value"));
1497 	case SADB_X_DIAGNOSTIC_BAD_DST:
1498 		return (dgettext(TEXT_DOMAIN, "Bad destination address value"));
1499 	case SADB_X_DIAGNOSTIC_ALLOC_HSERR:
1500 		return (dgettext(TEXT_DOMAIN,
1501 		    "Soft allocations limit more than hard limit"));
1502 	case SADB_X_DIAGNOSTIC_BYTES_HSERR:
1503 		return (dgettext(TEXT_DOMAIN,
1504 		    "Soft bytes limit more than hard limit"));
1505 	case SADB_X_DIAGNOSTIC_ADDTIME_HSERR:
1506 		return (dgettext(TEXT_DOMAIN, "Soft add expiration time later "
1507 		    "than hard expiration time"));
1508 	case SADB_X_DIAGNOSTIC_USETIME_HSERR:
1509 		return (dgettext(TEXT_DOMAIN, "Soft use expiration time later "
1510 		    "than hard expiration time"));
1511 	case SADB_X_DIAGNOSTIC_MISSING_SRC:
1512 		return (dgettext(TEXT_DOMAIN, "Missing source address"));
1513 	case SADB_X_DIAGNOSTIC_MISSING_DST:
1514 		return (dgettext(TEXT_DOMAIN, "Missing destination address"));
1515 	case SADB_X_DIAGNOSTIC_MISSING_SA:
1516 		return (dgettext(TEXT_DOMAIN, "Missing SA extension"));
1517 	case SADB_X_DIAGNOSTIC_MISSING_EKEY:
1518 		return (dgettext(TEXT_DOMAIN, "Missing encryption key"));
1519 	case SADB_X_DIAGNOSTIC_MISSING_AKEY:
1520 		return (dgettext(TEXT_DOMAIN, "Missing authentication key"));
1521 	case SADB_X_DIAGNOSTIC_MISSING_RANGE:
1522 		return (dgettext(TEXT_DOMAIN, "Missing SPI range"));
1523 	case SADB_X_DIAGNOSTIC_DUPLICATE_SRC:
1524 		return (dgettext(TEXT_DOMAIN, "Duplicate source address"));
1525 	case SADB_X_DIAGNOSTIC_DUPLICATE_DST:
1526 		return (dgettext(TEXT_DOMAIN, "Duplicate destination address"));
1527 	case SADB_X_DIAGNOSTIC_DUPLICATE_SA:
1528 		return (dgettext(TEXT_DOMAIN, "Duplicate SA extension"));
1529 	case SADB_X_DIAGNOSTIC_DUPLICATE_EKEY:
1530 		return (dgettext(TEXT_DOMAIN, "Duplicate encryption key"));
1531 	case SADB_X_DIAGNOSTIC_DUPLICATE_AKEY:
1532 		return (dgettext(TEXT_DOMAIN, "Duplicate authentication key"));
1533 	case SADB_X_DIAGNOSTIC_DUPLICATE_RANGE:
1534 		return (dgettext(TEXT_DOMAIN, "Duplicate SPI range"));
1535 	case SADB_X_DIAGNOSTIC_MALFORMED_SRC:
1536 		return (dgettext(TEXT_DOMAIN, "Malformed source address"));
1537 	case SADB_X_DIAGNOSTIC_MALFORMED_DST:
1538 		return (dgettext(TEXT_DOMAIN, "Malformed destination address"));
1539 	case SADB_X_DIAGNOSTIC_MALFORMED_SA:
1540 		return (dgettext(TEXT_DOMAIN, "Malformed SA extension"));
1541 	case SADB_X_DIAGNOSTIC_MALFORMED_EKEY:
1542 		return (dgettext(TEXT_DOMAIN, "Malformed encryption key"));
1543 	case SADB_X_DIAGNOSTIC_MALFORMED_AKEY:
1544 		return (dgettext(TEXT_DOMAIN, "Malformed authentication key"));
1545 	case SADB_X_DIAGNOSTIC_MALFORMED_RANGE:
1546 		return (dgettext(TEXT_DOMAIN, "Malformed SPI range"));
1547 	case SADB_X_DIAGNOSTIC_AKEY_PRESENT:
1548 		return (dgettext(TEXT_DOMAIN, "Authentication key not needed"));
1549 	case SADB_X_DIAGNOSTIC_EKEY_PRESENT:
1550 		return (dgettext(TEXT_DOMAIN, "Encryption key not needed"));
1551 	case SADB_X_DIAGNOSTIC_PROP_PRESENT:
1552 		return (dgettext(TEXT_DOMAIN, "Proposal extension not needed"));
1553 	case SADB_X_DIAGNOSTIC_SUPP_PRESENT:
1554 		return (dgettext(TEXT_DOMAIN,
1555 		    "Supported algorithms extension not needed"));
1556 	case SADB_X_DIAGNOSTIC_BAD_AALG:
1557 		return (dgettext(TEXT_DOMAIN,
1558 		    "Unsupported authentication algorithm"));
1559 	case SADB_X_DIAGNOSTIC_BAD_EALG:
1560 		return (dgettext(TEXT_DOMAIN,
1561 		    "Unsupported encryption algorithm"));
1562 	case SADB_X_DIAGNOSTIC_BAD_SAFLAGS:
1563 		return (dgettext(TEXT_DOMAIN, "Invalid SA flags"));
1564 	case SADB_X_DIAGNOSTIC_BAD_SASTATE:
1565 		return (dgettext(TEXT_DOMAIN, "Invalid SA state"));
1566 	case SADB_X_DIAGNOSTIC_BAD_AKEYBITS:
1567 		return (dgettext(TEXT_DOMAIN,
1568 		    "Bad number of authentication bits"));
1569 	case SADB_X_DIAGNOSTIC_BAD_EKEYBITS:
1570 		return (dgettext(TEXT_DOMAIN,
1571 		    "Bad number of encryption bits"));
1572 	case SADB_X_DIAGNOSTIC_ENCR_NOTSUPP:
1573 		return (dgettext(TEXT_DOMAIN,
1574 		    "Encryption not supported for this SA type"));
1575 	case SADB_X_DIAGNOSTIC_WEAK_EKEY:
1576 		return (dgettext(TEXT_DOMAIN, "Weak encryption key"));
1577 	case SADB_X_DIAGNOSTIC_WEAK_AKEY:
1578 		return (dgettext(TEXT_DOMAIN, "Weak authentication key"));
1579 	case SADB_X_DIAGNOSTIC_DUPLICATE_KMP:
1580 		return (dgettext(TEXT_DOMAIN,
1581 		    "Duplicate key management protocol"));
1582 	case SADB_X_DIAGNOSTIC_DUPLICATE_KMC:
1583 		return (dgettext(TEXT_DOMAIN,
1584 		    "Duplicate key management cookie"));
1585 	case SADB_X_DIAGNOSTIC_MISSING_NATT_LOC:
1586 		return (dgettext(TEXT_DOMAIN, "Missing NAT-T local address"));
1587 	case SADB_X_DIAGNOSTIC_MISSING_NATT_REM:
1588 		return (dgettext(TEXT_DOMAIN, "Missing NAT-T remote address"));
1589 	case SADB_X_DIAGNOSTIC_DUPLICATE_NATT_LOC:
1590 		return (dgettext(TEXT_DOMAIN, "Duplicate NAT-T local address"));
1591 	case SADB_X_DIAGNOSTIC_DUPLICATE_NATT_REM:
1592 		return (dgettext(TEXT_DOMAIN,
1593 		    "Duplicate NAT-T remote address"));
1594 	case SADB_X_DIAGNOSTIC_MALFORMED_NATT_LOC:
1595 		return (dgettext(TEXT_DOMAIN, "Malformed NAT-T local address"));
1596 	case SADB_X_DIAGNOSTIC_MALFORMED_NATT_REM:
1597 		return (dgettext(TEXT_DOMAIN,
1598 		    "Malformed NAT-T remote address"));
1599 	case SADB_X_DIAGNOSTIC_DUPLICATE_NATT_PORTS:
1600 		return (dgettext(TEXT_DOMAIN, "Duplicate NAT-T ports"));
1601 	case SADB_X_DIAGNOSTIC_MISSING_INNER_SRC:
1602 		return (dgettext(TEXT_DOMAIN, "Missing inner source address"));
1603 	case SADB_X_DIAGNOSTIC_MISSING_INNER_DST:
1604 		return (dgettext(TEXT_DOMAIN,
1605 		    "Missing inner destination address"));
1606 	case SADB_X_DIAGNOSTIC_DUPLICATE_INNER_SRC:
1607 		return (dgettext(TEXT_DOMAIN,
1608 		    "Duplicate inner source address"));
1609 	case SADB_X_DIAGNOSTIC_DUPLICATE_INNER_DST:
1610 		return (dgettext(TEXT_DOMAIN,
1611 		    "Duplicate inner destination address"));
1612 	case SADB_X_DIAGNOSTIC_MALFORMED_INNER_SRC:
1613 		return (dgettext(TEXT_DOMAIN,
1614 		    "Malformed inner source address"));
1615 	case SADB_X_DIAGNOSTIC_MALFORMED_INNER_DST:
1616 		return (dgettext(TEXT_DOMAIN,
1617 		    "Malformed inner destination address"));
1618 	case SADB_X_DIAGNOSTIC_PREFIX_INNER_SRC:
1619 		return (dgettext(TEXT_DOMAIN,
1620 		    "Invalid inner-source prefix length "));
1621 	case SADB_X_DIAGNOSTIC_PREFIX_INNER_DST:
1622 		return (dgettext(TEXT_DOMAIN,
1623 		    "Invalid inner-destination prefix length"));
1624 	case SADB_X_DIAGNOSTIC_BAD_INNER_DST_AF:
1625 		return (dgettext(TEXT_DOMAIN,
1626 		    "Bad inner-destination address family"));
1627 	case SADB_X_DIAGNOSTIC_INNER_AF_MISMATCH:
1628 		return (dgettext(TEXT_DOMAIN,
1629 		    "Inner source/destination address family mismatch"));
1630 	case SADB_X_DIAGNOSTIC_BAD_NATT_REM_AF:
1631 		return (dgettext(TEXT_DOMAIN,
1632 		    "Bad NAT-T remote address family"));
1633 	case SADB_X_DIAGNOSTIC_BAD_NATT_LOC_AF:
1634 		return (dgettext(TEXT_DOMAIN,
1635 		    "Bad NAT-T local address family"));
1636 	case SADB_X_DIAGNOSTIC_PROTO_MISMATCH:
1637 		return (dgettext(TEXT_DOMAIN,
1638 		    "Source/desination protocol mismatch"));
1639 	case SADB_X_DIAGNOSTIC_INNER_PROTO_MISMATCH:
1640 		return (dgettext(TEXT_DOMAIN,
1641 		    "Inner source/desination protocol mismatch"));
1642 	case SADB_X_DIAGNOSTIC_DUAL_PORT_SETS:
1643 		return (dgettext(TEXT_DOMAIN,
1644 		    "Both inner ports and outer ports are set"));
1645 	case SADB_X_DIAGNOSTIC_PAIR_INAPPROPRIATE:
1646 		return (dgettext(TEXT_DOMAIN,
1647 		    "Pairing failed, target SA unsuitable for pairing"));
1648 	case SADB_X_DIAGNOSTIC_PAIR_ADD_MISMATCH:
1649 		return (dgettext(TEXT_DOMAIN,
1650 		    "Source/destination address differs from pair SA"));
1651 	case SADB_X_DIAGNOSTIC_PAIR_ALREADY:
1652 		return (dgettext(TEXT_DOMAIN,
1653 		    "Already paired with another security association"));
1654 	case SADB_X_DIAGNOSTIC_PAIR_SA_NOTFOUND:
1655 		return (dgettext(TEXT_DOMAIN,
1656 		    "Command failed, pair security association not found"));
1657 	case SADB_X_DIAGNOSTIC_BAD_SA_DIRECTION:
1658 		return (dgettext(TEXT_DOMAIN,
1659 		    "Inappropriate SA direction"));
1660 	case SADB_X_DIAGNOSTIC_SA_NOTFOUND:
1661 		return (dgettext(TEXT_DOMAIN,
1662 		    "Security association not found"));
1663 	case SADB_X_DIAGNOSTIC_SA_EXPIRED:
1664 		return (dgettext(TEXT_DOMAIN,
1665 		    "Security association is not valid"));
1666 	case SADB_X_DIAGNOSTIC_BAD_CTX:
1667 		return (dgettext(TEXT_DOMAIN,
1668 		    "Algorithm invalid or not supported by Crypto Framework"));
1669 	case SADB_X_DIAGNOSTIC_INVALID_REPLAY:
1670 		return (dgettext(TEXT_DOMAIN,
1671 		    "Invalid Replay counter"));
1672 	case SADB_X_DIAGNOSTIC_MISSING_LIFETIME:
1673 		return (dgettext(TEXT_DOMAIN,
1674 		    "Inappropriate lifetimes"));
1675 	case SADB_X_DIAGNOSTIC_MISSING_ASTR:
1676 		return (dgettext(TEXT_DOMAIN, "Missing authentication string"));
1677 	case SADB_X_DIAGNOSTIC_DUPLICATE_ASTR:
1678 		return (dgettext(TEXT_DOMAIN,
1679 		    "Duplicate authentication string"));
1680 	case SADB_X_DIAGNOSTIC_MALFORMED_ASTR:
1681 		return (dgettext(TEXT_DOMAIN,
1682 		    "Malformed authentication string"));
1683 	default:
1684 		return (dgettext(TEXT_DOMAIN, "Unknown diagnostic code"));
1685 	}
1686 }
1687 
1688 /*
1689  * Convert an IPv6 mask to a prefix len.  I assume all IPv6 masks are
1690  * contiguous, so I stop at the first zero bit!
1691  */
1692 int
1693 in_masktoprefix(uint8_t *mask, boolean_t is_v4mapped)
1694 {
1695 	int rc = 0;
1696 	uint8_t last;
1697 	int limit = IPV6_ABITS;
1698 
1699 	if (is_v4mapped) {
1700 		mask += ((IPV6_ABITS - IP_ABITS)/8);
1701 		limit = IP_ABITS;
1702 	}
1703 
1704 	while (*mask == 0xff) {
1705 		rc += 8;
1706 		if (rc == limit)
1707 			return (limit);
1708 		mask++;
1709 	}
1710 
1711 	last = *mask;
1712 	while (last != 0) {
1713 		rc++;
1714 		last = (last << 1) & 0xff;
1715 	}
1716 
1717 	return (rc);
1718 }
1719 
1720 /*
1721  * Expand the diagnostic code into a message.
1722  */
1723 void
1724 print_diagnostic(FILE *file, uint16_t diagnostic)
1725 {
1726 	/* Use two spaces so above strings can fit on the line. */
1727 	(void) fprintf(file, dgettext(TEXT_DOMAIN,
1728 	    "  Diagnostic code %u:  %s.\n"),
1729 	    diagnostic, keysock_diag(diagnostic));
1730 }
1731 
1732 /*
1733  * Prints the base PF_KEY message.
1734  */
1735 void
1736 print_sadb_msg(FILE *file, struct sadb_msg *samsg, time_t wallclock,
1737     boolean_t vflag)
1738 {
1739 	if (wallclock != 0)
1740 		printsatime(file, wallclock, dgettext(TEXT_DOMAIN,
1741 		    "%sTimestamp: %s\n"), "", NULL,
1742 		    vflag);
1743 
1744 	(void) fprintf(file, dgettext(TEXT_DOMAIN,
1745 	    "Base message (version %u) type "),
1746 	    samsg->sadb_msg_version);
1747 	switch (samsg->sadb_msg_type) {
1748 	case SADB_RESERVED:
1749 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
1750 		    "RESERVED (warning: set to 0)"));
1751 		break;
1752 	case SADB_GETSPI:
1753 		(void) fprintf(file, "GETSPI");
1754 		break;
1755 	case SADB_UPDATE:
1756 		(void) fprintf(file, "UPDATE");
1757 		break;
1758 	case SADB_X_UPDATEPAIR:
1759 		(void) fprintf(file, "UPDATE PAIR");
1760 		break;
1761 	case SADB_ADD:
1762 		(void) fprintf(file, "ADD");
1763 		break;
1764 	case SADB_DELETE:
1765 		(void) fprintf(file, "DELETE");
1766 		break;
1767 	case SADB_X_DELPAIR:
1768 		(void) fprintf(file, "DELETE PAIR");
1769 		break;
1770 	case SADB_GET:
1771 		(void) fprintf(file, "GET");
1772 		break;
1773 	case SADB_ACQUIRE:
1774 		(void) fprintf(file, "ACQUIRE");
1775 		break;
1776 	case SADB_REGISTER:
1777 		(void) fprintf(file, "REGISTER");
1778 		break;
1779 	case SADB_EXPIRE:
1780 		(void) fprintf(file, "EXPIRE");
1781 		break;
1782 	case SADB_FLUSH:
1783 		(void) fprintf(file, "FLUSH");
1784 		break;
1785 	case SADB_DUMP:
1786 		(void) fprintf(file, "DUMP");
1787 		break;
1788 	case SADB_X_PROMISC:
1789 		(void) fprintf(file, "X_PROMISC");
1790 		break;
1791 	case SADB_X_INVERSE_ACQUIRE:
1792 		(void) fprintf(file, "X_INVERSE_ACQUIRE");
1793 		break;
1794 	default:
1795 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
1796 		    "Unknown (%u)"), samsg->sadb_msg_type);
1797 		break;
1798 	}
1799 	(void) fprintf(file, dgettext(TEXT_DOMAIN, ", SA type "));
1800 
1801 	switch (samsg->sadb_msg_satype) {
1802 	case SADB_SATYPE_UNSPEC:
1803 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
1804 		    "<unspecified/all>"));
1805 		break;
1806 	case SADB_SATYPE_AH:
1807 		(void) fprintf(file, "AH");
1808 		break;
1809 	case SADB_SATYPE_ESP:
1810 		(void) fprintf(file, "ESP");
1811 		break;
1812 	case SADB_X_SATYPE_TCPSIG:
1813 		(void) fprintf(file, "TCPSIG");
1814 		break;
1815 	case SADB_SATYPE_RSVP:
1816 		(void) fprintf(file, "RSVP");
1817 		break;
1818 	case SADB_SATYPE_OSPFV2:
1819 		(void) fprintf(file, "OSPFv2");
1820 		break;
1821 	case SADB_SATYPE_RIPV2:
1822 		(void) fprintf(file, "RIPv2");
1823 		break;
1824 	case SADB_SATYPE_MIP:
1825 		(void) fprintf(file, dgettext(TEXT_DOMAIN, "Mobile IP"));
1826 		break;
1827 	default:
1828 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
1829 		    "<unknown %u>"), samsg->sadb_msg_satype);
1830 		break;
1831 	}
1832 
1833 	(void) fprintf(file, ".\n");
1834 
1835 	if (samsg->sadb_msg_errno != 0) {
1836 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
1837 		    "Error %s from PF_KEY.\n"),
1838 		    strerror(samsg->sadb_msg_errno));
1839 		print_diagnostic(file, samsg->sadb_x_msg_diagnostic);
1840 	}
1841 
1842 	(void) fprintf(file, dgettext(TEXT_DOMAIN,
1843 	    "Message length %u bytes, seq=%u, pid=%u.\n"),
1844 	    SADB_64TO8(samsg->sadb_msg_len), samsg->sadb_msg_seq,
1845 	    samsg->sadb_msg_pid);
1846 }
1847 
1848 /*
1849  * Print the SA extension for PF_KEY.
1850  */
1851 void
1852 print_sa(FILE *file, char *prefix, struct sadb_sa *assoc)
1853 {
1854 	if (assoc->sadb_sa_len != SADB_8TO64(sizeof (*assoc))) {
1855 		warnxfp(EFD(file), dgettext(TEXT_DOMAIN,
1856 		    "WARNING: SA info extension length (%u) is bad."),
1857 		    SADB_64TO8(assoc->sadb_sa_len));
1858 	}
1859 
1860 	if ((assoc->sadb_sa_flags & SADB_X_SAFLAGS_TCPSIG) == 0) {
1861 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
1862 		    "%sSADB_ASSOC spi=0x%x, replay window size=%u, state="),
1863 		    prefix, ntohl(assoc->sadb_sa_spi), assoc->sadb_sa_replay);
1864 	} else {
1865 		(void) fprintf(file,
1866 		    dgettext(TEXT_DOMAIN, "%sSADB_ASSOC state="), prefix);
1867 	}
1868 	switch (assoc->sadb_sa_state) {
1869 	case SADB_SASTATE_LARVAL:
1870 		(void) fprintf(file, dgettext(TEXT_DOMAIN, "LARVAL"));
1871 		break;
1872 	case SADB_SASTATE_MATURE:
1873 		(void) fprintf(file, dgettext(TEXT_DOMAIN, "MATURE"));
1874 		break;
1875 	case SADB_SASTATE_DYING:
1876 		(void) fprintf(file, dgettext(TEXT_DOMAIN, "DYING"));
1877 		break;
1878 	case SADB_SASTATE_DEAD:
1879 		(void) fprintf(file, dgettext(TEXT_DOMAIN, "DEAD"));
1880 		break;
1881 	case SADB_X_SASTATE_ACTIVE_ELSEWHERE:
1882 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
1883 		    "ACTIVE_ELSEWHERE"));
1884 		break;
1885 	case SADB_X_SASTATE_IDLE:
1886 		(void) fprintf(file, dgettext(TEXT_DOMAIN, "IDLE"));
1887 		break;
1888 	default:
1889 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
1890 		    "<unknown %u>"), assoc->sadb_sa_state);
1891 	}
1892 
1893 	if (assoc->sadb_sa_auth != SADB_AALG_NONE) {
1894 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
1895 		    "\n%sAuthentication algorithm = "),
1896 		    prefix);
1897 		if ((assoc->sadb_sa_flags & SADB_X_SAFLAGS_TCPSIG) != 0)
1898 			(void) dump_tcpsigalg(assoc->sadb_sa_auth, file);
1899 		else
1900 			(void) dump_aalg(assoc->sadb_sa_auth, file);
1901 	}
1902 
1903 	if (assoc->sadb_sa_encrypt != SADB_EALG_NONE) {
1904 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
1905 		    "\n%sEncryption algorithm = "), prefix);
1906 		(void) dump_ealg(assoc->sadb_sa_encrypt, file);
1907 	}
1908 
1909 	(void) fprintf(file, dgettext(TEXT_DOMAIN, "\n%sflags=0x%x < "), prefix,
1910 	    assoc->sadb_sa_flags);
1911 	if (assoc->sadb_sa_flags & SADB_SAFLAGS_PFS)
1912 		(void) fprintf(file, "PFS ");
1913 	if (assoc->sadb_sa_flags & SADB_SAFLAGS_NOREPLAY)
1914 		(void) fprintf(file, "NOREPLAY ");
1915 
1916 	/* BEGIN Solaris-specific flags. */
1917 	if (assoc->sadb_sa_flags & SADB_X_SAFLAGS_USED)
1918 		(void) fprintf(file, "X_USED ");
1919 	if (assoc->sadb_sa_flags & SADB_X_SAFLAGS_PAIRED)
1920 		(void) fprintf(file, "X_PAIRED ");
1921 	if (assoc->sadb_sa_flags & SADB_X_SAFLAGS_OUTBOUND)
1922 		(void) fprintf(file, "X_OUTBOUND ");
1923 	if (assoc->sadb_sa_flags & SADB_X_SAFLAGS_INBOUND)
1924 		(void) fprintf(file, "X_INBOUND ");
1925 	if (assoc->sadb_sa_flags & SADB_X_SAFLAGS_UNIQUE)
1926 		(void) fprintf(file, "X_UNIQUE ");
1927 	if (assoc->sadb_sa_flags & SADB_X_SAFLAGS_AALG1)
1928 		(void) fprintf(file, "X_AALG1 ");
1929 	if (assoc->sadb_sa_flags & SADB_X_SAFLAGS_AALG2)
1930 		(void) fprintf(file, "X_AALG2 ");
1931 	if (assoc->sadb_sa_flags & SADB_X_SAFLAGS_EALG1)
1932 		(void) fprintf(file, "X_EALG1 ");
1933 	if (assoc->sadb_sa_flags & SADB_X_SAFLAGS_EALG2)
1934 		(void) fprintf(file, "X_EALG2 ");
1935 	if (assoc->sadb_sa_flags & SADB_X_SAFLAGS_NATT_LOC)
1936 		(void) fprintf(file, "X_NATT_LOC ");
1937 	if (assoc->sadb_sa_flags & SADB_X_SAFLAGS_NATT_REM)
1938 		(void) fprintf(file, "X_NATT_REM ");
1939 	if (assoc->sadb_sa_flags & SADB_X_SAFLAGS_TUNNEL)
1940 		(void) fprintf(file, "X_TUNNEL ");
1941 	if (assoc->sadb_sa_flags & SADB_X_SAFLAGS_NATTED)
1942 		(void) fprintf(file, "X_NATTED ");
1943 	if (assoc->sadb_sa_flags & SADB_X_SAFLAGS_TCPSIG)
1944 		(void) fprintf(file, "X_TCPSIG ");
1945 	/* END Solaris-specific flags. */
1946 
1947 	(void) fprintf(file, ">\n");
1948 }
1949 
1950 void
1951 printsatime(FILE *file, int64_t lt, const char *msg, const char *pfx,
1952     const char *pfx2, boolean_t vflag)
1953 {
1954 	char tbuf[TBUF_SIZE]; /* For strftime() call. */
1955 	const char *tp = tbuf;
1956 	time_t t = lt;
1957 	struct tm res;
1958 
1959 	if (t != lt) {
1960 		if (lt > 0)
1961 			t = LONG_MAX;
1962 		else
1963 			t = LONG_MIN;
1964 	}
1965 
1966 	if (strftime(tbuf, TBUF_SIZE, NULL, localtime_r(&t, &res)) == 0)
1967 		tp = dgettext(TEXT_DOMAIN, "<time conversion failed>");
1968 	(void) fprintf(file, msg, pfx, tp);
1969 	if (vflag && (pfx2 != NULL))
1970 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
1971 		    "%s\t(raw time value %" PRIu64 ")\n"), pfx2, lt);
1972 }
1973 
1974 /*
1975  * Print the SA lifetime information.  (An SADB_EXT_LIFETIME_* extension.)
1976  */
1977 void
1978 print_lifetimes(FILE *file, time_t wallclock, struct sadb_lifetime *current,
1979     struct sadb_lifetime *hard, struct sadb_lifetime *soft,
1980     struct sadb_lifetime *idle, boolean_t vflag)
1981 {
1982 	int64_t scratch;
1983 	char *soft_prefix = dgettext(TEXT_DOMAIN, "SLT: ");
1984 	char *hard_prefix = dgettext(TEXT_DOMAIN, "HLT: ");
1985 	char *current_prefix = dgettext(TEXT_DOMAIN, "CLT: ");
1986 	char *idle_prefix = dgettext(TEXT_DOMAIN, "ILT: ");
1987 	char byte_str[BYTE_STR_SIZE]; /* byte lifetime string representation */
1988 	char secs_str[SECS_STR_SIZE]; /* buffer for seconds representation */
1989 
1990 	if (current != NULL &&
1991 	    current->sadb_lifetime_len != SADB_8TO64(sizeof (*current))) {
1992 		warnxfp(EFD(file), dgettext(TEXT_DOMAIN,
1993 		    "WARNING: CURRENT lifetime extension length (%u) is bad."),
1994 		    SADB_64TO8(current->sadb_lifetime_len));
1995 	}
1996 
1997 	if (hard != NULL &&
1998 	    hard->sadb_lifetime_len != SADB_8TO64(sizeof (*hard))) {
1999 		warnxfp(EFD(file), dgettext(TEXT_DOMAIN,
2000 		    "WARNING: HARD lifetime extension length (%u) is bad."),
2001 		    SADB_64TO8(hard->sadb_lifetime_len));
2002 	}
2003 
2004 	if (soft != NULL &&
2005 	    soft->sadb_lifetime_len != SADB_8TO64(sizeof (*soft))) {
2006 		warnxfp(EFD(file), dgettext(TEXT_DOMAIN,
2007 		    "WARNING: SOFT lifetime extension length (%u) is bad."),
2008 		    SADB_64TO8(soft->sadb_lifetime_len));
2009 	}
2010 
2011 	if (idle != NULL &&
2012 	    idle->sadb_lifetime_len != SADB_8TO64(sizeof (*idle))) {
2013 		warnxfp(EFD(file), dgettext(TEXT_DOMAIN,
2014 		    "WARNING: IDLE lifetime extension length (%u) is bad."),
2015 		    SADB_64TO8(idle->sadb_lifetime_len));
2016 	}
2017 
2018 	(void) fprintf(file, " LT: Lifetime information\n");
2019 	if (current != NULL) {
2020 		/* Express values as current values. */
2021 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
2022 		    "%sCurrent lifetime information:\n"),
2023 		    current_prefix);
2024 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
2025 		    "%s%" PRIu64 " bytes %sprotected, %u allocations "
2026 		    "used.\n"), current_prefix,
2027 		    current->sadb_lifetime_bytes,
2028 		    bytecnt2out(current->sadb_lifetime_bytes, byte_str,
2029 		    sizeof (byte_str), SPC_END),
2030 		    current->sadb_lifetime_allocations);
2031 		printsatime(file, current->sadb_lifetime_addtime,
2032 		    dgettext(TEXT_DOMAIN, "%sSA added at time: %s\n"),
2033 		    current_prefix, current_prefix, vflag);
2034 		if (current->sadb_lifetime_usetime != 0) {
2035 			printsatime(file, current->sadb_lifetime_usetime,
2036 			    dgettext(TEXT_DOMAIN,
2037 			    "%sSA first used at time %s\n"),
2038 			    current_prefix, current_prefix, vflag);
2039 		}
2040 		printsatime(file, wallclock, dgettext(TEXT_DOMAIN,
2041 		    "%sTime now is %s\n"), current_prefix, current_prefix,
2042 		    vflag);
2043 	}
2044 
2045 	if (soft != NULL) {
2046 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
2047 		    "%sSoft lifetime information:\n"),
2048 		    soft_prefix);
2049 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
2050 		    "%s%" PRIu64 " bytes %sof lifetime, %u allocations.\n"),
2051 		    soft_prefix,
2052 		    soft->sadb_lifetime_bytes,
2053 		    bytecnt2out(soft->sadb_lifetime_bytes, byte_str,
2054 		    sizeof (byte_str), SPC_END),
2055 		    soft->sadb_lifetime_allocations);
2056 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
2057 		    "%s%" PRIu64 " seconds %sof post-add lifetime.\n"),
2058 		    soft_prefix, soft->sadb_lifetime_addtime,
2059 		    secs2out(soft->sadb_lifetime_addtime, secs_str,
2060 		    sizeof (secs_str), SPC_END));
2061 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
2062 		    "%s%" PRIu64 " seconds %sof post-use lifetime.\n"),
2063 		    soft_prefix, soft->sadb_lifetime_usetime,
2064 		    secs2out(soft->sadb_lifetime_usetime, secs_str,
2065 		    sizeof (secs_str), SPC_END));
2066 		/* If possible, express values as time remaining. */
2067 		if (current != NULL) {
2068 			if (soft->sadb_lifetime_bytes != 0)
2069 				(void) fprintf(file, dgettext(TEXT_DOMAIN, "%s"
2070 				    "%" PRIu64 " bytes %smore can be "
2071 				    "protected.\n"), soft_prefix,
2072 				    (soft->sadb_lifetime_bytes >
2073 				    current->sadb_lifetime_bytes) ?
2074 				    soft->sadb_lifetime_bytes -
2075 				    current->sadb_lifetime_bytes : 0,
2076 				    (soft->sadb_lifetime_bytes >
2077 				    current->sadb_lifetime_bytes) ?
2078 				    bytecnt2out(soft->sadb_lifetime_bytes -
2079 				    current->sadb_lifetime_bytes, byte_str,
2080 				    sizeof (byte_str), SPC_END) : "");
2081 			if (soft->sadb_lifetime_addtime != 0 ||
2082 			    (soft->sadb_lifetime_usetime != 0 &&
2083 			    current->sadb_lifetime_usetime != 0)) {
2084 				int64_t adddelta, usedelta;
2085 
2086 				if (soft->sadb_lifetime_addtime != 0) {
2087 					adddelta =
2088 					    current->sadb_lifetime_addtime +
2089 					    soft->sadb_lifetime_addtime -
2090 					    wallclock;
2091 				} else {
2092 					adddelta = TIME_MAX;
2093 				}
2094 
2095 				if (soft->sadb_lifetime_usetime != 0 &&
2096 				    current->sadb_lifetime_usetime != 0) {
2097 					usedelta =
2098 					    current->sadb_lifetime_usetime +
2099 					    soft->sadb_lifetime_usetime -
2100 					    wallclock;
2101 				} else {
2102 					usedelta = TIME_MAX;
2103 				}
2104 				(void) fprintf(file, "%s", soft_prefix);
2105 				scratch = MIN(adddelta, usedelta);
2106 				if (scratch >= 0) {
2107 					(void) fprintf(file,
2108 					    dgettext(TEXT_DOMAIN,
2109 					    "Soft expiration occurs in %"
2110 					    PRId64 " seconds%s\n"), scratch,
2111 					    secs2out(scratch, secs_str,
2112 					    sizeof (secs_str), SPC_BEGIN));
2113 				} else {
2114 					(void) fprintf(file,
2115 					    dgettext(TEXT_DOMAIN,
2116 					    "Soft expiration occurred\n"));
2117 				}
2118 				scratch += wallclock;
2119 				printsatime(file, scratch, dgettext(TEXT_DOMAIN,
2120 				    "%sTime of expiration: %s.\n"),
2121 				    soft_prefix, soft_prefix, vflag);
2122 			}
2123 		}
2124 	}
2125 
2126 	if (hard != NULL) {
2127 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
2128 		    "%sHard lifetime information:\n"), hard_prefix);
2129 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
2130 		    "%s%" PRIu64 " bytes %sof lifetime, %u allocations.\n"),
2131 		    hard_prefix,
2132 		    hard->sadb_lifetime_bytes,
2133 		    bytecnt2out(hard->sadb_lifetime_bytes, byte_str,
2134 		    sizeof (byte_str), SPC_END),
2135 		    hard->sadb_lifetime_allocations);
2136 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
2137 		    "%s%" PRIu64 " seconds %sof post-add lifetime.\n"),
2138 		    hard_prefix, hard->sadb_lifetime_addtime,
2139 		    secs2out(hard->sadb_lifetime_addtime, secs_str,
2140 		    sizeof (secs_str), SPC_END));
2141 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
2142 		    "%s%" PRIu64 " seconds %sof post-use lifetime.\n"),
2143 		    hard_prefix, hard->sadb_lifetime_usetime,
2144 		    secs2out(hard->sadb_lifetime_usetime, secs_str,
2145 		    sizeof (secs_str), SPC_END));
2146 		/* If possible, express values as time remaining. */
2147 		if (current != NULL) {
2148 			if (hard->sadb_lifetime_bytes != 0)
2149 				(void) fprintf(file, dgettext(TEXT_DOMAIN, "%s"
2150 				    "%" PRIu64 " bytes %smore can be "
2151 				    "protected.\n"), hard_prefix,
2152 				    (hard->sadb_lifetime_bytes >
2153 				    current->sadb_lifetime_bytes) ?
2154 				    hard->sadb_lifetime_bytes -
2155 				    current->sadb_lifetime_bytes : 0,
2156 				    (hard->sadb_lifetime_bytes >
2157 				    current->sadb_lifetime_bytes) ?
2158 				    bytecnt2out(hard->sadb_lifetime_bytes -
2159 				    current->sadb_lifetime_bytes, byte_str,
2160 				    sizeof (byte_str), SPC_END) : "");
2161 			if (hard->sadb_lifetime_addtime != 0 ||
2162 			    (hard->sadb_lifetime_usetime != 0 &&
2163 			    current->sadb_lifetime_usetime != 0)) {
2164 				int64_t adddelta, usedelta;
2165 
2166 				if (hard->sadb_lifetime_addtime != 0) {
2167 					adddelta =
2168 					    current->sadb_lifetime_addtime +
2169 					    hard->sadb_lifetime_addtime -
2170 					    wallclock;
2171 				} else {
2172 					adddelta = TIME_MAX;
2173 				}
2174 
2175 				if (hard->sadb_lifetime_usetime != 0 &&
2176 				    current->sadb_lifetime_usetime != 0) {
2177 					usedelta =
2178 					    current->sadb_lifetime_usetime +
2179 					    hard->sadb_lifetime_usetime -
2180 					    wallclock;
2181 				} else {
2182 					usedelta = TIME_MAX;
2183 				}
2184 				(void) fprintf(file, "%s", hard_prefix);
2185 				scratch = MIN(adddelta, usedelta);
2186 				if (scratch >= 0) {
2187 					(void) fprintf(file,
2188 					    dgettext(TEXT_DOMAIN,
2189 					    "Hard expiration occurs in %"
2190 					    PRId64 " seconds%s\n"), scratch,
2191 					    secs2out(scratch, secs_str,
2192 					    sizeof (secs_str), SPC_BEGIN));
2193 				} else {
2194 					(void) fprintf(file,
2195 					    dgettext(TEXT_DOMAIN,
2196 					    "Hard expiration occurred\n"));
2197 				}
2198 				scratch += wallclock;
2199 				printsatime(file, scratch, dgettext(TEXT_DOMAIN,
2200 				    "%sTime of expiration: %s.\n"),
2201 				    hard_prefix, hard_prefix, vflag);
2202 			}
2203 		}
2204 	}
2205 	if (idle != NULL) {
2206 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
2207 		    "%sIdle lifetime information:\n"), idle_prefix);
2208 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
2209 		    "%s%" PRIu64 " seconds %sof post-add lifetime.\n"),
2210 		    idle_prefix, idle->sadb_lifetime_addtime,
2211 		    secs2out(idle->sadb_lifetime_addtime, secs_str,
2212 		    sizeof (secs_str), SPC_END));
2213 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
2214 		    "%s%" PRIu64 " seconds %sof post-use lifetime.\n"),
2215 		    idle_prefix, idle->sadb_lifetime_usetime,
2216 		    secs2out(idle->sadb_lifetime_usetime, secs_str,
2217 		    sizeof (secs_str), SPC_END));
2218 	}
2219 }
2220 
2221 /*
2222  * Print an SADB_EXT_ADDRESS_* extension.
2223  */
2224 void
2225 print_address(FILE *file, char *prefix, struct sadb_address *addr,
2226     boolean_t ignore_nss)
2227 {
2228 	struct protoent *pe;
2229 
2230 	(void) fprintf(file, "%s", prefix);
2231 	switch (addr->sadb_address_exttype) {
2232 	case SADB_EXT_ADDRESS_SRC:
2233 		(void) fprintf(file, dgettext(TEXT_DOMAIN, "Source address "));
2234 		break;
2235 	case SADB_X_EXT_ADDRESS_INNER_SRC:
2236 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
2237 		    "Inner source address "));
2238 		break;
2239 	case SADB_EXT_ADDRESS_DST:
2240 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
2241 		    "Destination address "));
2242 		break;
2243 	case SADB_X_EXT_ADDRESS_INNER_DST:
2244 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
2245 		    "Inner destination address "));
2246 		break;
2247 	case SADB_X_EXT_ADDRESS_NATT_LOC:
2248 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
2249 		    "NAT-T local address "));
2250 		break;
2251 	case SADB_X_EXT_ADDRESS_NATT_REM:
2252 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
2253 		    "NAT-T remote address "));
2254 		break;
2255 	}
2256 
2257 	(void) fprintf(file, dgettext(TEXT_DOMAIN,
2258 	    "(proto=%d"), addr->sadb_address_proto);
2259 	if (ignore_nss == B_FALSE) {
2260 		if (addr->sadb_address_proto == 0) {
2261 			(void) fprintf(file, dgettext(TEXT_DOMAIN,
2262 			    "/<unspecified>"));
2263 		} else if ((pe = getprotobynumber(addr->sadb_address_proto))
2264 		    != NULL) {
2265 			(void) fprintf(file, "/%s", pe->p_name);
2266 		} else {
2267 			(void) fprintf(file, dgettext(TEXT_DOMAIN,
2268 			    "/<unknown>"));
2269 		}
2270 	}
2271 	(void) fprintf(file, dgettext(TEXT_DOMAIN, ")\n%s"), prefix);
2272 	(void) dump_sockaddr((struct sockaddr *)(addr + 1),
2273 	    addr->sadb_address_prefixlen, B_FALSE, file, ignore_nss);
2274 }
2275 
2276 /*
2277  * Print an SADB_EXT_KEY extension.
2278  */
2279 void
2280 print_key(FILE *file, char *prefix, struct sadb_key *key)
2281 {
2282 	(void) fprintf(file, "%s", prefix);
2283 
2284 	switch (key->sadb_key_exttype) {
2285 	case SADB_EXT_KEY_AUTH:
2286 		(void) fprintf(file, dgettext(TEXT_DOMAIN, "Authentication"));
2287 		break;
2288 	case SADB_EXT_KEY_ENCRYPT:
2289 		(void) fprintf(file, dgettext(TEXT_DOMAIN, "Encryption"));
2290 		break;
2291 	}
2292 
2293 	(void) fprintf(file, dgettext(TEXT_DOMAIN, " key.\n%s"), prefix);
2294 	(void) dump_key((uint8_t *)(key + 1), key->sadb_key_bits,
2295 	    key->sadb_key_reserved, file, B_TRUE);
2296 	(void) fprintf(file, "\n");
2297 }
2298 
2299 /*
2300  * Print an SADB_X_EXT_STR_AUTH extension.
2301  */
2302 void
2303 print_keystr(FILE *file, char *prefix, struct sadb_key *key)
2304 {
2305 	(void) fprintf(file, "%s", prefix);
2306 	(void) fprintf(file, dgettext(TEXT_DOMAIN, "Authentication"));
2307 	(void) fprintf(file, dgettext(TEXT_DOMAIN, " string.\n%s"), prefix);
2308 	(void) fprintf(file, "\"");
2309 	(void) dump_keystr((uint8_t *)(key + 1), key->sadb_key_bits, file);
2310 	(void) fprintf(file, "\"\n");
2311 }
2312 
2313 /*
2314  * Print an SADB_EXT_IDENTITY_* extension.
2315  */
2316 void
2317 print_ident(FILE *file, char *prefix, struct sadb_ident *id)
2318 {
2319 	boolean_t canprint = B_TRUE;
2320 
2321 	(void) fprintf(file, "%s", prefix);
2322 	switch (id->sadb_ident_exttype) {
2323 	case SADB_EXT_IDENTITY_SRC:
2324 		(void) fprintf(file, dgettext(TEXT_DOMAIN, "Source"));
2325 		break;
2326 	case SADB_EXT_IDENTITY_DST:
2327 		(void) fprintf(file, dgettext(TEXT_DOMAIN, "Destination"));
2328 		break;
2329 	}
2330 
2331 	(void) fprintf(file, dgettext(TEXT_DOMAIN,
2332 	    " identity, uid=%d, type "), id->sadb_ident_id);
2333 	canprint = dump_sadb_idtype(id->sadb_ident_type, file, NULL);
2334 	(void) fprintf(file, "\n%s", prefix);
2335 	if (canprint) {
2336 		(void) fprintf(file, "%s\n", (char *)(id + 1));
2337 	} else {
2338 		print_asn1_name(file, (const unsigned char *)(id + 1),
2339 		    SADB_64TO8(id->sadb_ident_len) - sizeof (sadb_ident_t));
2340 	}
2341 }
2342 
2343 /*
2344  * Convert sadb_sens extension into binary security label.
2345  */
2346 
2347 #include <tsol/label.h>
2348 #include <sys/tsol/tndb.h>
2349 #include <sys/tsol/label_macro.h>
2350 
2351 void
2352 ipsec_convert_sens_to_bslabel(const struct sadb_sens *sens, bslabel_t *sl)
2353 {
2354 	uint64_t *bitmap = (uint64_t *)(sens + 1);
2355 	int bitmap_len = SADB_64TO8(sens->sadb_sens_sens_len);
2356 
2357 	bsllow(sl);
2358 	LCLASS_SET((_bslabel_impl_t *)sl, sens->sadb_sens_sens_level);
2359 	bcopy(bitmap, &((_bslabel_impl_t *)sl)->compartments,
2360 	    bitmap_len);
2361 }
2362 
2363 void
2364 ipsec_convert_bslabel_to_string(bslabel_t *sl, char **plabel)
2365 {
2366 	if (label_to_str(sl, plabel, M_LABEL, DEF_NAMES) != 0) {
2367 		*plabel = strdup(dgettext(TEXT_DOMAIN,
2368 		    "** Label conversion failed **"));
2369 	}
2370 }
2371 
2372 void
2373 ipsec_convert_bslabel_to_hex(bslabel_t *sl, char **plabel)
2374 {
2375 	if (label_to_str(sl, plabel, M_INTERNAL, DEF_NAMES) != 0) {
2376 		*plabel = strdup(dgettext(TEXT_DOMAIN,
2377 		    "** Label conversion failed **"));
2378 	}
2379 }
2380 
2381 int
2382 ipsec_convert_sl_to_sens(int doi, bslabel_t *sl, sadb_sens_t *sens)
2383 {
2384 	uint8_t *bitmap;
2385 	int sens_len = sizeof (sadb_sens_t) + _C_LEN * 4;
2386 
2387 
2388 	if (sens == NULL)
2389 		return (sens_len);
2390 
2391 
2392 	(void) memset(sens, 0, sens_len);
2393 
2394 	sens->sadb_sens_exttype = SADB_EXT_SENSITIVITY;
2395 	sens->sadb_sens_len = SADB_8TO64(sens_len);
2396 	sens->sadb_sens_dpd = doi;
2397 
2398 	sens->sadb_sens_sens_level = LCLASS(sl);
2399 	sens->sadb_sens_integ_level = 0;
2400 	sens->sadb_sens_sens_len = _C_LEN >> 1;
2401 	sens->sadb_sens_integ_len = 0;
2402 
2403 	sens->sadb_x_sens_flags = 0;
2404 
2405 	bitmap = (uint8_t *)(sens + 1);
2406 	bcopy(&(((_bslabel_impl_t *)sl)->compartments), bitmap, _C_LEN * 4);
2407 
2408 	return (sens_len);
2409 }
2410 
2411 
2412 /*
2413  * Print an SADB_SENSITIVITY extension.
2414  */
2415 void
2416 print_sens(FILE *file, char *prefix, const struct sadb_sens *sens,
2417     boolean_t ignore_nss)
2418 {
2419 	char *plabel;
2420 	char *hlabel;
2421 	uint64_t *bitmap = (uint64_t *)(sens + 1);
2422 	bslabel_t sl;
2423 	int i;
2424 	int sens_len = sens->sadb_sens_sens_len;
2425 	int integ_len = sens->sadb_sens_integ_len;
2426 	boolean_t inner = (sens->sadb_sens_exttype == SADB_EXT_SENSITIVITY);
2427 	const char *sensname = inner ?
2428 	    dgettext(TEXT_DOMAIN, "Plaintext Sensitivity") :
2429 	    dgettext(TEXT_DOMAIN, "Ciphertext Sensitivity");
2430 
2431 	ipsec_convert_sens_to_bslabel(sens, &sl);
2432 
2433 	(void) fprintf(file, dgettext(TEXT_DOMAIN,
2434 	    "%s%s DPD %d, sens level=%d, integ level=%d, flags=%x\n"),
2435 	    prefix, sensname, sens->sadb_sens_dpd, sens->sadb_sens_sens_level,
2436 	    sens->sadb_sens_integ_level, sens->sadb_x_sens_flags);
2437 
2438 	ipsec_convert_bslabel_to_hex(&sl, &hlabel);
2439 
2440 	if (ignore_nss) {
2441 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
2442 		    "%s %s Label: %s\n"), prefix, sensname, hlabel);
2443 
2444 		for (i = 0; i < sens_len; i++, bitmap++)
2445 			(void) fprintf(file, dgettext(TEXT_DOMAIN,
2446 			    "%s %s BM extended word %d 0x%" PRIx64 "\n"),
2447 			    prefix, sensname, i, *bitmap);
2448 
2449 	} else {
2450 		ipsec_convert_bslabel_to_string(&sl, &plabel);
2451 
2452 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
2453 		    "%s %s Label: %s (%s)\n"),
2454 		    prefix, sensname, plabel, hlabel);
2455 		free(plabel);
2456 
2457 	}
2458 	free(hlabel);
2459 
2460 	bitmap = (uint64_t *)(sens + 1 + sens_len);
2461 
2462 	for (i = 0; i < integ_len; i++, bitmap++)
2463 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
2464 		    "%s Integrity BM extended word %d 0x%" PRIx64 "\n"),
2465 		    prefix, i, *bitmap);
2466 }
2467 
2468 /*
2469  * Print an SADB_EXT_PROPOSAL extension.
2470  */
2471 void
2472 print_prop(FILE *file, char *prefix, struct sadb_prop *prop)
2473 {
2474 	struct sadb_comb *combs;
2475 	int i, numcombs;
2476 
2477 	(void) fprintf(file, dgettext(TEXT_DOMAIN,
2478 	    "%sProposal, replay counter = %u.\n"), prefix,
2479 	    prop->sadb_prop_replay);
2480 
2481 	numcombs = prop->sadb_prop_len - SADB_8TO64(sizeof (*prop));
2482 	numcombs /= SADB_8TO64(sizeof (*combs));
2483 
2484 	combs = (struct sadb_comb *)(prop + 1);
2485 
2486 	for (i = 0; i < numcombs; i++) {
2487 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
2488 		    "%s Combination #%u "), prefix, i + 1);
2489 		if (combs[i].sadb_comb_auth != SADB_AALG_NONE) {
2490 			(void) fprintf(file, dgettext(TEXT_DOMAIN,
2491 			    "Authentication = "));
2492 			(void) dump_aalg(combs[i].sadb_comb_auth, file);
2493 			(void) fprintf(file, dgettext(TEXT_DOMAIN,
2494 			    "  minbits=%u, maxbits=%u.\n%s "),
2495 			    combs[i].sadb_comb_auth_minbits,
2496 			    combs[i].sadb_comb_auth_maxbits, prefix);
2497 		}
2498 
2499 		if (combs[i].sadb_comb_encrypt != SADB_EALG_NONE) {
2500 			(void) fprintf(file, dgettext(TEXT_DOMAIN,
2501 			    "Encryption = "));
2502 			(void) dump_ealg(combs[i].sadb_comb_encrypt, file);
2503 			(void) fprintf(file, dgettext(TEXT_DOMAIN,
2504 			    "  minbits=%u, maxbits=%u, saltbits=%u.\n%s "),
2505 			    combs[i].sadb_comb_encrypt_minbits,
2506 			    combs[i].sadb_comb_encrypt_maxbits,
2507 			    combs[i].sadb_x_comb_encrypt_saltbits, prefix);
2508 		}
2509 
2510 		(void) fprintf(file, dgettext(TEXT_DOMAIN, "HARD: "));
2511 		if (combs[i].sadb_comb_hard_allocations)
2512 			(void) fprintf(file, dgettext(TEXT_DOMAIN, "alloc=%u "),
2513 			    combs[i].sadb_comb_hard_allocations);
2514 		if (combs[i].sadb_comb_hard_bytes)
2515 			(void) fprintf(file, dgettext(TEXT_DOMAIN, "bytes=%"
2516 			    PRIu64 " "), combs[i].sadb_comb_hard_bytes);
2517 		if (combs[i].sadb_comb_hard_addtime)
2518 			(void) fprintf(file, dgettext(TEXT_DOMAIN,
2519 			    "post-add secs=%" PRIu64 " "),
2520 			    combs[i].sadb_comb_hard_addtime);
2521 		if (combs[i].sadb_comb_hard_usetime)
2522 			(void) fprintf(file, dgettext(TEXT_DOMAIN,
2523 			    "post-use secs=%" PRIu64 ""),
2524 			    combs[i].sadb_comb_hard_usetime);
2525 
2526 		(void) fprintf(file, dgettext(TEXT_DOMAIN, "\n%s SOFT: "),
2527 		    prefix);
2528 		if (combs[i].sadb_comb_soft_allocations)
2529 			(void) fprintf(file, dgettext(TEXT_DOMAIN, "alloc=%u "),
2530 			    combs[i].sadb_comb_soft_allocations);
2531 		if (combs[i].sadb_comb_soft_bytes)
2532 			(void) fprintf(file, dgettext(TEXT_DOMAIN, "bytes=%"
2533 			    PRIu64 " "), combs[i].sadb_comb_soft_bytes);
2534 		if (combs[i].sadb_comb_soft_addtime)
2535 			(void) fprintf(file, dgettext(TEXT_DOMAIN,
2536 			    "post-add secs=%" PRIu64 " "),
2537 			    combs[i].sadb_comb_soft_addtime);
2538 		if (combs[i].sadb_comb_soft_usetime)
2539 			(void) fprintf(file, dgettext(TEXT_DOMAIN,
2540 			    "post-use secs=%" PRIu64 ""),
2541 			    combs[i].sadb_comb_soft_usetime);
2542 		(void) fprintf(file, "\n");
2543 	}
2544 }
2545 
2546 /*
2547  * Print an extended proposal (SADB_X_EXT_EPROP).
2548  */
2549 void
2550 print_eprop(FILE *file, char *prefix, struct sadb_prop *eprop)
2551 {
2552 	uint64_t *sofar;
2553 	struct sadb_x_ecomb *ecomb;
2554 	struct sadb_x_algdesc *algdesc;
2555 	int i, j;
2556 
2557 	(void) fprintf(file, dgettext(TEXT_DOMAIN,
2558 	    "%sExtended Proposal, replay counter = %u, "), prefix,
2559 	    eprop->sadb_prop_replay);
2560 	(void) fprintf(file, dgettext(TEXT_DOMAIN,
2561 	    "number of combinations = %u.\n"), eprop->sadb_x_prop_numecombs);
2562 
2563 	sofar = (uint64_t *)(eprop + 1);
2564 	ecomb = (struct sadb_x_ecomb *)sofar;
2565 
2566 	for (i = 0; i < eprop->sadb_x_prop_numecombs; ) {
2567 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
2568 		    "%s Extended combination #%u:\n"), prefix, ++i);
2569 
2570 		(void) fprintf(file, dgettext(TEXT_DOMAIN, "%s HARD: "),
2571 		    prefix);
2572 		(void) fprintf(file, dgettext(TEXT_DOMAIN, "alloc=%u, "),
2573 		    ecomb->sadb_x_ecomb_hard_allocations);
2574 		(void) fprintf(file, dgettext(TEXT_DOMAIN, "bytes=%" PRIu64
2575 		    ", "), ecomb->sadb_x_ecomb_hard_bytes);
2576 		(void) fprintf(file, dgettext(TEXT_DOMAIN, "post-add secs=%"
2577 		    PRIu64 ", "), ecomb->sadb_x_ecomb_hard_addtime);
2578 		(void) fprintf(file, dgettext(TEXT_DOMAIN, "post-use secs=%"
2579 		    PRIu64 "\n"), ecomb->sadb_x_ecomb_hard_usetime);
2580 
2581 		(void) fprintf(file, dgettext(TEXT_DOMAIN, "%s SOFT: "),
2582 		    prefix);
2583 		(void) fprintf(file, dgettext(TEXT_DOMAIN, "alloc=%u, "),
2584 		    ecomb->sadb_x_ecomb_soft_allocations);
2585 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
2586 		    "bytes=%" PRIu64 ", "), ecomb->sadb_x_ecomb_soft_bytes);
2587 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
2588 		    "post-add secs=%" PRIu64 ", "),
2589 		    ecomb->sadb_x_ecomb_soft_addtime);
2590 		(void) fprintf(file, dgettext(TEXT_DOMAIN, "post-use secs=%"
2591 		    PRIu64 "\n"), ecomb->sadb_x_ecomb_soft_usetime);
2592 
2593 		sofar = (uint64_t *)(ecomb + 1);
2594 		algdesc = (struct sadb_x_algdesc *)sofar;
2595 
2596 		for (j = 0; j < ecomb->sadb_x_ecomb_numalgs; ) {
2597 			(void) fprintf(file, dgettext(TEXT_DOMAIN,
2598 			    "%s Alg #%u "), prefix, ++j);
2599 			switch (algdesc->sadb_x_algdesc_satype) {
2600 			case SADB_SATYPE_ESP:
2601 				(void) fprintf(file, dgettext(TEXT_DOMAIN,
2602 				    "for ESP "));
2603 				break;
2604 			case SADB_SATYPE_AH:
2605 				(void) fprintf(file, dgettext(TEXT_DOMAIN,
2606 				    "for AH "));
2607 				break;
2608 			case SADB_X_SATYPE_TCPSIG:
2609 				(void) fprintf(file, dgettext(TEXT_DOMAIN,
2610 				    "for TCPSIG "));
2611 				break;
2612 			default:
2613 				(void) fprintf(file, dgettext(TEXT_DOMAIN,
2614 				    "for satype=%d "),
2615 				    algdesc->sadb_x_algdesc_satype);
2616 			}
2617 			switch (algdesc->sadb_x_algdesc_algtype) {
2618 			case SADB_X_ALGTYPE_CRYPT:
2619 				(void) fprintf(file, dgettext(TEXT_DOMAIN,
2620 				    "Encryption = "));
2621 				(void) dump_ealg(algdesc->sadb_x_algdesc_alg,
2622 				    file);
2623 				break;
2624 			case SADB_X_ALGTYPE_AUTH:
2625 				(void) fprintf(file, dgettext(TEXT_DOMAIN,
2626 				    "Authentication = "));
2627 				(void) dump_aalg(algdesc->sadb_x_algdesc_alg,
2628 				    file);
2629 				break;
2630 			default:
2631 				(void) fprintf(file, dgettext(TEXT_DOMAIN,
2632 				    "algtype(%d) = alg(%d)"),
2633 				    algdesc->sadb_x_algdesc_algtype,
2634 				    algdesc->sadb_x_algdesc_alg);
2635 				break;
2636 			}
2637 
2638 			(void) fprintf(file, dgettext(TEXT_DOMAIN,
2639 			    "  minbits=%u, maxbits=%u, saltbits=%u\n"),
2640 			    algdesc->sadb_x_algdesc_minbits,
2641 			    algdesc->sadb_x_algdesc_maxbits,
2642 			    algdesc->sadb_x_algdesc_saltbits);
2643 
2644 			sofar = (uint64_t *)(++algdesc);
2645 		}
2646 		ecomb = (struct sadb_x_ecomb *)sofar;
2647 	}
2648 }
2649 
2650 /*
2651  * Print an SADB_EXT_SUPPORTED extension.
2652  */
2653 void
2654 print_supp(FILE *file, char *prefix, struct sadb_supported *supp)
2655 {
2656 	struct sadb_alg *algs;
2657 	int i, numalgs;
2658 
2659 	(void) fprintf(file, dgettext(TEXT_DOMAIN, "%sSupported "), prefix);
2660 	switch (supp->sadb_supported_exttype) {
2661 	case SADB_EXT_SUPPORTED_AUTH:
2662 		(void) fprintf(file, dgettext(TEXT_DOMAIN, "authentication"));
2663 		break;
2664 	case SADB_EXT_SUPPORTED_ENCRYPT:
2665 		(void) fprintf(file, dgettext(TEXT_DOMAIN, "encryption"));
2666 		break;
2667 	}
2668 	(void) fprintf(file, dgettext(TEXT_DOMAIN, " algorithms.\n"));
2669 
2670 	algs = (struct sadb_alg *)(supp + 1);
2671 	numalgs = supp->sadb_supported_len - SADB_8TO64(sizeof (*supp));
2672 	numalgs /= SADB_8TO64(sizeof (*algs));
2673 	for (i = 0; i < numalgs; i++) {
2674 		uint16_t exttype = supp->sadb_supported_exttype;
2675 
2676 		(void) fprintf(file, "%s", prefix);
2677 		switch (exttype) {
2678 		case SADB_EXT_SUPPORTED_AUTH:
2679 			(void) dump_aalg(algs[i].sadb_alg_id, file);
2680 			break;
2681 		case SADB_EXT_SUPPORTED_ENCRYPT:
2682 			(void) dump_ealg(algs[i].sadb_alg_id, file);
2683 			break;
2684 		}
2685 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
2686 		    " minbits=%u, maxbits=%u, ivlen=%u, saltbits=%u"),
2687 		    algs[i].sadb_alg_minbits, algs[i].sadb_alg_maxbits,
2688 		    algs[i].sadb_alg_ivlen, algs[i].sadb_x_alg_saltbits);
2689 		if (exttype == SADB_EXT_SUPPORTED_ENCRYPT)
2690 			(void) fprintf(file, dgettext(TEXT_DOMAIN,
2691 			    ", increment=%u"), algs[i].sadb_x_alg_increment);
2692 		(void) fprintf(file, dgettext(TEXT_DOMAIN, ".\n"));
2693 	}
2694 }
2695 
2696 /*
2697  * Print an SADB_EXT_SPIRANGE extension.
2698  */
2699 void
2700 print_spirange(FILE *file, char *prefix, struct sadb_spirange *range)
2701 {
2702 	(void) fprintf(file, dgettext(TEXT_DOMAIN,
2703 	    "%sSPI Range, min=0x%x, max=0x%x\n"), prefix,
2704 	    htonl(range->sadb_spirange_min),
2705 	    htonl(range->sadb_spirange_max));
2706 }
2707 
2708 /*
2709  * Print an SADB_X_EXT_KM_COOKIE extension.
2710  */
2711 
2712 void
2713 print_kmc(FILE *file, char *prefix, struct sadb_x_kmc *kmc)
2714 {
2715 	char *cookie_label;
2716 
2717 	switch (kmc->sadb_x_kmc_proto) {
2718 	case SADB_X_KMP_IKE:
2719 		cookie_label = kmc_lookup_by_cookie(kmc->sadb_x_kmc_cookie);
2720 		if (cookie_label == NULL)
2721 			cookie_label =
2722 			    dgettext(TEXT_DOMAIN, "<Label not found.>");
2723 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
2724 		    "%s Protocol %u, cookie=\"%s\" (%u)\n"), prefix,
2725 		    kmc->sadb_x_kmc_proto, cookie_label,
2726 		    kmc->sadb_x_kmc_cookie);
2727 		return;
2728 	case SADB_X_KMP_KINK:
2729 		cookie_label = dgettext(TEXT_DOMAIN, "KINK:");
2730 		break;
2731 	case SADB_X_KMP_MANUAL:
2732 		cookie_label = dgettext(TEXT_DOMAIN, "Manual SA with cookie:");
2733 		break;
2734 	case SADB_X_KMP_IKEV2:
2735 		cookie_label = dgettext(TEXT_DOMAIN, "IKEV2:");
2736 		break;
2737 	default:
2738 		cookie_label =
2739 		    dgettext(TEXT_DOMAIN, "<unknown KM protocol>");
2740 		break;
2741 	}
2742 
2743 	/*
2744 	 * Assume native-byte-order printing for now.  Exceptions (like
2745 	 * byte-swapping) should be handled in per-KM-protocol cases above.
2746 	 */
2747 	(void) fprintf(file, dgettext(TEXT_DOMAIN,
2748 	    "%s Protocol %u, cookie=\"%s\" (0x%"PRIx64"/%"PRIu64")\n"),
2749 	    prefix, kmc->sadb_x_kmc_proto, cookie_label,
2750 	    kmc->sadb_x_kmc_cookie64, kmc->sadb_x_kmc_cookie64);
2751 }
2752 
2753 /*
2754  * Print an SADB_X_EXT_REPLAY_CTR extension.
2755  */
2756 
2757 void
2758 print_replay(FILE *file, char *prefix, sadb_x_replay_ctr_t *repl)
2759 {
2760 	(void) fprintf(file, dgettext(TEXT_DOMAIN,
2761 	    "%sReplay Value "), prefix);
2762 	if ((repl->sadb_x_rc_replay32 == 0) &&
2763 	    (repl->sadb_x_rc_replay64 == 0)) {
2764 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
2765 		    "<Value not found.>"));
2766 	}
2767 	/*
2768 	 * We currently do not support a 64-bit replay value.
2769 	 * RFC 4301 will require one, however, and we have a field
2770 	 * in place when 4301 is built.
2771 	 */
2772 	(void) fprintf(file, "% " PRIu64 "\n",
2773 	    ((repl->sadb_x_rc_replay32 == 0) ?
2774 	    repl->sadb_x_rc_replay64 : repl->sadb_x_rc_replay32));
2775 }
2776 /*
2777  * Print an SADB_X_EXT_PAIR extension.
2778  */
2779 static void
2780 print_pair(FILE *file, char *prefix, struct sadb_x_pair *pair)
2781 {
2782 	(void) fprintf(file, dgettext(TEXT_DOMAIN, "%sPaired with spi=0x%x\n"),
2783 	    prefix, ntohl(pair->sadb_x_pair_spi));
2784 }
2785 
2786 /*
2787  * Take a PF_KEY message pointed to buffer and print it.  Useful for DUMP
2788  * and GET.
2789  */
2790 void
2791 print_samsg(FILE *file, uint64_t *buffer, boolean_t want_timestamp,
2792     boolean_t vflag, boolean_t ignore_nss)
2793 {
2794 	uint64_t *current;
2795 	struct sadb_msg *samsg = (struct sadb_msg *)buffer;
2796 	struct sadb_ext *ext;
2797 	struct sadb_lifetime *currentlt = NULL, *hardlt = NULL, *softlt = NULL;
2798 	struct sadb_lifetime *idlelt = NULL;
2799 	int i;
2800 	time_t wallclock;
2801 
2802 	(void) time(&wallclock);
2803 
2804 	print_sadb_msg(file, samsg, want_timestamp ? wallclock : 0, vflag);
2805 	current = (uint64_t *)(samsg + 1);
2806 	while (current - buffer < samsg->sadb_msg_len) {
2807 		int lenbytes;
2808 
2809 		ext = (struct sadb_ext *)current;
2810 		lenbytes = SADB_64TO8(ext->sadb_ext_len);
2811 		switch (ext->sadb_ext_type) {
2812 		case SADB_EXT_SA:
2813 			print_sa(file, dgettext(TEXT_DOMAIN,
2814 			    "SA: "), (struct sadb_sa *)current);
2815 			break;
2816 		/*
2817 		 * Pluck out lifetimes and print them at the end.  This is
2818 		 * to show relative lifetimes.
2819 		 */
2820 		case SADB_EXT_LIFETIME_CURRENT:
2821 			currentlt = (struct sadb_lifetime *)current;
2822 			break;
2823 		case SADB_EXT_LIFETIME_HARD:
2824 			hardlt = (struct sadb_lifetime *)current;
2825 			break;
2826 		case SADB_EXT_LIFETIME_SOFT:
2827 			softlt = (struct sadb_lifetime *)current;
2828 			break;
2829 		case SADB_X_EXT_LIFETIME_IDLE:
2830 			idlelt = (struct sadb_lifetime *)current;
2831 			break;
2832 
2833 		case SADB_EXT_ADDRESS_SRC:
2834 			print_address(file, dgettext(TEXT_DOMAIN, "SRC: "),
2835 			    (struct sadb_address *)current, ignore_nss);
2836 			break;
2837 		case SADB_X_EXT_ADDRESS_INNER_SRC:
2838 			print_address(file, dgettext(TEXT_DOMAIN, "INS: "),
2839 			    (struct sadb_address *)current, ignore_nss);
2840 			break;
2841 		case SADB_EXT_ADDRESS_DST:
2842 			print_address(file, dgettext(TEXT_DOMAIN, "DST: "),
2843 			    (struct sadb_address *)current, ignore_nss);
2844 			break;
2845 		case SADB_X_EXT_ADDRESS_INNER_DST:
2846 			print_address(file, dgettext(TEXT_DOMAIN, "IND: "),
2847 			    (struct sadb_address *)current, ignore_nss);
2848 			break;
2849 		case SADB_EXT_KEY_AUTH:
2850 			print_key(file, dgettext(TEXT_DOMAIN,
2851 			    "AKY: "), (struct sadb_key *)current);
2852 			break;
2853 		case SADB_X_EXT_STR_AUTH:
2854 			print_keystr(file, dgettext(TEXT_DOMAIN,
2855 			    "AST: "), (struct sadb_key *)current);
2856 			break;
2857 		case SADB_EXT_KEY_ENCRYPT:
2858 			print_key(file, dgettext(TEXT_DOMAIN,
2859 			    "EKY: "), (struct sadb_key *)current);
2860 			break;
2861 		case SADB_EXT_IDENTITY_SRC:
2862 			print_ident(file, dgettext(TEXT_DOMAIN, "SID: "),
2863 			    (struct sadb_ident *)current);
2864 			break;
2865 		case SADB_EXT_IDENTITY_DST:
2866 			print_ident(file, dgettext(TEXT_DOMAIN, "DID: "),
2867 			    (struct sadb_ident *)current);
2868 			break;
2869 		case SADB_EXT_SENSITIVITY:
2870 			print_sens(file, dgettext(TEXT_DOMAIN, "SNS: "),
2871 			    (struct sadb_sens *)current, ignore_nss);
2872 			break;
2873 		case SADB_EXT_PROPOSAL:
2874 			print_prop(file, dgettext(TEXT_DOMAIN, "PRP: "),
2875 			    (struct sadb_prop *)current);
2876 			break;
2877 		case SADB_EXT_SUPPORTED_AUTH:
2878 			print_supp(file, dgettext(TEXT_DOMAIN, "SUA: "),
2879 			    (struct sadb_supported *)current);
2880 			break;
2881 		case SADB_EXT_SUPPORTED_ENCRYPT:
2882 			print_supp(file, dgettext(TEXT_DOMAIN, "SUE: "),
2883 			    (struct sadb_supported *)current);
2884 			break;
2885 		case SADB_EXT_SPIRANGE:
2886 			print_spirange(file, dgettext(TEXT_DOMAIN, "SPR: "),
2887 			    (struct sadb_spirange *)current);
2888 			break;
2889 		case SADB_X_EXT_EPROP:
2890 			print_eprop(file, dgettext(TEXT_DOMAIN, "EPR: "),
2891 			    (struct sadb_prop *)current);
2892 			break;
2893 		case SADB_X_EXT_KM_COOKIE:
2894 			print_kmc(file, dgettext(TEXT_DOMAIN, "KMC: "),
2895 			    (struct sadb_x_kmc *)current);
2896 			break;
2897 		case SADB_X_EXT_ADDRESS_NATT_REM:
2898 			print_address(file, dgettext(TEXT_DOMAIN, "NRM: "),
2899 			    (struct sadb_address *)current, ignore_nss);
2900 			break;
2901 		case SADB_X_EXT_ADDRESS_NATT_LOC:
2902 			print_address(file, dgettext(TEXT_DOMAIN, "NLC: "),
2903 			    (struct sadb_address *)current, ignore_nss);
2904 			break;
2905 		case SADB_X_EXT_PAIR:
2906 			print_pair(file, dgettext(TEXT_DOMAIN, "OTH: "),
2907 			    (struct sadb_x_pair *)current);
2908 			break;
2909 		case SADB_X_EXT_OUTER_SENS:
2910 			print_sens(file, dgettext(TEXT_DOMAIN, "OSN: "),
2911 			    (struct sadb_sens *)current, ignore_nss);
2912 			break;
2913 		case SADB_X_EXT_REPLAY_VALUE:
2914 			(void) print_replay(file, dgettext(TEXT_DOMAIN,
2915 			    "RPL: "), (sadb_x_replay_ctr_t *)current);
2916 			break;
2917 		default:
2918 			(void) fprintf(file, dgettext(TEXT_DOMAIN,
2919 			    "UNK: Unknown ext. %d, len %d.\n"),
2920 			    ext->sadb_ext_type, lenbytes);
2921 			for (i = 0; i < ext->sadb_ext_len; i++)
2922 				(void) fprintf(file, dgettext(TEXT_DOMAIN,
2923 				    "UNK: 0x%" PRIx64 "\n"),
2924 				    ((uint64_t *)ext)[i]);
2925 			break;
2926 		}
2927 		current += (lenbytes == 0) ?
2928 		    SADB_8TO64(sizeof (struct sadb_ext)) : ext->sadb_ext_len;
2929 	}
2930 	/*
2931 	 * Print lifetimes NOW.
2932 	 */
2933 	if (currentlt != NULL || hardlt != NULL || softlt != NULL ||
2934 	    idlelt != NULL)
2935 		print_lifetimes(file, wallclock, currentlt, hardlt,
2936 		    softlt, idlelt, vflag);
2937 
2938 	if (current - buffer != samsg->sadb_msg_len) {
2939 		warnxfp(EFD(file), dgettext(TEXT_DOMAIN,
2940 		    "WARNING: insufficient buffer space or corrupt message."));
2941 	}
2942 
2943 	(void) fflush(file);	/* Make sure our message is out there. */
2944 }
2945 
2946 /*
2947  * save_XXX functions are used when "saving" the SA tables to either a
2948  * file or standard output.  They use the dump_XXX functions where needed,
2949  * but mostly they use the rparseXXX functions.
2950  */
2951 
2952 /*
2953  * Print save information for a lifetime extension.
2954  *
2955  * NOTE : It saves the lifetime in absolute terms.  For example, if you
2956  * had a hard_usetime of 60 seconds, you'll save it as 60 seconds, even though
2957  * there may have been 59 seconds burned off the clock.
2958  */
2959 boolean_t
2960 save_lifetime(struct sadb_lifetime *lifetime, FILE *ofile)
2961 {
2962 	char *prefix;
2963 
2964 	switch (lifetime->sadb_lifetime_exttype) {
2965 	case SADB_EXT_LIFETIME_HARD:
2966 		prefix = "hard";
2967 		break;
2968 	case SADB_EXT_LIFETIME_SOFT:
2969 		prefix = "soft";
2970 		break;
2971 	case SADB_X_EXT_LIFETIME_IDLE:
2972 		prefix = "idle";
2973 		break;
2974 	}
2975 
2976 	if (putc('\t', ofile) == EOF)
2977 		return (B_FALSE);
2978 
2979 	if (lifetime->sadb_lifetime_allocations != 0 && fprintf(ofile,
2980 	    "%s_alloc %u ", prefix, lifetime->sadb_lifetime_allocations) < 0)
2981 		return (B_FALSE);
2982 
2983 	if (lifetime->sadb_lifetime_bytes != 0 && fprintf(ofile,
2984 	    "%s_bytes %" PRIu64 " ", prefix, lifetime->sadb_lifetime_bytes) < 0)
2985 		return (B_FALSE);
2986 
2987 	if (lifetime->sadb_lifetime_addtime != 0 && fprintf(ofile,
2988 	    "%s_addtime %" PRIu64 " ", prefix,
2989 	    lifetime->sadb_lifetime_addtime) < 0)
2990 		return (B_FALSE);
2991 
2992 	if (lifetime->sadb_lifetime_usetime != 0 && fprintf(ofile,
2993 	    "%s_usetime %" PRIu64 " ", prefix,
2994 	    lifetime->sadb_lifetime_usetime) < 0)
2995 		return (B_FALSE);
2996 
2997 	return (B_TRUE);
2998 }
2999 
3000 /*
3001  * Print save information for an address extension.
3002  */
3003 boolean_t
3004 save_address(struct sadb_address *addr, FILE *ofile)
3005 {
3006 	char *printable_addr, buf[INET6_ADDRSTRLEN];
3007 	const char *prefix, *pprefix;
3008 	struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)(addr + 1);
3009 	struct sockaddr_in *sin = (struct sockaddr_in *)sin6;
3010 	int af = sin->sin_family;
3011 
3012 	/*
3013 	 * Address-family reality check.
3014 	 */
3015 	if (af != AF_INET6 && af != AF_INET)
3016 		return (B_FALSE);
3017 
3018 	switch (addr->sadb_address_exttype) {
3019 	case SADB_EXT_ADDRESS_SRC:
3020 		prefix = "src";
3021 		pprefix = "sport";
3022 		break;
3023 	case SADB_X_EXT_ADDRESS_INNER_SRC:
3024 		prefix = "isrc";
3025 		pprefix = "isport";
3026 		break;
3027 	case SADB_EXT_ADDRESS_DST:
3028 		prefix = "dst";
3029 		pprefix = "dport";
3030 		break;
3031 	case SADB_X_EXT_ADDRESS_INNER_DST:
3032 		prefix = "idst";
3033 		pprefix = "idport";
3034 		break;
3035 	case SADB_X_EXT_ADDRESS_NATT_LOC:
3036 		prefix = "nat_loc ";
3037 		pprefix = "nat_lport";
3038 		break;
3039 	case SADB_X_EXT_ADDRESS_NATT_REM:
3040 		prefix = "nat_rem ";
3041 		pprefix = "nat_rport";
3042 		break;
3043 	}
3044 
3045 	if (fprintf(ofile, "    %s ", prefix) < 0)
3046 		return (B_FALSE);
3047 
3048 	/*
3049 	 * Do not do address-to-name translation, given that we live in
3050 	 * an age of names that explode into many addresses.
3051 	 */
3052 	printable_addr = (char *)inet_ntop(af,
3053 	    (af == AF_INET) ? (char *)&sin->sin_addr : (char *)&sin6->sin6_addr,
3054 	    buf, sizeof (buf));
3055 	if (printable_addr == NULL)
3056 		printable_addr = "Invalid IP address.";
3057 	if (fprintf(ofile, "%s", printable_addr) < 0)
3058 		return (B_FALSE);
3059 	if (addr->sadb_address_prefixlen != 0 &&
3060 	    !((addr->sadb_address_prefixlen == 32 && af == AF_INET) ||
3061 	    (addr->sadb_address_prefixlen == 128 && af == AF_INET6))) {
3062 		if (fprintf(ofile, "/%d", addr->sadb_address_prefixlen) < 0)
3063 			return (B_FALSE);
3064 	}
3065 
3066 	/*
3067 	 * The port is in the same position for struct sockaddr_in and
3068 	 * struct sockaddr_in6.  We exploit that property here.
3069 	 */
3070 	if ((pprefix != NULL) && (sin->sin_port != 0))
3071 		(void) fprintf(ofile, " %s %d", pprefix, ntohs(sin->sin_port));
3072 
3073 	return (B_TRUE);
3074 }
3075 
3076 /*
3077  * Print save information for a key extension. Returns whether writing
3078  * to the specified output file was successful or not.
3079  */
3080 boolean_t
3081 save_key(struct sadb_key *key, FILE *ofile)
3082 {
3083 	char *prefix;
3084 
3085 	if (putc('\t', ofile) == EOF)
3086 		return (B_FALSE);
3087 
3088 	prefix = (key->sadb_key_exttype == SADB_EXT_KEY_AUTH) ? "auth" : "encr";
3089 
3090 	if (fprintf(ofile, "%skey ", prefix) < 0)
3091 		return (B_FALSE);
3092 
3093 	if (dump_key((uint8_t *)(key + 1), key->sadb_key_bits,
3094 	    key->sadb_key_reserved, ofile, B_FALSE) == -1)
3095 		return (B_FALSE);
3096 
3097 	return (B_TRUE);
3098 }
3099 
3100 /*
3101  * Print save information for a key extension. Returns whether writing
3102  * to the specified output file was successful or not.
3103  */
3104 boolean_t
3105 save_keystr(struct sadb_key *key, FILE *ofile)
3106 {
3107 	if (putc('\t', ofile) == EOF)
3108 		return (B_FALSE);
3109 
3110 	if (fprintf(ofile, "authstring \"") < 0)
3111 		return (B_FALSE);
3112 
3113 	if (dump_keystr((uint8_t *)(key + 1), key->sadb_key_bits, ofile) == -1)
3114 		return (B_FALSE);
3115 
3116 	if (fprintf(ofile, "\"") < 0)
3117 		return (B_FALSE);
3118 
3119 	return (B_TRUE);
3120 }
3121 
3122 /*
3123  * Print save information for an identity extension.
3124  */
3125 boolean_t
3126 save_ident(struct sadb_ident *ident, FILE *ofile)
3127 {
3128 	char *prefix;
3129 
3130 	if (putc('\t', ofile) == EOF)
3131 		return (B_FALSE);
3132 
3133 	prefix = (ident->sadb_ident_exttype == SADB_EXT_IDENTITY_SRC) ? "src" :
3134 	    "dst";
3135 
3136 	if (fprintf(ofile, "%sidtype %s ", prefix,
3137 	    rparseidtype(ident->sadb_ident_type)) < 0)
3138 		return (B_FALSE);
3139 
3140 	if (ident->sadb_ident_type == SADB_X_IDENTTYPE_DN ||
3141 	    ident->sadb_ident_type == SADB_X_IDENTTYPE_GN) {
3142 		if (fprintf(ofile, dgettext(TEXT_DOMAIN,
3143 		    "<can-not-print>")) < 0)
3144 			return (B_FALSE);
3145 	} else {
3146 		if (fprintf(ofile, "%s", (char *)(ident + 1)) < 0)
3147 			return (B_FALSE);
3148 	}
3149 
3150 	return (B_TRUE);
3151 }
3152 
3153 boolean_t
3154 save_sens(struct sadb_sens *sens, FILE *ofile)
3155 {
3156 	char *prefix;
3157 	char *hlabel;
3158 	bslabel_t sl;
3159 
3160 	if (putc('\t', ofile) == EOF)
3161 		return (B_FALSE);
3162 
3163 	if (sens->sadb_sens_exttype == SADB_EXT_SENSITIVITY)
3164 		prefix = "label";
3165 	else if ((sens->sadb_x_sens_flags & SADB_X_SENS_IMPLICIT) == 0)
3166 		prefix = "outer-label";
3167 	else
3168 		prefix = "implicit-label";
3169 
3170 	ipsec_convert_sens_to_bslabel(sens, &sl);
3171 	ipsec_convert_bslabel_to_hex(&sl, &hlabel);
3172 
3173 	if (fprintf(ofile, "%s %s ", prefix, hlabel) < 0) {
3174 		free(hlabel);
3175 		return (B_FALSE);
3176 	}
3177 	free(hlabel);
3178 
3179 	return (B_TRUE);
3180 }
3181 
3182 /*
3183  * "Save" a security association to an output file.
3184  *
3185  * NOTE the lack of calls to dgettext() because I'm outputting parseable stuff.
3186  * ALSO NOTE that if you change keywords (see parsecmd()), you'll have to
3187  * change them here as well.
3188  */
3189 void
3190 save_assoc(uint64_t *buffer, FILE *ofile)
3191 {
3192 	int terrno;
3193 	boolean_t seen_proto = B_FALSE, seen_iproto = B_FALSE;
3194 	uint64_t *current;
3195 	struct sadb_address *addr;
3196 	struct sadb_x_replay_ctr *repl;
3197 	struct sadb_msg *samsg = (struct sadb_msg *)buffer;
3198 	struct sadb_ext *ext;
3199 	boolean_t tcpsig = samsg->sadb_msg_satype == SADB_X_SATYPE_TCPSIG;
3200 
3201 #define	tidyup() \
3202 	terrno = errno; (void) fclose(ofile); errno = terrno; \
3203 	interactive = B_FALSE
3204 
3205 #define	savenl() if (fputs(" \\\n", ofile) == EOF) \
3206 	{ bail(dgettext(TEXT_DOMAIN, "savenl")); }
3207 
3208 	if (fputs("# begin assoc\n", ofile) == EOF)
3209 		bail(dgettext(TEXT_DOMAIN,
3210 		    "save_assoc: Opening comment of SA"));
3211 	if (tcpsig) {
3212 		if (fprintf(ofile, "add ") < 0) {
3213 			bail(dgettext(TEXT_DOMAIN,
3214 			    "save_assoc: First line of SA"));
3215 		}
3216 		seen_proto = B_TRUE;
3217 	} else {
3218 		if (fprintf(ofile, "add %s ",
3219 		    rparsesatype(samsg->sadb_msg_satype)) < 0) {
3220 			bail(dgettext(TEXT_DOMAIN,
3221 			    "save_assoc: First line of SA"));
3222 		}
3223 	}
3224 	savenl();
3225 
3226 	current = (uint64_t *)(samsg + 1);
3227 	while (current - buffer < samsg->sadb_msg_len) {
3228 		struct sadb_sa *assoc;
3229 
3230 		ext = (struct sadb_ext *)current;
3231 		addr = (struct sadb_address *)ext;  /* Just in case... */
3232 		switch (ext->sadb_ext_type) {
3233 		case SADB_EXT_SA:
3234 			assoc = (struct sadb_sa *)ext;
3235 			if (assoc->sadb_sa_state != SADB_SASTATE_MATURE) {
3236 				if (fprintf(ofile, "# WARNING: SA was dying "
3237 				    "or dead.\n") < 0) {
3238 					tidyup();
3239 					bail(dgettext(TEXT_DOMAIN,
3240 					    "save_assoc: fprintf not mature"));
3241 				}
3242 			}
3243 			if (!tcpsig) {
3244 				if (fprintf(ofile, "    spi 0x%x ",
3245 				    ntohl(assoc->sadb_sa_spi)) < 0) {
3246 					tidyup();
3247 					bail(dgettext(TEXT_DOMAIN,
3248 					    "save_assoc: fprintf spi"));
3249 				}
3250 			}
3251 			if (assoc->sadb_sa_encrypt != SADB_EALG_NONE) {
3252 				if (fprintf(ofile, "encr_alg %s ",
3253 				    rparsealg(assoc->sadb_sa_encrypt,
3254 				    IPSEC_PROTO_ESP)) < 0) {
3255 					tidyup();
3256 					bail(dgettext(TEXT_DOMAIN,
3257 					    "save_assoc: fprintf encrypt"));
3258 				}
3259 			}
3260 			if (assoc->sadb_sa_auth != SADB_AALG_NONE) {
3261 				int ret;
3262 
3263 				if ((assoc->sadb_sa_flags &
3264 				    SADB_X_SAFLAGS_TCPSIG) != 0) {
3265 					ret = fprintf(ofile, "    authalg %s ",
3266 					    rparsetcpsigalg(
3267 					    assoc->sadb_sa_auth));
3268 				} else {
3269 					ret = fprintf(ofile, "auth_alg %s ",
3270 					    rparsealg(assoc->sadb_sa_auth,
3271 					    IPSEC_PROTO_AH));
3272 				}
3273 				if (ret < 0) {
3274 					tidyup();
3275 					bail(dgettext(TEXT_DOMAIN,
3276 					    "save_assoc: fprintf auth"));
3277 				}
3278 			}
3279 			if ((assoc->sadb_sa_flags &
3280 			    SADB_X_SAFLAGS_TCPSIG) == 0) {
3281 				if (fprintf(ofile, "replay %d ",
3282 				    assoc->sadb_sa_replay) < 0) {
3283 					tidyup();
3284 					bail(dgettext(TEXT_DOMAIN,
3285 					    "save_assoc: fprintf replay"));
3286 				}
3287 			}
3288 			if (assoc->sadb_sa_flags & (SADB_X_SAFLAGS_NATT_LOC |
3289 			    SADB_X_SAFLAGS_NATT_REM)) {
3290 				if (fprintf(ofile, "encap udp") < 0) {
3291 					tidyup();
3292 					bail(dgettext(TEXT_DOMAIN,
3293 					    "save_assoc: fprintf encap"));
3294 				}
3295 			}
3296 			savenl();
3297 			break;
3298 		case SADB_EXT_LIFETIME_HARD:
3299 		case SADB_EXT_LIFETIME_SOFT:
3300 		case SADB_X_EXT_LIFETIME_IDLE:
3301 			if (!save_lifetime((struct sadb_lifetime *)ext,
3302 			    ofile)) {
3303 				tidyup();
3304 				bail(dgettext(TEXT_DOMAIN, "save_lifetime"));
3305 			}
3306 			savenl();
3307 			break;
3308 		case SADB_X_EXT_ADDRESS_INNER_SRC:
3309 		case SADB_X_EXT_ADDRESS_INNER_DST:
3310 			if (!seen_iproto && addr->sadb_address_proto) {
3311 				(void) fprintf(ofile, "    iproto %d",
3312 				    addr->sadb_address_proto);
3313 				savenl();
3314 				seen_iproto = B_TRUE;
3315 			}
3316 			goto skip_srcdst;  /* Hack to avoid cases below... */
3317 			/* FALLTHRU */
3318 		case SADB_EXT_ADDRESS_SRC:
3319 		case SADB_EXT_ADDRESS_DST:
3320 			if (!seen_proto && addr->sadb_address_proto) {
3321 				(void) fprintf(ofile, "    proto %d",
3322 				    addr->sadb_address_proto);
3323 				savenl();
3324 				seen_proto = B_TRUE;
3325 			}
3326 			/* FALLTHRU */
3327 		case SADB_X_EXT_ADDRESS_NATT_REM:
3328 		case SADB_X_EXT_ADDRESS_NATT_LOC:
3329 skip_srcdst:
3330 			if (!save_address(addr, ofile)) {
3331 				tidyup();
3332 				bail(dgettext(TEXT_DOMAIN, "save_address"));
3333 			}
3334 			savenl();
3335 			break;
3336 		case SADB_EXT_KEY_AUTH:
3337 		case SADB_EXT_KEY_ENCRYPT:
3338 			if (!save_key((struct sadb_key *)ext, ofile)) {
3339 				tidyup();
3340 				bail(dgettext(TEXT_DOMAIN, "save_key"));
3341 			}
3342 			savenl();
3343 			break;
3344 		case SADB_X_EXT_STR_AUTH:
3345 			if (!save_keystr((struct sadb_key *)ext, ofile)) {
3346 				tidyup();
3347 				bail(dgettext(TEXT_DOMAIN, "save_keystr"));
3348 			}
3349 			savenl();
3350 			break;
3351 		case SADB_EXT_IDENTITY_SRC:
3352 		case SADB_EXT_IDENTITY_DST:
3353 			if (!save_ident((struct sadb_ident *)ext, ofile)) {
3354 				tidyup();
3355 				bail(dgettext(TEXT_DOMAIN, "save_ident"));
3356 			}
3357 			savenl();
3358 			break;
3359 		case SADB_X_EXT_REPLAY_VALUE:
3360 			repl = (sadb_x_replay_ctr_t *)ext;
3361 			if ((repl->sadb_x_rc_replay32 == 0) &&
3362 			    (repl->sadb_x_rc_replay64 == 0)) {
3363 				tidyup();
3364 				bail(dgettext(TEXT_DOMAIN, "Replay Value"));
3365 			}
3366 			if (fprintf(ofile, "replay_value %" PRIu64 "",
3367 			    (repl->sadb_x_rc_replay32 == 0 ?
3368 			    repl->sadb_x_rc_replay64 :
3369 			    repl->sadb_x_rc_replay32)) < 0) {
3370 				tidyup();
3371 				bail(dgettext(TEXT_DOMAIN,
3372 				    "save_assoc: fprintf replay value"));
3373 			}
3374 			savenl();
3375 			break;
3376 		case SADB_EXT_SENSITIVITY:
3377 		case SADB_X_EXT_OUTER_SENS:
3378 			if (!save_sens((struct sadb_sens *)ext, ofile)) {
3379 				tidyup();
3380 				bail(dgettext(TEXT_DOMAIN, "save_sens"));
3381 			}
3382 			savenl();
3383 			break;
3384 		default:
3385 			/* Skip over irrelevant extensions. */
3386 			break;
3387 		}
3388 		current += ext->sadb_ext_len;
3389 	}
3390 
3391 	if (fputs(dgettext(TEXT_DOMAIN, "\n# end assoc\n\n"), ofile) == EOF) {
3392 		tidyup();
3393 		bail(dgettext(TEXT_DOMAIN, "save_assoc: last fputs"));
3394 	}
3395 }
3396 
3397 /*
3398  * Open the output file for the "save" command.
3399  */
3400 FILE *
3401 opensavefile(char *filename)
3402 {
3403 	int fd;
3404 	FILE *retval;
3405 	struct stat buf;
3406 
3407 	/*
3408 	 * If the user specifies "-" or doesn't give a filename, then
3409 	 * dump to stdout.  Make sure to document the dangers of files
3410 	 * that are NFS, directing your output to strange places, etc.
3411 	 */
3412 	if (filename == NULL || strcmp("-", filename) == 0)
3413 		return (stdout);
3414 
3415 	/*
3416 	 * open the file with the create bits set.  Since I check for
3417 	 * real UID == root in main(), I won't worry about the ownership
3418 	 * problem.
3419 	 */
3420 	fd = open(filename, O_WRONLY | O_EXCL | O_CREAT | O_TRUNC, S_IRUSR);
3421 	if (fd == -1) {
3422 		if (errno != EEXIST)
3423 			bail_msg("%s %s: %s", filename, dgettext(TEXT_DOMAIN,
3424 			    "open error"),
3425 			    strerror(errno));
3426 		fd = open(filename, O_WRONLY | O_TRUNC, 0);
3427 		if (fd == -1)
3428 			bail_msg("%s %s: %s", filename, dgettext(TEXT_DOMAIN,
3429 			    "open error"), strerror(errno));
3430 		if (fstat(fd, &buf) == -1) {
3431 			(void) close(fd);
3432 			bail_msg("%s fstat: %s", filename, strerror(errno));
3433 		}
3434 		if (S_ISREG(buf.st_mode) &&
3435 		    ((buf.st_mode & S_IAMB) != S_IRUSR)) {
3436 			warnx(dgettext(TEXT_DOMAIN,
3437 			    "WARNING: Save file already exists with "
3438 			    "permission %o."), buf.st_mode & S_IAMB);
3439 			warnx(dgettext(TEXT_DOMAIN,
3440 			    "Normal users may be able to read IPsec "
3441 			    "keying material."));
3442 		}
3443 	}
3444 
3445 	/* Okay, we have an FD.  Assign it to a stdio FILE pointer. */
3446 	retval = fdopen(fd, "w");
3447 	if (retval == NULL) {
3448 		(void) close(fd);
3449 		bail_msg("%s %s: %s", filename, dgettext(TEXT_DOMAIN,
3450 		    "fdopen error"), strerror(errno));
3451 	}
3452 	return (retval);
3453 }
3454 
3455 const char *
3456 do_inet_ntop(const void *addr, char *cp, size_t size)
3457 {
3458 	boolean_t isv4;
3459 	struct in6_addr *inaddr6 = (struct in6_addr *)addr;
3460 	struct in_addr inaddr;
3461 
3462 	if ((isv4 = IN6_IS_ADDR_V4MAPPED(inaddr6)) == B_TRUE) {
3463 		IN6_V4MAPPED_TO_INADDR(inaddr6, &inaddr);
3464 	}
3465 
3466 	return (inet_ntop(isv4 ? AF_INET : AF_INET6,
3467 	    isv4 ? (void *)&inaddr : inaddr6, cp, size));
3468 }
3469 
3470 char numprint[NBUF_SIZE];
3471 
3472 /*
3473  * Parse and reverse parse a specific SA type (AH, ESP, etc.).
3474  */
3475 static struct typetable {
3476 	char *type;
3477 	int token;
3478 } type_table[] = {
3479 	{"all", SADB_SATYPE_UNSPEC},
3480 	{"ah",  SADB_SATYPE_AH},
3481 	{"esp", SADB_SATYPE_ESP},
3482 	{"tcpsig", SADB_X_SATYPE_TCPSIG},
3483 	/* PF_KEY NOTE:  More to come if net/pfkeyv2.h gets updated. */
3484 	{NULL, 0}	/* Token value is irrelevant for this entry. */
3485 };
3486 
3487 char *
3488 rparsesatype(int type)
3489 {
3490 	struct typetable *tt = type_table;
3491 
3492 	while (tt->type != NULL && type != tt->token)
3493 		tt++;
3494 
3495 	if (tt->type == NULL) {
3496 		(void) snprintf(numprint, NBUF_SIZE, "%d", type);
3497 	} else {
3498 		return (tt->type);
3499 	}
3500 
3501 	return (numprint);
3502 }
3503 
3504 
3505 /*
3506  * Return a string containing the name of the specified numerical algorithm
3507  * identifier.
3508  */
3509 char *
3510 rparsealg(uint8_t alg, int proto_num)
3511 {
3512 	static struct ipsecalgent *holder = NULL; /* we're single-threaded */
3513 
3514 	if (holder != NULL)
3515 		freeipsecalgent(holder);
3516 
3517 	holder = getipsecalgbynum(alg, proto_num, NULL);
3518 	if (holder == NULL) {
3519 		(void) snprintf(numprint, NBUF_SIZE, "%d", alg);
3520 		return (numprint);
3521 	}
3522 
3523 	return (*(holder->a_names));
3524 }
3525 
3526 const char *
3527 rparsetcpsigalg(uint8_t alg)
3528 {
3529 	const char *name = gettcpsigalgbynum(alg);
3530 
3531 	if (name == NULL) {
3532 		(void) snprintf(numprint, NBUF_SIZE, "%d", alg);
3533 		return (numprint);
3534 	}
3535 
3536 	return (name);
3537 }
3538 
3539 /*
3540  * Parse and reverse parse out a source/destination ID type.
3541  */
3542 static struct idtypes {
3543 	char *idtype;
3544 	uint8_t retval;
3545 } idtypes[] = {
3546 	{"prefix",	SADB_IDENTTYPE_PREFIX},
3547 	{"fqdn",	SADB_IDENTTYPE_FQDN},
3548 	{"domain",	SADB_IDENTTYPE_FQDN},
3549 	{"domainname",	SADB_IDENTTYPE_FQDN},
3550 	{"user_fqdn",	SADB_IDENTTYPE_USER_FQDN},
3551 	{"mailbox",	SADB_IDENTTYPE_USER_FQDN},
3552 	{"der_dn",	SADB_X_IDENTTYPE_DN},
3553 	{"der_gn",	SADB_X_IDENTTYPE_GN},
3554 	{NULL,		0}
3555 };
3556 
3557 char *
3558 rparseidtype(uint16_t type)
3559 {
3560 	struct idtypes *idp;
3561 
3562 	for (idp = idtypes; idp->idtype != NULL; idp++) {
3563 		if (type == idp->retval)
3564 			return (idp->idtype);
3565 	}
3566 
3567 	(void) snprintf(numprint, NBUF_SIZE, "%d", type);
3568 	return (numprint);
3569 }
3570 
3571 /*
3572  * This is a general purpose exit function, calling functions can specify an
3573  * error type. If the command calling this function was started by smf(7) the
3574  * error type could be used as a hint to the restarter. In the future this
3575  * function could be used to do something more intelligent with a process that
3576  * encounters an error. If exit() is called with an error code other than those
3577  * defined by smf(7), the program will just get restarted. Unless restarting
3578  * is likely to resolve the error condition, its probably sensible to just
3579  * log the error and keep running.
3580  *
3581  * The SERVICE_* exit_types mean nothing if the command was run from the
3582  * command line, just exit(). There are two special cases:
3583  *
3584  * SERVICE_DEGRADE - Not implemented in smf(7), one day it could hint that
3585  *                   the service is not running as well is it could. For
3586  *                   now, don't do anything, just record the error.
3587  * DEBUG_FATAL - Something happened, if the command was being run in debug
3588  *               mode, exit() as you really want to know something happened,
3589  *               otherwise just keep running. This is ignored when running
3590  *               under smf(7).
3591  *
3592  * The function will handle an optional variable args error message, this
3593  * will be written to the error stream, typically a log file or stderr.
3594  */
3595 void
3596 ipsecutil_exit(exit_type_t type, char *fmri, FILE *fp, const char *fmt, ...)
3597 {
3598 	int exit_status;
3599 	va_list args;
3600 
3601 	if (fp == NULL)
3602 		fp = stderr;
3603 	if (fmt != NULL) {
3604 		va_start(args, fmt);
3605 		vwarnxfp(fp, fmt, args);
3606 		va_end(args);
3607 	}
3608 
3609 	if (fmri == NULL) {
3610 		/* Command being run directly from a shell. */
3611 		switch (type) {
3612 		case SERVICE_EXIT_OK:
3613 			exit_status = 0;
3614 			break;
3615 		case SERVICE_DEGRADE:
3616 			return;
3617 		case SERVICE_BADPERM:
3618 		case SERVICE_BADCONF:
3619 		case SERVICE_MAINTAIN:
3620 		case SERVICE_DISABLE:
3621 		case SERVICE_FATAL:
3622 		case SERVICE_RESTART:
3623 		case DEBUG_FATAL:
3624 			warnxfp(fp, "Fatal error - exiting.");
3625 			exit_status = 1;
3626 			break;
3627 		}
3628 	} else {
3629 		/* Command being run as a smf(7) method. */
3630 		switch (type) {
3631 		case SERVICE_EXIT_OK:
3632 			exit_status = SMF_EXIT_OK;
3633 			break;
3634 		case SERVICE_DEGRADE: /* Not implemented yet. */
3635 		case DEBUG_FATAL:
3636 			/* Keep running, don't exit(). */
3637 			return;
3638 		case SERVICE_BADPERM:
3639 			warnxfp(fp, dgettext(TEXT_DOMAIN,
3640 			    "Permission error with %s."), fmri);
3641 			exit_status = SMF_EXIT_ERR_PERM;
3642 			break;
3643 		case SERVICE_BADCONF:
3644 			warnxfp(fp, dgettext(TEXT_DOMAIN,
3645 			    "Bad configuration of service %s."), fmri);
3646 			exit_status = SMF_EXIT_ERR_FATAL;
3647 			break;
3648 		case SERVICE_MAINTAIN:
3649 			warnxfp(fp, dgettext(TEXT_DOMAIN,
3650 			    "Service %s needs maintenance."), fmri);
3651 			exit_status = SMF_EXIT_ERR_FATAL;
3652 			break;
3653 		case SERVICE_DISABLE:
3654 			exit_status = SMF_EXIT_ERR_FATAL;
3655 			break;
3656 		case SERVICE_FATAL:
3657 			warnxfp(fp, dgettext(TEXT_DOMAIN,
3658 			    "Service %s fatal error."), fmri);
3659 			exit_status = SMF_EXIT_ERR_FATAL;
3660 			break;
3661 		case SERVICE_RESTART:
3662 			exit_status = 1;
3663 			break;
3664 		}
3665 	}
3666 	(void) fflush(fp);
3667 	(void) fclose(fp);
3668 	exit(exit_status);
3669 }
3670 
3671 void
3672 print_asn1_name(FILE *file, const unsigned char *buf, long buflen)
3673 {
3674 	KMF_X509_NAME name = { 0 };
3675 	KMF_DATA data = { 0 };
3676 	char *str = NULL;
3677 
3678 	data.Data = (unsigned char *)buf;
3679 	data.Length = buflen;
3680 
3681 	if (DerDecodeName(&data, &name) != KMF_OK)
3682 		goto fail;
3683 
3684 	if (kmf_dn_to_string(&name, &str) != KMF_OK)
3685 		goto fail;
3686 
3687 	(void) fprintf(file, "%s\n", str);
3688 	kmf_free_dn(&name);
3689 	free(str);
3690 	return;
3691 fail:
3692 	kmf_free_dn(&name);
3693 	(void) fprintf(file, dgettext(TEXT_DOMAIN, "<cannot interpret>\n"));
3694 }
3695