xref: /titanic_41/usr/src/cmd/cmd-inet/usr.sbin/ipsecutils/ipseckey.c (revision 2a9459bdd821c1cf59590a7a9069ac9c591e8a6b)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 /*
27  * NOTE:I'm trying to use "struct sadb_foo" instead of "sadb_foo_t"
28  *	as a maximal PF_KEY portability test.
29  *
30  *	Also, this is a deliberately single-threaded app, also for portability
31  *	to systems without POSIX threads.
32  */
33 
34 #pragma ident	"%Z%%M%	%I%	%E% SMI"
35 
36 #include <sys/types.h>
37 #include <sys/stat.h>
38 #include <sys/socket.h>
39 #include <sys/sysmacros.h>
40 #include <sys/fcntl.h>
41 #include <net/pfkeyv2.h>
42 #include <arpa/inet.h>
43 #include <netinet/in.h>
44 #include <sys/uio.h>
45 
46 #include <syslog.h>
47 #include <signal.h>
48 #include <unistd.h>
49 #include <limits.h>
50 #include <stdlib.h>
51 #include <stdio.h>
52 #include <stdarg.h>
53 #include <netdb.h>
54 #include <pwd.h>
55 #include <errno.h>
56 #include <libintl.h>
57 #include <locale.h>
58 #include <fcntl.h>
59 #include <strings.h>
60 #include <ctype.h>
61 
62 #include <ipsec_util.h>
63 
64 static int keysock;
65 static uint32_t seq;
66 static pid_t mypid;
67 static boolean_t vflag = B_FALSE;	/* Verbose? */
68 static boolean_t cflag = B_FALSE;	/* Check Only */
69 
70 char *my_fmri = NULL;
71 FILE *debugfile = stdout;
72 
73 #define	MAX_GET_SIZE	1024
74 /*
75  * WARN() and ERROR() do the same thing really, with ERROR() the function
76  * that prints the error buffer needs to be called at the end of a code block
77  * This will print out all accumulated errors before bailing. The WARN()
78  * macro calls handle_errors() in such a way that it prints the message
79  * then continues.
80  * If the FATAL() macro used call handle_errors() immediately.
81  */
82 #define	ERROR(x, y, z)  x = record_error(x, y, z)
83 #define	ERROR1(w, x, y, z)  w = record_error(w, x, y, z)
84 #define	ERROR2(v, w, x, y, z)  v = record_error(v, w, x, y, z)
85 #define	WARN(x, y, z) ERROR(x, y, z);\
86 	handle_errors(x, NULL, B_FALSE, B_FALSE); x = NULL
87 #define	WARN1(w, x, y, z) ERROR1(w, x, y, z);\
88 	handle_errors(w, NULL, B_FALSE, B_FALSE); w = NULL
89 #define	WARN2(v, w, x, y, z) ERROR2(v, w, x, y, z);\
90 	handle_errors(v, NULL, B_FALSE, B_FALSE); v = NULL
91 #define	FATAL(x, y, z) ERROR(x, y, z);\
92 	handle_errors(x, y, B_TRUE, B_TRUE)
93 #define	FATAL1(w, x, y, z) ERROR1(w, x, y, z);\
94 	handle_errors(w, x, B_TRUE, B_TRUE)
95 
96 /* Defined as a uint64_t array for alignment purposes. */
97 static uint64_t get_buffer[MAX_GET_SIZE];
98 
99 /*
100  * Create/Grow a buffer large enough to hold error messages. If *ebuf
101  * is not NULL then it will contain a copy of the command line that
102  * triggered the error/warning, copy this into a new buffer or
103  * append new messages to the existing buffer.
104  */
105 /*PRINTFLIKE1*/
106 char *
107 record_error(char *ep, char *ebuf, char *fmt, ...)
108 {
109 	char *err_ptr;
110 	char tmp_buff[1024];
111 	va_list ap;
112 	int length = 0;
113 	err_ptr = ep;
114 
115 	va_start(ap, fmt);
116 	length = vsnprintf(tmp_buff, sizeof (tmp_buff), fmt, ap);
117 	va_end(ap);
118 
119 	/* There is a new line character */
120 	length++;
121 
122 	if (ep == NULL) {
123 		if (ebuf != NULL)
124 			length += strlen(ebuf);
125 	} else  {
126 		length += strlen(ep);
127 	}
128 
129 	if (err_ptr == NULL)
130 		err_ptr = calloc(length, sizeof (char));
131 	else
132 		err_ptr = realloc(err_ptr, length);
133 
134 	if (err_ptr == NULL)
135 		Bail("realloc() failure");
136 
137 	/*
138 	 * If (ep == NULL) then this is the first error to record,
139 	 * copy in the command line that triggered this error/warning.
140 	 */
141 	if (ep == NULL && ebuf != NULL)
142 		(void) strlcpy(err_ptr, ebuf, length);
143 
144 	/*
145 	 * Now the actual error.
146 	 */
147 	(void) strlcat(err_ptr, tmp_buff, length);
148 	return (err_ptr);
149 }
150 
151 /*
152  * Print usage message.
153  */
154 static void
155 usage(void)
156 {
157 	if (!interactive) {
158 		(void) fprintf(stderr, gettext("Usage:\t"
159 		    "ipseckey [ -nvp ] | cmd [sa_type] [extfield value]*\n"));
160 		(void) fprintf(stderr,
161 		    gettext("\tipseckey [ -nvp ] -f infile\n"));
162 		(void) fprintf(stderr,
163 		    gettext("\tipseckey [ -nvp ] -s outfile\n"));
164 	}
165 	EXIT_FATAL(NULL);
166 }
167 
168 
169 /*
170  * Print out any errors, tidy up as required.
171  * error pointer ep will be free()'d
172  */
173 void
174 handle_errors(char *ep, char *ebuf, boolean_t fatal, boolean_t done)
175 {
176 	if (ep != NULL) {
177 		if (my_fmri == NULL) {
178 			/*
179 			 * For now suppress the errors when run from smf(5)
180 			 * because potentially sensitive information could
181 			 * end up in a publicly readable logfile.
182 			 */
183 			(void) fprintf(stdout, "%s\n", ep);
184 			(void) fflush(stdout);
185 		}
186 		free(ep);
187 		if (fatal) {
188 			if (ebuf != NULL) {
189 				free(ebuf);
190 			}
191 			/* reset command buffer */
192 			if (interactive)
193 				longjmp(env, 1);
194 		} else {
195 			return;
196 		}
197 	} else {
198 		/*
199 		 * No errors, if this is the last time that this function
200 		 * is called, free(ebuf) and reset command buffer.
201 		 */
202 		if (done) {
203 			if (ebuf != NULL) {
204 				free(ebuf);
205 			}
206 			/* reset command buffer */
207 			if (interactive)
208 				longjmp(env, 1);
209 		}
210 		return;
211 	}
212 	EXIT_FATAL(NULL);
213 }
214 
215 /*
216  * Initialize a PF_KEY base message.
217  */
218 static void
219 msg_init(struct sadb_msg *msg, uint8_t type, uint8_t satype)
220 {
221 	msg->sadb_msg_version = PF_KEY_V2;
222 	msg->sadb_msg_type = type;
223 	msg->sadb_msg_errno = 0;
224 	msg->sadb_msg_satype = satype;
225 	/* For starters... */
226 	msg->sadb_msg_len = SADB_8TO64(sizeof (*msg));
227 	msg->sadb_msg_reserved = 0;
228 	msg->sadb_msg_seq = ++seq;
229 	msg->sadb_msg_pid = mypid;
230 }
231 
232 /*
233  * parseXXX and rparseXXX commands parse input and convert them to PF_KEY
234  * field values, or do the reverse for the purposes of saving the SA tables.
235  * (See the save_XXX functions.)
236  */
237 
238 #define	CMD_NONE	0
239 #define	CMD_UPDATE	2
240 #define	CMD_ADD		3
241 #define	CMD_DELETE	4
242 #define	CMD_GET		5
243 #define	CMD_FLUSH	9
244 #define	CMD_DUMP	10
245 #define	CMD_MONITOR	11
246 #define	CMD_PMONITOR	12
247 #define	CMD_QUIT	13
248 #define	CMD_SAVE	14
249 #define	CMD_HELP	15
250 
251 /*
252  * Parse the command.
253  */
254 static int
255 parsecmd(char *cmdstr)
256 {
257 	static struct cmdtable {
258 		char *cmd;
259 		int token;
260 	} table[] = {
261 		/*
262 		 * Q: Do we want to do GETSPI?
263 		 * A: No, it's for automated key mgmt. only.  Either that,
264 		 *    or it isn't relevant until we support non IPsec SA types.
265 		 */
266 		{"update",		CMD_UPDATE},
267 		{"add",			CMD_ADD},
268 		{"delete", 		CMD_DELETE},
269 		{"get", 		CMD_GET},
270 		/*
271 		 * Q: And ACQUIRE and REGISTER and EXPIRE?
272 		 * A: not until we support non IPsec SA types.
273 		 */
274 		{"flush",		CMD_FLUSH},
275 		{"dump",		CMD_DUMP},
276 		{"monitor",		CMD_MONITOR},
277 		{"passive_monitor",	CMD_PMONITOR},
278 		{"pmonitor",		CMD_PMONITOR},
279 		{"quit",		CMD_QUIT},
280 		{"exit",		CMD_QUIT},
281 		{"save",		CMD_SAVE},
282 		{"help",		CMD_HELP},
283 		{"?",			CMD_HELP},
284 		{NULL,			CMD_NONE}
285 	};
286 	struct cmdtable *ct = table;
287 
288 	while (ct->cmd != NULL && strcmp(ct->cmd, cmdstr) != 0)
289 		ct++;
290 	return (ct->token);
291 }
292 
293 /*
294  * Convert a number from a command line.  I picked "u_longlong_t" for the
295  * number because we need the largest number available.  Also, the strto<num>
296  * calls don't deal in units of uintNN_t.
297  */
298 static u_longlong_t
299 parsenum(char *num, boolean_t bail, char *ebuf)
300 {
301 	u_longlong_t rc = 0;
302 	char *end = NULL;
303 	char *ep = NULL;
304 
305 	if (num == NULL) {
306 		FATAL(ep, ebuf, gettext("Unexpected end of command line,"
307 		    " was expecting a number.\n"));
308 		/* NOTREACHED */
309 	}
310 
311 	errno = 0;
312 	rc = strtoull(num, &end, 0);
313 	if (errno != 0 || end == num || *end != '\0') {
314 		if (bail) {
315 			ERROR1(ep, ebuf, gettext(
316 			"Expecting a number, not \"%s\"!\n"), num);
317 		} else {
318 			/*
319 			 * -1, while not optimal, is sufficiently out of range
320 			 * for most of this function's applications when
321 			 * we don't just bail.
322 			 */
323 			return ((u_longlong_t)-1);
324 		}
325 	}
326 	handle_errors(ep, NULL, B_FALSE, B_FALSE);
327 	return (rc);
328 }
329 
330 /*
331  * Parse and reverse parse a specific SA type (AH, ESP, etc.).
332  */
333 static struct typetable {
334 	char *type;
335 	int token;
336 } type_table[] = {
337 	{"all",	SADB_SATYPE_UNSPEC},
338 	{"ah",	SADB_SATYPE_AH},
339 	{"esp",	SADB_SATYPE_ESP},
340 	/* PF_KEY NOTE:  More to come if net/pfkeyv2.h gets updated. */
341 	{NULL,	0}	/* Token value is irrelevant for this entry. */
342 };
343 
344 
345 static int
346 parsesatype(char *type, char *ebuf)
347 {
348 	struct typetable *tt = type_table;
349 	char *ep = NULL;
350 
351 	if (type == NULL)
352 		return (SADB_SATYPE_UNSPEC);
353 
354 	while (tt->type != NULL && strcasecmp(tt->type, type) != 0)
355 		tt++;
356 
357 	/*
358 	 * New SA types (including ones keysock maintains for user-land
359 	 * protocols) may be added, so parse a numeric value if possible.
360 	 */
361 	if (tt->type == NULL) {
362 		tt->token = (int)parsenum(type, B_FALSE, ebuf);
363 		if (tt->token == -1) {
364 			ERROR1(ep, ebuf, gettext(
365 			    "Unknown SA type (%s).\n"), type);
366 			tt->token = SADB_SATYPE_UNSPEC;
367 		}
368 	}
369 	handle_errors(ep, NULL, B_FALSE, B_FALSE);
370 	return (tt->token);
371 }
372 
373 #define	NEXTEOF		0
374 #define	NEXTNONE	1
375 #define	NEXTNUM		2
376 #define	NEXTSTR		3
377 #define	NEXTNUMSTR	4
378 #define	NEXTADDR	5
379 #define	NEXTHEX		6
380 #define	NEXTIDENT	7
381 #define	NEXTADDR4	8
382 #define	NEXTADDR6	9
383 
384 #define	TOK_EOF			0
385 #define	TOK_UNKNOWN		1
386 #define	TOK_SPI			2
387 #define	TOK_REPLAY		3
388 #define	TOK_STATE		4
389 #define	TOK_AUTHALG		5
390 #define	TOK_ENCRALG		6
391 #define	TOK_FLAGS		7
392 #define	TOK_SOFT_ALLOC		8
393 #define	TOK_SOFT_BYTES		9
394 #define	TOK_SOFT_ADDTIME	10
395 #define	TOK_SOFT_USETIME	11
396 #define	TOK_HARD_ALLOC		12
397 #define	TOK_HARD_BYTES		13
398 #define	TOK_HARD_ADDTIME	14
399 #define	TOK_HARD_USETIME	15
400 #define	TOK_CURRENT_ALLOC	16
401 #define	TOK_CURRENT_BYTES	17
402 #define	TOK_CURRENT_ADDTIME	18
403 #define	TOK_CURRENT_USETIME	19
404 #define	TOK_SRCADDR		20
405 #define	TOK_DSTADDR		21
406 #define	TOK_PROXYADDR		22
407 #define	TOK_AUTHKEY		23
408 #define	TOK_ENCRKEY		24
409 #define	TOK_SRCIDTYPE		25
410 #define	TOK_DSTIDTYPE		26
411 #define	TOK_DPD			27
412 #define	TOK_SENS_LEVEL		28
413 #define	TOK_SENS_MAP		29
414 #define	TOK_INTEG_LEVEL		30
415 #define	TOK_INTEG_MAP		31
416 #define	TOK_SRCADDR6		32
417 #define	TOK_DSTADDR6		33
418 #define	TOK_PROXYADDR6		34
419 #define	TOK_SRCPORT		35
420 #define	TOK_DSTPORT		36
421 #define	TOK_PROTO		37
422 #define	TOK_ENCAP		38
423 #define	TOK_NATLOC		39
424 #define	TOK_NATREM		40
425 #define	TOK_NATLPORT		41
426 #define	TOK_NATRPORT		42
427 #define	TOK_IPROTO		43
428 #define	TOK_IDSTADDR		44
429 #define	TOK_IDSTADDR6		45
430 #define	TOK_ISRCPORT		46
431 #define	TOK_IDSTPORT		47
432 
433 static struct toktable {
434 	char *string;
435 	int token;
436 	int next;
437 } tokens[] = {
438 	/* "String",		token value,		next arg is */
439 	{"spi",			TOK_SPI,		NEXTNUM},
440 	{"replay",		TOK_REPLAY,		NEXTNUM},
441 	{"state",		TOK_STATE,		NEXTNUMSTR},
442 	{"auth_alg",		TOK_AUTHALG,		NEXTNUMSTR},
443 	{"authalg",		TOK_AUTHALG,		NEXTNUMSTR},
444 	{"encr_alg",		TOK_ENCRALG,		NEXTNUMSTR},
445 	{"encralg",		TOK_ENCRALG,		NEXTNUMSTR},
446 	{"flags",		TOK_FLAGS,		NEXTNUM},
447 	{"soft_alloc",		TOK_SOFT_ALLOC,		NEXTNUM},
448 	{"soft_bytes",		TOK_SOFT_BYTES,		NEXTNUM},
449 	{"soft_addtime",	TOK_SOFT_ADDTIME,	NEXTNUM},
450 	{"soft_usetime",	TOK_SOFT_USETIME,	NEXTNUM},
451 	{"hard_alloc",		TOK_HARD_ALLOC,		NEXTNUM},
452 	{"hard_bytes",		TOK_HARD_BYTES,		NEXTNUM},
453 	{"hard_addtime",	TOK_HARD_ADDTIME,	NEXTNUM},
454 	{"hard_usetime",	TOK_HARD_USETIME,	NEXTNUM},
455 	{"current_alloc",	TOK_CURRENT_ALLOC,	NEXTNUM},
456 	{"current_bytes",	TOK_CURRENT_BYTES,	NEXTNUM},
457 	{"current_addtime",	TOK_CURRENT_ADDTIME,	NEXTNUM},
458 	{"current_usetime",	TOK_CURRENT_USETIME,	NEXTNUM},
459 
460 	{"saddr",		TOK_SRCADDR,		NEXTADDR},
461 	{"srcaddr",		TOK_SRCADDR,		NEXTADDR},
462 	{"src",			TOK_SRCADDR,		NEXTADDR},
463 	{"daddr",		TOK_DSTADDR,		NEXTADDR},
464 	{"dstaddr",		TOK_DSTADDR,		NEXTADDR},
465 	{"dst",			TOK_DSTADDR,		NEXTADDR},
466 	{"proxyaddr",		TOK_PROXYADDR,		NEXTADDR},
467 	{"proxy",		TOK_PROXYADDR,		NEXTADDR},
468 	{"innersrc",		TOK_PROXYADDR,		NEXTADDR},
469 	{"isrc",		TOK_PROXYADDR,		NEXTADDR},
470 	{"innerdst",		TOK_IDSTADDR,		NEXTADDR},
471 	{"idst",		TOK_IDSTADDR,		NEXTADDR},
472 
473 	{"sport",		TOK_SRCPORT,		NEXTNUM},
474 	{"dport",		TOK_DSTPORT,		NEXTNUM},
475 	{"innersport",		TOK_ISRCPORT,		NEXTNUM},
476 	{"isport",		TOK_ISRCPORT,		NEXTNUM},
477 	{"innerdport",		TOK_IDSTPORT,		NEXTNUM},
478 	{"idport",		TOK_IDSTPORT,		NEXTNUM},
479 	{"proto",		TOK_PROTO,		NEXTNUM},
480 	{"ulp",			TOK_PROTO,		NEXTNUM},
481 	{"iproto",		TOK_IPROTO,		NEXTNUM},
482 	{"iulp",		TOK_IPROTO,		NEXTNUM},
483 
484 	{"saddr6",		TOK_SRCADDR6,		NEXTADDR},
485 	{"srcaddr6",		TOK_SRCADDR6,		NEXTADDR},
486 	{"src6",		TOK_SRCADDR6,		NEXTADDR},
487 	{"daddr6",		TOK_DSTADDR6,		NEXTADDR},
488 	{"dstaddr6",		TOK_DSTADDR6,		NEXTADDR},
489 	{"dst6",		TOK_DSTADDR6,		NEXTADDR},
490 	{"proxyaddr6",		TOK_PROXYADDR6,		NEXTADDR},
491 	{"proxy6",		TOK_PROXYADDR6,		NEXTADDR},
492 	{"innersrc6",		TOK_PROXYADDR6,		NEXTADDR},
493 	{"isrc6",		TOK_PROXYADDR6,		NEXTADDR},
494 	{"innerdst6",		TOK_IDSTADDR6,		NEXTADDR},
495 	{"idst6",		TOK_IDSTADDR6,		NEXTADDR},
496 
497 	{"authkey",		TOK_AUTHKEY,		NEXTHEX},
498 	{"encrkey",		TOK_ENCRKEY,		NEXTHEX},
499 	{"srcidtype",		TOK_SRCIDTYPE,		NEXTIDENT},
500 	{"dstidtype",		TOK_DSTIDTYPE,		NEXTIDENT},
501 	{"dpd",			TOK_DPD,		NEXTNUM},
502 	{"sens_level",		TOK_SENS_LEVEL,		NEXTNUM},
503 	{"sens_map",		TOK_SENS_MAP,		NEXTHEX},
504 	{"integ_level",		TOK_INTEG_LEVEL,	NEXTNUM},
505 	{"integ_map",		TOK_INTEG_MAP,		NEXTHEX},
506 	{"nat_loc",		TOK_NATLOC,		NEXTADDR},
507 	{"nat_rem",		TOK_NATREM,		NEXTADDR},
508 	{"nat_lport",		TOK_NATLPORT,		NEXTNUM},
509 	{"nat_rport",		TOK_NATRPORT,		NEXTNUM},
510 	{"encap",		TOK_ENCAP,		NEXTNUMSTR},
511 	{NULL,			TOK_UNKNOWN,		NEXTEOF}
512 };
513 
514 /*
515  * Q:	Do I need stuff for proposals, combinations, supported algorithms,
516  *	or SPI ranges?
517  *
518  * A:	Probably not, but you never know.
519  *
520  * Parse out extension header type values.
521  */
522 static int
523 parseextval(char *value, int *next)
524 {
525 	struct toktable *tp;
526 
527 	if (value == NULL)
528 		return (TOK_EOF);
529 
530 	for (tp = tokens; tp->string != NULL; tp++)
531 		if (strcmp(value, tp->string) == 0)
532 			break;
533 
534 	/*
535 	 * Since the OS controls what extensions are available, we don't have
536 	 * to parse numeric values here.
537 	 */
538 
539 	*next = tp->next;
540 	return (tp->token);
541 }
542 
543 /*
544  * Parse possible state values.
545  */
546 static uint8_t
547 parsestate(char *state, char *ebuf)
548 {
549 	struct states {
550 		char *state;
551 		uint8_t retval;
552 	} states[] = {
553 		{"larval",	SADB_SASTATE_LARVAL},
554 		{"mature",	SADB_SASTATE_MATURE},
555 		{"dying",	SADB_SASTATE_DYING},
556 		{"dead",	SADB_SASTATE_DEAD},
557 		{NULL,		0}
558 	};
559 	struct states *sp;
560 	char *ep = NULL;
561 
562 	if (state == NULL) {
563 		FATAL(ep, ebuf, "Unexpected end of command line "
564 		    "was expecting a state.\n");
565 	}
566 
567 	for (sp = states; sp->state != NULL; sp++) {
568 		if (strcmp(sp->state, state) == 0)
569 			return (sp->retval);
570 	}
571 	ERROR1(ep, ebuf, gettext("Unknown state type \"%s\"\n"), state);
572 	handle_errors(ep, NULL, B_FALSE, B_FALSE);
573 	return (0);
574 }
575 
576 /*
577  * Return the numerical algorithm identifier corresponding to the specified
578  * algorithm name.
579  */
580 static uint8_t
581 parsealg(char *alg, int proto_num, char *ebuf)
582 {
583 	u_longlong_t invalue;
584 	struct ipsecalgent *algent;
585 	char *ep = NULL;
586 
587 	if (alg == NULL) {
588 		FATAL(ep, ebuf, gettext("Unexpected end of command line, "
589 		    "was expecting an algorithm name.\n"));
590 	}
591 
592 	algent = getipsecalgbyname(alg, proto_num, NULL);
593 	if (algent != NULL) {
594 		uint8_t alg_num;
595 
596 		alg_num = algent->a_alg_num;
597 		freeipsecalgent(algent);
598 
599 		return (alg_num);
600 	}
601 
602 	/*
603 	 * Since algorithms can be loaded during kernel run-time, check for
604 	 * numeric algorithm values too.  PF_KEY can catch bad ones with EINVAL.
605 	 */
606 	invalue = parsenum(alg, B_FALSE, ebuf);
607 	if (invalue != (u_longlong_t)-1 &&
608 	    (u_longlong_t)(invalue & (u_longlong_t)0xff) == invalue)
609 		return ((uint8_t)invalue);
610 
611 	if (proto_num == IPSEC_PROTO_ESP) {
612 		ERROR1(ep, ebuf, gettext(
613 		    "Unknown encryption algorithm type \"%s\"\n"), alg);
614 	} else {
615 		ERROR1(ep, ebuf, gettext(
616 		    "Unknown authentication algorithm type \"%s\"\n"), alg);
617 	}
618 	handle_errors(ep, NULL, B_FALSE, B_FALSE);
619 	return (0);
620 }
621 
622 /*
623  * Parse and reverse parse out a source/destination ID type.
624  */
625 static struct idtypes {
626 	char *idtype;
627 	uint8_t retval;
628 } idtypes[] = {
629 	{"prefix",	SADB_IDENTTYPE_PREFIX},
630 	{"fqdn",	SADB_IDENTTYPE_FQDN},
631 	{"domain",	SADB_IDENTTYPE_FQDN},
632 	{"domainname",	SADB_IDENTTYPE_FQDN},
633 	{"user_fqdn",	SADB_IDENTTYPE_USER_FQDN},
634 	{"mailbox",	SADB_IDENTTYPE_USER_FQDN},
635 	{"der_dn",	SADB_X_IDENTTYPE_DN},
636 	{"der_gn",	SADB_X_IDENTTYPE_GN},
637 	{NULL,		0}
638 };
639 
640 static uint16_t
641 parseidtype(char *type, char *ebuf)
642 {
643 	struct idtypes *idp;
644 	u_longlong_t invalue;
645 	char *ep = NULL;
646 
647 	if (type == NULL) {
648 		/* Shouldn't reach here, see callers for why. */
649 		FATAL(ep, ebuf, gettext("Unexpected end of command line, "
650 		    "was expecting a type.\n"));
651 	}
652 
653 	for (idp = idtypes; idp->idtype != NULL; idp++) {
654 		if (strcasecmp(idp->idtype, type) == 0)
655 			return (idp->retval);
656 	}
657 	/*
658 	 * Since identity types are almost arbitrary, check for numeric
659 	 * algorithm values too.  PF_KEY can catch bad ones with EINVAL.
660 	 */
661 	invalue = parsenum(type, B_FALSE, ebuf);
662 	if (invalue != (u_longlong_t)-1 &&
663 	    (u_longlong_t)(invalue & (u_longlong_t)0xffff) == invalue)
664 		return ((uint16_t)invalue);
665 
666 
667 	ERROR1(ep, ebuf, gettext("Unknown identity type \"%s\"\n"), type);
668 
669 	handle_errors(ep, NULL, B_FALSE, B_FALSE);
670 	return (0);
671 }
672 
673 /*
674  * Parse an address off the command line.  Return length of sockaddr,
675  * and either return a hostent pointer (caller frees).  The new
676  * getipnodebyname() call does the Right Thing (TM), even with
677  * raw addresses (colon-separated IPv6 or dotted decimal IPv4).
678  */
679 
680 static struct {
681 	struct hostent he;
682 	char *addtl[2];
683 	} dummy;
684 static union {
685 	struct in6_addr ipv6;
686 	struct in_addr ipv4;
687 	uint64_t aligner;
688 } addr1;
689 
690 static int
691 parseaddr(char *addr, struct hostent **hpp, boolean_t v6only, char *ebuf)
692 {
693 	int hp_errno;
694 	struct hostent *hp = NULL;
695 	char *ep = NULL;
696 
697 	if (addr == NULL) {
698 		FATAL(ep, ebuf, gettext("Unexpected end of command line, "
699 		    "was expecting an address.\n"));
700 	}
701 
702 	if (!nflag) {
703 		/*
704 		 * Try name->address first.  Assume AF_INET6, and
705 		 * get IPv4's, plus IPv6's if and only if IPv6 is configured.
706 		 * This means to add IPv6 SAs, you must have IPv6
707 		 * up-and-running.  (AI_DEFAULT works here.)
708 		 */
709 		hp = getipnodebyname(addr, AF_INET6,
710 		    (v6only ? AI_ADDRCONFIG : (AI_DEFAULT | AI_ALL)),
711 		    &hp_errno);
712 	} else {
713 		/*
714 		 * Try a normal address conversion only.  Use "dummy"
715 		 * to construct a fake hostent.  Caller will know not
716 		 * to free this one.
717 		 */
718 		if (inet_pton(AF_INET6, addr, &addr1) == 1) {
719 			dummy.he.h_addr_list = dummy.addtl;
720 			dummy.addtl[0] = (char *)&addr1;
721 			dummy.addtl[1] = NULL;
722 			hp = &dummy.he;
723 			dummy.he.h_addrtype = AF_INET6;
724 			dummy.he.h_length = sizeof (struct in6_addr);
725 		} else if (inet_pton(AF_INET, addr, &addr1) == 1) {
726 			/*
727 			 * Remap to AF_INET6 anyway.
728 			 */
729 			dummy.he.h_addr_list = dummy.addtl;
730 			dummy.addtl[0] = (char *)&addr1;
731 			dummy.addtl[1] = NULL;
732 			hp = &dummy.he;
733 			dummy.he.h_addrtype = AF_INET6;
734 			dummy.he.h_length = sizeof (struct in6_addr);
735 			/*
736 			 * NOTE:  If macro changes to disallow in-place
737 			 * conversion, rewhack this.
738 			 */
739 			IN6_INADDR_TO_V4MAPPED(&addr1.ipv4, &addr1.ipv6);
740 		} else {
741 			hp = NULL;
742 		}
743 	}
744 
745 	if (hp == NULL)
746 		WARN1(ep, ebuf, gettext("Unknown address %s."), addr);
747 
748 	*hpp = hp;
749 	/* Always return sockaddr_in6 for now. */
750 	handle_errors(ep, NULL, B_FALSE, B_FALSE);
751 	return (sizeof (struct sockaddr_in6));
752 }
753 
754 /*
755  * Parse a hex character for a key.  A string will take the form:
756  *	xxxxxxxxx/nn
757  * where
758  *	xxxxxxxxx == a string of hex characters ([0-9][a-f][A-F])
759  *	nn == an optional decimal "mask".  If it is not present, it
760  *	is assumed that the hex string will be rounded to the nearest
761  *	byte, where odd nibbles, like 123 will become 0x0123.
762  *
763  * NOTE:Unlike the expression of IP addresses, I will not allow an
764  *	excessive "mask".  For example 2112/50 is very illegal.
765  * NOTE2:	This key should be in canonical order.  Consult your man
766  *		pages per algorithm about said order.
767  */
768 
769 #define	hd2num(hd) (((hd) >= '0' && (hd) <= '9') ? ((hd) - '0') : \
770 	(((hd) >= 'a' && (hd) <= 'f') ? ((hd) - 'a' + 10) : ((hd) - 'A' + 10)))
771 
772 static struct sadb_key *
773 parsekey(char *input, char *ebuf)
774 {
775 	struct sadb_key *retval;
776 	uint_t i, hexlen = 0, bits, alloclen;
777 	uint8_t *key;
778 	char *ep = NULL;
779 
780 	if (input == NULL) {
781 		FATAL(ep, ebuf, gettext("Unexpected end of command line, "
782 		    "was expecting a key.\n"));
783 	}
784 	/* Allow hex values prepended with 0x convention */
785 	if ((strnlen(input, sizeof (hexlen)) > 2) &&
786 	    (strncasecmp(input, "0x", 2) == 0))
787 		input += 2;
788 
789 	for (i = 0; input[i] != '\0' && input[i] != '/'; i++)
790 		hexlen++;
791 
792 	if (input[i] == '\0') {
793 		bits = 0;
794 	} else {
795 		/* Have /nn. */
796 		input[i] = '\0';
797 		if (sscanf((input + i + 1), "%u", &bits) != 1) {
798 			FATAL1(ep, ebuf, gettext(
799 			    "\"%s\" is not a bit specifier.\n"),
800 			    (input + i + 1));
801 		}
802 		/* hexlen in nibbles */
803 		if (((bits + 3) >> 2) > hexlen) {
804 			ERROR2(ep, ebuf, gettext(
805 			    "bit length %d is too big for %s.\n"), bits, input);
806 		}
807 		/*
808 		 * Adjust hexlen down if user gave us too small of a bit
809 		 * count.
810 		 */
811 		if ((hexlen << 2) > bits + 3) {
812 			WARN2(ep, ebuf, gettext(
813 			    "WARNING: Lower bits will be truncated "
814 			    "for:\n\t%s/%d.\n"), input, bits);
815 			hexlen = (bits + 3) >> 2;
816 			input[hexlen] = '\0';
817 		}
818 	}
819 
820 	/*
821 	 * Allocate.  Remember, hexlen is in nibbles.
822 	 */
823 
824 	alloclen = sizeof (*retval) + roundup((hexlen/2 + (hexlen & 0x1)), 8);
825 	retval = malloc(alloclen);
826 
827 	if (retval == NULL)
828 		Bail("malloc(parsekey)");
829 	retval->sadb_key_len = SADB_8TO64(alloclen);
830 	retval->sadb_key_reserved = 0;
831 	if (bits == 0)
832 		retval->sadb_key_bits = (hexlen + (hexlen & 0x1)) << 2;
833 	else
834 		retval->sadb_key_bits = bits;
835 
836 	/*
837 	 * Read in nibbles.  Read in odd-numbered as shifted high.
838 	 * (e.g. 123 becomes 0x1230).
839 	 */
840 
841 	key = (uint8_t *)(retval + 1);
842 	for (i = 0; input[i] != '\0'; i += 2) {
843 		boolean_t second = (input[i + 1] != '\0');
844 
845 		if (!isxdigit(input[i]) ||
846 		    (!isxdigit(input[i + 1]) && second)) {
847 			ERROR1(ep, ebuf, gettext(
848 			    "string '%s' not a hex value.\n"), input);
849 			free(retval);
850 			retval = NULL;
851 			break;
852 		}
853 		*key = (hd2num(input[i]) << 4);
854 		if (second)
855 			*key |= hd2num(input[i + 1]);
856 		else
857 			break;	/* out of for loop. */
858 		key++;
859 	}
860 
861 	/* bzero the remaining bits if we're a non-octet amount. */
862 	if (bits & 0x7)
863 		*((input[i] == '\0') ? key - 1 : key) &=
864 		    0xff << (8 - (bits & 0x7));
865 
866 	handle_errors(ep, NULL, B_FALSE, B_FALSE);
867 	return (retval);
868 }
869 
870 /*
871  * Write a message to the PF_KEY socket.  If verbose, print the message
872  * heading into the kernel.
873  */
874 static int
875 key_write(int fd, void *msg, size_t len)
876 {
877 	if (vflag) {
878 		(void) printf(
879 		    gettext("VERBOSE ON:  Message to kernel looks like:\n"));
880 		(void) printf("==========================================\n");
881 		print_samsg(stdout, msg, B_FALSE, vflag, nflag);
882 		(void) printf("==========================================\n");
883 	}
884 
885 	return (write(fd, msg, len));
886 }
887 
888 /*
889  * SIGALRM handler for time_critical_enter.
890  */
891 static void
892 time_critical_catch(int signal)
893 {
894 	if (signal == SIGALRM) {
895 		errx(1, gettext("Reply message from PF_KEY timed out."));
896 	} else {
897 		errx(1, gettext("Caught signal %d while trying to receive"
898 		    "PF_KEY reply message"), signal);
899 	}
900 	/* errx() calls exit. */
901 }
902 
903 #define	TIME_CRITICAL_TIME 10	/* In seconds */
904 
905 /*
906  * Enter a "time critical" section where key is waiting for a return message.
907  */
908 static void
909 time_critical_enter(void)
910 {
911 	(void) signal(SIGALRM, time_critical_catch);
912 	(void) alarm(TIME_CRITICAL_TIME);
913 }
914 
915 /*
916  * Exit the "time critical" section after getting an appropriate return
917  * message.
918  */
919 static void
920 time_critical_exit(void)
921 {
922 	(void) alarm(0);
923 	(void) signal(SIGALRM, SIG_DFL);
924 }
925 
926 /*
927  * Construct a PF_KEY FLUSH message for the SA type specified.
928  */
929 static void
930 doflush(int satype)
931 {
932 	struct sadb_msg msg;
933 	int rc;
934 
935 	msg_init(&msg, SADB_FLUSH, (uint8_t)satype);
936 	rc = key_write(keysock, &msg, sizeof (msg));
937 	if (rc == -1)
938 		Bail("write() to PF_KEY socket failed (in doflush)");
939 
940 	time_critical_enter();
941 	do {
942 		rc = read(keysock, &msg, sizeof (msg));
943 		if (rc == -1)
944 			Bail("read (in doflush)");
945 	} while (msg.sadb_msg_seq != seq || msg.sadb_msg_pid != mypid);
946 	time_critical_exit();
947 
948 	/*
949 	 * I should _never_ hit the following unless:
950 	 *
951 	 * 1. There is a kernel bug.
952 	 * 2. There is another process filling in its pid with mine, and
953 	 *    issuing a different message that would cause a different result.
954 	 */
955 	if (msg.sadb_msg_type != SADB_FLUSH ||
956 	    msg.sadb_msg_satype != (uint8_t)satype) {
957 		syslog((LOG_NOTICE|LOG_AUTH),
958 		    gettext("doflush: Return message not of type SADB_FLUSH!"));
959 		Bail("doflush: Return message not of type SADB_FLUSH!");
960 	}
961 
962 	if (msg.sadb_msg_errno != 0) {
963 		errno = msg.sadb_msg_errno;
964 		if (errno == EINVAL) {
965 			print_diagnostic(stderr, msg.sadb_x_msg_diagnostic);
966 			warnx(gettext("Cannot flush SA type %d."), satype);
967 		}
968 		Bail("return message (in doflush)");
969 	}
970 }
971 
972 /*
973  * save_XXX functions are used when "saving" the SA tables to either a
974  * file or standard output.  They use the dump_XXX functions where needed,
975  * but mostly they use the rparseXXX functions.
976  */
977 
978 /*
979  * Because "save" and "dump" both use the SADB_DUMP message, fold both
980  * into the same function.
981  */
982 static void
983 dodump(int satype, FILE *ofile)
984 {
985 	struct sadb_msg *msg = (struct sadb_msg *)get_buffer;
986 	int rc;
987 
988 	if (ofile != NULL) {
989 		(void) fprintf(ofile,
990 		    gettext("# This key file was generated by the"));
991 		(void) fprintf(ofile,
992 		    gettext(" ipseckey(1m) command's 'save' feature.\n\n"));
993 	}
994 	msg_init(msg, SADB_DUMP, (uint8_t)satype);
995 	rc = key_write(keysock, msg, sizeof (*msg));
996 	if (rc == -1)
997 		Bail("write to PF_KEY socket failed (in dodump)");
998 
999 	do {
1000 		/*
1001 		 * For DUMP, do only the read as a time critical section.
1002 		 */
1003 		time_critical_enter();
1004 		rc = read(keysock, get_buffer, sizeof (get_buffer));
1005 		time_critical_exit();
1006 		if (rc == -1)
1007 			Bail("read (in dodump)");
1008 		if (msg->sadb_msg_pid == mypid &&
1009 		    msg->sadb_msg_type == SADB_DUMP &&
1010 		    msg->sadb_msg_seq != 0 &&
1011 		    msg->sadb_msg_errno == 0) {
1012 			if (ofile == NULL) {
1013 				print_samsg(stdout, get_buffer, B_FALSE, vflag,
1014 				    nflag);
1015 				(void) putchar('\n');
1016 			} else {
1017 				save_assoc(get_buffer, ofile);
1018 			}
1019 		}
1020 	} while (msg->sadb_msg_pid != mypid ||
1021 	    (msg->sadb_msg_errno == 0 && msg->sadb_msg_seq != 0));
1022 
1023 	if (ofile != NULL && ofile != stdout)
1024 		(void) fclose(ofile);
1025 
1026 	if (msg->sadb_msg_errno == 0) {
1027 		if (ofile == NULL)
1028 			(void) printf(
1029 			    gettext("Dump succeeded for SA type %d.\n"),
1030 			    satype);
1031 	} else {
1032 		print_diagnostic(stderr, msg->sadb_x_msg_diagnostic);
1033 		errno = msg->sadb_msg_errno;
1034 		Bail("Dump failed");
1035 	}
1036 }
1037 
1038 #define	SCOPE_UNSPEC 0
1039 #define	SCOPE_LINKLOCAL 1
1040 #define	SCOPE_SITELOCAL 2
1041 #define	SCOPE_GLOBAL 3
1042 #define	SCOPE_V4COMPAT 4
1043 #define	SCOPE_LOOPBACK 5	/* Pedantic, yes, but necessary. */
1044 
1045 static int
1046 ipv6_addr_scope(struct in6_addr *addr)
1047 {
1048 	/* Don't return anything regarding multicast for now... */
1049 
1050 	if (IN6_IS_ADDR_UNSPECIFIED(addr))
1051 		return (SCOPE_UNSPEC);
1052 
1053 	if (IN6_IS_ADDR_LINKLOCAL(addr))
1054 		return (SCOPE_LINKLOCAL);
1055 
1056 	if (IN6_IS_ADDR_SITELOCAL(addr))
1057 		return (SCOPE_SITELOCAL);
1058 
1059 	if (IN6_IS_ADDR_V4COMPAT(addr))
1060 		return (SCOPE_V4COMPAT);
1061 
1062 	if (IN6_IS_ADDR_LOOPBACK(addr))
1063 		return (SCOPE_LOOPBACK);
1064 
1065 	/* For now, return global by default. */
1066 	return (SCOPE_GLOBAL);
1067 }
1068 
1069 /*
1070  * doaddresses():
1071  *
1072  * Used by doaddup() and dodelget() to create new SA's based on the
1073  * provided source and destination addresses hostent.
1074  *
1075  * sadb_msg_type: expected PF_KEY reply message type
1076  * sadb_msg_satype: expected PF_KEY reply satype
1077  * cmd: user command
1078  * srchp: hostent for the source address(es)
1079  * dsthp: hostent for the destination address(es)
1080  * src: points to the SADB source address extension
1081  * dst: points to the SADB destination address extension
1082  * unspec_src: indicates an unspecified source address.
1083  * buffer: pointer to the SADB buffer to use with PF_KEY
1084  * buffer_size: size of buffer
1085  * spi: spi for this message (set by caller)
1086  * srcport: source port if specified
1087  * dstport: destination port if specified
1088  * proto: IP protocol number if specified
1089  * iproto: Inner (tunnel mode) IP protocol number if specified
1090  * NATT note: we are going to assume a semi-sane world where NAT
1091  * boxen don't explode to multiple addresses.
1092  */
1093 static void
1094 doaddresses(uint8_t sadb_msg_type, uint8_t sadb_msg_satype, int cmd,
1095     struct hostent *srchp, struct hostent *dsthp,
1096     struct sadb_address *src, struct sadb_address *dst,
1097     boolean_t unspec_src, uint64_t *buffer, int buffer_size, uint32_t spi,
1098     char *ebuf)
1099 {
1100 	boolean_t single_dst;
1101 	struct sockaddr_in6 *sin6;
1102 	struct sadb_msg *msgp;
1103 	int i, rc;
1104 	char **walker;	/* For the SRC and PROXY walking functions. */
1105 	char *first_match;
1106 	uint64_t savebuf[MAX_GET_SIZE];
1107 	uint16_t srcport = 0, dstport = 0;
1108 	char *ep = NULL;
1109 
1110 	/*
1111 	 * Okay, now we have "src", "dst", and maybe "proxy" reassigned
1112 	 * to point into the buffer to be written to PF_KEY, we can do
1113 	 * potentially several writes based on destination address.
1114 	 *
1115 	 * First, obtain port numbers from passed-in extensions.
1116 	 */
1117 
1118 	if (src != NULL) {
1119 		sin6 = (struct sockaddr_in6 *)(src + 1);
1120 		srcport = ntohs(sin6->sin6_port);
1121 	}
1122 	if (dst != NULL) {
1123 		sin6 = (struct sockaddr_in6 *)(dst + 1);
1124 		dstport = ntohs(sin6->sin6_port);
1125 	}
1126 
1127 	/*
1128 	 * The rules for ADD, GET, and UPDATE: (NOTE:  This assumes IPsec.
1129 	 * If other consumers of PF_KEY happen, this will have to be
1130 	 * rewhacked.):
1131 	 *
1132 	 *	Do a message for every possible DST address.
1133 	 *
1134 	 *	If a source or proxy address explodes, keep unspecified
1135 	 *	(and mention unspecified).
1136 	 *
1137 	 * If dsthp is == dummy.he, then go through the loop once.
1138 	 * If any other hp is == dummy.he, then you don't have to apply any
1139 	 * silly rules.
1140 	 *
1141 	 * DELETE is different, because you can leave either "src" or "dst"
1142 	 * blank!  You need to explode if one of them is full, and not assume
1143 	 * that the other is set.
1144 	 */
1145 
1146 	if (dsthp == NULL) {
1147 		/*
1148 		 * No destination address specified.
1149 		 * With extended diagnostics, we don't have to bail the
1150 		 * non-DELETE cases here.  The EINVAL diagnostics will be
1151 		 * enough to inform the user(s) what happened.
1152 		 */
1153 		i = 0;
1154 		do {
1155 			if (srchp == &dummy.he) {
1156 				/* Just to be sure... */
1157 				srchp->h_addr_list[1] = NULL;
1158 			} else if (srchp != NULL) {
1159 				/* Degenerate case, h_addr_list[0] == NULL. */
1160 				if (srchp->h_addr_list[i] == NULL)
1161 					Bail("Empty source address list");
1162 
1163 				/*
1164 				 * Fill in the src sockaddr.
1165 				 */
1166 				sin6 = (struct sockaddr_in6 *)(src + 1);
1167 				bzero(sin6, sizeof (*sin6));
1168 				bcopy(srchp->h_addr_list[i], &sin6->sin6_addr,
1169 				    sizeof (struct in6_addr));
1170 				sin6->sin6_family = AF_INET6;
1171 				sin6->sin6_port = htons(srcport);
1172 			}
1173 
1174 			/* Save off a copy for later writing... */
1175 			msgp = (struct sadb_msg *)buffer;
1176 			bcopy(buffer, savebuf, SADB_64TO8(msgp->sadb_msg_len));
1177 
1178 			rc = key_write(keysock, buffer,
1179 			    SADB_64TO8(msgp->sadb_msg_len));
1180 			if (rc == -1)
1181 				Bail("write() to PF_KEY socket "
1182 				    "(in doaddresses)");
1183 
1184 			time_critical_enter();
1185 			do {
1186 				rc = read(keysock, buffer, buffer_size);
1187 				if (rc == -1)
1188 					Bail("read (in doaddresses)");
1189 			} while (msgp->sadb_msg_seq != seq ||
1190 			    msgp->sadb_msg_pid != mypid);
1191 			time_critical_exit();
1192 
1193 			if (msgp->sadb_msg_type != sadb_msg_type ||
1194 			    msgp->sadb_msg_satype != sadb_msg_satype) {
1195 				syslog((LOG_NOTICE|LOG_AUTH), gettext(
1196 				    "doaddresses: Unexpected returned message "
1197 				    "(%d exp %d)\n"), msgp->sadb_msg_type,
1198 				    sadb_msg_type);
1199 				Bail("doaddresses: Unexpected returned "
1200 				    "message");
1201 			}
1202 
1203 			errno = msgp->sadb_msg_errno;
1204 			if (errno != 0) {
1205 				if (errno == EINVAL) {
1206 					WARN(ep, ebuf, gettext(
1207 					    "One of the entered "
1208 					    "values is incorrect."));
1209 					print_diagnostic(stderr,
1210 					    msgp->sadb_x_msg_diagnostic);
1211 				} else {
1212 					Bail("return message (in doaddresses)");
1213 				}
1214 			}
1215 
1216 			/* ...and then restore the saved buffer. */
1217 			msgp = (struct sadb_msg *)savebuf;
1218 			bcopy(savebuf, buffer, SADB_64TO8(msgp->sadb_msg_len));
1219 		} while (srchp != NULL && srchp->h_addr_list[++i] != NULL);
1220 		return;
1221 	}
1222 
1223 	single_dst = (dsthp == &dummy.he || dsthp->h_addr_list[1] == NULL);
1224 
1225 	for (i = 0; dsthp->h_addr_list[i] != NULL; i++) {
1226 		if (dsthp == &dummy.he) {
1227 			/* Just to be sure... */
1228 			dsthp->h_addr_list[1] = NULL;
1229 		} else {
1230 			/*
1231 			 * Fill in the dst sockaddr.
1232 			 */
1233 			sin6 = (struct sockaddr_in6 *)(dst + 1);
1234 			bzero(sin6, sizeof (*sin6));
1235 			bcopy(dsthp->h_addr_list[i], &sin6->sin6_addr,
1236 			    sizeof (struct in6_addr));
1237 			sin6->sin6_family = AF_INET6;
1238 			sin6->sin6_port = htons(dstport);
1239 		}
1240 
1241 		/*
1242 		 * Try and assign src, if there's any ambiguity.
1243 		 */
1244 		if (!unspec_src && srchp != &dummy.he) {
1245 			if (IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
1246 				/*
1247 				 * IPv4 address.  Find an IPv4 address, then
1248 				 * keep looking for a second one.  If a second
1249 				 * exists, print a message, and fill in the
1250 				 * unspecified address.
1251 				 */
1252 				first_match = NULL;
1253 
1254 				for (walker = srchp->h_addr_list;
1255 				    *walker != NULL; walker++) {
1256 					/* LINTED E_BAD_PTR_CAST_ALIGN */
1257 					if (IN6_IS_ADDR_V4MAPPED(
1258 					    (struct in6_addr *)*walker)) {
1259 						if (first_match != NULL)
1260 							break;
1261 						else
1262 							first_match = *walker;
1263 					}
1264 				}
1265 				sin6 = (struct sockaddr_in6 *)(src + 1);
1266 				bzero(sin6, sizeof (*sin6));
1267 
1268 				if (first_match == NULL) {
1269 					/*
1270 					 * No IPv4 hits.  Is this a single
1271 					 * dest?
1272 					 */
1273 					WARN1(ep, ebuf, gettext(
1274 					    "No IPv4 source address "
1275 					    "for name %s.\n"), srchp->h_name);
1276 					if (single_dst) {
1277 						ERROR(ep, ebuf, gettext(
1278 						    "Only single destination "
1279 						    "IP address.\n"));
1280 					} else {
1281 						/* Continue, but do I print? */
1282 						continue;  /* for loop */
1283 					}
1284 
1285 					/* I should never reach here. */
1286 				}
1287 
1288 				sin6->sin6_family = AF_INET6;
1289 				sin6->sin6_port = htons(srcport);
1290 				if (*walker != NULL) {
1291 					/*
1292 					 * Early loop exit.  It must've been
1293 					 * multiple hits...
1294 					 *
1295 					 * Issue a null-source warning?
1296 					 */
1297 					WARN1(ep, ebuf, gettext(
1298 					    "Multiple IPv4 source addresses "
1299 					    "for %s, using unspecified source "
1300 					    "instead."), srchp->h_name);
1301 				} else {
1302 					/*
1303 					 * If I reach here w/o hitting the
1304 					 * previous if statements, I have a
1305 					 * single source address for this
1306 					 * destination.
1307 					 */
1308 					bcopy(first_match, &sin6->sin6_addr,
1309 					    sizeof (struct in6_addr));
1310 				}
1311 			} else {
1312 				/*
1313 				 * IPv6 address.  Find an IPv6 address.
1314 				 * Unlike IPv4 addresses, things can get a
1315 				 * little more sticky with scopes, etc.
1316 				 */
1317 				int dst_scope, src_scope;
1318 
1319 				dst_scope = ipv6_addr_scope(&sin6->sin6_addr);
1320 
1321 				first_match = NULL;
1322 				for (walker = srchp->h_addr_list;
1323 				    *walker != NULL; walker++) {
1324 					/* LINTED E_BAD_PTR_CAST_ALIGN */
1325 					if (!IN6_IS_ADDR_V4MAPPED(
1326 					    (struct in6_addr *)*walker)) {
1327 						/*
1328 						 * Set first-match, etc.
1329 						 * Take into account scopes,
1330 						 * and other IPv6 thingies.
1331 						 */
1332 						src_scope = ipv6_addr_scope(
1333 						    /* LINTED E_BAD_PTR_CAST */
1334 						    (struct in6_addr *)*walker);
1335 						if (src_scope == SCOPE_UNSPEC ||
1336 						    src_scope == dst_scope) {
1337 							if (first_match !=
1338 							    NULL)
1339 								break;
1340 							else
1341 								first_match =
1342 								    *walker;
1343 						}
1344 					}
1345 				}
1346 
1347 				sin6 = (struct sockaddr_in6 *)(src + 1);
1348 				bzero(sin6, sizeof (*sin6));
1349 				sin6->sin6_port = htons(srcport);
1350 				if (first_match == NULL) {
1351 					/*
1352 					 * No IPv6 hits.  Is this a single
1353 					 * dest?
1354 					 */
1355 					WARN1(ep, ebuf, gettext(
1356 					    "No IPv6 source address of "
1357 					    "matching scope for name %s.\n"),
1358 					    srchp->h_name);
1359 					if (single_dst) {
1360 						ERROR(ep, ebuf, gettext(
1361 						    "Only a single IPV6 "
1362 						    "destination "
1363 						    "address.\n"));
1364 					} else {
1365 						/* Continue, but do I print? */
1366 						continue;  /* for loop */
1367 					}
1368 
1369 					/* I should never reach here. */
1370 				}
1371 				sin6->sin6_family = AF_INET6;
1372 				if (*walker != NULL) {
1373 					/*
1374 					 * Early loop exit.  Issue a
1375 					 * null-source warning?
1376 					 */
1377 					WARN1(ep, ebuf, gettext(
1378 					    "Multiple IPv6 source addresses "
1379 					    "for %s of the same scope, using "
1380 					    "unspecified source instead.\n"),
1381 					    srchp->h_name);
1382 				} else {
1383 					/*
1384 					 * If I reach here w/o hitting the
1385 					 * previous if statements, I have a
1386 					 * single source address for this
1387 					 * destination.
1388 					 */
1389 					bcopy(first_match, &sin6->sin6_addr,
1390 					    sizeof (struct in6_addr));
1391 				}
1392 			}
1393 		}
1394 
1395 		/*
1396 		 * If there are errors at this point there is no
1397 		 * point sending anything to PF_KEY.
1398 		 */
1399 		handle_errors(ep, ebuf, B_TRUE, B_FALSE);
1400 
1401 		/* Save off a copy for later writing... */
1402 		msgp = (struct sadb_msg *)buffer;
1403 		bcopy(buffer, savebuf, SADB_64TO8(msgp->sadb_msg_len));
1404 
1405 		rc = key_write(keysock, buffer, SADB_64TO8(msgp->sadb_msg_len));
1406 		if (rc == -1)
1407 			Bail("write() to PF_KEY socket (in doaddresses)");
1408 
1409 		/* Blank the key for paranoia's sake. */
1410 		bzero(buffer, buffer_size);
1411 		time_critical_enter();
1412 		do {
1413 			rc = read(keysock, buffer, buffer_size);
1414 			if (rc == -1)
1415 				Bail("read (in doaddresses)");
1416 		} while (msgp->sadb_msg_seq != seq ||
1417 		    msgp->sadb_msg_pid != mypid);
1418 		time_critical_exit();
1419 
1420 		/*
1421 		 * I should _never_ hit the following unless:
1422 		 *
1423 		 * 1. There is a kernel bug.
1424 		 * 2. Another process is mistakenly using my pid in a PF_KEY
1425 		 *    message.
1426 		 */
1427 		if (msgp->sadb_msg_type != sadb_msg_type ||
1428 		    msgp->sadb_msg_satype != sadb_msg_satype) {
1429 			syslog((LOG_NOTICE|LOG_AUTH), gettext(
1430 			    "doaddresses: Unexpected returned message "
1431 			    "(%d exp %d)\n"), msgp->sadb_msg_type,
1432 			    sadb_msg_type);
1433 			Bail("doaddresses: Unexpected returned message");
1434 		}
1435 
1436 		if (msgp->sadb_msg_errno != 0) {
1437 			char addrprint[INET6_ADDRSTRLEN];
1438 			int on_errno = 0;
1439 			char *on_errno_msg;
1440 
1441 			/*
1442 			 * Print different error messages depending
1443 			 * on the SADB message type being processed.
1444 			 * If we get a ESRCH error for a GET/DELETE
1445 			 * messages, we report that the SA does not
1446 			 * exist. If we get a EEXIST error for a
1447 			 * ADD/UPDATE message, we report that the
1448 			 * SA already exists.
1449 			 */
1450 			if (sadb_msg_type == SADB_GET ||
1451 			    sadb_msg_type == SADB_DELETE) {
1452 				on_errno = ESRCH;
1453 				on_errno_msg = "does not exist";
1454 			} else if (sadb_msg_type == SADB_ADD ||
1455 			    sadb_msg_type == SADB_UPDATE) {
1456 				on_errno = EEXIST;
1457 				on_errno_msg = "already exists";
1458 			}
1459 
1460 			errno = msgp->sadb_msg_errno;
1461 			if (errno == on_errno) {
1462 				ERROR2(ep, ebuf, gettext(
1463 				    "Association (type = %s) "
1464 				    "with spi 0x%x and addr\n"),
1465 				    rparsesatype(msgp->sadb_msg_satype),
1466 				    ntohl(spi));
1467 				ERROR2(ep, ebuf, "%s %s.\n",
1468 				    do_inet_ntop(dsthp->h_addr_list[i],
1469 				    addrprint, sizeof (addrprint)),
1470 				    on_errno_msg);
1471 				msgp = (struct sadb_msg *)savebuf;
1472 				bcopy(savebuf, buffer,
1473 				    SADB_64TO8(msgp->sadb_msg_len));
1474 				continue;
1475 			} else {
1476 				if (errno == EINVAL) {
1477 					ERROR2(ep, ebuf, gettext(
1478 					    "PF_KEY Diagnostic code %u: %s.\n"),
1479 					    msgp->sadb_x_msg_diagnostic,
1480 					    keysock_diag(
1481 					    msgp->sadb_x_msg_diagnostic));
1482 				} else {
1483 					Bail("return message (in doaddresses)");
1484 				}
1485 			}
1486 		}
1487 
1488 		if (cmd == CMD_GET) {
1489 			if (msgp->sadb_msg_len > MAX_GET_SIZE) {
1490 				WARN1(ep, ebuf, gettext("WARNING:  "
1491 				    "SA information bigger than %d bytes.\n"),
1492 				    SADB_64TO8(MAX_GET_SIZE));
1493 			}
1494 			print_samsg(stdout, buffer, B_FALSE, vflag, nflag);
1495 		}
1496 
1497 		handle_errors(ep, ebuf, B_TRUE, B_FALSE);
1498 
1499 		/* ...and then restore the saved buffer. */
1500 		msgp = (struct sadb_msg *)savebuf;
1501 		bcopy(savebuf, buffer, SADB_64TO8(msgp->sadb_msg_len));
1502 		lines_added++;
1503 	}
1504 
1505 	/* Degenerate case, h_addr_list[0] == NULL. */
1506 	if (i == 0)
1507 		Bail("Empty destination address list");
1508 
1509 	/*
1510 	 * free(ebuf) even if there are no errors.
1511 	 * handle_errors() won't return here.
1512 	 */
1513 	handle_errors(ep, ebuf, B_TRUE, B_TRUE);
1514 }
1515 
1516 /*
1517  * Perform an add or an update.  ADD and UPDATE are similar in the extensions
1518  * they need.
1519  */
1520 static void
1521 doaddup(int cmd, int satype, char *argv[], char *ebuf)
1522 {
1523 	uint64_t *buffer, *nexthdr;
1524 	struct sadb_msg msg;
1525 	struct sadb_sa *assoc = NULL;
1526 	struct sadb_address *src = NULL, *dst = NULL;
1527 	struct sadb_address *isrc = NULL, *idst = NULL;
1528 	struct sadb_address *natt_local = NULL, *natt_remote = NULL;
1529 	struct sadb_key *encrypt = NULL, *auth = NULL;
1530 	struct sadb_ident *srcid = NULL, *dstid = NULL;
1531 	struct sadb_lifetime *hard = NULL, *soft = NULL;  /* Current? */
1532 	struct sockaddr_in6 *sin6;
1533 	/* MLS TODO:  Need sensitivity eventually. */
1534 	int next, token, sa_len, alloclen, totallen = sizeof (msg), prefix;
1535 	uint32_t spi;
1536 	char *thiscmd, *pstr;
1537 	boolean_t readstate = B_FALSE, unspec_src = B_FALSE;
1538 	boolean_t alloc_inner = B_FALSE, use_natt = B_FALSE;
1539 	struct hostent *srchp = NULL, *dsthp = NULL, *isrchp = NULL,
1540 	    *idsthp = NULL;
1541 	struct hostent *natt_lhp = NULL, *natt_rhp = NULL;
1542 	uint16_t srcport = 0, dstport = 0, natt_lport = 0, natt_rport = 0,
1543 	    isrcport = 0, idstport = 0;
1544 	uint8_t proto = 0, iproto = 0;
1545 	char *ep = NULL;
1546 
1547 	thiscmd = (cmd == CMD_ADD) ? "add" : "update";
1548 
1549 	msg_init(&msg, ((cmd == CMD_ADD) ? SADB_ADD : SADB_UPDATE),
1550 	    (uint8_t)satype);
1551 
1552 	/* Assume last element in argv is set to NULL. */
1553 	do {
1554 		token = parseextval(*argv, &next);
1555 		argv++;
1556 		switch (token) {
1557 		case TOK_EOF:
1558 			/* Do nothing, I'm done. */
1559 			break;
1560 		case TOK_UNKNOWN:
1561 			ERROR1(ep, ebuf, gettext(
1562 			    "Unknown extension field \"%s\" \n"), *(argv - 1));
1563 			break;
1564 		case TOK_SPI:
1565 		case TOK_REPLAY:
1566 		case TOK_STATE:
1567 		case TOK_AUTHALG:
1568 		case TOK_ENCRALG:
1569 		case TOK_ENCAP:
1570 			/*
1571 			 * May want to place this chunk of code in a function.
1572 			 *
1573 			 * This code checks for duplicate entries on a command
1574 			 * line.
1575 			 */
1576 
1577 			/* Allocate the SADB_EXT_SA extension. */
1578 			if (assoc == NULL) {
1579 				assoc = malloc(sizeof (*assoc));
1580 				if (assoc == NULL)
1581 					Bail("malloc(assoc)");
1582 				bzero(assoc, sizeof (*assoc));
1583 				assoc->sadb_sa_exttype = SADB_EXT_SA;
1584 				assoc->sadb_sa_len =
1585 				    SADB_8TO64(sizeof (*assoc));
1586 				totallen += sizeof (*assoc);
1587 			}
1588 			switch (token) {
1589 			case TOK_SPI:
1590 				/*
1591 				 * If some cretin types in "spi 0" then he/she
1592 				 * can type in another SPI.
1593 				 */
1594 				if (assoc->sadb_sa_spi != 0) {
1595 					ERROR(ep, ebuf, gettext(
1596 					    "Can only specify "
1597 					    "single SPI value.\n"));
1598 					break;
1599 				}
1600 				/* Must convert SPI to network order! */
1601 				assoc->sadb_sa_spi =
1602 				    htonl((uint32_t)parsenum(*argv, B_TRUE,
1603 				    ebuf));
1604 				if (assoc->sadb_sa_spi == 0) {
1605 					ERROR(ep, ebuf, gettext(
1606 					    "Invalid SPI value \"0\" .\n"));
1607 				}
1608 				break;
1609 			case TOK_REPLAY:
1610 				/*
1611 				 * That same cretin can do the same with
1612 				 * replay.
1613 				 */
1614 				if (assoc->sadb_sa_replay != 0) {
1615 					ERROR(ep, ebuf, gettext(
1616 					    "Can only specify "
1617 					    "single replay window size.\n"));
1618 					break;
1619 				}
1620 				assoc->sadb_sa_replay =
1621 				    (uint8_t)parsenum(*argv, B_TRUE, ebuf);
1622 				if (assoc->sadb_sa_replay != 0) {
1623 					WARN(ep, ebuf, gettext(
1624 					    "WARNING:  Replay with manual"
1625 					    " keying considered harmful.\n"));
1626 				}
1627 				break;
1628 			case TOK_STATE:
1629 				/*
1630 				 * 0 is an actual state value, LARVAL.  This
1631 				 * means that one can type in the larval state
1632 				 * and then type in another state on the same
1633 				 * command line.
1634 				 */
1635 				if (assoc->sadb_sa_state != 0) {
1636 					ERROR(ep, ebuf, gettext(
1637 					    "Can only specify "
1638 					    "single SA state.\n"));
1639 					break;
1640 				}
1641 				assoc->sadb_sa_state = parsestate(*argv,
1642 				    ebuf);
1643 				readstate = B_TRUE;
1644 				break;
1645 			case TOK_AUTHALG:
1646 				if (assoc->sadb_sa_auth != 0) {
1647 					ERROR(ep, ebuf, gettext(
1648 					    "Can only specify "
1649 					    "single auth algorithm.\n"));
1650 					break;
1651 				}
1652 				assoc->sadb_sa_auth = parsealg(*argv,
1653 				    IPSEC_PROTO_AH, ebuf);
1654 				break;
1655 			case TOK_ENCRALG:
1656 				if (satype == SADB_SATYPE_AH) {
1657 					ERROR(ep, ebuf, gettext("Cannot specify"
1658 					    " encryption with SA type ah.\n"));
1659 					break;
1660 				}
1661 				if (assoc->sadb_sa_encrypt != 0) {
1662 					ERROR(ep, ebuf, gettext(
1663 					    "Can only specify "
1664 					    "single encryption algorithm.\n"));
1665 					break;
1666 				}
1667 				assoc->sadb_sa_encrypt = parsealg(*argv,
1668 				    IPSEC_PROTO_ESP, ebuf);
1669 				break;
1670 			case TOK_ENCAP:
1671 				if (use_natt) {
1672 					ERROR(ep, ebuf, gettext(
1673 					    "Can only specify single"
1674 					    " encapsulation.\n"));
1675 					break;
1676 				}
1677 				if (strncmp(*argv, "udp", 3)) {
1678 					ERROR(ep, ebuf, gettext(
1679 					    "Can only specify udp"
1680 					    " encapsulation.\n"));
1681 					break;
1682 				}
1683 				use_natt = B_TRUE;
1684 				/* set assoc flags later */
1685 				break;
1686 			}
1687 			argv++;
1688 			break;
1689 		case TOK_SRCPORT:
1690 			if (srcport != 0) {
1691 				ERROR(ep, ebuf,  gettext("Can only specify "
1692 				    "single source port.\n"));
1693 				break;
1694 			}
1695 			srcport = parsenum(*argv, B_TRUE, ebuf);
1696 			argv++;
1697 			break;
1698 		case TOK_DSTPORT:
1699 			if (dstport != 0) {
1700 				ERROR(ep, ebuf, gettext("Can only specify "
1701 				    "single destination port.\n"));
1702 				break;
1703 			}
1704 			dstport = parsenum(*argv, B_TRUE, ebuf);
1705 			argv++;
1706 			break;
1707 		case TOK_ISRCPORT:
1708 			alloc_inner = B_TRUE;
1709 			if (isrcport != 0) {
1710 				ERROR(ep, ebuf, gettext(
1711 				    "Can only specify "
1712 				    "single inner-source port.\n"));
1713 				break;
1714 			}
1715 			isrcport = parsenum(*argv, B_TRUE, ebuf);
1716 			argv++;
1717 			break;
1718 		case TOK_IDSTPORT:
1719 			alloc_inner = B_TRUE;
1720 			if (idstport != 0) {
1721 				ERROR(ep, ebuf, gettext(
1722 				    "Can only specify "
1723 				    "single inner-destination port.\n"));
1724 				break;
1725 			}
1726 			idstport = parsenum(*argv, B_TRUE, ebuf);
1727 			argv++;
1728 			break;
1729 		case TOK_NATLPORT:
1730 			if (natt_lport != 0) {
1731 				ERROR(ep, ebuf, gettext(
1732 				    "Can only specify "
1733 				    "single NAT-T local port.\n"));
1734 				break;
1735 			}
1736 			natt_lport = parsenum(*argv, B_TRUE, ebuf);
1737 			argv++;
1738 			break;
1739 		case TOK_NATRPORT:
1740 			if (natt_rport != 0) {
1741 				ERROR(ep, ebuf, gettext(
1742 				    "Can only specify "
1743 				    "single NAT-T remote port.\n"));
1744 				break;
1745 			}
1746 			natt_rport = parsenum(*argv, B_TRUE, ebuf);
1747 			argv++;
1748 			break;
1749 
1750 		case TOK_PROTO:
1751 			if (proto != 0) {
1752 				ERROR(ep, ebuf, gettext(
1753 				    "Can only specify "
1754 				    "single protocol.\n"));
1755 				break;
1756 			}
1757 			proto = parsenum(*argv, B_TRUE, ebuf);
1758 			argv++;
1759 			break;
1760 		case TOK_IPROTO:
1761 			alloc_inner = B_TRUE;
1762 			if (iproto != 0) {
1763 				ERROR(ep, ebuf, gettext(
1764 				    "Can only specify "
1765 				    "single inner protocol.\n"));
1766 				break;
1767 			}
1768 			iproto = parsenum(*argv, B_TRUE, ebuf);
1769 			argv++;
1770 			break;
1771 		case TOK_SRCADDR:
1772 		case TOK_SRCADDR6:
1773 			if (src != NULL) {
1774 				ERROR(ep, ebuf, gettext(
1775 				    "Can only specify "
1776 				    "single source address.\n"));
1777 				break;
1778 			}
1779 			sa_len = parseaddr(*argv, &srchp,
1780 			    (token == TOK_SRCADDR6), ebuf);
1781 			if (srchp == NULL) {
1782 				ERROR1(ep, ebuf, gettext(
1783 				    "Unknown src address \"%s\"\n"), *argv);
1784 				break;
1785 			}
1786 			argv++;
1787 			/*
1788 			 * Round of the sockaddr length to an 8 byte
1789 			 * boundary to make PF_KEY happy.
1790 			 */
1791 			alloclen = sizeof (*src) + roundup(sa_len, 8);
1792 			src = malloc(alloclen);
1793 			if (src == NULL)
1794 				Bail("malloc(src)");
1795 			totallen += alloclen;
1796 			src->sadb_address_len = SADB_8TO64(alloclen);
1797 			src->sadb_address_exttype = SADB_EXT_ADDRESS_SRC;
1798 			src->sadb_address_reserved = 0;
1799 			src->sadb_address_prefixlen = 0;
1800 			src->sadb_address_proto = 0;
1801 			if (srchp == &dummy.he) {
1802 				/*
1803 				 * Single address with -n flag.
1804 				 */
1805 				sin6 = (struct sockaddr_in6 *)(src + 1);
1806 				bzero(sin6, sizeof (*sin6));
1807 				sin6->sin6_family = AF_INET6;
1808 				bcopy(srchp->h_addr_list[0], &sin6->sin6_addr,
1809 				    sizeof (struct in6_addr));
1810 			}
1811 			break;
1812 		case TOK_DSTADDR:
1813 		case TOK_DSTADDR6:
1814 			if (dst != NULL) {
1815 				ERROR(ep, ebuf, gettext(
1816 				    "Can only specify single "
1817 				    "destination address.\n"));
1818 				break;
1819 			}
1820 			sa_len = parseaddr(*argv, &dsthp,
1821 			    (token == TOK_DSTADDR6), ebuf);
1822 			if (dsthp == NULL) {
1823 				ERROR1(ep, ebuf, gettext(
1824 				    "Unknown dst address \"%s\"\n"), *argv);
1825 				break;
1826 			}
1827 			argv++;
1828 			alloclen = sizeof (*dst) + roundup(sa_len, 8);
1829 			dst = malloc(alloclen);
1830 			if (dst == NULL)
1831 				Bail("malloc(dst)");
1832 			totallen += alloclen;
1833 			dst->sadb_address_len = SADB_8TO64(alloclen);
1834 			dst->sadb_address_exttype = SADB_EXT_ADDRESS_DST;
1835 			dst->sadb_address_reserved = 0;
1836 			dst->sadb_address_prefixlen = 0;
1837 			dst->sadb_address_proto = 0;
1838 			if (dsthp == &dummy.he) {
1839 				/*
1840 				 * Single address with -n flag.
1841 				 */
1842 				sin6 = (struct sockaddr_in6 *)(dst + 1);
1843 				bzero(sin6, sizeof (*sin6));
1844 				sin6->sin6_family = AF_INET6;
1845 				bcopy(dsthp->h_addr_list[0], &sin6->sin6_addr,
1846 				    sizeof (struct in6_addr));
1847 			}
1848 			break;
1849 		case TOK_PROXYADDR:
1850 		case TOK_PROXYADDR6:
1851 			if (isrc != NULL) {
1852 				ERROR(ep, ebuf, gettext(
1853 				    "Can only specify single "
1854 				    "proxy/inner-source address.\n"));
1855 				break;
1856 			}
1857 			if ((pstr = strchr(*argv, '/')) != NULL) {
1858 				/* Parse out the prefix. */
1859 				errno = 0;
1860 				prefix = strtol(pstr + 1, NULL, 10);
1861 				if (errno != 0) {
1862 					ERROR1(ep, ebuf, gettext(
1863 					    "Invalid prefix %s."), pstr);
1864 					break;
1865 				}
1866 				/* Recycle pstr */
1867 				alloclen = (int)(pstr - *argv);
1868 				pstr = malloc(alloclen + 1);
1869 				if (pstr == NULL) {
1870 					Bail("malloc(pstr)");
1871 				}
1872 				(void) strlcpy(pstr, *argv, alloclen + 1);
1873 			} else {
1874 				pstr = *argv;
1875 				/*
1876 				 * Assume mapping to AF_INET6, and we're a host.
1877 				 * XXX some miscreants may still make classful
1878 				 * assumptions.  If this is a problem, fix it
1879 				 * here.
1880 				 */
1881 				prefix = 128;
1882 			}
1883 			sa_len = parseaddr(pstr, &isrchp,
1884 			    (token == TOK_PROXYADDR6), ebuf);
1885 			if (isrchp == NULL) {
1886 				ERROR1(ep, ebuf, gettext(
1887 				    "Unknown proxy/inner-source address "
1888 				    "\"%s\"\n"), *argv);
1889 				break;
1890 			}
1891 			if (pstr != *argv)
1892 				free(pstr);
1893 			argv++;
1894 			alloclen = sizeof (*isrc) + roundup(sa_len, 8);
1895 			isrc = malloc(alloclen);
1896 			if (isrc == NULL)
1897 				Bail("malloc(isrc)");
1898 			totallen += alloclen;
1899 			isrc->sadb_address_len = SADB_8TO64(alloclen);
1900 			isrc->sadb_address_exttype = SADB_EXT_ADDRESS_PROXY;
1901 			isrc->sadb_address_reserved = 0;
1902 			isrc->sadb_address_prefixlen = prefix;
1903 			isrc->sadb_address_proto = 0;
1904 			if (isrchp == &dummy.he ||
1905 			    isrchp->h_addr_list[1] == NULL) {
1906 				/*
1907 				 * Single address with -n flag or single name.
1908 				 */
1909 				sin6 = (struct sockaddr_in6 *)(isrc + 1);
1910 				bzero(sin6, sizeof (*sin6));
1911 				sin6->sin6_family = AF_INET6;
1912 				bcopy(isrchp->h_addr_list[0], &sin6->sin6_addr,
1913 				    sizeof (struct in6_addr));
1914 				/*
1915 				 * normalize prefixlen for IPv4-mapped
1916 				 * addresses.
1917 				 */
1918 				if (prefix <= 32 &&
1919 				    IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr))
1920 					isrc->sadb_address_prefixlen += 96;
1921 				alloc_inner = B_TRUE;
1922 			} else {
1923 				/*
1924 				 * If the proxy/isrc address is vague, don't
1925 				 * bother.
1926 				 */
1927 				totallen -= alloclen;
1928 				free(isrc);
1929 				isrc = NULL;
1930 				WARN1(ep, ebuf, gettext(
1931 				    "Proxy/inner-source address %s "
1932 				    "is vague, not using.\n"), isrchp->h_name);
1933 				freehostent(isrchp);
1934 				isrchp = NULL;
1935 				break;
1936 			}
1937 			break;
1938 		case TOK_IDSTADDR:
1939 		case TOK_IDSTADDR6:
1940 			if (idst != NULL) {
1941 				ERROR(ep, ebuf, gettext(
1942 				    "Can only specify single "
1943 				    "inner-destination address.\n"));
1944 				break;
1945 			}
1946 			if ((pstr = strchr(*argv, '/')) != NULL) {
1947 				/* Parse out the prefix. */
1948 				errno = 0;
1949 				prefix = strtol(pstr + 1, NULL, 10);
1950 				if (errno != 0) {
1951 					ERROR1(ep, ebuf, gettext(
1952 					    "Invalid prefix %s.\n"), pstr);
1953 					break;
1954 				}
1955 				/* Recycle pstr */
1956 				alloclen = (int)(pstr - *argv);
1957 				pstr = malloc(alloclen + 1);
1958 				if (pstr == NULL) {
1959 					Bail("malloc(pstr)");
1960 				}
1961 				(void) strlcpy(pstr, *argv, alloclen + 1);
1962 			} else {
1963 				pstr = *argv;
1964 				/*
1965 				 * Assume mapping to AF_INET6, and we're a host.
1966 				 * XXX some miscreants may still make classful
1967 				 * assumptions.  If this is a problem, fix it
1968 				 * here.
1969 				 */
1970 				prefix = 128;
1971 			}
1972 			sa_len = parseaddr(pstr, &idsthp,
1973 			    (token == TOK_IDSTADDR6), ebuf);
1974 			if (idsthp == NULL) {
1975 				ERROR1(ep, ebuf, gettext(
1976 				    "Unknown Inner Src address "
1977 				    " \"%s\"\n"), *argv);
1978 				break;
1979 			}
1980 			if (pstr != *argv)
1981 				free(pstr);
1982 			argv++;
1983 			alloclen = sizeof (*idst) + roundup(sa_len, 8);
1984 			idst = malloc(alloclen);
1985 			if (idst == NULL)
1986 				Bail("malloc(idst)");
1987 			totallen += alloclen;
1988 			idst->sadb_address_len = SADB_8TO64(alloclen);
1989 			idst->sadb_address_exttype =
1990 			    SADB_X_EXT_ADDRESS_INNER_DST;
1991 			idst->sadb_address_reserved = 0;
1992 			idst->sadb_address_prefixlen = prefix;
1993 			idst->sadb_address_proto = 0;
1994 			if (idsthp == &dummy.he ||
1995 			    idsthp->h_addr_list[1] == NULL) {
1996 				/*
1997 				 * Single address with -n flag or single name.
1998 				 */
1999 				sin6 = (struct sockaddr_in6 *)(idst + 1);
2000 				bzero(sin6, sizeof (*sin6));
2001 				sin6->sin6_family = AF_INET6;
2002 				bcopy(idsthp->h_addr_list[0], &sin6->sin6_addr,
2003 				    sizeof (struct in6_addr));
2004 				/*
2005 				 * normalize prefixlen for IPv4-mapped
2006 				 * addresses.
2007 				 */
2008 				if (prefix <= 32 &&
2009 				    IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr))
2010 					idst->sadb_address_prefixlen += 96;
2011 				alloc_inner = B_TRUE;
2012 			} else {
2013 				/*
2014 				 * If the idst address is vague, don't bother.
2015 				 */
2016 				totallen -= alloclen;
2017 				free(idst);
2018 				idst = NULL;
2019 				WARN1(ep, ebuf, gettext(
2020 				    "Inner destination address %s "
2021 				    "is vague, not using.\n"), idsthp->h_name);
2022 				freehostent(idsthp);
2023 				idsthp = NULL;
2024 				break;
2025 			}
2026 			break;
2027 		case TOK_NATLOC:
2028 			if (natt_local != NULL) {
2029 				ERROR(ep, ebuf, gettext(
2030 				    "Can only specify "
2031 				    "single NAT-T local address.\n"));
2032 				break;
2033 			}
2034 			sa_len = parseaddr(*argv, &natt_lhp, 0, ebuf);
2035 			if (natt_lhp == NULL) {
2036 				ERROR1(ep, ebuf, gettext(
2037 				    "Unknown NAT-T local address \"%s\"\n"),
2038 				    *argv);
2039 				break;
2040 			}
2041 			argv++;
2042 			/*
2043 			 * Round of the sockaddr length to an 8 byte
2044 			 * boundary to make PF_KEY happy.
2045 			 */
2046 			alloclen = sizeof (*natt_local) + roundup(sa_len, 8);
2047 			natt_local = malloc(alloclen);
2048 			if (natt_local == NULL)
2049 				Bail("malloc(natt_local)");
2050 			totallen += alloclen;
2051 			natt_local->sadb_address_len = SADB_8TO64(alloclen);
2052 			natt_local->sadb_address_exttype =
2053 			    SADB_X_EXT_ADDRESS_NATT_LOC;
2054 			natt_local->sadb_address_reserved = 0;
2055 			natt_local->sadb_address_prefixlen = 0;
2056 			natt_local->sadb_address_proto = 0;
2057 			if (natt_lhp == &dummy.he ||
2058 			    natt_lhp->h_addr_list[1] == NULL) {
2059 				/*
2060 				 * Single address with -n flag or single name.
2061 				 */
2062 				sin6 = (struct sockaddr_in6 *)(natt_local + 1);
2063 				bzero(sin6, sizeof (*sin6));
2064 				sin6->sin6_family = AF_INET6;
2065 				bcopy(natt_lhp->h_addr_list[0],
2066 				    &sin6->sin6_addr, sizeof (struct in6_addr));
2067 			} else {
2068 				/*
2069 				 * If the nat-local address is vague, don't
2070 				 * bother.
2071 				 */
2072 				totallen -= alloclen;
2073 				free(natt_local);
2074 				natt_local = NULL;
2075 				WARN1(ep, ebuf, gettext(
2076 				    "NAT-T local address %s "
2077 				    "is vague, not using.\n"),
2078 				    natt_lhp->h_name);
2079 				freehostent(natt_lhp);
2080 				natt_lhp = NULL;
2081 				break;
2082 			}
2083 			break;
2084 		case TOK_NATREM:
2085 			if (natt_remote != NULL) {
2086 				ERROR(ep, ebuf, gettext(
2087 				    "Can only specify "
2088 				    "single NAT-T remote address.\n"));
2089 				break;
2090 			}
2091 			sa_len = parseaddr(*argv, &natt_rhp, 0, ebuf);
2092 			if (natt_rhp == NULL) {
2093 				ERROR1(ep, ebuf, gettext(
2094 				    "Unknown NAT-T remote address \"%s\"\n"),
2095 				    *argv);
2096 				break;
2097 			}
2098 			argv++;
2099 			/*
2100 			 * Round of the sockaddr length to an 8 byte
2101 			 * boundary to make PF_KEY happy.
2102 			 */
2103 			alloclen = sizeof (*natt_remote) + roundup(sa_len, 8);
2104 			natt_remote = malloc(alloclen);
2105 			if (natt_remote == NULL)
2106 				Bail("malloc(natt_remote)");
2107 			totallen += alloclen;
2108 			natt_remote->sadb_address_len = SADB_8TO64(alloclen);
2109 			natt_remote->sadb_address_exttype =
2110 			    SADB_X_EXT_ADDRESS_NATT_REM;
2111 			natt_remote->sadb_address_reserved = 0;
2112 			natt_remote->sadb_address_prefixlen = 0;
2113 			natt_remote->sadb_address_proto = 0;
2114 			if (natt_rhp == &dummy.he ||
2115 			    natt_rhp->h_addr_list[1] == NULL) {
2116 				/*
2117 				 * Single address with -n flag or single name.
2118 				 */
2119 				sin6 = (struct sockaddr_in6 *)(natt_remote + 1);
2120 				bzero(sin6, sizeof (*sin6));
2121 				sin6->sin6_family = AF_INET6;
2122 				bcopy(natt_rhp->h_addr_list[0],
2123 				    &sin6->sin6_addr, sizeof (struct in6_addr));
2124 			} else {
2125 				/*
2126 				 * If the nat-renote address is vague, don't
2127 				 * bother.
2128 				 */
2129 				totallen -= alloclen;
2130 				free(natt_remote);
2131 				natt_remote = NULL;
2132 				WARN1(ep, ebuf, gettext(
2133 				    "NAT-T remote address %s "
2134 				    "is vague, not using.\n"),
2135 				    natt_rhp->h_name);
2136 				freehostent(natt_rhp);
2137 				natt_rhp = NULL;
2138 				break;
2139 			}
2140 			break;
2141 		case TOK_ENCRKEY:
2142 			if (encrypt != NULL) {
2143 				ERROR(ep, ebuf, gettext(
2144 				    "Can only specify "
2145 				    "single encryption key.\n"));
2146 				break;
2147 			}
2148 			if (assoc->sadb_sa_encrypt == SADB_EALG_NULL) {
2149 				FATAL(ep, ebuf, gettext(
2150 				    "Cannot specify a key with NULL "
2151 				    "encryption algorithm.\n"));
2152 				break;
2153 			}
2154 			encrypt = parsekey(*argv, ebuf);
2155 			argv++;
2156 			if (encrypt == NULL) {
2157 				ERROR(ep, ebuf, gettext(
2158 				    "Invalid encryption key.\n"));
2159 				break;
2160 			}
2161 			totallen += SADB_64TO8(encrypt->sadb_key_len);
2162 			encrypt->sadb_key_exttype = SADB_EXT_KEY_ENCRYPT;
2163 			break;
2164 		case TOK_AUTHKEY:
2165 			if (auth != NULL) {
2166 				ERROR(ep, ebuf, gettext(
2167 				    "Can only specify single"
2168 				    " authentication key.\n"));
2169 				break;
2170 			}
2171 			auth = parsekey(*argv, ebuf);
2172 			argv++;
2173 			if (auth == NULL) {
2174 				ERROR(ep, ebuf, gettext(
2175 				    "Invalid authentication key.\n"));
2176 				break;
2177 			}
2178 			totallen += SADB_64TO8(auth->sadb_key_len);
2179 			auth->sadb_key_exttype = SADB_EXT_KEY_AUTH;
2180 			break;
2181 		case TOK_SRCIDTYPE:
2182 			if (*argv == NULL || *(argv + 1) == NULL) {
2183 				FATAL(ep, ebuf, gettext(
2184 				    "Unexpected end of command "
2185 				    "line - Expecting Src Type.\n"));
2186 				/* NOTREACHED */
2187 				break;
2188 			}
2189 			if (srcid != NULL) {
2190 				ERROR(ep, ebuf, gettext(
2191 				    "Can only specify single"
2192 				    " source certificate identity.\n"));
2193 				break;
2194 			}
2195 			alloclen = sizeof (*srcid) +
2196 			    roundup(strlen(*(argv + 1)) + 1, 8);
2197 			srcid = malloc(alloclen);
2198 			if (srcid == NULL)
2199 				Bail("malloc(srcid)");
2200 			totallen += alloclen;
2201 			srcid->sadb_ident_type = parseidtype(*argv, ebuf);
2202 			argv++;
2203 			srcid->sadb_ident_len = SADB_8TO64(alloclen);
2204 			srcid->sadb_ident_exttype = SADB_EXT_IDENTITY_SRC;
2205 			srcid->sadb_ident_reserved = 0;
2206 			srcid->sadb_ident_id = 0;  /* Not useful here. */
2207 			(void) strlcpy((char *)(srcid + 1), *argv, alloclen);
2208 			argv++;
2209 			break;
2210 		case TOK_DSTIDTYPE:
2211 			if (*argv == NULL || *(argv + 1) == NULL) {
2212 				ERROR(ep, ebuf, gettext(
2213 				    "Unexpected end of command"
2214 				    " line - expecting dst type.\n"));
2215 				break;
2216 			}
2217 			if (dstid != NULL) {
2218 				ERROR(ep, ebuf, gettext(
2219 				    "Can only specify single destination "
2220 				    "certificate identity.\n"));
2221 				break;
2222 			}
2223 			alloclen = sizeof (*dstid) +
2224 			    roundup(strlen(*(argv + 1)) + 1, 8);
2225 			dstid = malloc(alloclen);
2226 			if (dstid == NULL)
2227 				Bail("malloc(dstid)");
2228 			totallen += alloclen;
2229 			dstid->sadb_ident_type = parseidtype(*argv, ebuf);
2230 			argv++;
2231 			dstid->sadb_ident_len = SADB_8TO64(alloclen);
2232 			dstid->sadb_ident_exttype = SADB_EXT_IDENTITY_DST;
2233 			dstid->sadb_ident_reserved = 0;
2234 			dstid->sadb_ident_id = 0;  /* Not useful here. */
2235 			(void) strlcpy((char *)(dstid + 1), *argv, alloclen);
2236 			argv++;
2237 			break;
2238 		case TOK_HARD_ALLOC:
2239 		case TOK_HARD_BYTES:
2240 		case TOK_HARD_ADDTIME:
2241 		case TOK_HARD_USETIME:
2242 			if (hard == NULL) {
2243 				hard = malloc(sizeof (*hard));
2244 				if (hard == NULL)
2245 					Bail("malloc(hard_lifetime)");
2246 				bzero(hard, sizeof (*hard));
2247 				hard->sadb_lifetime_exttype =
2248 				    SADB_EXT_LIFETIME_HARD;
2249 				hard->sadb_lifetime_len =
2250 				    SADB_8TO64(sizeof (*hard));
2251 				totallen += sizeof (*hard);
2252 			}
2253 			switch (token) {
2254 			case TOK_HARD_ALLOC:
2255 				if (hard->sadb_lifetime_allocations != 0) {
2256 					ERROR(ep, ebuf, gettext(
2257 					    "Can only specify single"
2258 					    " hard allocation limit.\n"));
2259 					break;
2260 				}
2261 				hard->sadb_lifetime_allocations =
2262 				    (uint32_t)parsenum(*argv, B_TRUE, ebuf);
2263 				break;
2264 			case TOK_HARD_BYTES:
2265 				if (hard->sadb_lifetime_bytes != 0) {
2266 					ERROR(ep, ebuf, gettext(
2267 					    "Can only specify "
2268 					    "single hard byte limit.\n"));
2269 					break;
2270 				}
2271 				hard->sadb_lifetime_bytes = parsenum(*argv,
2272 				    B_TRUE, ebuf);
2273 				break;
2274 			case TOK_HARD_ADDTIME:
2275 				if (hard->sadb_lifetime_addtime != 0) {
2276 					ERROR(ep, ebuf, gettext(
2277 					    "Can only specify "
2278 					    "single past-add lifetime.\n"));
2279 					break;
2280 				}
2281 				hard->sadb_lifetime_addtime = parsenum(*argv,
2282 				    B_TRUE, ebuf);
2283 				break;
2284 			case TOK_HARD_USETIME:
2285 				if (hard->sadb_lifetime_usetime != 0) {
2286 					ERROR(ep, ebuf, gettext(
2287 					    "Can only specify "
2288 					    "single past-use lifetime.\n"));
2289 					break;
2290 				}
2291 				hard->sadb_lifetime_usetime = parsenum(*argv,
2292 				    B_TRUE, ebuf);
2293 				break;
2294 			}
2295 			argv++;
2296 			break;
2297 		case TOK_SOFT_ALLOC:
2298 		case TOK_SOFT_BYTES:
2299 		case TOK_SOFT_ADDTIME:
2300 		case TOK_SOFT_USETIME:
2301 			if (soft == NULL) {
2302 				soft = malloc(sizeof (*soft));
2303 				if (soft == NULL)
2304 					Bail("malloc(soft_lifetime)");
2305 				bzero(soft, sizeof (*soft));
2306 				soft->sadb_lifetime_exttype =
2307 				    SADB_EXT_LIFETIME_SOFT;
2308 				soft->sadb_lifetime_len =
2309 				    SADB_8TO64(sizeof (*soft));
2310 				totallen += sizeof (*soft);
2311 			}
2312 			switch (token) {
2313 			case TOK_SOFT_ALLOC:
2314 				if (soft->sadb_lifetime_allocations != 0) {
2315 					ERROR(ep, ebuf, gettext(
2316 					    "Can only specify single"
2317 					    " soft allocation limit.\n"));
2318 					break;
2319 				}
2320 				soft->sadb_lifetime_allocations =
2321 				    (uint32_t)parsenum(*argv, B_TRUE, ebuf);
2322 				break;
2323 			case TOK_SOFT_BYTES:
2324 				if (soft->sadb_lifetime_bytes != 0) {
2325 					ERROR(ep, ebuf, gettext(
2326 					    "Can only specify single"
2327 					    " soft byte limit.\n"));
2328 					break;
2329 				}
2330 				soft->sadb_lifetime_bytes = parsenum(*argv,
2331 				    B_TRUE, ebuf);
2332 				break;
2333 			case TOK_SOFT_ADDTIME:
2334 				if (soft->sadb_lifetime_addtime != 0) {
2335 					ERROR(ep, ebuf, gettext(
2336 					    "Can only specify single"
2337 					    " past-add lifetime.\n"));
2338 					break;
2339 				}
2340 				soft->sadb_lifetime_addtime = parsenum(*argv,
2341 				    B_TRUE, ebuf);
2342 				break;
2343 			case TOK_SOFT_USETIME:
2344 				if (soft->sadb_lifetime_usetime != 0) {
2345 					ERROR(ep, ebuf, gettext(
2346 					    "Can only specify single"
2347 					    " past-use lifetime.\n"));
2348 					break;
2349 				}
2350 				soft->sadb_lifetime_usetime = parsenum(*argv,
2351 				    B_TRUE, ebuf);
2352 				break;
2353 			}
2354 			argv++;
2355 			break;
2356 		default:
2357 			ERROR1(ep, ebuf, gettext(
2358 			    "Don't use extension %s for add/update.\n"),
2359 			    *(argv - 1));
2360 			break;
2361 		}
2362 	} while (token != TOK_EOF);
2363 
2364 	handle_errors(ep, ebuf, B_TRUE, B_FALSE);
2365 
2366 #define	PORT_ONLY_ALLOCATE(af, socktype, exttype, extvar, port) {  \
2367 	alloclen = sizeof (sadb_address_t) + roundup(sizeof (socktype), 8); \
2368 	(extvar) = calloc(1, alloclen); \
2369 	if ((extvar) == NULL) { \
2370 		Bail("malloc(implicit port)"); \
2371 	} \
2372 	totallen += alloclen; \
2373 	(extvar)->sadb_address_len = SADB_8TO64(alloclen); \
2374 	(extvar)->sadb_address_exttype = (exttype); \
2375 	/* sin/sin6 has equivalent offsets for ports! */ \
2376 	sin6 = (struct sockaddr_in6 *)((extvar) + 1); \
2377 	sin6->sin6_family = (af); \
2378 	sin6->sin6_port = (port); \
2379 	}
2380 
2381 	/*
2382 	 * If we specify inner ports or NAT ports w/o addresses, we still need
2383 	 * to allocate.  Also, if we have one inner address, we need the
2384 	 * other, even if we don't specify anything.
2385 	 */
2386 	if (use_natt) {
2387 		if (natt_lport != 0 && natt_local == NULL) {
2388 			PORT_ONLY_ALLOCATE(AF_INET, struct sockaddr_in,
2389 			    SADB_X_EXT_ADDRESS_NATT_LOC, natt_local,
2390 			    natt_lport);
2391 		}
2392 
2393 		if (natt_rport != 0 && natt_remote == NULL) {
2394 			PORT_ONLY_ALLOCATE(AF_INET, struct sockaddr_in,
2395 			    SADB_X_EXT_ADDRESS_NATT_REM, natt_remote,
2396 			    natt_rport);
2397 		}
2398 	} else {
2399 		if (natt_lport != 0 || natt_rport != 0) {
2400 			ERROR(ep, ebuf, gettext("Must specify 'encap udp' "
2401 			    "with any NAT-T port.\n"));
2402 		} else if (natt_local != NULL || natt_remote != NULL) {
2403 			ERROR(ep, ebuf, gettext("Must specify 'encap udp' "
2404 			    "with any NAT-T address.\n"));
2405 		}
2406 	}
2407 
2408 	if (alloc_inner && idst == NULL) {
2409 		PORT_ONLY_ALLOCATE(AF_INET6, struct sockaddr_in6,
2410 		    SADB_X_EXT_ADDRESS_INNER_DST, idst, 0);
2411 	}
2412 
2413 	if (alloc_inner && isrc == NULL) {
2414 		PORT_ONLY_ALLOCATE(AF_INET6, struct sockaddr_in6,
2415 		    SADB_X_EXT_ADDRESS_INNER_SRC, isrc, 0);
2416 	}
2417 #undef PORT_ONLY_ALLOCATE
2418 
2419 	/*
2420 	 * Okay, so now I have all of the potential extensions!
2421 	 * Allocate a single contiguous buffer.  Keep in mind that it'll
2422 	 * be enough because the key itself will be yanked.
2423 	 */
2424 
2425 	if (src == NULL && dst != NULL) {
2426 		/*
2427 		 * Set explicit unspecified source address.
2428 		 */
2429 		size_t lenbytes = SADB_64TO8(dst->sadb_address_len);
2430 
2431 		unspec_src = B_TRUE;
2432 		totallen += lenbytes;
2433 		src = malloc(lenbytes);
2434 		if (src == NULL)
2435 			Bail("malloc(implicit src)");
2436 		/* Confusing, but we're copying from DST to SRC.  :) */
2437 		bcopy(dst, src, lenbytes);
2438 		src->sadb_address_exttype = SADB_EXT_ADDRESS_SRC;
2439 		sin6 = (struct sockaddr_in6 *)(src + 1);
2440 		bzero(sin6, sizeof (*sin6));
2441 		sin6->sin6_family = AF_INET6;
2442 	}
2443 
2444 	msg.sadb_msg_len = SADB_8TO64(totallen);
2445 
2446 	buffer = malloc(totallen);
2447 	nexthdr = buffer;
2448 	bcopy(&msg, nexthdr, sizeof (msg));
2449 	nexthdr += SADB_8TO64(sizeof (msg));
2450 	if (assoc != NULL) {
2451 		if (assoc->sadb_sa_spi == 0) {
2452 			ERROR1(ep, ebuf, gettext(
2453 			    "The SPI value is missing for "
2454 			    "the association you wish to %s.\n"), thiscmd);
2455 		}
2456 		if (assoc->sadb_sa_auth == 0 && assoc->sadb_sa_encrypt == 0 &&
2457 		    cmd == CMD_ADD) {
2458 			free(assoc);
2459 			FATAL(ep, ebuf, gettext(
2460 			    "Select at least one algorithm "
2461 			    "for this add.\n"));
2462 		}
2463 
2464 		/* Hack to let user specify NULL ESP implicitly. */
2465 		if (msg.sadb_msg_satype == SADB_SATYPE_ESP &&
2466 		    assoc->sadb_sa_encrypt == 0)
2467 			assoc->sadb_sa_encrypt = SADB_EALG_NULL;
2468 
2469 		/* 0 is an actual value.  Print a warning if it was entered. */
2470 		if (assoc->sadb_sa_state == 0) {
2471 			if (readstate) {
2472 				ERROR(ep, ebuf, gettext(
2473 				    "WARNING: Cannot set LARVAL SA state.\n"));
2474 			}
2475 			assoc->sadb_sa_state = SADB_SASTATE_MATURE;
2476 		}
2477 
2478 		if (use_natt) {
2479 			if (natt_remote != NULL)
2480 				assoc->sadb_sa_flags |= SADB_X_SAFLAGS_NATT_REM;
2481 			if (natt_local != NULL)
2482 				assoc->sadb_sa_flags |= SADB_X_SAFLAGS_NATT_LOC;
2483 		}
2484 
2485 		if (alloc_inner) {
2486 			/*
2487 			 * For now, assume RFC 3884's dream of transport-mode
2488 			 * SAs with inner IP address selectors will not
2489 			 * happen.
2490 			 */
2491 			assoc->sadb_sa_flags |= SADB_X_SAFLAGS_TUNNEL;
2492 			if (proto != 0 && proto != IPPROTO_ENCAP &&
2493 			    proto != IPPROTO_IPV6) {
2494 				ERROR1(ep, ebuf, gettext(
2495 				    "WARNING: Protocol type %d not "
2496 				    "for use with Tunnel-Mode SA.\n"), proto);
2497 				/* Continue and let PF_KEY scream... */
2498 			}
2499 		}
2500 
2501 		bcopy(assoc, nexthdr, SADB_64TO8(assoc->sadb_sa_len));
2502 		nexthdr += assoc->sadb_sa_len;
2503 		/* Save the SPI for the case of an error. */
2504 		spi = assoc->sadb_sa_spi;
2505 		free(assoc);
2506 	} else {
2507 		ERROR1(ep, ebuf, gettext(
2508 		    "Need SA parameters for %s.\n"), thiscmd);
2509 	}
2510 
2511 	if (hard != NULL) {
2512 		bcopy(hard, nexthdr, SADB_64TO8(hard->sadb_lifetime_len));
2513 		nexthdr += hard->sadb_lifetime_len;
2514 		free(hard);
2515 	}
2516 
2517 	if (soft != NULL) {
2518 		bcopy(soft, nexthdr, SADB_64TO8(soft->sadb_lifetime_len));
2519 		nexthdr += soft->sadb_lifetime_len;
2520 		free(soft);
2521 	}
2522 
2523 	if (encrypt == NULL && auth == NULL && cmd == CMD_ADD) {
2524 		ERROR(ep, ebuf, gettext(
2525 		    "Must have at least one key for an add.\n"));
2526 	}
2527 
2528 	if (encrypt != NULL) {
2529 		bcopy(encrypt, nexthdr, SADB_64TO8(encrypt->sadb_key_len));
2530 		nexthdr += encrypt->sadb_key_len;
2531 		bzero(encrypt, SADB_64TO8(encrypt->sadb_key_len));
2532 		free(encrypt);
2533 	}
2534 
2535 	if (auth != NULL) {
2536 		bcopy(auth, nexthdr, SADB_64TO8(auth->sadb_key_len));
2537 		nexthdr += auth->sadb_key_len;
2538 		bzero(auth, SADB_64TO8(auth->sadb_key_len));
2539 		free(auth);
2540 	}
2541 
2542 	if (srcid != NULL) {
2543 		bcopy(srcid, nexthdr, SADB_64TO8(srcid->sadb_ident_len));
2544 		nexthdr += srcid->sadb_ident_len;
2545 		free(srcid);
2546 	}
2547 
2548 	if (dstid != NULL) {
2549 		bcopy(dstid, nexthdr, SADB_64TO8(dstid->sadb_ident_len));
2550 		nexthdr += dstid->sadb_ident_len;
2551 		free(dstid);
2552 	}
2553 
2554 	if (dst != NULL) {
2555 		bcopy(dst, nexthdr, SADB_64TO8(dst->sadb_address_len));
2556 		free(dst);
2557 		dst = (struct sadb_address *)nexthdr;
2558 		dst->sadb_address_proto = proto;
2559 		((struct sockaddr_in6 *)(dst + 1))->sin6_port = htons(dstport);
2560 		nexthdr += dst->sadb_address_len;
2561 	} else {
2562 		FATAL1(ep, ebuf, gettext(
2563 		    "Need destination address for %s.\n"), thiscmd);
2564 	}
2565 
2566 	if (use_natt) {
2567 		if (natt_remote == NULL && natt_local == NULL) {
2568 			ERROR(ep, ebuf, gettext(
2569 			    "Must specify NAT-T remote or local address "
2570 			    "for UDP encapsulation.\n"));
2571 		}
2572 
2573 		if (natt_remote != NULL) {
2574 			bcopy(natt_remote, nexthdr,
2575 			    SADB_64TO8(natt_remote->sadb_address_len));
2576 			free(natt_remote);
2577 			natt_remote = (struct sadb_address *)nexthdr;
2578 			nexthdr += natt_remote->sadb_address_len;
2579 			((struct sockaddr_in6 *)(natt_remote + 1))->sin6_port =
2580 			    htons(natt_rport);
2581 		}
2582 
2583 		if (natt_local != NULL) {
2584 			bcopy(natt_local, nexthdr,
2585 			    SADB_64TO8(natt_local->sadb_address_len));
2586 			free(natt_local);
2587 			natt_local = (struct sadb_address *)nexthdr;
2588 			nexthdr += natt_local->sadb_address_len;
2589 			((struct sockaddr_in6 *)(natt_local + 1))->sin6_port =
2590 			    htons(natt_lport);
2591 		}
2592 	}
2593 
2594 	handle_errors(ep, ebuf, B_TRUE, B_FALSE);
2595 
2596 	/*
2597 	 * PF_KEY requires a source address extension, even if the source
2598 	 * address itself is unspecified. (See "Set explicit unspecified..."
2599 	 * code fragment above. Destination reality check was above.)
2600 	 */
2601 	bcopy(src, nexthdr, SADB_64TO8(src->sadb_address_len));
2602 	free(src);
2603 	src = (struct sadb_address *)nexthdr;
2604 	src->sadb_address_proto = proto;
2605 	((struct sockaddr_in6 *)(src + 1))->sin6_port = htons(srcport);
2606 	nexthdr += src->sadb_address_len;
2607 
2608 	if (isrc != NULL) {
2609 		bcopy(isrc, nexthdr, SADB_64TO8(isrc->sadb_address_len));
2610 		free(isrc);
2611 		isrc = (struct sadb_address *)nexthdr;
2612 		isrc->sadb_address_proto = iproto;
2613 		((struct sockaddr_in6 *)(isrc + 1))->sin6_port =
2614 		    htons(isrcport);
2615 		nexthdr += isrc->sadb_address_len;
2616 	}
2617 
2618 	if (idst != NULL) {
2619 		bcopy(idst, nexthdr, SADB_64TO8(idst->sadb_address_len));
2620 		free(idst);
2621 		idst = (struct sadb_address *)nexthdr;
2622 		idst->sadb_address_proto = iproto;
2623 		((struct sockaddr_in6 *)(idst + 1))->sin6_port =
2624 		    htons(idstport);
2625 		nexthdr += idst->sadb_address_len;
2626 	}
2627 
2628 	if (cflag) {
2629 		/*
2630 		 * Assume the checked cmd would have worked if it was actually
2631 		 * used. doaddresses() will increment lines_added if it
2632 		 * succeeds.
2633 		 */
2634 		lines_added++;
2635 	} else {
2636 		doaddresses((cmd == CMD_ADD) ? SADB_ADD : SADB_UPDATE, satype,
2637 		    cmd, srchp, dsthp, src, dst, unspec_src, buffer, totallen,
2638 		    spi, ebuf);
2639 	}
2640 
2641 	if (isrchp != NULL && isrchp != &dummy.he)
2642 		freehostent(isrchp);
2643 	if (idsthp != NULL && idsthp != &dummy.he)
2644 		freehostent(idsthp);
2645 	if (srchp != NULL && srchp != &dummy.he)
2646 		freehostent(srchp);
2647 	if (dsthp != NULL && dsthp != &dummy.he)
2648 		freehostent(dsthp);
2649 	if (natt_lhp != NULL && natt_lhp != &dummy.he)
2650 		freehostent(natt_lhp);
2651 	if (natt_rhp != NULL && natt_rhp != &dummy.he)
2652 		freehostent(natt_rhp);
2653 
2654 	free(ebuf);
2655 	free(buffer);
2656 }
2657 
2658 /*
2659  * DELETE and GET are similar, in that they only need the extensions
2660  * required to _find_ an SA, and then either delete it or obtain its
2661  * information.
2662  */
2663 static void
2664 dodelget(int cmd, int satype, char *argv[], char *ebuf)
2665 {
2666 	struct sadb_msg *msg = (struct sadb_msg *)get_buffer;
2667 	uint64_t *nextext;
2668 	struct sadb_sa *assoc = NULL;
2669 	struct sadb_address *src = NULL, *dst = NULL;
2670 	int next, token, sa_len;
2671 	char *thiscmd;
2672 	uint32_t spi;
2673 	struct hostent *srchp = NULL, *dsthp = NULL;
2674 	struct sockaddr_in6 *sin6;
2675 	boolean_t unspec_src = B_TRUE;
2676 	uint16_t srcport = 0, dstport = 0;
2677 	uint8_t proto = 0;
2678 	char *ep = NULL;
2679 
2680 	msg_init(msg, ((cmd == CMD_GET) ? SADB_GET : SADB_DELETE),
2681 	    (uint8_t)satype);
2682 	/* Set the first extension header to right past the base message. */
2683 	nextext = (uint64_t *)(msg + 1);
2684 	bzero(nextext, sizeof (get_buffer) - sizeof (*msg));
2685 
2686 	thiscmd = (cmd == CMD_GET) ? "get" : "delete";
2687 
2688 #define	ALLOC_ADDR_EXT(ext, exttype)			\
2689 	(ext) = (struct sadb_address *)nextext;		\
2690 	nextext = (uint64_t *)((ext) + 1);		\
2691 	nextext += SADB_8TO64(roundup(sa_len, 8));	\
2692 	(ext)->sadb_address_exttype = exttype;		\
2693 	(ext)->sadb_address_len = nextext - ((uint64_t *)ext);
2694 
2695 	/* Assume last element in argv is set to NULL. */
2696 	do {
2697 		token = parseextval(*argv, &next);
2698 		argv++;
2699 		switch (token) {
2700 		case TOK_EOF:
2701 			/* Do nothing, I'm done. */
2702 			break;
2703 		case TOK_UNKNOWN:
2704 			ERROR1(ep, ebuf, gettext(
2705 			    "Unknown extension field \"%s\"\n"), *(argv - 1));
2706 			break;
2707 		case TOK_SPI:
2708 			if (assoc != NULL) {
2709 				ERROR(ep, ebuf, gettext(
2710 				    "Can only specify single SPI value.\n"));
2711 				break;
2712 			}
2713 			assoc = (struct sadb_sa *)nextext;
2714 			nextext = (uint64_t *)(assoc + 1);
2715 			assoc->sadb_sa_len = SADB_8TO64(sizeof (*assoc));
2716 			assoc->sadb_sa_exttype = SADB_EXT_SA;
2717 			assoc->sadb_sa_spi = htonl((uint32_t)parsenum(*argv,
2718 			    B_TRUE, ebuf));
2719 			spi = assoc->sadb_sa_spi;
2720 			argv++;
2721 			break;
2722 		case TOK_SRCPORT:
2723 			if (srcport != 0) {
2724 				ERROR(ep, ebuf, gettext(
2725 				    "Can only specify single source port.\n"));
2726 				break;
2727 			}
2728 			srcport = parsenum(*argv, B_TRUE, ebuf);
2729 			argv++;
2730 			break;
2731 		case TOK_DSTPORT:
2732 			if (dstport != 0) {
2733 				ERROR(ep, ebuf, gettext(
2734 				    "Can only "
2735 				    "specify single destination port.\n"));
2736 				break;
2737 			}
2738 			dstport = parsenum(*argv, B_TRUE, ebuf);
2739 			argv++;
2740 			break;
2741 		case TOK_PROTO:
2742 			if (proto != 0) {
2743 				ERROR(ep, ebuf, gettext(
2744 				    "Can only specify single protocol.\n"));
2745 				break;
2746 			}
2747 			proto = parsenum(*argv, B_TRUE, ebuf);
2748 			argv++;
2749 			break;
2750 		case TOK_SRCADDR:
2751 		case TOK_SRCADDR6:
2752 			if (src != NULL) {
2753 				ERROR(ep, ebuf, gettext(
2754 				    "Can only specify single source addr.\n"));
2755 				break;
2756 			}
2757 			sa_len = parseaddr(*argv, &srchp,
2758 			    (token == TOK_SRCADDR6), ebuf);
2759 			if (srchp == NULL) {
2760 				ERROR1(ep, ebuf, gettext(
2761 				    "Unknown source address \"%s\"\n"), *argv);
2762 				break;
2763 			}
2764 			argv++;
2765 
2766 			unspec_src = B_FALSE;
2767 
2768 			ALLOC_ADDR_EXT(src, SADB_EXT_ADDRESS_SRC);
2769 
2770 			if (srchp == &dummy.he) {
2771 				/*
2772 				 * Single address with -n flag.
2773 				 */
2774 				sin6 = (struct sockaddr_in6 *)(src + 1);
2775 				bzero(sin6, sizeof (*sin6));
2776 				sin6->sin6_family = AF_INET6;
2777 				bcopy(srchp->h_addr_list[0], &sin6->sin6_addr,
2778 				    sizeof (struct in6_addr));
2779 			}
2780 			/* The rest is pre-bzeroed for us. */
2781 			break;
2782 		case TOK_DSTADDR:
2783 		case TOK_DSTADDR6:
2784 			if (dst != NULL) {
2785 				ERROR(ep, ebuf, gettext(
2786 				    "Can only specify single destination "
2787 				    "address.\n"));
2788 				break;
2789 			}
2790 			sa_len = parseaddr(*argv, &dsthp,
2791 			    (token == TOK_SRCADDR6), ebuf);
2792 			if (dsthp == NULL) {
2793 				ERROR1(ep, ebuf, gettext(
2794 				    "Unknown destination address \"%s\"\n"),
2795 				    *argv);
2796 				break;
2797 			}
2798 			argv++;
2799 
2800 			ALLOC_ADDR_EXT(dst, SADB_EXT_ADDRESS_DST);
2801 
2802 			if (dsthp == &dummy.he) {
2803 				/*
2804 				 * Single address with -n flag.
2805 				 */
2806 				sin6 = (struct sockaddr_in6 *)(dst + 1);
2807 				bzero(sin6, sizeof (*sin6));
2808 				sin6->sin6_family = AF_INET6;
2809 				bcopy(dsthp->h_addr_list[0], &sin6->sin6_addr,
2810 				    sizeof (struct in6_addr));
2811 			}
2812 			/* The rest is pre-bzeroed for us. */
2813 			break;
2814 		default:
2815 			ERROR2(ep, ebuf, gettext(
2816 			    "Don't use extension %s for '%s' command.\n"),
2817 			    *(argv - 1), thiscmd);
2818 			break;
2819 		}
2820 	} while (token != TOK_EOF);
2821 
2822 	handle_errors(ep, ebuf, B_TRUE, B_FALSE);
2823 
2824 	if ((srcport != 0) && (src == NULL)) {
2825 		ALLOC_ADDR_EXT(src, SADB_EXT_ADDRESS_SRC);
2826 		sin6 = (struct sockaddr_in6 *)(src + 1);
2827 		src->sadb_address_proto = proto;
2828 		bzero(sin6, sizeof (*sin6));
2829 		sin6->sin6_family = AF_INET6;
2830 		sin6->sin6_port = htons(srcport);
2831 	}
2832 
2833 	if ((dstport != 0) && (dst == NULL)) {
2834 		ALLOC_ADDR_EXT(dst, SADB_EXT_ADDRESS_DST);
2835 		sin6 = (struct sockaddr_in6 *)(dst + 1);
2836 		src->sadb_address_proto = proto;
2837 		bzero(sin6, sizeof (*sin6));
2838 		sin6->sin6_family = AF_INET6;
2839 		sin6->sin6_port = htons(dstport);
2840 	}
2841 
2842 	/* So I have enough of the message to send it down! */
2843 	msg->sadb_msg_len = nextext - get_buffer;
2844 
2845 	if (assoc == NULL) {
2846 		FATAL1(ep, ebuf, gettext(
2847 		    "Need SA parameters for %s.\n"), thiscmd);
2848 	}
2849 
2850 	if (cflag) {
2851 		/*
2852 		 * Assume the checked cmd would have worked if it was actually
2853 		 * used. doaddresses() will increment lines_added if it
2854 		 * succeeds.
2855 		 */
2856 		lines_added++;
2857 	} else {
2858 		doaddresses((cmd == CMD_GET) ? SADB_GET : SADB_DELETE, satype,
2859 		    cmd, srchp, dsthp, src, dst, unspec_src, get_buffer,
2860 		    sizeof (get_buffer), spi, NULL);
2861 	}
2862 
2863 	if (srchp != NULL && srchp != &dummy.he)
2864 		freehostent(srchp);
2865 	if (dsthp != NULL && dsthp != &dummy.he)
2866 		freehostent(dsthp);
2867 }
2868 
2869 /*
2870  * "ipseckey monitor" should exit very gracefully if ^C is tapped.
2871  */
2872 static void
2873 monitor_catch(int signal)
2874 {
2875 	errx(signal, gettext("Bailing on signal %d."), signal);
2876 }
2877 
2878 /*
2879  * Loop forever, listening on PF_KEY messages.
2880  */
2881 static void
2882 domonitor(boolean_t passive)
2883 {
2884 	struct sadb_msg *samsg;
2885 	int rc;
2886 
2887 	/* Catch ^C. */
2888 	(void) signal(SIGINT, monitor_catch);
2889 
2890 	samsg = (struct sadb_msg *)get_buffer;
2891 	if (!passive) {
2892 		(void) printf(gettext("Actively"));
2893 		msg_init(samsg, SADB_X_PROMISC, 1);	/* Turn ON promisc. */
2894 		rc = key_write(keysock, samsg, sizeof (*samsg));
2895 		if (rc == -1)
2896 			Bail("write (SADB_X_PROMISC)");
2897 	} else {
2898 		(void) printf(gettext("Passively"));
2899 	}
2900 	(void) printf(gettext(" monitoring the PF_KEY socket.\n"));
2901 
2902 	for (; ; ) {
2903 		/*
2904 		 * I assume that read() is non-blocking, and will never
2905 		 * return 0.
2906 		 */
2907 		rc = read(keysock, samsg, sizeof (get_buffer));
2908 		if (rc == -1)
2909 			Bail("read (in domonitor)");
2910 		(void) printf(gettext("Read %d bytes.\n"), rc);
2911 		/*
2912 		 * Q:  Should I use the same method of printing as GET does?
2913 		 * A:  For now, yes.
2914 		 */
2915 		print_samsg(stdout, get_buffer, B_TRUE, vflag, nflag);
2916 		(void) putchar('\n');
2917 	}
2918 }
2919 
2920 /*
2921  * Either mask or unmask all relevant signals.
2922  */
2923 static void
2924 mask_signals(boolean_t unmask)
2925 {
2926 	sigset_t set;
2927 	static sigset_t oset;
2928 
2929 	if (unmask) {
2930 		(void) sigprocmask(SIG_SETMASK, &oset, NULL);
2931 	} else {
2932 		(void) sigfillset(&set);
2933 		(void) sigprocmask(SIG_SETMASK, &set, &oset);
2934 	}
2935 }
2936 
2937 /*
2938  * Assorted functions to print help text.
2939  */
2940 #define	puts_tr(s) (void) puts(gettext(s))
2941 
2942 static void
2943 doattrhelp()
2944 {
2945 	int i;
2946 
2947 	puts_tr("\nSA attributes:");
2948 
2949 	for (i = 0; tokens[i].string != NULL; i++) {
2950 		if (i%3 == 0)
2951 			(void) printf("\n");
2952 		(void) printf("    %-15.15s", tokens[i].string);
2953 	}
2954 	(void) printf("\n");
2955 }
2956 
2957 static void
2958 dohelpcmd(char *cmds)
2959 {
2960 	int cmd;
2961 
2962 	if (strcmp(cmds, "attr") == 0) {
2963 		doattrhelp();
2964 		return;
2965 	}
2966 
2967 	cmd = parsecmd(cmds);
2968 	switch (cmd) {
2969 	case CMD_UPDATE:
2970 		puts_tr("update	 - Update an existing SA");
2971 		break;
2972 	case CMD_ADD:
2973 		puts_tr("add	 - Add a new security association (SA)");
2974 		break;
2975 	case CMD_DELETE:
2976 		puts_tr("delete - Delete an SA");
2977 		break;
2978 	case CMD_GET:
2979 		puts_tr("get - Display an SA");
2980 		break;
2981 	case CMD_FLUSH:
2982 		puts_tr("flush - Delete all SAs");
2983 		break;
2984 	case CMD_DUMP:
2985 		puts_tr("dump - Display all SAs");
2986 		break;
2987 	case CMD_MONITOR:
2988 		puts_tr("monitor - Monitor all PF_KEY reply messages.");
2989 		break;
2990 	case CMD_PMONITOR:
2991 		puts_tr(
2992 "pmonitor, passive_monitor - Monitor PF_KEY messages that");
2993 		puts_tr(
2994 "                            reply to all PF_KEY sockets.");
2995 		break;
2996 
2997 	case CMD_QUIT:
2998 		puts_tr("quit, exit - Exit the program");
2999 		break;
3000 	case CMD_SAVE:
3001 		puts_tr("save	    - Saves all SAs to a file");
3002 		break;
3003 	case CMD_HELP:
3004 		puts_tr("help	    - Display list of commands");
3005 		puts_tr("help <cmd> - Display help for command");
3006 		puts_tr("help attr  - Display possible SA attributes");
3007 		break;
3008 	default:
3009 		(void) printf(gettext("%s: Unknown command\n"), cmds);
3010 		break;
3011 	}
3012 }
3013 
3014 
3015 static void
3016 dohelp(char *cmds)
3017 {
3018 	if (cmds != NULL) {
3019 		dohelpcmd(cmds);
3020 		return;
3021 	}
3022 	puts_tr("Commands");
3023 	puts_tr("--------");
3024 	puts_tr("?, help  - Display this list");
3025 	puts_tr("help <cmd> - Display help for command");
3026 	puts_tr("help attr  - Display possible SA attributes");
3027 	puts_tr("quit, exit - Exit the program");
3028 	puts_tr("monitor - Monitor all PF_KEY reply messages.");
3029 	puts_tr("pmonitor, passive_monitor - Monitor PF_KEY messages that");
3030 	puts_tr("                            reply to all PF_KEY sockets.");
3031 	puts_tr("");
3032 	puts_tr("The following commands are of the form:");
3033 	puts_tr("    <command> {SA type} {attribute value}*");
3034 	puts_tr("");
3035 	puts_tr("add (interactive only) - Add a new security association (SA)");
3036 	puts_tr("update (interactive only) - Update an existing SA");
3037 	puts_tr("delete - Delete an SA");
3038 	puts_tr("get - Display an SA");
3039 	puts_tr("flush - Delete all SAs");
3040 	puts_tr("dump - Display all SAs");
3041 	puts_tr("save - Saves all SAs to a file");
3042 }
3043 
3044 /*
3045  * "Parse" a command line from argv.
3046  */
3047 static void
3048 parseit(int argc, char *argv[], char *ebuf, boolean_t read_cmdfile)
3049 {
3050 	int cmd, satype;
3051 	char *ep = NULL;
3052 
3053 	if (argc == 0)
3054 		return;
3055 	cmd = parsecmd(*argv++);
3056 
3057 	/*
3058 	 * Some commands loop forever and should only be run from the command
3059 	 * line, they should never be run from a command file as this may
3060 	 * be used at boot time.
3061 	 */
3062 	switch (cmd) {
3063 	case CMD_HELP:
3064 		if (read_cmdfile)
3065 			ERROR(ep, ebuf, gettext("Help not appropriate in "
3066 			    "config file."));
3067 		else
3068 			dohelp(*argv);
3069 		return;
3070 	case CMD_MONITOR:
3071 		if (read_cmdfile)
3072 			ERROR(ep, ebuf, gettext("Monitor not appropriate in "
3073 			    "config file."));
3074 		else
3075 			domonitor(B_FALSE);
3076 		break;
3077 	case CMD_PMONITOR:
3078 		if (read_cmdfile)
3079 			ERROR(ep, ebuf, gettext("Monitor not appropriate in "
3080 			    "config file."));
3081 		else
3082 			domonitor(B_TRUE);
3083 		break;
3084 	case CMD_QUIT:
3085 		EXIT_OK(NULL);
3086 	}
3087 
3088 	handle_errors(ep, ebuf, B_FALSE, B_FALSE);
3089 
3090 	satype = parsesatype(*argv, ebuf);
3091 
3092 	if (satype != SADB_SATYPE_UNSPEC) {
3093 		argv++;
3094 	} else {
3095 		/*
3096 		 * You must specify either "all" or a specific SA type
3097 		 * for the "save" command.
3098 		 */
3099 		if (cmd == CMD_SAVE)
3100 			if (*argv == NULL) {
3101 				FATAL(ep, ebuf, gettext(
3102 				    "Must specify a specific "
3103 				    "SA type for save.\n"));
3104 			} else {
3105 				argv++;
3106 			}
3107 	}
3108 
3109 	switch (cmd) {
3110 	case CMD_FLUSH:
3111 		if (!cflag)
3112 			doflush(satype);
3113 		/*
3114 		 * If this was called because of an entry in a cmd file
3115 		 * then this action needs to be counted to prevent
3116 		 * do_interactive() treating this as an error.
3117 		 */
3118 		lines_added++;
3119 		break;
3120 	case CMD_ADD:
3121 	case CMD_UPDATE:
3122 		/*
3123 		 * NOTE: Shouldn't allow ADDs or UPDATEs with keying material
3124 		 * from the command line.
3125 		 */
3126 		if (!interactive) {
3127 			errx(1, gettext(
3128 			    "can't do ADD or UPDATE from the command line.\n"));
3129 		}
3130 		if (satype == SADB_SATYPE_UNSPEC) {
3131 			FATAL(ep, ebuf, gettext(
3132 			    "Must specify a specific SA type."));
3133 			/* NOTREACHED */
3134 		}
3135 		/* Parse for extensions, including keying material. */
3136 		doaddup(cmd, satype, argv, ebuf);
3137 		break;
3138 	case CMD_DELETE:
3139 	case CMD_GET:
3140 		if (satype == SADB_SATYPE_UNSPEC) {
3141 			FATAL(ep, ebuf, gettext(
3142 			    "Must specify a single SA type."));
3143 			/* NOTREACHED */
3144 		}
3145 		/* Parse for bare minimum to locate an SA. */
3146 		dodelget(cmd, satype, argv, ebuf);
3147 		break;
3148 	case CMD_DUMP:
3149 		if (read_cmdfile)
3150 			ERROR(ep, ebuf, gettext("Dump not appropriate in "
3151 			    "config file."));
3152 		else
3153 			dodump(satype, NULL);
3154 		break;
3155 	case CMD_SAVE:
3156 		if (read_cmdfile) {
3157 			ERROR(ep, ebuf, gettext("Save not appropriate in "
3158 			    "config file."));
3159 		} else {
3160 			mask_signals(B_FALSE);	/* Mask signals */
3161 			dodump(satype, opensavefile(argv[0]));
3162 			mask_signals(B_TRUE);	/* Unmask signals */
3163 		}
3164 		break;
3165 	default:
3166 		warnx(gettext("Unknown command (%s).\n"),
3167 		    *(argv - ((satype == SADB_SATYPE_UNSPEC) ? 1 : 2)));
3168 		usage();
3169 	}
3170 	handle_errors(ep, ebuf, B_FALSE, B_FALSE);
3171 }
3172 
3173 int
3174 main(int argc, char *argv[])
3175 {
3176 	int ch;
3177 	FILE *infile = stdin, *savefile;
3178 	boolean_t dosave = B_FALSE, readfile = B_FALSE;
3179 	char *configfile = NULL;
3180 	struct stat sbuf;
3181 
3182 	(void) setlocale(LC_ALL, "");
3183 #if !defined(TEXT_DOMAIN)
3184 #define	TEXT_DOMAIN "SYS_TEST"
3185 #endif
3186 	(void) textdomain(TEXT_DOMAIN);
3187 
3188 	/*
3189 	 * Check to see if the command is being run from smf(5).
3190 	 */
3191 	my_fmri = getenv("SMF_FMRI");
3192 
3193 	openlog("ipseckey", LOG_CONS, LOG_AUTH);
3194 	if (getuid() != 0) {
3195 		errx(1, "Insufficient privileges to run ipseckey.");
3196 	}
3197 
3198 	/* umask me to paranoid, I only want to create files read-only */
3199 	(void) umask((mode_t)00377);
3200 
3201 	while ((ch = getopt(argc, argv, "pnvf:s:c:")) != EOF)
3202 		switch (ch) {
3203 		case 'p':
3204 			pflag = B_TRUE;
3205 			break;
3206 		case 'n':
3207 			nflag = B_TRUE;
3208 			break;
3209 		case 'v':
3210 			vflag = B_TRUE;
3211 			break;
3212 		case 'c':
3213 			cflag = B_TRUE;
3214 			/* FALLTHRU */
3215 		case 'f':
3216 			if (dosave)
3217 				usage();
3218 			infile = fopen(optarg, "r");
3219 			if (infile == NULL) {
3220 				EXIT_BADCONFIG2("Unable to open configuration "
3221 				    "file: %s\n", optarg);
3222 			}
3223 			/*
3224 			 * Check file permissions/ownership and warn or
3225 			 * fail depending on state of SMF control.
3226 			 */
3227 			if (fstat(fileno(infile), &sbuf) == -1) {
3228 				(void) fclose(infile);
3229 				EXIT_BADCONFIG2("Unable to stat configuration "
3230 				    "file: %s\n", optarg);
3231 			}
3232 			if (INSECURE_PERMS(sbuf)) {
3233 				if (my_fmri != NULL) {
3234 					(void) fclose(infile);
3235 					EXIT_BADCONFIG2("Config file "
3236 					    "%s has insecure permissions.",
3237 					    optarg);
3238 				} else 	{
3239 					(void) fprintf(stderr, "%s %s\n",
3240 					    optarg, gettext(
3241 					    "has insecure permissions, will be "
3242 					    "rejected in permanent config."));
3243 				}
3244 			}
3245 			configfile = strdup(optarg);
3246 			readfile = B_TRUE;
3247 			break;
3248 		case 's':
3249 			if (readfile)
3250 				usage();
3251 			dosave = B_TRUE;
3252 			savefile = opensavefile(optarg);
3253 			break;
3254 		default:
3255 			usage();
3256 		}
3257 
3258 	argc -= optind;
3259 	argv += optind;
3260 
3261 	mypid = getpid();
3262 
3263 	keysock = socket(PF_KEY, SOCK_RAW, PF_KEY_V2);
3264 
3265 	if (keysock == -1) {
3266 		if (errno == EPERM) {
3267 			EXIT_BADPERM("Insufficient privileges to open "
3268 			    "PF_KEY socket.\n");
3269 		} else {
3270 			/* some other reason */
3271 			EXIT_FATAL("Opening PF_KEY socket");
3272 		}
3273 	}
3274 
3275 	if (dosave) {
3276 		mask_signals(B_FALSE);	/* Mask signals */
3277 		dodump(SADB_SATYPE_UNSPEC, savefile);
3278 		mask_signals(B_TRUE);	/* Unmask signals */
3279 		EXIT_OK(NULL);
3280 	}
3281 
3282 	/*
3283 	 * When run from smf(5) flush any existing SA's first
3284 	 * otherwise you will end up in maintenance mode.
3285 	 */
3286 	if ((my_fmri != NULL) && readfile) {
3287 		(void) fprintf(stdout, gettext(
3288 		    "Flushing existing SA's before adding new SA's\n"));
3289 		(void) fflush(stdout);
3290 		doflush(SADB_SATYPE_UNSPEC);
3291 	}
3292 	if (infile != stdin || *argv == NULL) {
3293 		/* Go into interactive mode here. */
3294 		do_interactive(infile, configfile, "ipseckey> ", my_fmri,
3295 		    parseit);
3296 	}
3297 	parseit(argc, argv, NULL, B_FALSE);
3298 
3299 	return (0);
3300 }
3301