xref: /openbsd/sbin/isakmpd/pf_key_v2.c (revision 76d0caae)
1 /* $OpenBSD: pf_key_v2.c,v 1.202 2021/10/22 12:30:54 bluhm Exp $  */
2 /* $EOM: pf_key_v2.c,v 1.79 2000/12/12 00:33:19 niklas Exp $	 */
3 
4 /*
5  * Copyright (c) 1999, 2000, 2001 Niklas Hallqvist.  All rights reserved.
6  * Copyright (c) 1999, 2000, 2001 Angelos D. Keromytis.  All rights reserved.
7  * Copyright (c) 2001 H�kan Olsson.  All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
19  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
20  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
21  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
22  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
23  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
27  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28  */
29 
30 /*
31  * This code was written under funding by Ericsson Radio Systems.
32  */
33 
34 #include <sys/types.h>
35 #include <sys/ioctl.h>
36 #include <sys/queue.h>
37 #include <sys/socket.h>
38 #include <sys/uio.h>
39 
40 #include <net/pfkeyv2.h>
41 #include <netinet/in.h>
42 #include <netinet/ip_ipsp.h>
43 #include <arpa/inet.h>
44 #include <stdlib.h>
45 #include <poll.h>
46 #include <string.h>
47 #include <unistd.h>
48 #include <pwd.h>
49 #include <errno.h>
50 #include <bitstring.h>
51 
52 #include "cert.h"
53 #include "conf.h"
54 #include "connection.h"
55 #include "exchange.h"
56 #include "ipsec.h"
57 #include "ipsec_num.h"
58 #include "key.h"
59 #include "log.h"
60 #include "pf_key_v2.h"
61 #include "sa.h"
62 #include "timer.h"
63 #include "transport.h"
64 #include "ui.h"
65 #include "util.h"
66 
67 #include "policy.h"
68 
69 #include "udp_encap.h"
70 
71 #define IN6_IS_ADDR_FULL(a)						\
72 	((*(u_int32_t *)(void *)(&(a)->s6_addr[0]) == 0xffffffff) &&	\
73 	(*(u_int32_t *)(void *)(&(a)->s6_addr[4]) == 0xffffffff) &&	\
74 	(*(u_int32_t *)(void *)(&(a)->s6_addr[8]) == 0xffffffff) &&	\
75 	(*(u_int32_t *)(void *)(&(a)->s6_addr[12]) == 0xffffffff))
76 
77 #define ADDRESS_MAX sizeof "ffff:ffff:ffff:ffff:ffff:ffff:255.255.255.255"
78 
79 /*
80  * PF_KEY v2 always work with 64-bit entities and aligns on 64-bit boundaries.
81  */
82 #define PF_KEY_V2_CHUNK 8
83 #define PF_KEY_V2_ROUND(x)						\
84 	(((x) + PF_KEY_V2_CHUNK - 1) & ~(PF_KEY_V2_CHUNK - 1))
85 
86 /* How many microseconds we will wait for a reply from the PF_KEY socket.  */
87 #define PF_KEY_REPLY_TIMEOUT 1000
88 
89 struct pf_key_v2_node {
90 	TAILQ_ENTRY(pf_key_v2_node) link;
91 	void           *seg;
92 	size_t		sz;
93 	int		cnt;
94 	u_int16_t       type;
95 	u_int8_t	flags;
96 };
97 
98 TAILQ_HEAD(pf_key_v2_msg, pf_key_v2_node);
99 
100 #define PF_KEY_V2_NODE_MALLOCED 1
101 #define PF_KEY_V2_NODE_MARK 2
102 
103 /* Used to derive "unique" connection identifiers. */
104 int		connection_seq = 0;
105 
106 static u_int8_t *pf_key_v2_convert_id(u_int8_t *, int, size_t *, int *);
107 static struct pf_key_v2_msg *pf_key_v2_call(struct pf_key_v2_msg *);
108 static struct pf_key_v2_node *pf_key_v2_find_ext(struct pf_key_v2_msg *,
109 		    u_int16_t);
110 static void     pf_key_v2_notify(struct pf_key_v2_msg *);
111 static struct pf_key_v2_msg *pf_key_v2_read(u_int32_t);
112 static u_int32_t pf_key_v2_seq(void);
113 static u_int32_t pf_key_v2_write(struct pf_key_v2_msg *);
114 static int      pf_key_v2_remove_conf(char *);
115 static int      pf_key_v2_conf_refhandle(int, char *);
116 
117 static int      pf_key_v2_conf_refinc(int, char *);
118 
119 /* The socket to use for PF_KEY interactions.  */
120 int      pf_key_v2_socket;
121 
122 static struct pf_key_v2_msg *
123 pf_key_v2_msg_new(struct sadb_msg *msg, int flags)
124 {
125 	struct pf_key_v2_node *node;
126 	struct pf_key_v2_msg *ret;
127 
128 	node = malloc(sizeof *node);
129 	if (!node)
130 		goto cleanup;
131 	ret = malloc(sizeof *ret);
132 	if (!ret)
133 		goto cleanup;
134 	TAILQ_INIT(ret);
135 	node->seg = msg;
136 	node->sz = sizeof *msg;
137 	node->type = 0;
138 	node->cnt = 1;
139 	node->flags = flags;
140 	TAILQ_INSERT_HEAD(ret, node, link);
141 	return ret;
142 
143 cleanup:
144 	free(node);
145 	return 0;
146 }
147 
148 /* Add a SZ sized segment SEG to the PF_KEY message MSG.  */
149 static int
150 pf_key_v2_msg_add(struct pf_key_v2_msg *msg, struct sadb_ext *ext, int flags)
151 {
152 	struct pf_key_v2_node *node;
153 
154 	node = malloc(sizeof *node);
155 	if (!node)
156 		return -1;
157 	node->seg = ext;
158 	node->sz = ext->sadb_ext_len * PF_KEY_V2_CHUNK;
159 	node->type = ext->sadb_ext_type;
160 	node->flags = flags;
161 	TAILQ_FIRST(msg)->cnt++;
162 	TAILQ_INSERT_TAIL(msg, node, link);
163 	return 0;
164 }
165 
166 /* Deallocate the PF_KEY message MSG.  */
167 static void
168 pf_key_v2_msg_free(struct pf_key_v2_msg *msg)
169 {
170 	struct pf_key_v2_node *np;
171 
172 	np = TAILQ_FIRST(msg);
173 	while (np) {
174 		TAILQ_REMOVE(msg, np, link);
175 		if (np->flags & PF_KEY_V2_NODE_MALLOCED)
176 			free(np->seg);
177 		free(np);
178 		np = TAILQ_FIRST(msg);
179 	}
180 	free(msg);
181 }
182 
183 /* Just return a new sequence number.  */
184 static u_int32_t
185 pf_key_v2_seq(void)
186 {
187 	static u_int32_t seq = 0;
188 
189 	return ++seq;
190 }
191 
192 /*
193  * Read a PF_KEY packet with SEQ as the sequence number, looping if necessary.
194  * If SEQ is zero just read the first message we see, otherwise we queue
195  * messages up until both the PID and the sequence number match.
196  */
197 static struct pf_key_v2_msg *
198 pf_key_v2_read(u_int32_t seq)
199 {
200 	ssize_t		n;
201 	u_int8_t       *buf = 0;
202 	struct pf_key_v2_msg *ret = 0;
203 	struct sadb_msg *msg;
204 	struct sadb_msg hdr;
205 	struct sadb_ext *ext;
206 	struct timespec	ts;
207 	struct pollfd	pfd[1];
208 
209 	pfd[0].fd = pf_key_v2_socket;
210 	pfd[0].events = POLLIN;
211 
212 	while (1) {
213 		/*
214 		 * If this is a read of a reply we should actually expect the
215 		 * reply to get lost as PF_KEY is an unreliable service per
216 		 * the specs. Currently we do this by setting a short timeout,
217 		 * and if it is not readable in that time, we fail the read.
218 		 */
219 		if (seq) {
220 			n = poll(pfd, 1, PF_KEY_REPLY_TIMEOUT / 1000);
221 			if (n == -1) {
222 				log_error("pf_key_v2_read: poll() failed");
223 				goto cleanup;
224 			}
225 			if (!n) {
226 				log_print("pf_key_v2_read: "
227 				    "no reply from PF_KEY");
228 				goto cleanup;
229 			}
230 		}
231 		n = recv(pf_key_v2_socket, &hdr, sizeof hdr, MSG_PEEK);
232 		if (n == -1) {
233 			log_error("pf_key_v2_read: recv (%d, ...) failed",
234 			    pf_key_v2_socket);
235 			goto cleanup;
236 		}
237 		if (n != sizeof hdr) {
238 			log_error("pf_key_v2_read: recv (%d, ...) "
239 			    "returned short packet (%lu bytes)",
240 			    pf_key_v2_socket, (unsigned long) n);
241 			goto cleanup;
242 		}
243 		buf = reallocarray(NULL, hdr.sadb_msg_len, PF_KEY_V2_CHUNK);
244 		if (!buf) {
245 			log_error("pf_key_v2_read: reallocarray (%d, %d) failed",
246 			    hdr.sadb_msg_len, PF_KEY_V2_CHUNK);
247 			goto cleanup;
248 		}
249 		n = hdr.sadb_msg_len * PF_KEY_V2_CHUNK;
250 
251 		n = read(pf_key_v2_socket, buf, n);
252 		if (n == -1) {
253 			log_error("pf_key_v2_read: read (%d, ...) failed",
254 				  pf_key_v2_socket);
255 			goto cleanup;
256 		}
257 		if (n != hdr.sadb_msg_len * PF_KEY_V2_CHUNK) {
258 			log_print("pf_key_v2_read: read (%d, ...) "
259 			    "returned short packet (%lu bytes)",
260 			    pf_key_v2_socket, (unsigned long) n);
261 			goto cleanup;
262 		}
263 		LOG_DBG_BUF((LOG_SYSDEP, 80, "pf_key_v2_read: msg", buf, n));
264 
265 		/* We drop all messages that is not what we expect.  */
266 		msg = (struct sadb_msg *) buf;
267 		if (msg->sadb_msg_version != PF_KEY_V2 ||
268 		    (msg->sadb_msg_pid != 0 &&
269 		    msg->sadb_msg_pid != (u_int32_t) getpid())) {
270 			if (seq) {
271 				free(buf);
272 				buf = 0;
273 				continue;
274 			} else {
275 				LOG_DBG((LOG_SYSDEP, 90, "pf_key_v2_read:"
276 				    "bad version (%d) or PID (%d, mine is "
277 				    "%ld), ignored", msg->sadb_msg_version,
278 				    msg->sadb_msg_pid, (long) getpid()));
279 				goto cleanup;
280 			}
281 		}
282 		/* Parse the message.  */
283 		ret = pf_key_v2_msg_new(msg, PF_KEY_V2_NODE_MALLOCED);
284 		if (!ret)
285 			goto cleanup;
286 		buf = 0;
287 		for (ext = (struct sadb_ext *) (msg + 1);
288 		    (u_int8_t *) ext - (u_int8_t *) msg <
289 		    msg->sadb_msg_len * PF_KEY_V2_CHUNK;
290 		    ext = (struct sadb_ext *) ((u_int8_t *) ext +
291 		    ext->sadb_ext_len * PF_KEY_V2_CHUNK))
292 			pf_key_v2_msg_add(ret, ext, 0);
293 
294 		/*
295 		 * If the message is not the one we are waiting for, queue it
296 		 * up.
297 		 */
298 		if (seq && (msg->sadb_msg_pid != (u_int32_t) getpid() ||
299 		    msg->sadb_msg_seq != seq)) {
300 			clock_gettime(CLOCK_MONOTONIC, &ts);
301 			timer_add_event("pf_key_v2_notify",
302 			    (void (*) (void *)) pf_key_v2_notify, ret, &ts);
303 			ret = 0;
304 			continue;
305 		}
306 		return ret;
307 	}
308 
309 cleanup:
310 	free(buf);
311 	if (ret)
312 		pf_key_v2_msg_free(ret);
313 	return 0;
314 }
315 
316 /* Write the message in PMSG to the PF_KEY socket.  */
317 u_int32_t
318 pf_key_v2_write(struct pf_key_v2_msg *pmsg)
319 {
320 	struct iovec   *iov = 0;
321 	ssize_t		n;
322 	size_t		len;
323 	int		i, cnt = TAILQ_FIRST(pmsg)->cnt;
324 	char		header[80];
325 	struct sadb_msg *msg = TAILQ_FIRST(pmsg)->seg;
326 	struct pf_key_v2_node *np = TAILQ_FIRST(pmsg);
327 
328 	iov = calloc(cnt, sizeof *iov);
329 	if (!iov) {
330 		log_error("pf_key_v2_write: malloc (%lu) failed",
331 		    cnt * (unsigned long) sizeof *iov);
332 		return 0;
333 	}
334 	msg->sadb_msg_version = PF_KEY_V2;
335 	msg->sadb_msg_errno = 0;
336 	msg->sadb_msg_reserved = 0;
337 	msg->sadb_msg_pid = getpid();
338 	if (!msg->sadb_msg_seq)
339 		msg->sadb_msg_seq = pf_key_v2_seq();
340 
341 	/* Compute the iovec segments as well as the message length.  */
342 	len = 0;
343 	for (i = 0; i < cnt; i++) {
344 		iov[i].iov_base = np->seg;
345 		len += iov[i].iov_len = np->sz;
346 
347 		/*
348 		 * XXX One can envision setting specific extension fields,
349 		 * like *_reserved ones here.  For now we require them to be
350 		 * set by the caller.
351 		 */
352 
353 		np = TAILQ_NEXT(np, link);
354 	}
355 	msg->sadb_msg_len = len / PF_KEY_V2_CHUNK;
356 
357 	for (i = 0; i < cnt; i++) {
358 		snprintf(header, sizeof header, "pf_key_v2_write: iov[%d]", i);
359 		LOG_DBG_BUF((LOG_SYSDEP, 80, header,
360 		    (u_int8_t *) iov[i].iov_base, iov[i].iov_len));
361 	}
362 
363 	do {
364 		n = writev(pf_key_v2_socket, iov, cnt);
365 	} while (n == -1 && (errno == EAGAIN || errno == EINTR));
366 	if (n == -1) {
367 		log_error("pf_key_v2_write: writev (%d, %p, %d) failed",
368 		    pf_key_v2_socket, iov, cnt);
369 		goto cleanup;
370 	}
371 	if ((size_t) n != len) {
372 		log_error("pf_key_v2_write: "
373 		    "writev (%d, ...) returned prematurely (%lu)",
374 		    pf_key_v2_socket, (unsigned long) n);
375 		goto cleanup;
376 	}
377 	free(iov);
378 	return msg->sadb_msg_seq;
379 
380 cleanup:
381 	free(iov);
382 	return 0;
383 }
384 
385 /*
386  * Do a PF_KEY "call", i.e. write a message MSG, read the reply and return
387  * it to the caller.
388  */
389 static struct pf_key_v2_msg *
390 pf_key_v2_call(struct pf_key_v2_msg *msg)
391 {
392 	u_int32_t       seq;
393 
394 	seq = pf_key_v2_write(msg);
395 	if (!seq)
396 		return 0;
397 	return pf_key_v2_read(seq);
398 }
399 
400 /* Find the TYPE extension in MSG.  Return zero if none found.  */
401 static struct pf_key_v2_node *
402 pf_key_v2_find_ext(struct pf_key_v2_msg *msg, u_int16_t type)
403 {
404 	struct pf_key_v2_node *ext;
405 
406 	for (ext = TAILQ_NEXT(TAILQ_FIRST(msg), link); ext;
407 	    ext = TAILQ_NEXT(ext, link))
408 		if (ext->type == type)
409 			return ext;
410 	return 0;
411 }
412 
413 /*
414  * Open the PF_KEYv2 sockets and return the descriptor used for notifies.
415  * Return -1 for failure and -2 if no notifies will show up.
416  */
417 int
418 pf_key_v2_open(void)
419 {
420 	int		fd = -1, err;
421 	struct sadb_msg msg;
422 	struct pf_key_v2_msg *regmsg = 0, *ret = 0;
423 
424 	/* Open the socket we use to speak to IPsec. */
425 	pf_key_v2_socket = -1;
426 	fd = socket(PF_KEY, SOCK_RAW, PF_KEY_V2);
427 	if (fd == -1) {
428 		log_error("pf_key_v2_open: "
429 		    "socket (PF_KEY, SOCK_RAW, PF_KEY_V2) failed");
430 		goto cleanup;
431 	}
432 	pf_key_v2_socket = fd;
433 
434 	/* Register it to get ESP and AH acquires from the kernel.  */
435 	msg.sadb_msg_seq = 0;
436 	msg.sadb_msg_type = SADB_REGISTER;
437 	msg.sadb_msg_satype = SADB_SATYPE_ESP;
438 	regmsg = pf_key_v2_msg_new(&msg, 0);
439 	if (!regmsg)
440 		goto cleanup;
441 	ret = pf_key_v2_call(regmsg);
442 	pf_key_v2_msg_free(regmsg);
443 	if (!ret)
444 		goto cleanup;
445 	err = ((struct sadb_msg *)TAILQ_FIRST(ret)->seg)->sadb_msg_errno;
446 	if (err) {
447 		log_print("pf_key_v2_open: REGISTER: %s", strerror(err));
448 		goto cleanup;
449 	}
450 	/* XXX Register the accepted transforms.  */
451 
452 	pf_key_v2_msg_free(ret);
453 	ret = 0;
454 
455 	msg.sadb_msg_seq = 0;
456 	msg.sadb_msg_type = SADB_REGISTER;
457 	msg.sadb_msg_satype = SADB_SATYPE_AH;
458 	regmsg = pf_key_v2_msg_new(&msg, 0);
459 	if (!regmsg)
460 		goto cleanup;
461 	ret = pf_key_v2_call(regmsg);
462 	pf_key_v2_msg_free(regmsg);
463 	if (!ret)
464 		goto cleanup;
465 	err = ((struct sadb_msg *)TAILQ_FIRST(ret)->seg)->sadb_msg_errno;
466 	if (err) {
467 		log_print("pf_key_v2_open: REGISTER: %s", strerror(err));
468 		goto cleanup;
469 	}
470 	/* XXX Register the accepted transforms.  */
471 
472 	pf_key_v2_msg_free(ret);
473 	ret = 0;
474 
475 	msg.sadb_msg_seq = 0;
476 	msg.sadb_msg_type = SADB_REGISTER;
477 	msg.sadb_msg_satype = SADB_X_SATYPE_IPCOMP;
478 	regmsg = pf_key_v2_msg_new(&msg, 0);
479 	if (!regmsg)
480 		goto cleanup;
481 	ret = pf_key_v2_call(regmsg);
482 	pf_key_v2_msg_free(regmsg);
483 	if (!ret)
484 		goto cleanup;
485 	err = ((struct sadb_msg *)TAILQ_FIRST(ret)->seg)->sadb_msg_errno;
486 	if (err) {
487 		log_print("pf_key_v2_open: REGISTER: %s", strerror(err));
488 		goto cleanup;
489 	}
490 	/* XXX Register the accepted transforms.  */
491 
492 	pf_key_v2_msg_free(ret);
493 
494 	return fd;
495 
496 cleanup:
497 	if (pf_key_v2_socket != -1) {
498 		close(pf_key_v2_socket);
499 		pf_key_v2_socket = -1;
500 	}
501 	if (ret)
502 		pf_key_v2_msg_free(ret);
503 	return -1;
504 }
505 
506 /*
507  * Generate a SPI for protocol PROTO and the source/destination pair given by
508  * SRC, SRCLEN, DST & DSTLEN.  Stash the SPI size in SZ.
509  */
510 u_int8_t *
511 pf_key_v2_get_spi(size_t *sz, u_int8_t proto, struct sockaddr *src,
512     struct sockaddr *dst, u_int32_t seq)
513 {
514 	struct sadb_msg msg;
515 	struct sadb_sa *sa;
516 	struct sadb_address *addr = 0;
517 	struct sadb_spirange spirange;
518 	struct pf_key_v2_msg *getspi = 0, *ret = 0;
519 	struct pf_key_v2_node *ext;
520 	u_int8_t       *spi = 0;
521 	int		len, err;
522 
523 	msg.sadb_msg_type = SADB_GETSPI;
524 	switch (proto) {
525 	case IPSEC_PROTO_IPSEC_ESP:
526 		msg.sadb_msg_satype = SADB_SATYPE_ESP;
527 		break;
528 	case IPSEC_PROTO_IPSEC_AH:
529 		msg.sadb_msg_satype = SADB_SATYPE_AH;
530 		break;
531 	case IPSEC_PROTO_IPCOMP:
532 		msg.sadb_msg_satype = SADB_X_SATYPE_IPCOMP;
533 		break;
534 	default:
535 		log_print("pf_key_v2_get_spi: invalid proto %d", proto);
536 		goto cleanup;
537 	}
538 
539 	/* Set the sequence number from the ACQUIRE message. */
540 	msg.sadb_msg_seq = seq;
541 	getspi = pf_key_v2_msg_new(&msg, 0);
542 	if (!getspi)
543 		goto cleanup;
544 
545 	/* Setup the ADDRESS extensions.  */
546 	len =
547 	    sizeof(struct sadb_address) + PF_KEY_V2_ROUND(SA_LEN(src));
548 	addr = calloc(1, len);
549 	if (!addr)
550 		goto cleanup;
551 	addr->sadb_address_exttype = SADB_EXT_ADDRESS_SRC;
552 	addr->sadb_address_len = len / PF_KEY_V2_CHUNK;
553 	addr->sadb_address_reserved = 0;
554 	memcpy(addr + 1, src, SA_LEN(src));
555 	switch (((struct sockaddr *) (addr + 1))->sa_family) {
556 	case AF_INET:
557 		((struct sockaddr_in *) (addr + 1))->sin_port = 0;
558 		break;
559 	case AF_INET6:
560 		((struct sockaddr_in6 *) (addr + 1))->sin6_port = 0;
561 		break;
562 	}
563 	if (pf_key_v2_msg_add(getspi, (struct sadb_ext *) addr,
564 	    PF_KEY_V2_NODE_MALLOCED) == -1)
565 		goto cleanup;
566 	addr = 0;
567 
568 	len = sizeof(struct sadb_address) + PF_KEY_V2_ROUND(SA_LEN(dst));
569 	addr = calloc(1, len);
570 	if (!addr)
571 		goto cleanup;
572 	addr->sadb_address_exttype = SADB_EXT_ADDRESS_DST;
573 	addr->sadb_address_len = len / PF_KEY_V2_CHUNK;
574 	addr->sadb_address_reserved = 0;
575 	memcpy(addr + 1, dst, SA_LEN(dst));
576 	switch (((struct sockaddr *) (addr + 1))->sa_family) {
577 	case AF_INET:
578 		((struct sockaddr_in *) (addr + 1))->sin_port = 0;
579 		break;
580 	case AF_INET6:
581 		((struct sockaddr_in6 *) (addr + 1))->sin6_port = 0;
582 		break;
583 	}
584 	if (pf_key_v2_msg_add(getspi, (struct sadb_ext *) addr,
585 	    PF_KEY_V2_NODE_MALLOCED) == -1)
586 		goto cleanup;
587 	addr = 0;
588 
589 	/* Setup the SPIRANGE extension.  */
590 	spirange.sadb_spirange_exttype = SADB_EXT_SPIRANGE;
591 	spirange.sadb_spirange_len = sizeof spirange / PF_KEY_V2_CHUNK;
592 	if (proto == IPSEC_PROTO_IPCOMP) {
593 		spirange.sadb_spirange_min = CPI_RESERVED_MAX + 1;
594 		spirange.sadb_spirange_max = CPI_PRIVATE_MIN - 1;
595 	} else {
596 		spirange.sadb_spirange_min = IPSEC_SPI_LOW;
597 		spirange.sadb_spirange_max = 0xffffffff;
598 	}
599 	spirange.sadb_spirange_reserved = 0;
600 	if (pf_key_v2_msg_add(getspi, (struct sadb_ext *)&spirange, 0) == -1)
601 		goto cleanup;
602 
603 	ret = pf_key_v2_call(getspi);
604 	pf_key_v2_msg_free(getspi);
605 	getspi = 0;
606 	if (!ret)
607 		goto cleanup;
608 	err = ((struct sadb_msg *)TAILQ_FIRST(ret)->seg)->sadb_msg_errno;
609 	if (err) {
610 		log_print("pf_key_v2_get_spi: GETSPI: %s", strerror(err));
611 		goto cleanup;
612 	}
613 	ext = pf_key_v2_find_ext(ret, SADB_EXT_SA);
614 	if (!ext) {
615 		log_print("pf_key_v2_get_spi: no SA extension found");
616 		goto cleanup;
617 	}
618 	sa = ext->seg;
619 
620 	/* IPCOMP CPIs are only 16 bits long.  */
621 	*sz = (proto == IPSEC_PROTO_IPCOMP) ? sizeof(u_int16_t)
622 		: sizeof sa->sadb_sa_spi;
623 	spi = malloc(*sz);
624 	if (!spi)
625 		goto cleanup;
626 	/* XXX This is ugly.  */
627 	if (proto == IPSEC_PROTO_IPCOMP) {
628 		u_int32_t       tspi = ntohl(sa->sadb_sa_spi);
629 		*(u_int16_t *) spi = htons((u_int16_t) tspi);
630 	} else
631 		memcpy(spi, &sa->sadb_sa_spi, *sz);
632 
633 	pf_key_v2_msg_free(ret);
634 
635 	LOG_DBG_BUF((LOG_SYSDEP, 50, "pf_key_v2_get_spi: spi", spi, *sz));
636 	return spi;
637 
638 cleanup:
639 	free(spi);
640 	free(addr);
641 	if (getspi)
642 		pf_key_v2_msg_free(getspi);
643 	if (ret)
644 		pf_key_v2_msg_free(ret);
645 	return 0;
646 }
647 
648 /* Fetch SA information from the kernel. XXX OpenBSD only?  */
649 struct sa_kinfo *
650 pf_key_v2_get_kernel_sa(u_int8_t *spi, size_t spi_sz, u_int8_t proto,
651     struct sockaddr *dst)
652 {
653 	struct sadb_msg msg;
654 	struct sadb_sa *ssa;
655 	struct sadb_address *addr = 0;
656 	struct sockaddr *sa;
657 	struct sadb_lifetime *life;
658 	struct pf_key_v2_msg *gettdb = 0, *ret = 0;
659 	struct pf_key_v2_node *ext;
660 	static struct sa_kinfo ksa;
661 	struct sadb_x_udpencap *udpencap;
662 	int len, err;
663 
664 	if (spi_sz != sizeof (ssa->sadb_sa_spi))
665 		return 0;
666 
667 	msg.sadb_msg_type = SADB_GET;
668 	switch (proto) {
669 	case IPSEC_PROTO_IPSEC_ESP:
670 		msg.sadb_msg_satype = SADB_SATYPE_ESP;
671 		break;
672 	case IPSEC_PROTO_IPSEC_AH:
673 		msg.sadb_msg_satype = SADB_SATYPE_AH;
674 		break;
675 	case IPSEC_PROTO_IPCOMP:
676 		msg.sadb_msg_satype = SADB_X_SATYPE_IPCOMP;
677 		break;
678 	default:
679 		log_print("pf_key_v2_get_kernel_sa: invalid proto %d", proto);
680 		goto cleanup;
681 	}
682 
683 	gettdb = pf_key_v2_msg_new(&msg, 0);
684 	if (!gettdb)
685 		goto cleanup;
686 
687 	/* SPI */
688 	ssa = calloc(1, sizeof *ssa);
689 	if (!ssa) {
690 		log_print("pf_key_v2_get_kernel_sa: calloc(1, %lu) failed",
691 		    (unsigned long)sizeof *ssa);
692 		goto cleanup;
693 	}
694 
695 	ssa->sadb_sa_exttype = SADB_EXT_SA;
696 	ssa->sadb_sa_len = sizeof *ssa / PF_KEY_V2_CHUNK;
697 	memcpy(&ssa->sadb_sa_spi, spi, sizeof ssa->sadb_sa_spi);
698 	ssa->sadb_sa_state = SADB_SASTATE_MATURE;
699 	if (pf_key_v2_msg_add(gettdb, (struct sadb_ext *)ssa,
700 	    PF_KEY_V2_NODE_MALLOCED) == -1)
701 		goto cleanup;
702 	ssa = 0;
703 
704 	/* Address */
705 	len =
706 	    sizeof(struct sadb_address) + PF_KEY_V2_ROUND(SA_LEN(dst));
707 	addr = calloc(1, len);
708 	if (!addr)
709 		goto cleanup;
710 	addr->sadb_address_exttype = SADB_EXT_ADDRESS_DST;
711 	addr->sadb_address_len = len / PF_KEY_V2_CHUNK;
712 	addr->sadb_address_reserved = 0;
713 	memcpy(addr + 1, dst, SA_LEN(dst));
714 	switch (((struct sockaddr *) (addr + 1))->sa_family) {
715 	case AF_INET:
716 		((struct sockaddr_in *) (addr + 1))->sin_port = 0;
717 		break;
718 	case AF_INET6:
719 		((struct sockaddr_in6 *) (addr + 1))->sin6_port = 0;
720 		break;
721 	}
722 	if (pf_key_v2_msg_add(gettdb, (struct sadb_ext *)addr,
723 	    PF_KEY_V2_NODE_MALLOCED) == -1)
724 		goto cleanup;
725 	addr = 0;
726 
727 	ret = pf_key_v2_call(gettdb);
728 	pf_key_v2_msg_free(gettdb);
729 	gettdb = 0;
730 	if (!ret)
731 		goto cleanup;
732 	err = ((struct sadb_msg *)TAILQ_FIRST(ret)->seg)->sadb_msg_errno;
733 	if (err) {
734 		log_print("pf_key_v2_get_kernel_sa: SADB_GET: %s",
735 		    strerror(err));
736 		goto cleanup;
737 	}
738 
739 	/* Extract the data.  */
740 	bzero(&ksa, sizeof ksa);
741 
742 	ext = pf_key_v2_find_ext(ret, SADB_EXT_SA);
743 	if (!ext)
744 		goto cleanup;
745 
746 	ssa = (struct sadb_sa *)ext;
747 	ksa.spi = ssa->sadb_sa_spi;
748 	ksa.wnd = ssa->sadb_sa_replay;
749 	ksa.flags = ssa->sadb_sa_flags;
750 
751 	ext = pf_key_v2_find_ext(ret, SADB_EXT_LIFETIME_CURRENT);
752 	if (ext) {
753 		life = (struct sadb_lifetime *)ext->seg;
754 		ksa.cur_allocations = life->sadb_lifetime_allocations;
755 		ksa.cur_bytes =	life->sadb_lifetime_bytes;
756 		ksa.first_use = life->sadb_lifetime_usetime;
757 		ksa.established = life->sadb_lifetime_addtime;
758 	}
759 
760 	ext = pf_key_v2_find_ext(ret, SADB_EXT_LIFETIME_SOFT);
761 	if (ext) {
762 		life = (struct sadb_lifetime *)ext->seg;
763 		ksa.soft_allocations = life->sadb_lifetime_allocations;
764 		ksa.soft_bytes = life->sadb_lifetime_bytes;
765 		ksa.soft_timeout = life->sadb_lifetime_addtime;
766 		ksa.soft_first_use = life->sadb_lifetime_usetime;
767 	}
768 
769 	ext = pf_key_v2_find_ext(ret, SADB_EXT_LIFETIME_HARD);
770 	if (ext) {
771 		life = (struct sadb_lifetime *)ext->seg;
772 		ksa.exp_allocations = life->sadb_lifetime_allocations;
773 		ksa.exp_bytes = life->sadb_lifetime_bytes;
774 		ksa.exp_timeout = life->sadb_lifetime_addtime;
775 		ksa.exp_first_use = life->sadb_lifetime_usetime;
776 	}
777 
778 	ext = pf_key_v2_find_ext(ret, SADB_X_EXT_LIFETIME_LASTUSE);
779 	if (ext) {
780 		life = (struct sadb_lifetime *)ext->seg;
781 		ksa.last_used = life->sadb_lifetime_usetime;
782 	}
783 
784 	ext = pf_key_v2_find_ext(ret, SADB_EXT_ADDRESS_SRC);
785 	if (ext) {
786 		sa = (struct sockaddr *)ext->seg;
787 		memcpy(&ksa.src, sa,
788 		    sa->sa_family == AF_INET ? sizeof(struct sockaddr_in) :
789 		    sizeof(struct sockaddr_in6));
790 	}
791 
792 	ext = pf_key_v2_find_ext(ret, SADB_EXT_ADDRESS_DST);
793 	if (ext) {
794 		sa = (struct sockaddr *)ext->seg;
795 		memcpy(&ksa.dst, sa,
796 		    sa->sa_family == AF_INET ? sizeof(struct sockaddr_in) :
797 		    sizeof(struct sockaddr_in6));
798 	}
799 
800 	ext = pf_key_v2_find_ext(ret, SADB_X_EXT_UDPENCAP);
801 	if (ext) {
802 		udpencap = (struct sadb_x_udpencap *)ext->seg;
803 		ksa.udpencap_port = udpencap->sadb_x_udpencap_port;
804 	}
805 
806 	pf_key_v2_msg_free(ret);
807 
808 	LOG_DBG_BUF((LOG_SYSDEP, 50, "pf_key_v2_get_kernel_sa: spi", spi,
809 	    spi_sz));
810 
811 	return &ksa;
812 
813   cleanup:
814 	free(addr);
815 	if (gettdb)
816 		pf_key_v2_msg_free(gettdb);
817 	if (ret)
818 		pf_key_v2_msg_free(ret);
819 	return 0;
820 }
821 
822 static void
823 pf_key_v2_setup_sockaddr(void *res, struct sockaddr *src,
824     struct sockaddr *dst, in_port_t port, int ingress)
825 {
826 	struct sockaddr_in *ip4_sa;
827 	struct sockaddr_in6 *ip6_sa;
828 	u_int8_t       *p;
829 
830 	switch (src->sa_family) {
831 	case AF_INET:
832 		ip4_sa = (struct sockaddr_in *) res;
833 		ip4_sa->sin_family = AF_INET;
834 		ip4_sa->sin_len = sizeof *ip4_sa;
835 		ip4_sa->sin_port = port;
836 		if (dst)
837 			p = (u_int8_t *) (ingress ?
838 			    &((struct sockaddr_in *)src)->sin_addr.s_addr :
839 			    &((struct sockaddr_in *)dst)->sin_addr.s_addr);
840 		else
841 			p = (u_int8_t *)&((struct sockaddr_in *)src)->sin_addr.s_addr;
842 		ip4_sa->sin_addr.s_addr = *((in_addr_t *) p);
843 		break;
844 
845 	case AF_INET6:
846 		ip6_sa = (struct sockaddr_in6 *) res;
847 		ip6_sa->sin6_family = AF_INET6;
848 		ip6_sa->sin6_len = sizeof *ip6_sa;
849 		ip6_sa->sin6_port = port;
850 		if (dst)
851 			p = (u_int8_t *) (ingress ?
852 			    &((struct sockaddr_in6 *)src)->sin6_addr.s6_addr :
853 			    &((struct sockaddr_in6 *)dst)->sin6_addr.s6_addr);
854 		else
855 			p = (u_int8_t *)&((struct sockaddr_in6 *)src)->sin6_addr.s6_addr;
856 		memcpy(ip6_sa->sin6_addr.s6_addr, p, sizeof(struct in6_addr));
857 		break;
858 
859 	default:
860 		log_print("pf_key_v2_setup_sockaddr: unknown family %d\n",
861 		    src->sa_family);
862 		break;
863 	}
864 }
865 
866 /*
867  * Store/update a PF_KEY_V2 security association with full information from the
868  * IKE SA and PROTO into the kernel.  INCOMING is set if we are setting the
869  * parameters for the incoming SA, and cleared otherwise.
870  */
871 int
872 pf_key_v2_set_spi(struct sa *sa, struct proto *proto, int incoming,
873     struct sa *isakmp_sa)
874 {
875 	struct sadb_msg msg;
876 	struct sadb_sa  ssa;
877 	struct sadb_x_tag *stag = NULL;
878 	struct sadb_lifetime *life = 0;
879 	struct sadb_address *addr = 0;
880 	struct sadb_key *key = 0;
881 	struct sadb_ident *sid = 0;
882 	struct sockaddr *src, *dst;
883 	struct pf_key_v2_msg *update = 0, *ret = 0;
884 	struct ipsec_proto *iproto = proto->data;
885 	size_t		len;
886 	int		keylen, hashlen, err;
887 	u_int8_t       *pp;
888 	int		idtype;
889 	struct ipsec_sa *isa = sa->data;
890 	struct sadb_protocol flowtype, tprotocol;
891 	struct sadb_x_udpencap udpencap;
892 	char           *addr_str, *s;
893 
894 	msg.sadb_msg_type = incoming ? SADB_UPDATE : SADB_ADD;
895 	switch (proto->proto) {
896 	case IPSEC_PROTO_IPSEC_ESP:
897 		msg.sadb_msg_satype = SADB_SATYPE_ESP;
898 		keylen = ipsec_esp_enckeylength(proto);
899 		hashlen = ipsec_esp_authkeylength(proto);
900 
901 		switch (proto->id) {
902 		case IPSEC_ESP_3DES:
903 			ssa.sadb_sa_encrypt = SADB_EALG_3DESCBC;
904 			break;
905 
906 		case IPSEC_ESP_AES:
907 			ssa.sadb_sa_encrypt = SADB_X_EALG_AES;
908 			break;
909 
910 		case IPSEC_ESP_AES_CTR:
911 			ssa.sadb_sa_encrypt = SADB_X_EALG_AESCTR;
912 			break;
913 
914 		case IPSEC_ESP_AES_GCM_16:
915 			ssa.sadb_sa_encrypt = SADB_X_EALG_AESGCM16;
916 			break;
917 
918 		case IPSEC_ESP_AES_GMAC:
919 			ssa.sadb_sa_encrypt = SADB_X_EALG_AESGMAC;
920 			break;
921 
922 		case IPSEC_ESP_CAST:
923 			ssa.sadb_sa_encrypt = SADB_X_EALG_CAST;
924 			break;
925 
926 		case IPSEC_ESP_BLOWFISH:
927 			ssa.sadb_sa_encrypt = SADB_X_EALG_BLF;
928 			break;
929 
930 		case IPSEC_ESP_NULL:
931 			ssa.sadb_sa_encrypt = SADB_EALG_NULL;
932 			break;
933 
934 		default:
935 			LOG_DBG((LOG_SYSDEP, 50, "pf_key_v2_set_spi: "
936 			    "unknown encryption algorithm %d", proto->id));
937 			return -1;
938 		}
939 
940 		switch (iproto->auth) {
941 		case IPSEC_AUTH_HMAC_MD5:
942 			ssa.sadb_sa_auth = SADB_AALG_MD5HMAC;
943 			break;
944 
945 		case IPSEC_AUTH_HMAC_SHA:
946 			ssa.sadb_sa_auth = SADB_AALG_SHA1HMAC;
947 			break;
948 
949 		case IPSEC_AUTH_HMAC_RIPEMD:
950 			ssa.sadb_sa_auth = SADB_X_AALG_RIPEMD160HMAC;
951 			break;
952 
953 		case IPSEC_AUTH_HMAC_SHA2_256:
954 			ssa.sadb_sa_auth = SADB_X_AALG_SHA2_256;
955 			break;
956 
957 		case IPSEC_AUTH_HMAC_SHA2_384:
958 			ssa.sadb_sa_auth = SADB_X_AALG_SHA2_384;
959 			break;
960 
961 		case IPSEC_AUTH_HMAC_SHA2_512:
962 			ssa.sadb_sa_auth = SADB_X_AALG_SHA2_512;
963 			break;
964 
965 		case IPSEC_AUTH_DES_MAC:
966 		case IPSEC_AUTH_KPDK:
967 			/* XXX We should be supporting KPDK */
968 			LOG_DBG((LOG_SYSDEP, 50, "pf_key_v2_set_spi: "
969 			    "unknown authentication algorithm %d",
970 			    iproto->auth));
971 			return -1;
972 
973 		default:
974 			ssa.sadb_sa_auth = SADB_AALG_NONE;
975 		}
976 		break;
977 
978 	case IPSEC_PROTO_IPSEC_AH:
979 		msg.sadb_msg_satype = SADB_SATYPE_AH;
980 		hashlen = ipsec_ah_keylength(proto);
981 		keylen = 0;
982 
983 		ssa.sadb_sa_encrypt = SADB_EALG_NONE;
984 		switch (proto->id) {
985 		case IPSEC_AH_MD5:
986 			ssa.sadb_sa_auth = SADB_AALG_MD5HMAC;
987 			break;
988 
989 		case IPSEC_AH_SHA:
990 			ssa.sadb_sa_auth = SADB_AALG_SHA1HMAC;
991 			break;
992 
993 		case IPSEC_AH_RIPEMD:
994 			ssa.sadb_sa_auth = SADB_X_AALG_RIPEMD160HMAC;
995 			break;
996 
997 		case IPSEC_AH_SHA2_256:
998 			ssa.sadb_sa_auth = SADB_X_AALG_SHA2_256;
999 			break;
1000 
1001 		case IPSEC_AH_SHA2_384:
1002 			ssa.sadb_sa_auth = SADB_X_AALG_SHA2_384;
1003 			break;
1004 
1005 		case IPSEC_AH_SHA2_512:
1006 			ssa.sadb_sa_auth = SADB_X_AALG_SHA2_512;
1007 			break;
1008 
1009 		default:
1010 			LOG_DBG((LOG_SYSDEP, 50, "pf_key_v2_set_spi: "
1011 			    "unknown authentication algorithm %d", proto->id));
1012 			goto cleanup;
1013 		}
1014 		break;
1015 
1016 	case IPSEC_PROTO_IPCOMP:
1017 		msg.sadb_msg_satype = SADB_X_SATYPE_IPCOMP;
1018 		ssa.sadb_sa_auth = SADB_AALG_NONE;
1019 		keylen = 0;
1020 		hashlen = 0;
1021 
1022 		/*
1023 		 * Put compression algorithm type in the sadb_sa_encrypt
1024 		 * field.
1025 		 */
1026 		switch (proto->id) {
1027 		case IPSEC_IPCOMP_OUI:
1028 			ssa.sadb_sa_encrypt = SADB_X_CALG_OUI;
1029 			break;
1030 
1031 		case IPSEC_IPCOMP_DEFLATE:
1032 			ssa.sadb_sa_encrypt = SADB_X_CALG_DEFLATE;
1033 			break;
1034 
1035 		default:
1036 			break;
1037 		}
1038 		break;
1039 
1040 	default:
1041 		log_print("pf_key_v2_set_spi: invalid proto %d", proto->proto);
1042 		goto cleanup;
1043 	}
1044 	if (incoming)
1045 		sa->transport->vtbl->get_src(sa->transport, &dst);
1046 	else
1047 		sa->transport->vtbl->get_dst(sa->transport, &dst);
1048 	msg.sadb_msg_seq = sa->seq;
1049 	update = pf_key_v2_msg_new(&msg, 0);
1050 	if (!update)
1051 		goto cleanup;
1052 
1053 	/* Setup the rest of the SA extension.  */
1054 	ssa.sadb_sa_exttype = SADB_EXT_SA;
1055 	ssa.sadb_sa_len = sizeof ssa / PF_KEY_V2_CHUNK;
1056 	if (proto->spi_sz[incoming] == 2)	/* IPCOMP uses 16bit CPIs.  */
1057 		ssa.sadb_sa_spi = htonl(proto->spi[incoming][0] << 8 |
1058 		    proto->spi[incoming][1]);
1059 	else
1060 		memcpy(&ssa.sadb_sa_spi, proto->spi[incoming],
1061 		    sizeof ssa.sadb_sa_spi);
1062 	ssa.sadb_sa_replay = conf_get_str("General", "Shared-SADB") ? 0 :
1063 	    iproto->replay_window;
1064 	ssa.sadb_sa_state = SADB_SASTATE_MATURE;
1065 	ssa.sadb_sa_flags = 0;
1066 	if (iproto->encap_mode == IPSEC_ENCAP_TUNNEL ||
1067 	    iproto->encap_mode == IPSEC_ENCAP_UDP_ENCAP_TUNNEL ||
1068 	    iproto->encap_mode == IPSEC_ENCAP_UDP_ENCAP_TUNNEL_DRAFT)
1069 		ssa.sadb_sa_flags = SADB_X_SAFLAGS_TUNNEL;
1070 
1071 	if (isakmp_sa->flags & SA_FLAG_NAT_T_ENABLE) {
1072 		bzero(&udpencap, sizeof udpencap);
1073 		ssa.sadb_sa_flags |= SADB_X_SAFLAGS_UDPENCAP;
1074 		udpencap.sadb_x_udpencap_exttype = SADB_X_EXT_UDPENCAP;
1075 		udpencap.sadb_x_udpencap_len =
1076 		    sizeof udpencap / PF_KEY_V2_CHUNK;
1077 		udpencap.sadb_x_udpencap_port = sockaddr_port(dst);
1078 		if (pf_key_v2_msg_add(update, (struct sadb_ext *)&udpencap, 0)
1079 		    == -1)
1080 			goto cleanup;
1081 	}
1082 
1083 	if (pf_key_v2_msg_add(update, (struct sadb_ext *)&ssa, 0) == -1)
1084 		goto cleanup;
1085 
1086 	if (sa->seconds || sa->kilobytes) {
1087 		/* Setup the hard limits.  */
1088 		life = malloc(sizeof *life);
1089 		if (!life)
1090 			goto cleanup;
1091 		life->sadb_lifetime_len = sizeof *life / PF_KEY_V2_CHUNK;
1092 		life->sadb_lifetime_exttype = SADB_EXT_LIFETIME_HARD;
1093 		life->sadb_lifetime_allocations = 0;
1094 		life->sadb_lifetime_bytes = sa->kilobytes * 1024;
1095 		/*
1096 		 * XXX I am not sure which one is best in security respect.
1097 		 * Maybe the RFCs actually mandate what a lifetime really is.
1098 		 */
1099 #if 0
1100 		life->sadb_lifetime_addtime = 0;
1101 		life->sadb_lifetime_usetime = sa->seconds;
1102 #else
1103 		life->sadb_lifetime_addtime = sa->seconds;
1104 		life->sadb_lifetime_usetime = 0;
1105 #endif
1106 		if (pf_key_v2_msg_add(update, (struct sadb_ext *) life,
1107 		    PF_KEY_V2_NODE_MALLOCED) == -1)
1108 			goto cleanup;
1109 		life = 0;
1110 
1111 		/*
1112 		 * Setup the soft limits, we use 90 % of the hard ones.
1113 		 * XXX A configurable ratio would be better.
1114 		 */
1115 		life = malloc(sizeof *life);
1116 		if (!life)
1117 			goto cleanup;
1118 		life->sadb_lifetime_len = sizeof *life / PF_KEY_V2_CHUNK;
1119 		life->sadb_lifetime_exttype = SADB_EXT_LIFETIME_SOFT;
1120 		life->sadb_lifetime_allocations = 0;
1121 		life->sadb_lifetime_bytes = sa->kilobytes * 1024 * 9 / 10;
1122 		/*
1123 		 * XXX I am not sure which one is best in security respect.
1124 		 * Maybe the RFCs actually mandate what a lifetime really is.
1125 		 */
1126 #if 0
1127 		life->sadb_lifetime_addtime = 0;
1128 		life->sadb_lifetime_usetime = sa->seconds * 9 / 10;
1129 #else
1130 		life->sadb_lifetime_addtime = sa->seconds * 9 / 10;
1131 		life->sadb_lifetime_usetime = 0;
1132 #endif
1133 		if (pf_key_v2_msg_add(update, (struct sadb_ext *) life,
1134 		    PF_KEY_V2_NODE_MALLOCED) == -1)
1135 			goto cleanup;
1136 		life = 0;
1137 	}
1138 	/*
1139 	 * Setup the ADDRESS extensions.
1140 	 */
1141 	if (incoming)
1142 		sa->transport->vtbl->get_dst(sa->transport, &src);
1143 	else
1144 		sa->transport->vtbl->get_src(sa->transport, &src);
1145 	len = sizeof *addr + PF_KEY_V2_ROUND(SA_LEN(src));
1146 	addr = calloc(1, len);
1147 	if (!addr)
1148 		goto cleanup;
1149 	addr->sadb_address_exttype = SADB_EXT_ADDRESS_SRC;
1150 	addr->sadb_address_len = len / PF_KEY_V2_CHUNK;
1151 	addr->sadb_address_reserved = 0;
1152 	memcpy(addr + 1, src, SA_LEN(src));
1153 	switch (((struct sockaddr *) (addr + 1))->sa_family) {
1154 	case AF_INET:
1155 		((struct sockaddr_in *) (addr + 1))->sin_port = 0;
1156 		break;
1157 	case AF_INET6:
1158 		((struct sockaddr_in6 *) (addr + 1))->sin6_port = 0;
1159 		break;
1160 	}
1161 	if (pf_key_v2_msg_add(update, (struct sadb_ext *) addr,
1162 	    PF_KEY_V2_NODE_MALLOCED) == -1)
1163 		goto cleanup;
1164 	addr = 0;
1165 
1166 	len = sizeof *addr + PF_KEY_V2_ROUND(SA_LEN(dst));
1167 	addr = calloc(1, len);
1168 	if (!addr)
1169 		goto cleanup;
1170 	addr->sadb_address_exttype = SADB_EXT_ADDRESS_DST;
1171 	addr->sadb_address_len = len / PF_KEY_V2_CHUNK;
1172 	addr->sadb_address_reserved = 0;
1173 	memcpy(addr + 1, dst, SA_LEN(dst));
1174 	switch (((struct sockaddr *) (addr + 1))->sa_family) {
1175 	case AF_INET:
1176 		((struct sockaddr_in *) (addr + 1))->sin_port = 0;
1177 		break;
1178 	case AF_INET6:
1179 		((struct sockaddr_in6 *) (addr + 1))->sin6_port = 0;
1180 		break;
1181 	}
1182 	if (pf_key_v2_msg_add(update, (struct sadb_ext *) addr,
1183 	    PF_KEY_V2_NODE_MALLOCED) == -1)
1184 		goto cleanup;
1185 	addr = 0;
1186 
1187 	if (proto->proto != IPSEC_PROTO_IPCOMP) {
1188 		/* Setup the KEY extensions.  */
1189 		if (hashlen) {
1190 			len = sizeof *key + PF_KEY_V2_ROUND(hashlen);
1191 			key = malloc(len);
1192 			if (!key)
1193 				goto cleanup;
1194 			key->sadb_key_exttype = SADB_EXT_KEY_AUTH;
1195 			key->sadb_key_len = len / PF_KEY_V2_CHUNK;
1196 			key->sadb_key_bits = hashlen * 8;
1197 			key->sadb_key_reserved = 0;
1198 			memcpy(key + 1,
1199 			    iproto->keymat[incoming] +
1200 			    (proto->proto ==
1201 				IPSEC_PROTO_IPSEC_ESP ? keylen : 0),
1202 			    hashlen);
1203 			if (pf_key_v2_msg_add(update, (struct sadb_ext *) key,
1204 			    PF_KEY_V2_NODE_MALLOCED) == -1)
1205 				goto cleanup;
1206 			key = 0;
1207 		}
1208 		if (keylen) {
1209 			len = sizeof *key + PF_KEY_V2_ROUND(keylen);
1210 			key = malloc(len);
1211 			if (!key)
1212 				goto cleanup;
1213 			key->sadb_key_exttype = SADB_EXT_KEY_ENCRYPT;
1214 			key->sadb_key_len = len / PF_KEY_V2_CHUNK;
1215 			key->sadb_key_bits = keylen * 8;
1216 			key->sadb_key_reserved = 0;
1217 			memcpy(key + 1, iproto->keymat[incoming], keylen);
1218 			if (pf_key_v2_msg_add(update, (struct sadb_ext *) key,
1219 			    PF_KEY_V2_NODE_MALLOCED) == -1)
1220 				goto cleanup;
1221 			key = 0;
1222 		}
1223 	}
1224 	/* Setup identity extensions. */
1225 	if (isakmp_sa->id_i) {
1226 		pp = pf_key_v2_convert_id(isakmp_sa->id_i, isakmp_sa->id_i_len,
1227 		    &len, &idtype);
1228 		if (!pp)
1229 			goto nosid;
1230 
1231 		sid = calloc(PF_KEY_V2_ROUND(len + 1) + sizeof *sid,
1232 		    sizeof(u_int8_t));
1233 		if (!sid) {
1234 			free(pp);
1235 			goto cleanup;
1236 		}
1237 		sid->sadb_ident_type = idtype;
1238 		sid->sadb_ident_len = ((sizeof *sid) / PF_KEY_V2_CHUNK) +
1239 		    PF_KEY_V2_ROUND(len + 1) / PF_KEY_V2_CHUNK;
1240 		if ((isakmp_sa->initiator && !incoming) ||
1241 		    (!isakmp_sa->initiator && incoming))
1242 			sid->sadb_ident_exttype = SADB_EXT_IDENTITY_SRC;
1243 		else
1244 			sid->sadb_ident_exttype = SADB_EXT_IDENTITY_DST;
1245 
1246 		memcpy(sid + 1, pp, len);
1247 		free(pp);
1248 
1249 		if (pf_key_v2_msg_add(update, (struct sadb_ext *) sid,
1250 		    PF_KEY_V2_NODE_MALLOCED) == -1)
1251 			goto cleanup;
1252 		sid = 0;
1253 
1254 nosid:
1255 		free(sid);
1256 		sid = 0;
1257 	}
1258 	if (isakmp_sa->id_r) {
1259 		pp = pf_key_v2_convert_id(isakmp_sa->id_r, isakmp_sa->id_r_len,
1260 		    &len, &idtype);
1261 		if (!pp)
1262 			goto nodid;
1263 
1264 		sid = calloc(PF_KEY_V2_ROUND(len + 1) + sizeof *sid,
1265 		    sizeof(u_int8_t));
1266 		if (!sid) {
1267 			free(pp);
1268 			goto cleanup;
1269 		}
1270 		sid->sadb_ident_type = idtype;
1271 		sid->sadb_ident_len = ((sizeof *sid) / PF_KEY_V2_CHUNK) +
1272 		    PF_KEY_V2_ROUND(len + 1) / PF_KEY_V2_CHUNK;
1273 		if ((isakmp_sa->initiator && !incoming) ||
1274 		    (!isakmp_sa->initiator && incoming))
1275 			sid->sadb_ident_exttype = SADB_EXT_IDENTITY_DST;
1276 		else
1277 			sid->sadb_ident_exttype = SADB_EXT_IDENTITY_SRC;
1278 
1279 		memcpy(sid + 1, pp, len);
1280 		free(pp);
1281 
1282 		if (pf_key_v2_msg_add(update, (struct sadb_ext *) sid,
1283 		    PF_KEY_V2_NODE_MALLOCED) == -1)
1284 			goto cleanup;
1285 		sid = 0;
1286 
1287 nodid:
1288 		free(sid);
1289 		sid = 0;
1290 	}
1291 
1292 	/* Setup the flow type extension.  */
1293 	bzero(&flowtype, sizeof flowtype);
1294 	flowtype.sadb_protocol_exttype = SADB_X_EXT_FLOW_TYPE;
1295 	flowtype.sadb_protocol_len = sizeof flowtype / PF_KEY_V2_CHUNK;
1296 	flowtype.sadb_protocol_direction = incoming ?
1297 	    IPSP_DIRECTION_IN : IPSP_DIRECTION_OUT;
1298 
1299 	if (pf_key_v2_msg_add(update, (struct sadb_ext *)&flowtype, 0) == -1)
1300 		goto cleanup;
1301 
1302 	bzero(&tprotocol, sizeof tprotocol);
1303 	tprotocol.sadb_protocol_exttype = SADB_X_EXT_PROTOCOL;
1304 	tprotocol.sadb_protocol_len = sizeof tprotocol / PF_KEY_V2_CHUNK;
1305 	tprotocol.sadb_protocol_proto = isa->tproto;
1306 
1307 	if (pf_key_v2_msg_add(update, (struct sadb_ext *)&tprotocol,
1308 	    0) == -1)
1309 		goto cleanup;
1310 
1311 	len = sizeof *addr + PF_KEY_V2_ROUND(SA_LEN(isa->src_net));
1312 	addr = calloc(1, len);
1313 	if (!addr)
1314 		goto cleanup;
1315 	addr->sadb_address_exttype = incoming ?
1316 	    SADB_X_EXT_DST_FLOW : SADB_X_EXT_SRC_FLOW;
1317 	addr->sadb_address_len = len / PF_KEY_V2_CHUNK;
1318 	addr->sadb_address_reserved = 0;
1319 	pf_key_v2_setup_sockaddr(addr + 1, isa->src_net, 0, isa->sport, 0);
1320 	if (pf_key_v2_msg_add(update, (struct sadb_ext *) addr,
1321 	    PF_KEY_V2_NODE_MALLOCED) == -1)
1322 		goto cleanup;
1323 	addr = 0;
1324 
1325 	addr = calloc(1, len);
1326 	if (!addr)
1327 		goto cleanup;
1328 	addr->sadb_address_exttype =
1329 		incoming ? SADB_X_EXT_DST_MASK : SADB_X_EXT_SRC_MASK;
1330 	addr->sadb_address_len = len / PF_KEY_V2_CHUNK;
1331 	addr->sadb_address_reserved = 0;
1332 	pf_key_v2_setup_sockaddr(addr + 1, isa->src_mask, 0,
1333 	    isa->sport ? 0xffff : 0, 0);
1334 	if (pf_key_v2_msg_add(update, (struct sadb_ext *) addr,
1335 	    PF_KEY_V2_NODE_MALLOCED) == -1)
1336 		goto cleanup;
1337 	addr = 0;
1338 
1339 	addr = calloc(1, len);
1340 	if (!addr)
1341 		goto cleanup;
1342 	addr->sadb_address_exttype = incoming ?
1343 	    SADB_X_EXT_SRC_FLOW : SADB_X_EXT_DST_FLOW;
1344 	addr->sadb_address_len = len / PF_KEY_V2_CHUNK;
1345 	addr->sadb_address_reserved = 0;
1346 	pf_key_v2_setup_sockaddr(addr + 1, isa->dst_net, 0, isa->dport, 0);
1347 	if (pf_key_v2_msg_add(update, (struct sadb_ext *) addr,
1348 	    PF_KEY_V2_NODE_MALLOCED) == -1)
1349 		goto cleanup;
1350 	addr = 0;
1351 
1352 	addr = calloc(1, len);
1353 	if (!addr)
1354 		goto cleanup;
1355 	addr->sadb_address_exttype =
1356 		incoming ? SADB_X_EXT_SRC_MASK : SADB_X_EXT_DST_MASK;
1357 	addr->sadb_address_len = len / PF_KEY_V2_CHUNK;
1358 	addr->sadb_address_reserved = 0;
1359 	pf_key_v2_setup_sockaddr(addr + 1, isa->dst_mask, 0,
1360 	    isa->dport ? 0xffff : 0, 0);
1361 	if (pf_key_v2_msg_add(update, (struct sadb_ext *) addr,
1362 	    PF_KEY_V2_NODE_MALLOCED) == -1)
1363 		goto cleanup;
1364 	addr = 0;
1365 
1366 	/* Add a pf tag to matching packets of this SA. */
1367 	if (sa->tag != NULL) {
1368 		len = sizeof(*stag) + PF_KEY_V2_ROUND(strlen(sa->tag) + 1);
1369 		if ((stag = calloc(1, len)) == NULL)
1370 			goto cleanup;
1371 		stag->sadb_x_tag_exttype = SADB_X_EXT_TAG;
1372 		stag->sadb_x_tag_len = len / PF_KEY_V2_CHUNK;
1373 		stag->sadb_x_tag_taglen = strlen(sa->tag) + 1;
1374 		s = (char *)(stag + 1);
1375 		strlcpy(s, sa->tag, stag->sadb_x_tag_taglen);
1376 		if (pf_key_v2_msg_add(update, (struct sadb_ext *)stag,
1377 		    PF_KEY_V2_NODE_MALLOCED) == -1)
1378 			goto cleanup;
1379 	}
1380 
1381 	/* XXX Here can sensitivity extensions be setup.  */
1382 
1383 	if (sockaddr2text(dst, &addr_str, 0))
1384 		addr_str = 0;
1385 
1386 	LOG_DBG((LOG_SYSDEP, 10, "pf_key_v2_set_spi: "
1387 	    "satype %d dst %s SPI 0x%x%s%s", msg.sadb_msg_satype,
1388 	    addr_str ? addr_str : "unknown",
1389 	    ntohl(ssa.sadb_sa_spi), sa->tag ? " tag " : "",
1390 	    sa->tag ? sa->tag : ""));
1391 
1392 	free(addr_str);
1393 
1394 	/*
1395 	 * Although PF_KEY knows about expirations, it is unreliable per the
1396 	 * specs thus we need to do them inside isakmpd as well.
1397 	 */
1398 	if (sa->seconds)
1399 		if (sa_setup_expirations(sa))
1400 			goto cleanup;
1401 
1402 	ret = pf_key_v2_call(update);
1403 	pf_key_v2_msg_free(update);
1404 	update = 0;
1405 	if (!ret)
1406 		goto cleanup;
1407 	err = ((struct sadb_msg *)TAILQ_FIRST(ret)->seg)->sadb_msg_errno;
1408 	pf_key_v2_msg_free(ret);
1409 	ret = 0;
1410 
1411 	/*
1412 	 * If we are doing an addition into an SADB shared with our peer,
1413 	 * errors here are to be expected as the peer will already have
1414 	 * created the SA, and can thus be ignored.
1415 	 */
1416 	if (err && !(msg.sadb_msg_type == SADB_ADD &&
1417 	    conf_get_str("General", "Shared-SADB"))) {
1418 		log_print("pf_key_v2_set_spi: %s: %s",
1419 		    msg.sadb_msg_type == SADB_ADD ? "ADD" : "UPDATE",
1420 		    strerror(err));
1421 		goto cleanup;
1422 	}
1423 	LOG_DBG((LOG_SYSDEP, 50, "pf_key_v2_set_spi: done"));
1424 
1425 	return 0;
1426 
1427 cleanup:
1428 	free(sid);
1429 	free(addr);
1430 	free(life);
1431 	free(key);
1432 	if (update)
1433 		pf_key_v2_msg_free(update);
1434 	if (ret)
1435 		pf_key_v2_msg_free(ret);
1436 	return -1;
1437 }
1438 
1439 static __inline__ int
1440 pf_key_v2_mask_to_bits(u_int32_t mask)
1441 {
1442 	u_int32_t       hmask = ntohl(mask);
1443 
1444 	return (33 - ffs(~hmask + 1)) % 33;
1445 }
1446 
1447 static int
1448 pf_key_v2_mask6_to_bits(u_int8_t *mask)
1449 {
1450 	int		n;
1451 
1452 	bit_ffc(mask, 128, &n);
1453 	return n == -1 ? 128 : n;
1454 }
1455 
1456 /*
1457  * Enable/disable a flow.
1458  * XXX Assumes OpenBSD {ADD,DEL}FLOW extensions.
1459  */
1460 static int
1461 pf_key_v2_flow(struct sockaddr *laddr, struct sockaddr *lmask,
1462     struct sockaddr *raddr, struct sockaddr *rmask,
1463     u_int8_t tproto, u_int16_t sport, u_int16_t dport,
1464     u_int8_t *spi, u_int8_t proto, struct sockaddr *dst,
1465     struct sockaddr *src, int delete, int ingress,
1466     u_int8_t srcid_type, u_int8_t *srcid, int srcid_len,
1467     u_int8_t dstid_type, u_int8_t *dstid, int dstid_len,
1468     struct ipsec_proto *iproto)
1469 {
1470 	char           *laddr_str, *lmask_str, *raddr_str, *rmask_str;
1471 
1472 	struct sadb_msg msg;
1473 	struct sadb_protocol flowtype;
1474 	struct sadb_ident *sid = 0;
1475 	struct sadb_address *addr = 0;
1476 	struct sadb_protocol tprotocol;
1477 	struct pf_key_v2_msg *flow = 0, *ret = 0;
1478 	size_t		len;
1479 	int		err;
1480 
1481 	msg.sadb_msg_type = delete ? SADB_X_DELFLOW : SADB_X_ADDFLOW;
1482 	switch (proto) {
1483 	case IPSEC_PROTO_IPSEC_ESP:
1484 		msg.sadb_msg_satype = SADB_SATYPE_ESP;
1485 		break;
1486 	case IPSEC_PROTO_IPSEC_AH:
1487 		msg.sadb_msg_satype = SADB_SATYPE_AH;
1488 		break;
1489 	case IPSEC_PROTO_IPCOMP:
1490 		msg.sadb_msg_satype = SADB_X_SATYPE_IPCOMP;
1491 		break;
1492 	default:
1493 		log_print("pf_key_v2_flow: invalid proto %d", proto);
1494 		goto cleanup;
1495 	}
1496 	msg.sadb_msg_seq = 0;
1497 	flow = pf_key_v2_msg_new(&msg, 0);
1498 	if (!flow)
1499 		goto cleanup;
1500 
1501 	if (!delete) {
1502 		/* Setup the source ID, if provided. */
1503 		if (srcid) {
1504 			sid = calloc(
1505 			    PF_KEY_V2_ROUND(srcid_len + 1) + sizeof *sid,
1506 			    sizeof(u_int8_t));
1507 			if (!sid)
1508 				goto cleanup;
1509 
1510 			sid->sadb_ident_len = ((sizeof *sid) / PF_KEY_V2_CHUNK)
1511 			    + PF_KEY_V2_ROUND(srcid_len + 1) / PF_KEY_V2_CHUNK;
1512 			sid->sadb_ident_exttype = SADB_EXT_IDENTITY_SRC;
1513 			sid->sadb_ident_type = srcid_type;
1514 
1515 			memcpy(sid + 1, srcid, srcid_len);
1516 
1517 			if (pf_key_v2_msg_add(flow, (struct sadb_ext *) sid,
1518 			    PF_KEY_V2_NODE_MALLOCED) == -1)
1519 				goto cleanup;
1520 
1521 			sid = 0;
1522 		}
1523 		/* Setup the destination ID, if provided. */
1524 		if (dstid) {
1525 			sid = calloc(
1526 			    PF_KEY_V2_ROUND(dstid_len + 1) + sizeof *sid,
1527 			    sizeof(u_int8_t));
1528 			if (!sid)
1529 				goto cleanup;
1530 
1531 			sid->sadb_ident_len = ((sizeof *sid) / PF_KEY_V2_CHUNK)
1532 			    + PF_KEY_V2_ROUND(dstid_len + 1) / PF_KEY_V2_CHUNK;
1533 			sid->sadb_ident_exttype = SADB_EXT_IDENTITY_DST;
1534 			sid->sadb_ident_type = dstid_type;
1535 
1536 			memcpy(sid + 1, dstid, dstid_len);
1537 
1538 			if (pf_key_v2_msg_add(flow, (struct sadb_ext *) sid,
1539 			    PF_KEY_V2_NODE_MALLOCED) == -1)
1540 				goto cleanup;
1541 
1542 			sid = 0;
1543 		}
1544 	}
1545 	/* Setup the flow type extension.  */
1546 	bzero(&flowtype, sizeof flowtype);
1547 	flowtype.sadb_protocol_exttype = SADB_X_EXT_FLOW_TYPE;
1548 	flowtype.sadb_protocol_len = sizeof flowtype / PF_KEY_V2_CHUNK;
1549 	flowtype.sadb_protocol_direction =
1550 	    ingress ? IPSP_DIRECTION_IN : IPSP_DIRECTION_OUT;
1551 	flowtype.sadb_protocol_proto = SADB_X_FLOW_TYPE_REQUIRE;
1552 
1553 	if (pf_key_v2_msg_add(flow, (struct sadb_ext *)&flowtype, 0) == -1)
1554 		goto cleanup;
1555 
1556 	/*
1557 	 * Setup the ADDRESS extensions.
1558 	 */
1559 	len = sizeof *addr + PF_KEY_V2_ROUND(SA_LEN(src));
1560 	if (!delete)
1561 	{
1562 		addr = calloc(1, len);
1563 		if (!addr)
1564 			goto cleanup;
1565 		addr->sadb_address_exttype = SADB_EXT_ADDRESS_DST;
1566 		addr->sadb_address_len = len / PF_KEY_V2_CHUNK;
1567 		addr->sadb_address_reserved = 0;
1568 		pf_key_v2_setup_sockaddr(addr + 1, src, dst, 0, ingress);
1569 		if (pf_key_v2_msg_add(flow, (struct sadb_ext *) addr,
1570 		    PF_KEY_V2_NODE_MALLOCED) == -1)
1571 			goto cleanup;
1572 		addr = 0;
1573 	}
1574 	len = sizeof *addr + PF_KEY_V2_ROUND(SA_LEN(laddr));
1575 	addr = calloc(1, len);
1576 	if (!addr)
1577 		goto cleanup;
1578 	addr->sadb_address_exttype = SADB_X_EXT_SRC_FLOW;
1579 	addr->sadb_address_len = len / PF_KEY_V2_CHUNK;
1580 	addr->sadb_address_reserved = 0;
1581 	pf_key_v2_setup_sockaddr(addr + 1, laddr, 0, sport, 0);
1582 	if (pf_key_v2_msg_add(flow, (struct sadb_ext *) addr,
1583 	    PF_KEY_V2_NODE_MALLOCED) == -1)
1584 		goto cleanup;
1585 	addr = 0;
1586 
1587 	addr = calloc(1, len);
1588 	if (!addr)
1589 		goto cleanup;
1590 	addr->sadb_address_exttype = SADB_X_EXT_SRC_MASK;
1591 	addr->sadb_address_len = len / PF_KEY_V2_CHUNK;
1592 	addr->sadb_address_reserved = 0;
1593 	pf_key_v2_setup_sockaddr(addr + 1, lmask, 0, sport ? 0xffff : 0, 0);
1594 	if (pf_key_v2_msg_add(flow, (struct sadb_ext *) addr,
1595 	    PF_KEY_V2_NODE_MALLOCED) == -1)
1596 		goto cleanup;
1597 	addr = 0;
1598 
1599 	addr = calloc(1, len);
1600 	if (!addr)
1601 		goto cleanup;
1602 	addr->sadb_address_exttype = SADB_X_EXT_DST_FLOW;
1603 	addr->sadb_address_len = len / PF_KEY_V2_CHUNK;
1604 	addr->sadb_address_reserved = 0;
1605 	pf_key_v2_setup_sockaddr(addr + 1, raddr, 0, dport, 0);
1606 	if (pf_key_v2_msg_add(flow, (struct sadb_ext *) addr,
1607 	    PF_KEY_V2_NODE_MALLOCED) == -1)
1608 		goto cleanup;
1609 	addr = 0;
1610 
1611 	addr = calloc(1, len);
1612 	if (!addr)
1613 		goto cleanup;
1614 	addr->sadb_address_exttype = SADB_X_EXT_DST_MASK;
1615 	addr->sadb_address_len = len / PF_KEY_V2_CHUNK;
1616 	addr->sadb_address_reserved = 0;
1617 	pf_key_v2_setup_sockaddr(addr + 1, rmask, 0, dport ? 0xffff : 0, 0);
1618 	if (pf_key_v2_msg_add(flow, (struct sadb_ext *) addr,
1619 	    PF_KEY_V2_NODE_MALLOCED) == -1)
1620 		goto cleanup;
1621 	addr = 0;
1622 
1623 	/* Setup the protocol extension.  */
1624 	bzero(&tprotocol, sizeof tprotocol);
1625 	tprotocol.sadb_protocol_exttype = SADB_X_EXT_PROTOCOL;
1626 	tprotocol.sadb_protocol_len = sizeof tprotocol / PF_KEY_V2_CHUNK;
1627 	tprotocol.sadb_protocol_proto = tproto;
1628 
1629 	if (pf_key_v2_msg_add(flow, (struct sadb_ext *)&tprotocol, 0) == -1)
1630 		goto cleanup;
1631 
1632 	if (sockaddr2text(laddr, &laddr_str, 0))
1633 		laddr_str = 0;
1634 	if (sockaddr2text(lmask, &lmask_str, 0))
1635 		lmask_str = 0;
1636 	if (sockaddr2text(raddr, &raddr_str, 0))
1637 		raddr_str = 0;
1638 	if (sockaddr2text(rmask, &rmask_str, 0))
1639 		rmask_str = 0;
1640 
1641 	LOG_DBG((LOG_SYSDEP, 50,
1642 	   "pf_key_v2_flow: src %s %s dst %s %s proto %u sport %u dport %u",
1643 	 laddr_str ? laddr_str : "<??\?>", lmask_str ? lmask_str : "<??\?>",
1644 	 raddr_str ? raddr_str : "<??\?>", rmask_str ? rmask_str : "<??\?>",
1645 		 tproto, ntohs(sport), ntohs(dport)));
1646 
1647 	free(laddr_str);
1648 	free(lmask_str);
1649 	free(raddr_str);
1650 	free(rmask_str);
1651 
1652 	ret = pf_key_v2_call(flow);
1653 	pf_key_v2_msg_free(flow);
1654 	flow = 0;
1655 	if (!ret)
1656 		goto cleanup;
1657 	err = ((struct sadb_msg *)TAILQ_FIRST(ret)->seg)->sadb_msg_errno;
1658 	if (err) {
1659 		if (err == ESRCH)	/* These are common and usually
1660 					 * harmless.  */
1661 			LOG_DBG((LOG_SYSDEP, 10, "pf_key_v2_flow: %sFLOW: %s",
1662 				 delete ? "DEL" : "ADD", strerror(err)));
1663 		else
1664 			log_print("pf_key_v2_flow: %sFLOW: %s",
1665 			    delete ? "DEL" : "ADD", strerror(err));
1666 		goto cleanup;
1667 	}
1668 	pf_key_v2_msg_free(ret);
1669 
1670 	LOG_DBG((LOG_MISC, 50, "pf_key_v2_flow: %sFLOW: done",
1671 		 delete ? "DEL" : "ADD"));
1672 
1673 	return 0;
1674 
1675 cleanup:
1676 	free(sid);
1677 	free(addr);
1678 	if (flow)
1679 		pf_key_v2_msg_free(flow);
1680 	if (ret)
1681 		pf_key_v2_msg_free(ret);
1682 	return -1;
1683 }
1684 
1685 static u_int8_t *
1686 pf_key_v2_convert_id(u_int8_t *id, int idlen, size_t *reslen, int *idtype)
1687 {
1688 	u_int8_t       *addr, *res = 0;
1689 	char		addrbuf[ADDRESS_MAX + 5];
1690 
1691 	switch (id[0]) {
1692 	case IPSEC_ID_FQDN:
1693 		res = calloc(idlen - ISAKMP_ID_DATA_OFF + ISAKMP_GEN_SZ,
1694 		    sizeof(u_int8_t));
1695 		if (!res)
1696 			return 0;
1697 
1698 		*reslen = idlen - ISAKMP_ID_DATA_OFF + ISAKMP_GEN_SZ;
1699 		memcpy(res, id + ISAKMP_ID_DATA_OFF - ISAKMP_GEN_SZ, *reslen);
1700 		*idtype = SADB_IDENTTYPE_FQDN;
1701 		LOG_DBG((LOG_SYSDEP, 40, "pf_key_v2_convert_id: FQDN %.*s",
1702 		    (int) *reslen, res));
1703 		return res;
1704 
1705 	case IPSEC_ID_USER_FQDN:
1706 		res = calloc(idlen - ISAKMP_ID_DATA_OFF + ISAKMP_GEN_SZ,
1707 		    sizeof(u_int8_t));
1708 		if (!res)
1709 			return 0;
1710 
1711 		*reslen = idlen - ISAKMP_ID_DATA_OFF + ISAKMP_GEN_SZ;
1712 		memcpy(res, id + ISAKMP_ID_DATA_OFF - ISAKMP_GEN_SZ, *reslen);
1713 		*idtype = SADB_IDENTTYPE_USERFQDN;
1714 		LOG_DBG((LOG_SYSDEP, 40, "pf_key_v2_convert_id: UFQDN %.*s",
1715 		    (int) *reslen, res));
1716 		return res;
1717 
1718 	case IPSEC_ID_IPV4_ADDR:
1719 		if (inet_ntop(AF_INET, id + ISAKMP_ID_DATA_OFF - ISAKMP_GEN_SZ,
1720 		    addrbuf, ADDRESS_MAX) == NULL)
1721 			return 0;
1722 		*reslen = strlen(addrbuf) + 3;
1723 		strlcat(addrbuf, "/32", ADDRESS_MAX + 5);
1724 		res = (u_int8_t *) strdup(addrbuf);
1725 		if (!res)
1726 			return 0;
1727 		*idtype = SADB_IDENTTYPE_PREFIX;
1728 		LOG_DBG((LOG_SYSDEP, 40, "pf_key_v2_convert_id: "
1729 		    "IPv4 address %s", res));
1730 		return res;
1731 
1732 	case IPSEC_ID_IPV6_ADDR:
1733 		if (inet_ntop(AF_INET6,
1734 		    id + ISAKMP_ID_DATA_OFF - ISAKMP_GEN_SZ,
1735 		    addrbuf, ADDRESS_MAX) == NULL)
1736 			return 0;
1737 		*reslen = strlen(addrbuf) + 4;
1738 		strlcat(addrbuf, "/128", ADDRESS_MAX + 5);
1739 		res = (u_int8_t *) strdup(addrbuf);
1740 		if (!res)
1741 			return 0;
1742 		LOG_DBG((LOG_SYSDEP, 40, "pf_key_v2_convert_id: "
1743 		    "IPv6 address %s", res));
1744 		*idtype = SADB_IDENTTYPE_PREFIX;
1745 		return res;
1746 
1747 	case IPSEC_ID_IPV4_ADDR_SUBNET:	/* XXX PREFIX */
1748 		addr = id + ISAKMP_ID_DATA_OFF - ISAKMP_GEN_SZ;
1749 		if (inet_ntop(AF_INET, addr, addrbuf, ADDRESS_MAX) == NULL)
1750 			return 0;
1751 		snprintf(addrbuf + strlen(addrbuf),
1752 		    ADDRESS_MAX - strlen(addrbuf), "/%d",
1753 		    pf_key_v2_mask_to_bits(*(u_int32_t *)(addr +
1754 			sizeof(struct in_addr))));
1755 		*reslen = strlen(addrbuf);
1756 		res = (u_int8_t *) strdup(addrbuf);
1757 		if (!res)
1758 			return 0;
1759 		*idtype = SADB_IDENTTYPE_PREFIX;
1760 		LOG_DBG((LOG_SYSDEP, 40, "pf_key_v2_convert_id: "
1761 		    "IPv4 subnet %s", res));
1762 		return res;
1763 
1764 	case IPSEC_ID_IPV6_ADDR_SUBNET:	/* XXX PREFIX */
1765 		addr = id + ISAKMP_ID_DATA_OFF - ISAKMP_GEN_SZ;
1766 		if (inet_ntop(AF_INET6, addr, addrbuf, ADDRESS_MAX) == NULL)
1767 			return 0;
1768 		snprintf(addrbuf + strlen(addrbuf),
1769 		    ADDRESS_MAX - strlen(addrbuf), "/%d",
1770 		    pf_key_v2_mask6_to_bits(addr +
1771 			sizeof(struct in6_addr)));
1772 		*reslen = strlen(addrbuf);
1773 		res = (u_int8_t *) strdup(addrbuf);
1774 		if (!res)
1775 			return 0;
1776 		LOG_DBG((LOG_SYSDEP, 40, "pf_key_v2_convert_id: "
1777 		    "IPv6 subnet %s", res));
1778 		*idtype = SADB_IDENTTYPE_PREFIX;
1779 		return res;
1780 
1781 	case IPSEC_ID_IPV4_RANGE:
1782 	case IPSEC_ID_IPV6_RANGE:
1783 	case IPSEC_ID_DER_ASN1_DN:
1784 	case IPSEC_ID_DER_ASN1_GN:
1785 	case IPSEC_ID_KEY_ID:
1786 		/* XXX Not implemented yet.  */
1787 		return 0;
1788 	}
1789 
1790 	return 0;
1791 }
1792 
1793 /* Enable a flow given an SA.  */
1794 int
1795 pf_key_v2_enable_sa(struct sa *sa, struct sa *isakmp_sa)
1796 {
1797 	struct ipsec_sa *isa = sa->data;
1798 	struct sockaddr *dst, *src;
1799 	int		error;
1800 	struct proto   *proto = TAILQ_FIRST(&sa->protos);
1801 	int		sidtype = 0, didtype = 0;
1802 	size_t		sidlen = 0, didlen = 0;
1803 	u_int8_t       *sid = 0, *did = 0;
1804 
1805 	sa->transport->vtbl->get_dst(sa->transport, &dst);
1806 	sa->transport->vtbl->get_src(sa->transport, &src);
1807 
1808 	if (isakmp_sa->id_i) {
1809 		if (isakmp_sa->initiator)
1810 			sid = pf_key_v2_convert_id(isakmp_sa->id_i,
1811 			    isakmp_sa->id_i_len, &sidlen, &sidtype);
1812 		else
1813 			did = pf_key_v2_convert_id(isakmp_sa->id_i,
1814 			    isakmp_sa->id_i_len, &didlen, &didtype);
1815 	}
1816 	if (isakmp_sa->id_r) {
1817 		if (isakmp_sa->initiator)
1818 			did = pf_key_v2_convert_id(isakmp_sa->id_r,
1819 			    isakmp_sa->id_r_len, &didlen, &didtype);
1820 		else
1821 			sid = pf_key_v2_convert_id(isakmp_sa->id_r,
1822 			    isakmp_sa->id_r_len, &sidlen, &sidtype);
1823 	}
1824 
1825 	error = pf_key_v2_flow(isa->src_net, isa->src_mask, isa->dst_net,
1826 	    isa->dst_mask, isa->tproto, isa->sport, isa->dport, proto->spi[0],
1827 	    proto->proto, dst, src, 0, 0, sidtype, sid, sidlen, didtype, did,
1828 	    didlen, proto->data);
1829 	if (error)
1830 		goto cleanup;
1831 
1832 	error = pf_key_v2_flow(isa->dst_net, isa->dst_mask, isa->src_net,
1833 	    isa->src_mask, isa->tproto, isa->dport, isa->sport, proto->spi[1],
1834 	    proto->proto, src, dst, 0, 1, sidtype, sid, sidlen, didtype, did,
1835 	    didlen, proto->data);
1836 
1837 cleanup:
1838 	free(sid);
1839 	free(did);
1840 
1841 	return error;
1842 }
1843 
1844 /* Increase reference count of refcounted sections. */
1845 static int
1846 pf_key_v2_conf_refinc(int af, char *section)
1847 {
1848 	char		conn[22];
1849 	int		num;
1850 
1851 	if (!section)
1852 		return 0;
1853 
1854 	num = conf_get_num(section, "Refcount", 0);
1855 	if (num == 0)
1856 		return 0;
1857 
1858 	snprintf(conn, sizeof conn, "%d", num + 1);
1859 	conf_set(af, section, "Refcount", conn, 1, 0);
1860 	return 0;
1861 }
1862 
1863 /*
1864  * Return 0 if the section didn't exist or was removed, non-zero otherwise.
1865  * Don't touch non-refcounted (statically defined) sections.
1866  */
1867 static int
1868 pf_key_v2_conf_refhandle(int af, char *section)
1869 {
1870 	char		conn[22];
1871 	int		num;
1872 
1873 	if (!section)
1874 		return 0;
1875 
1876 	num = conf_get_num(section, "Refcount", 0);
1877 	if (num == 1) {
1878 		conf_remove_section(af, section);
1879 		num--;
1880 	} else if (num != 0) {
1881 		snprintf(conn, sizeof conn, "%d", num - 1);
1882 		conf_set(af, section, "Refcount", conn, 1, 0);
1883 	}
1884 	return num;
1885 }
1886 
1887 /* Remove all dynamically-established configuration entries.  */
1888 static int
1889 pf_key_v2_remove_conf(char *section)
1890 {
1891 	char           *ikepeer, *localid, *remoteid, *configname;
1892 	struct conf_list_node *attr;
1893 	struct conf_list *attrs;
1894 	int		af;
1895 
1896 	if (!section)
1897 		return 0;
1898 
1899 	if (!conf_get_str(section, "Phase"))
1900 		return 0;
1901 
1902 	/* Only remove dynamically-established entries. */
1903 	attrs = conf_get_list(section, "Flags");
1904 	if (attrs) {
1905 		for (attr = TAILQ_FIRST(&attrs->fields); attr;
1906 		    attr = TAILQ_NEXT(attr, link))
1907 			if (!strcasecmp(attr->field, "__ondemand"))
1908 				goto passed;
1909 
1910 		conf_free_list(attrs);
1911 	}
1912 	return 0;
1913 
1914 passed:
1915 	conf_free_list(attrs);
1916 
1917 	af = conf_begin();
1918 
1919 	configname = conf_get_str(section, "Configuration");
1920 	pf_key_v2_conf_refhandle(af, configname);
1921 
1922 	/* These are the Phase 2 Local/Remote IDs. */
1923 	localid = conf_get_str(section, "Local-ID");
1924 	pf_key_v2_conf_refhandle(af, localid);
1925 
1926 	remoteid = conf_get_str(section, "Remote-ID");
1927 	pf_key_v2_conf_refhandle(af, remoteid);
1928 
1929 	ikepeer = conf_get_str(section, "ISAKMP-peer");
1930 
1931 	pf_key_v2_conf_refhandle(af, section);
1932 
1933 	if (ikepeer) {
1934 		remoteid = conf_get_str(ikepeer, "Remote-ID");
1935 		localid = conf_get_str(ikepeer, "ID");
1936 		configname = conf_get_str(ikepeer, "Configuration");
1937 
1938 		pf_key_v2_conf_refhandle(af, ikepeer);
1939 		pf_key_v2_conf_refhandle(af, configname);
1940 
1941 		/* Phase 1 IDs */
1942 		pf_key_v2_conf_refhandle(af, localid);
1943 		pf_key_v2_conf_refhandle(af, remoteid);
1944 	}
1945 	conf_end(af, 1);
1946 	return 0;
1947 }
1948 
1949 /* Disable a flow given a SA.  */
1950 int
1951 pf_key_v2_disable_sa(struct sa *sa, int incoming)
1952 {
1953 	struct ipsec_sa *isa = sa->data;
1954 	struct sockaddr *dst, *src;
1955 	struct proto   *proto = TAILQ_FIRST(&sa->protos);
1956 
1957 	sa->transport->vtbl->get_dst(sa->transport, &dst);
1958 	sa->transport->vtbl->get_src(sa->transport, &src);
1959 
1960 	if (!incoming)
1961 		return pf_key_v2_flow(isa->src_net, isa->src_mask,
1962 		    isa->dst_net, isa->dst_mask, isa->tproto, isa->sport,
1963 		    isa->dport, proto->spi[0], proto->proto, src, dst, 1, 0,
1964 		    0, 0, 0, 0, 0, 0, proto->data);
1965 	else {
1966 		return pf_key_v2_flow(isa->dst_net, isa->dst_mask,
1967 		    isa->src_net, isa->src_mask, isa->tproto, isa->dport,
1968 		    isa->sport, proto->spi[1], proto->proto, src, dst, 1, 1,
1969 		    0, 0, 0, 0, 0, 0, proto->data);
1970 	}
1971 }
1972 
1973 /*
1974  * Delete the IPsec SA represented by the INCOMING direction in protocol PROTO
1975  * of the IKE security association SA.  Also delete potential flows tied to it.
1976  */
1977 int
1978 pf_key_v2_delete_spi(struct sa *sa, struct proto *proto, int incoming)
1979 {
1980 	struct sadb_msg msg;
1981 	struct sadb_sa  ssa;
1982 	struct sadb_address *addr = 0;
1983 	struct sockaddr *saddr;
1984 	int		len, err;
1985 	struct pf_key_v2_msg *delete = 0, *ret = 0;
1986 
1987 	/* If it's not an established SA, don't proceed. */
1988 	if (!(sa->flags & SA_FLAG_READY))
1989 		return 0;
1990 
1991 	if (sa->name && !(sa->flags & SA_FLAG_REPLACED)) {
1992 		LOG_DBG((LOG_SYSDEP, 50,
1993 			 "pf_key_v2_delete_spi: removing configuration %s",
1994 			 sa->name));
1995 		pf_key_v2_remove_conf(sa->name);
1996 	}
1997 	msg.sadb_msg_type = SADB_DELETE;
1998 	switch (proto->proto) {
1999 	case IPSEC_PROTO_IPSEC_ESP:
2000 		msg.sadb_msg_satype = SADB_SATYPE_ESP;
2001 		break;
2002 	case IPSEC_PROTO_IPSEC_AH:
2003 		msg.sadb_msg_satype = SADB_SATYPE_AH;
2004 		break;
2005 	case IPSEC_PROTO_IPCOMP:
2006 		msg.sadb_msg_satype = SADB_X_SATYPE_IPCOMP;
2007 		break;
2008 	default:
2009 		log_print("pf_key_v2_delete_spi: invalid proto %d",
2010 		    proto->proto);
2011 		goto cleanup;
2012 	}
2013 	msg.sadb_msg_seq = 0;
2014 	delete = pf_key_v2_msg_new(&msg, 0);
2015 	if (!delete)
2016 		goto cleanup;
2017 
2018 	/* Setup the SA extension.  */
2019 	ssa.sadb_sa_exttype = SADB_EXT_SA;
2020 	ssa.sadb_sa_len = sizeof ssa / PF_KEY_V2_CHUNK;
2021 	memcpy(&ssa.sadb_sa_spi, proto->spi[incoming], sizeof ssa.sadb_sa_spi);
2022 	ssa.sadb_sa_replay = 0;
2023 	ssa.sadb_sa_state = 0;
2024 	ssa.sadb_sa_auth = 0;
2025 	ssa.sadb_sa_encrypt = 0;
2026 	ssa.sadb_sa_flags = 0;
2027 	if (pf_key_v2_msg_add(delete, (struct sadb_ext *)&ssa, 0) == -1)
2028 		goto cleanup;
2029 
2030 	/*
2031 	 * Setup the ADDRESS extensions.
2032 	 */
2033 	if (incoming)
2034 		sa->transport->vtbl->get_dst(sa->transport, &saddr);
2035 	else
2036 		sa->transport->vtbl->get_src(sa->transport, &saddr);
2037 	len = sizeof *addr + PF_KEY_V2_ROUND(SA_LEN(saddr));
2038 	addr = calloc(1, len);
2039 	if (!addr)
2040 		goto cleanup;
2041 	addr->sadb_address_exttype = SADB_EXT_ADDRESS_SRC;
2042 	addr->sadb_address_len = len / PF_KEY_V2_CHUNK;
2043 	addr->sadb_address_reserved = 0;
2044 	memcpy(addr + 1, saddr, SA_LEN(saddr));
2045 	switch (saddr->sa_family) {
2046 	case AF_INET:
2047 		((struct sockaddr_in *) (addr + 1))->sin_port = 0;
2048 		break;
2049 	case AF_INET6:
2050 		((struct sockaddr_in6 *) (addr + 1))->sin6_port = 0;
2051 		break;
2052 	}
2053 	if (pf_key_v2_msg_add(delete, (struct sadb_ext *) addr,
2054 	    PF_KEY_V2_NODE_MALLOCED) == -1)
2055 		goto cleanup;
2056 	addr = 0;
2057 
2058 	if (incoming)
2059 		sa->transport->vtbl->get_src(sa->transport, &saddr);
2060 	else
2061 		sa->transport->vtbl->get_dst(sa->transport, &saddr);
2062 	len = sizeof *addr + PF_KEY_V2_ROUND(SA_LEN(saddr));
2063 	addr = calloc(1, len);
2064 	if (!addr)
2065 		goto cleanup;
2066 	addr->sadb_address_exttype = SADB_EXT_ADDRESS_DST;
2067 	addr->sadb_address_len = len / PF_KEY_V2_CHUNK;
2068 	addr->sadb_address_reserved = 0;
2069 	memcpy(addr + 1, saddr, SA_LEN(saddr));
2070 	switch (saddr->sa_family) {
2071 	case AF_INET:
2072 		((struct sockaddr_in *) (addr + 1))->sin_port = 0;
2073 		break;
2074 	case AF_INET6:
2075 		((struct sockaddr_in6 *) (addr + 1))->sin6_port = 0;
2076 		break;
2077 	}
2078 	if (pf_key_v2_msg_add(delete, (struct sadb_ext *) addr,
2079 	    PF_KEY_V2_NODE_MALLOCED) == -1)
2080 		goto cleanup;
2081 	addr = 0;
2082 
2083 	ret = pf_key_v2_call(delete);
2084 	pf_key_v2_msg_free(delete);
2085 	delete = 0;
2086 	if (!ret)
2087 		goto cleanup;
2088 	err = ((struct sadb_msg *)TAILQ_FIRST(ret)->seg)->sadb_msg_errno;
2089 	if (err) {
2090 		LOG_DBG((LOG_SYSDEP, 10, "pf_key_v2_delete_spi: DELETE: %s",
2091 			 strerror(err)));
2092 		goto cleanup;
2093 	}
2094 	pf_key_v2_msg_free(ret);
2095 
2096 	LOG_DBG((LOG_SYSDEP, 50, "pf_key_v2_delete_spi: done"));
2097 
2098 	return 0;
2099 
2100 cleanup:
2101 	free(addr);
2102 	if (delete)
2103 		pf_key_v2_msg_free(delete);
2104 	if (ret)
2105 		pf_key_v2_msg_free(ret);
2106 	return -1;
2107 }
2108 
2109 static void
2110 pf_key_v2_stayalive(struct exchange *exchange, void *vconn, int fail)
2111 {
2112 	char           *conn = vconn;
2113 	struct sa      *sa;
2114 
2115 	/* XXX What if it is phase 1 ? */
2116 	sa = sa_lookup_by_name(conn, 2);
2117 	if (sa)
2118 		sa->flags |= SA_FLAG_STAYALIVE;
2119 
2120 	/*
2121 	 * Remove failed configuration entry -- call twice because it is
2122 	 * created with a Refcount of 2.
2123 	 */
2124 	if (fail && (!exchange || exchange->name)) {
2125 		pf_key_v2_remove_conf(conn);
2126 		pf_key_v2_remove_conf(conn);
2127 	}
2128 	free(conn);
2129 }
2130 
2131 /* Check if a connection CONN exists, otherwise establish it.  */
2132 void
2133 pf_key_v2_connection_check(char *conn)
2134 {
2135 	if (!sa_lookup_by_name(conn, 2)) {
2136 		LOG_DBG((LOG_SYSDEP, 70,
2137 		    "pf_key_v2_connection_check: SA for %s missing", conn));
2138 		exchange_establish(conn, pf_key_v2_stayalive, conn, 0);
2139 	} else {
2140 		LOG_DBG((LOG_SYSDEP, 70, "pf_key_v2_connection_check: "
2141 		    "SA for %s exists", conn));
2142 		free(conn);
2143 	}
2144 }
2145 
2146 /* Handle a PF_KEY lifetime expiration message PMSG.  */
2147 static void
2148 pf_key_v2_expire(struct pf_key_v2_msg *pmsg)
2149 {
2150 	struct sadb_msg *msg;
2151 	struct sadb_sa *ssa;
2152 	struct sadb_address *dst;
2153 	struct sockaddr *dstaddr;
2154 	struct sadb_lifetime *life, *lifecurrent;
2155 	struct sa      *sa;
2156 	struct pf_key_v2_node *lifenode, *ext;
2157 	char           *dst_str;
2158 
2159 	msg = (struct sadb_msg *)TAILQ_FIRST(pmsg)->seg;
2160 	ext = pf_key_v2_find_ext(pmsg, SADB_EXT_SA);
2161 	if (!ext) {
2162 		log_print("pf_key_v2_expire: no SA extension found");
2163 		return;
2164 	}
2165 	ssa = ext->seg;
2166 	ext = pf_key_v2_find_ext(pmsg, SADB_EXT_ADDRESS_DST);
2167 	if (!ext) {
2168 		log_print("pf_key_v2_expire: "
2169 		    "no destination address extension found");
2170 		return;
2171 	}
2172 	dst = ext->seg;
2173 	dstaddr = (struct sockaddr *) (dst + 1);
2174 	lifenode = pf_key_v2_find_ext(pmsg, SADB_EXT_LIFETIME_HARD);
2175 	if (!lifenode)
2176 		lifenode = pf_key_v2_find_ext(pmsg, SADB_EXT_LIFETIME_SOFT);
2177 	if (!lifenode) {
2178 		log_print("pf_key_v2_expire: no lifetime extension found");
2179 		return;
2180 	}
2181 	life = lifenode->seg;
2182 
2183 	lifenode = pf_key_v2_find_ext(pmsg, SADB_EXT_LIFETIME_CURRENT);
2184 	if (!lifenode) {
2185 		log_print("pf_key_v2_expire: "
2186 		    "no current lifetime extension found");
2187 		return;
2188 	}
2189 	lifecurrent = lifenode->seg;
2190 
2191 	if (sockaddr2text(dstaddr, &dst_str, 0))
2192 		dst_str = 0;
2193 
2194 	LOG_DBG((LOG_SYSDEP, 20, "pf_key_v2_expire: "
2195 	    "%s dst %s SPI %x sproto %d",
2196 	    life->sadb_lifetime_exttype == SADB_EXT_LIFETIME_SOFT ? "SOFT"
2197 	    : "HARD", dst_str ? dst_str : "<unknown>",
2198 	    ntohl(ssa->sadb_sa_spi), msg->sadb_msg_satype));
2199 
2200 	free(dst_str);
2201 
2202 	/*
2203 	 * Find the IPsec SA.  The IPsec stack has two SAs for every IKE SA,
2204 	 * one outgoing and one incoming, we regard expirations for any of
2205 	 * them as an expiration of the full IKE SA.  Likewise, in
2206 	 * protection suites consisting of more than one protocol, any
2207 	 * expired individual IPsec stack SA will be seen as an expiration
2208 	 * of the full suite.
2209 	 */
2210 	switch (msg->sadb_msg_satype) {
2211 	case SADB_SATYPE_ESP:
2212 		sa = ipsec_sa_lookup(dstaddr, ssa->sadb_sa_spi,
2213 		    IPSEC_PROTO_IPSEC_ESP);
2214 		break;
2215 
2216 	case SADB_SATYPE_AH:
2217 		sa = ipsec_sa_lookup(dstaddr, ssa->sadb_sa_spi,
2218 		    IPSEC_PROTO_IPSEC_AH);
2219 		break;
2220 
2221 	case SADB_X_SATYPE_IPCOMP:
2222 		sa = ipsec_sa_lookup(dstaddr, ssa->sadb_sa_spi,
2223 		    IPSEC_PROTO_IPCOMP);
2224 		break;
2225 
2226 	default:
2227 		/* XXX Log? */
2228 		sa = 0;
2229 		break;
2230 	}
2231 
2232 	/* If the SA is already gone, don't do anything.  */
2233 	if (!sa)
2234 		return;
2235 
2236 	/*
2237 	 * If we got a notification, try to renegotiate the SA -- unless of
2238 	 * course it has already been replaced by another.
2239 	 * Also, ignore SAs that were not dynamically established, or that
2240 	 * did not see any use.
2241 	 */
2242 	if (!(sa->flags & SA_FLAG_REPLACED) &&
2243 	    (sa->flags & SA_FLAG_ONDEMAND) &&
2244 	    lifecurrent->sadb_lifetime_bytes)
2245 		exchange_establish(sa->name, 0, 0, 0);
2246 
2247 	if (life->sadb_lifetime_exttype == SADB_EXT_LIFETIME_HARD) {
2248 		/* Remove the old SA, it isn't useful anymore.  */
2249 		sa_free(sa);
2250 	}
2251 }
2252 
2253 static int
2254 mask4len(const struct sockaddr_in *mask)
2255 {
2256 	int len;
2257 	u_int32_t m;
2258 
2259 	len = 0;
2260 	for (m = 0x80000000; m & ntohl(mask->sin_addr.s_addr); m >>= 1)
2261 		len++;
2262 	if (len == 32)
2263 		len = -1;
2264 	return len;
2265 }
2266 
2267 #ifndef s6_addr8
2268 #define s6_addr8 __u6_addr.__u6_addr8
2269 #endif
2270 
2271 static int
2272 mask6len(const struct sockaddr_in6 *mask)
2273 {
2274 	int i, len;
2275 	u_int8_t m;
2276 
2277 	len = 0;
2278 	for (i = 0, m = 0; i < 16 && !m; i++)
2279 		for (m = 0x80; m & mask->sin6_addr.s6_addr8[i]; m >>= 1)
2280 			len++;
2281 	if (len == 128)
2282 		len = -1;
2283 	return len;
2284 }
2285 
2286 static int
2287 phase2id(char *str, size_t size, const char *side, const char *sflow,
2288     int masklen, u_int8_t proto, u_int16_t port)
2289 {
2290 	char smasklen[10], sproto[10], sport[10];
2291 
2292 	smasklen[0] = sproto[0] = sport[0] = 0;
2293 	if (masklen != -1)
2294 		snprintf(smasklen, sizeof smasklen, "/%d", masklen);
2295 	if (proto)
2296 		snprintf(sproto, sizeof sproto, "=%u", proto);
2297 	if (port)
2298 		snprintf(sport, sizeof sport, ":%u", ntohs(port));
2299 
2300 	return snprintf(str, size, "%s-%s%s%s%s", side, sflow, smasklen,
2301 	    sproto, sport);
2302 }
2303 
2304 /* Handle a PF_KEY SA ACQUIRE message PMSG.  */
2305 static void
2306 pf_key_v2_acquire(struct pf_key_v2_msg *pmsg)
2307 {
2308 	struct sadb_msg *msg, askpolicy_msg;
2309 	struct pf_key_v2_msg *askpolicy = 0, *ret = 0;
2310 	struct sadb_x_policy policy;
2311 	struct sadb_address *dst = 0, *src = 0;
2312 	struct sockaddr *dstaddr, *srcaddr = 0;
2313 	struct sadb_comb *scmb = 0;
2314 	struct sadb_prop *sprp = 0;
2315 	struct sadb_ident *srcident = 0, *dstident = 0;
2316 	char		dstbuf[ADDRESS_MAX], srcbuf[ADDRESS_MAX], *peer = 0;
2317 	char		confname[120], *conn = 0;
2318 	char           *srcid = 0, *dstid = 0, *prefstring = 0;
2319 	int		slen, af, afamily, masklen;
2320 	struct sockaddr *smask, *sflow, *dmask, *dflow;
2321 	struct sadb_protocol *sproto;
2322 	char		ssflow[ADDRESS_MAX], sdflow[ADDRESS_MAX];
2323 	char		sdmask[ADDRESS_MAX], ssmask[ADDRESS_MAX];
2324 	int		dmasklen, smasklen;
2325 	char           *sidtype = 0, *didtype = 0;
2326 	char		lname[100], dname[100], configname[200];
2327 	int		shostflag = 0, dhostflag = 0;
2328 	struct pf_key_v2_node *ext;
2329 	struct passwd  *pwd = 0;
2330 	u_int16_t       sport = 0, dport = 0;
2331 	u_int8_t	tproto = 0;
2332 	char		tmbuf[sizeof sport * 3 + 1], *xform;
2333 	int		connlen;
2334 
2335 	/* This needs to be dynamically allocated. */
2336 	connlen = 22;
2337 	conn = malloc(connlen);
2338 	if (!conn) {
2339 		log_error("pf_key_v2_acquire: malloc (%d) failed", connlen);
2340 		return;
2341 	}
2342 	msg = (struct sadb_msg *)TAILQ_FIRST(pmsg)->seg;
2343 
2344 	ext = pf_key_v2_find_ext(pmsg, SADB_EXT_ADDRESS_DST);
2345 	if (!ext) {
2346 		log_print("pf_key_v2_acquire: "
2347 		    "no destination address specified");
2348 		free(conn);
2349 		return;
2350 	}
2351 	dst = ext->seg;
2352 
2353 	ext = pf_key_v2_find_ext(pmsg, SADB_EXT_ADDRESS_SRC);
2354 	if (ext)
2355 		src = ext->seg;
2356 
2357 	ext = pf_key_v2_find_ext(pmsg, SADB_EXT_PROPOSAL);
2358 	if (ext) {
2359 		sprp = ext->seg;
2360 		scmb = (struct sadb_comb *) (sprp + 1);
2361 	}
2362 	ext = pf_key_v2_find_ext(pmsg, SADB_EXT_IDENTITY_SRC);
2363 	if (ext)
2364 		srcident = ext->seg;
2365 
2366 	ext = pf_key_v2_find_ext(pmsg, SADB_EXT_IDENTITY_DST);
2367 	if (ext)
2368 		dstident = ext->seg;
2369 
2370 	/* Ask the kernel for the matching policy. */
2371 	bzero(&askpolicy_msg, sizeof askpolicy_msg);
2372 	askpolicy_msg.sadb_msg_type = SADB_X_ASKPOLICY;
2373 	askpolicy = pf_key_v2_msg_new(&askpolicy_msg, 0);
2374 	if (!askpolicy)
2375 		goto fail;
2376 
2377 	policy.sadb_x_policy_exttype = SADB_X_EXT_POLICY;
2378 	policy.sadb_x_policy_len = sizeof policy / PF_KEY_V2_CHUNK;
2379 	policy.sadb_x_policy_seq = msg->sadb_msg_seq;
2380 	if (pf_key_v2_msg_add(askpolicy, (struct sadb_ext *)&policy, 0) == -1)
2381 		goto fail;
2382 
2383 	ret = pf_key_v2_call(askpolicy);
2384 	if (!ret)
2385 		goto fail;
2386 
2387 	/* Now we have all the information needed. */
2388 
2389 	ext = pf_key_v2_find_ext(ret, SADB_X_EXT_SRC_FLOW);
2390 	if (!ext) {
2391 		log_print("pf_key_v2_acquire: no source flow extension found");
2392 		goto fail;
2393 	}
2394 	sflow = (struct sockaddr *) (((struct sadb_address *) ext->seg) + 1);
2395 
2396 	ext = pf_key_v2_find_ext(ret, SADB_X_EXT_DST_FLOW);
2397 	if (!ext) {
2398 		log_print("pf_key_v2_acquire: "
2399 		    "no destination flow extension found");
2400 		goto fail;
2401 	}
2402 	dflow = (struct sockaddr *) (((struct sadb_address *) ext->seg) + 1);
2403 	ext = pf_key_v2_find_ext(ret, SADB_X_EXT_SRC_MASK);
2404 	if (!ext) {
2405 		log_print("pf_key_v2_acquire: no source mask extension found");
2406 		goto fail;
2407 	}
2408 	smask = (struct sockaddr *) (((struct sadb_address *) ext->seg) + 1);
2409 
2410 	ext = pf_key_v2_find_ext(ret, SADB_X_EXT_DST_MASK);
2411 	if (!ext) {
2412 		log_print("pf_key_v2_acquire: "
2413 		    "no destination mask extension found");
2414 		goto fail;
2415 	}
2416 	dmask = (struct sockaddr *) (((struct sadb_address *) ext->seg) + 1);
2417 
2418 	ext = pf_key_v2_find_ext(ret, SADB_X_EXT_FLOW_TYPE);
2419 	if (!ext) {
2420 		log_print("pf_key_v2_acquire: no flow type extension found");
2421 		goto fail;
2422 	}
2423 	sproto = ext->seg;
2424 	tproto = sproto->sadb_protocol_proto;
2425 
2426 	bzero(ssflow, sizeof ssflow);
2427 	bzero(sdflow, sizeof sdflow);
2428 	bzero(ssmask, sizeof ssmask);
2429 	bzero(sdmask, sizeof sdmask);
2430 	smasklen = dmasklen = -1;
2431 
2432 	sidtype = didtype = "IPV4_ADDR_SUBNET";	/* default */
2433 
2434 	switch (sflow->sa_family) {
2435 	case AF_INET:
2436 		if (inet_ntop(AF_INET,
2437 		    &((struct sockaddr_in *) sflow)->sin_addr, ssflow,
2438 		    ADDRESS_MAX) == NULL) {
2439 			log_print("pf_key_v2_acquire: inet_ntop failed");
2440 			goto fail;
2441 		}
2442 		sport = ((struct sockaddr_in *) sflow)->sin_port;
2443 		if (inet_ntop(AF_INET,
2444 		    &((struct sockaddr_in *) dflow)->sin_addr, sdflow,
2445 		    ADDRESS_MAX) == NULL) {
2446 			log_print("pf_key_v2_acquire: inet_ntop failed");
2447 			goto fail;
2448 		}
2449 		dport = ((struct sockaddr_in *) dflow)->sin_port;
2450 		if (inet_ntop(AF_INET,
2451 		    &((struct sockaddr_in *) smask)->sin_addr, ssmask,
2452 		    ADDRESS_MAX) == NULL) {
2453 			log_print("pf_key_v2_acquire: inet_ntop failed");
2454 			goto fail;
2455 		}
2456 		if (inet_ntop(AF_INET,
2457 		    &((struct sockaddr_in *) dmask)->sin_addr, sdmask,
2458 		    ADDRESS_MAX) == NULL) {
2459 			log_print("pf_key_v2_acquire: inet_ntop failed");
2460 			goto fail;
2461 		}
2462 		smasklen = mask4len((struct sockaddr_in *) smask);
2463 		dmasklen = mask4len((struct sockaddr_in *) dmask);
2464 		if (((struct sockaddr_in *) smask)->sin_addr.s_addr ==
2465 		    INADDR_BROADCAST) {
2466 			shostflag = 1;
2467 			sidtype = "IPV4_ADDR";
2468 		}
2469 		if (((struct sockaddr_in *) dmask)->sin_addr.s_addr ==
2470 		    INADDR_BROADCAST) {
2471 			dhostflag = 1;
2472 			didtype = "IPV4_ADDR";
2473 		}
2474 		break;
2475 
2476 	case AF_INET6:
2477 		if (inet_ntop(AF_INET6,
2478 		    &((struct sockaddr_in6 *) sflow)->sin6_addr,
2479 		    ssflow, ADDRESS_MAX) == NULL) {
2480 			log_print("pf_key_v2_acquire: inet_ntop failed");
2481 			goto fail;
2482 		}
2483 		sport = ((struct sockaddr_in6 *) sflow)->sin6_port;
2484 		if (inet_ntop(AF_INET6,
2485 		    &((struct sockaddr_in6 *) dflow)->sin6_addr,
2486 		    sdflow, ADDRESS_MAX) == NULL) {
2487 			log_print("pf_key_v2_acquire: inet_ntop failed");
2488 			goto fail;
2489 		}
2490 		dport = ((struct sockaddr_in6 *) dflow)->sin6_port;
2491 		if (inet_ntop(AF_INET6,
2492 		    &((struct sockaddr_in6 *) smask)->sin6_addr,
2493 		    ssmask, ADDRESS_MAX) == NULL) {
2494 			log_print("pf_key_v2_acquire: inet_ntop failed");
2495 			goto fail;
2496 		}
2497 		if (inet_ntop(AF_INET6,
2498 		    &((struct sockaddr_in6 *) dmask)->sin6_addr,
2499 		    sdmask, ADDRESS_MAX) == NULL) {
2500 			log_print("pf_key_v2_acquire: inet_ntop failed");
2501 			goto fail;
2502 		}
2503 		smasklen = mask6len((struct sockaddr_in6 *) smask);
2504 		dmasklen = mask6len((struct sockaddr_in6 *) dmask);
2505 		sidtype = didtype = "IPV6_ADDR_SUBNET";
2506 		if (IN6_IS_ADDR_FULL(&((struct sockaddr_in6 *)smask)->sin6_addr)) {
2507 			shostflag = 1;
2508 			sidtype = "IPV6_ADDR";
2509 		}
2510 		if (IN6_IS_ADDR_FULL(&((struct sockaddr_in6 *)dmask)->sin6_addr)) {
2511 			dhostflag = 1;
2512 			didtype = "IPV6_ADDR";
2513 		}
2514 		break;
2515 	}
2516 
2517 	dstaddr = (struct sockaddr *)(dst + 1);
2518 	bzero(dstbuf, sizeof dstbuf);
2519 	bzero(srcbuf, sizeof srcbuf);
2520 
2521 	if (dstaddr->sa_family == 0) {
2522 		/*
2523 		 * Destination was not specified in the flow -- can we derive
2524 		 * it?
2525 		 */
2526 		if (dhostflag == 0) {
2527 			log_print("pf_key_v2_acquire: "
2528 			    "Cannot determine precise destination");
2529 			goto fail;
2530 		}
2531 		dstaddr = dflow;
2532 	}
2533 	switch (dstaddr->sa_family) {
2534 	case AF_INET:
2535 		if (inet_ntop(AF_INET,
2536 		    &((struct sockaddr_in *) dstaddr)->sin_addr,
2537 		    dstbuf, ADDRESS_MAX) == NULL) {
2538 			log_print("pf_key_v2_acquire: inet_ntop failed");
2539 			goto fail;
2540 		}
2541 		LOG_DBG((LOG_SYSDEP, 20,
2542 		    "pf_key_v2_acquire: dst=%s sproto %d", dstbuf,
2543 		    msg->sadb_msg_satype));
2544 		break;
2545 
2546 	case AF_INET6:
2547 		if (inet_ntop(AF_INET6,
2548 		    &((struct sockaddr_in6 *) dstaddr)->sin6_addr,
2549 		    dstbuf, ADDRESS_MAX) == NULL) {
2550 			log_print("pf_key_v2_acquire: inet_ntop failed");
2551 			goto fail;
2552 		}
2553 		LOG_DBG((LOG_SYSDEP, 20,
2554 		    "pf_key_v2_acquire: dst=%s sproto %d", dstbuf,
2555 		    msg->sadb_msg_satype));
2556 		break;
2557 	}
2558 
2559 	if (src) {
2560 		srcaddr = (struct sockaddr *) (src + 1);
2561 
2562 		switch (srcaddr->sa_family) {
2563 		case AF_INET:
2564 			if (inet_ntop(AF_INET,
2565 			    &((struct sockaddr_in *) srcaddr)->sin_addr,
2566 			    srcbuf, ADDRESS_MAX) == NULL) {
2567 				log_print("pf_key_v2_acquire: "
2568 				    "inet_ntop failed");
2569 				goto fail;
2570 			}
2571 			break;
2572 
2573 		case AF_INET6:
2574 			if (inet_ntop(AF_INET6,
2575 			    &((struct sockaddr_in6 *)srcaddr)->sin6_addr,
2576 			    srcbuf, ADDRESS_MAX) == NULL) {
2577 				log_print("pf_key_v2_acquire: "
2578 				    "inet_ntop failed");
2579 				goto fail;
2580 			}
2581 			break;
2582 
2583 		default:
2584 			/*
2585 			 * The kernel will pass an all '0' EXT_ADDRESS_SRC if
2586 			 * it wasn't specified for the flow. In that case, do
2587 			 * NOT specify the srcaddr in the Peer-name below
2588 			 */
2589 			srcbuf[0] = 0;
2590 			srcaddr = NULL;
2591 			break;
2592 		}
2593 	}
2594 	/* Insert source ID. */
2595 	if (srcident) {
2596 		slen = (srcident->sadb_ident_len * sizeof(u_int64_t))
2597 			- sizeof(struct sadb_ident);
2598 		if (((unsigned char *) (srcident + 1))[slen - 1] != '\0') {
2599 			log_print("pf_key_v2_acquire: "
2600 			    "source identity not NUL-terminated");
2601 			goto fail;
2602 		}
2603 		/* Check for valid type. */
2604 		switch (srcident->sadb_ident_type) {
2605 		case SADB_IDENTTYPE_PREFIX:
2606 			/* Determine what the address family is. */
2607 			srcid = memchr(srcident + 1, ':', slen);
2608 			if (srcid)
2609 				afamily = AF_INET6;
2610 			else
2611 				afamily = AF_INET;
2612 
2613 			srcid = memchr(srcident + 1, '/', slen);
2614 			if (!srcid) {
2615 				log_print("pf_key_v2_acquire: "
2616 				    "badly formatted PREFIX identity");
2617 				goto fail;
2618 			}
2619 			masklen = atoi(srcid + 1);
2620 
2621 			/* XXX We only support host addresses. */
2622 			if ((afamily == AF_INET6 && masklen != 128) ||
2623 			    (afamily == AF_INET && masklen != 32)) {
2624 				log_print("pf_key_v2_acquire: "
2625 				    "non-host address specified in source "
2626 				    "identity (mask length %d), ignoring "
2627 				    "request", masklen);
2628 				goto fail;
2629 			}
2630 			/*
2631 			 * NUL-terminate the PREFIX string at the separator,
2632 			 * then dup.
2633 			 */
2634 			*srcid = '\0';
2635 			if (asprintf(&srcid, "id-%s",
2636 			    (char *) (srcident + 1)) == -1) {
2637 				log_error("pf_key_v2_acquire: asprintf() failed");
2638 				goto fail;
2639 			}
2640 
2641 			/* Set the section if it doesn't already exist. */
2642 			af = conf_begin();
2643 			if (!conf_get_str(srcid, "ID-type")) {
2644 				if (conf_set(af, srcid, "ID-type",
2645 				    afamily == AF_INET ? "IPV4_ADDR" :
2646 				    "IPV6_ADDR", 1, 0) ||
2647 				    conf_set(af, srcid, "Refcount", "1", 1, 0) ||
2648 				    conf_set(af, srcid, "Address",
2649 					(char *) (srcident + 1), 1, 0)) {
2650 					conf_end(af, 0);
2651 					goto fail;
2652 				}
2653 			} else
2654 				pf_key_v2_conf_refinc(af, srcid);
2655 			conf_end(af, 1);
2656 			break;
2657 
2658 		case SADB_IDENTTYPE_FQDN:
2659 			prefstring = "FQDN";
2660 			/*FALLTHROUGH*/
2661 		case SADB_IDENTTYPE_USERFQDN:
2662 			if (!prefstring) {
2663 				prefstring = "USER_FQDN";
2664 
2665 				/*
2666 				 * Check whether there is a string following
2667 				 * the header; if no, that there is a user ID
2668 				 * (and acquire the login name). If there is
2669 				 * both a string and a user ID, check that
2670 				 * they match.
2671 				 */
2672 				if ((slen == 0) &&
2673 				    (srcident->sadb_ident_id == 0)) {
2674 					log_print("pf_key_v2_acquire: "
2675 					    "no user FQDN or ID provided");
2676 					goto fail;
2677 				}
2678 				if (srcident->sadb_ident_id) {
2679 					pwd =
2680 					    getpwuid(srcident->sadb_ident_id);
2681 					if (!pwd) {
2682 						log_error("pf_key_v2_acquire: "
2683 						    "could not acquire "
2684 						    "username from provided "
2685 						    "ID %llu",
2686 						    srcident->sadb_ident_id);
2687 						goto fail;
2688 					}
2689 					if (slen != 0)
2690 						if (strcmp(pwd->pw_name,
2691 						    (char *) (srcident + 1))
2692 						    != 0) {
2693 							log_print("pf_key_v2_acquire: "
2694 							    "provided user "
2695 							    "name and ID do "
2696 							    "not match (%s != "
2697 							    "%s)",
2698 							    (char *) (srcident + 1),
2699 							    pwd->pw_name);
2700 							/*
2701 							 * String has
2702 							 * precedence, per
2703 							 * RFC 2367.
2704 							 */
2705 						}
2706 				}
2707 			}
2708 			if (asprintf(&srcid, "id-%s",
2709 			    slen ? (char *) (srcident + 1) : pwd->pw_name) == -1) {
2710 				log_error("pf_key_v2_acquire: asprintf() failed");
2711 				goto fail;
2712 			}
2713 			pwd = 0;
2714 
2715 			/* Set the section if it doesn't already exist. */
2716 			af = conf_begin();
2717 			if (!conf_get_str(srcid, "ID-type")) {
2718 				if (conf_set(af, srcid, "ID-type", prefstring,
2719 				    1, 0) ||
2720 				    conf_set(af, srcid, "Refcount", "1", 1, 0) ||
2721 				    conf_set(af, srcid, "Name",
2722 					srcid + 3, 1, 0)) {
2723 					conf_end(af, 0);
2724 					goto fail;
2725 				}
2726 			} else
2727 				pf_key_v2_conf_refinc(af, srcid);
2728 			conf_end(af, 1);
2729 			break;
2730 
2731 		default:
2732 			LOG_DBG((LOG_SYSDEP, 20,
2733 			    "pf_key_v2_acquire: invalid source ID type %d",
2734 			    srcident->sadb_ident_type));
2735 			goto fail;
2736 		}
2737 
2738 		LOG_DBG((LOG_SYSDEP, 50,
2739 		    "pf_key_v2_acquire: constructed source ID \"%s\"", srcid));
2740 		prefstring = 0;
2741 	}
2742 	/* Insert destination ID. */
2743 	if (dstident) {
2744 		slen = (dstident->sadb_ident_len * sizeof(u_int64_t))
2745 			- sizeof(struct sadb_ident);
2746 
2747 		/* Check for valid type. */
2748 		switch (dstident->sadb_ident_type) {
2749 		case SADB_IDENTTYPE_PREFIX:
2750 			/* Determine what the address family is. */
2751 			dstid = memchr(dstident + 1, ':', slen);
2752 			if (dstid)
2753 				afamily = AF_INET6;
2754 			else
2755 				afamily = AF_INET;
2756 
2757 			dstid = memchr(dstident + 1, '/', slen);
2758 			if (!dstid) {
2759 				log_print("pf_key_v2_acquire: "
2760 				    "badly formatted PREFIX identity");
2761 				goto fail;
2762 			}
2763 			masklen = atoi(dstid + 1);
2764 
2765 			/* XXX We only support host addresses. */
2766 			if ((afamily == AF_INET6 && masklen != 128) ||
2767 			    (afamily == AF_INET && masklen != 32)) {
2768 				log_print("pf_key_v2_acquire: "
2769 				    "non-host address specified in "
2770 				    "destination identity (mask length %d), "
2771 				    "ignoring request", masklen);
2772 				goto fail;
2773 			}
2774 			/*
2775 			 * NUL-terminate the PREFIX string at the separator,
2776 			 * then dup.
2777 			 */
2778 			*dstid = '\0';
2779 			if (asprintf(&dstid, "id-%s",
2780 			    (char *) (dstident + 1)) == -1) {
2781 				log_error("pf_key_v2_acquire: asprintf() failed");
2782 				goto fail;
2783 			}
2784 
2785 			/* Set the section if it doesn't already exist. */
2786 			af = conf_begin();
2787 			if (!conf_get_str(dstid, "ID-type")) {
2788 				if (conf_set(af, dstid, "ID-type",
2789 				    afamily == AF_INET ? "IPV4_ADDR" :
2790 				    "IPV6_ADDR", 1, 0) ||
2791 				    conf_set(af, dstid, "Refcount", "1", 1, 0) ||
2792 				    conf_set(af, dstid, "Address",
2793 					(char *) (dstident + 1), 1, 0)) {
2794 					conf_end(af, 0);
2795 					goto fail;
2796 				}
2797 			} else
2798 				pf_key_v2_conf_refinc(af, dstid);
2799 			conf_end(af, 1);
2800 			break;
2801 
2802 		case SADB_IDENTTYPE_FQDN:
2803 			prefstring = "FQDN";
2804 			/*FALLTHROUGH*/
2805 		case SADB_IDENTTYPE_USERFQDN:
2806 			if (!prefstring) {
2807 				prefstring = "USER_FQDN";
2808 
2809 				/*
2810 				 * Check whether there is a string following
2811 				 * the header; if no, that there is a user ID
2812 				 * (and acquire the login name). If there is
2813 				 * both a string and a user ID, check that
2814 				 * they match.
2815 				 */
2816 				if (slen == 0 &&
2817 				    dstident->sadb_ident_id == 0) {
2818 					log_print("pf_key_v2_acquire: "
2819 					    "no user FQDN or ID provided");
2820 					goto fail;
2821 				}
2822 				if (dstident->sadb_ident_id) {
2823 					pwd = getpwuid(dstident->sadb_ident_id);
2824 					if (!pwd) {
2825 						log_error("pf_key_v2_acquire: "
2826 						    "could not acquire "
2827 						    "username from provided "
2828 						    "ID %llu",
2829 						    dstident->sadb_ident_id);
2830 						goto fail;
2831 					}
2832 					if (slen != 0)
2833 						if (strcmp(pwd->pw_name,
2834 						    (char *) (dstident + 1))
2835 						    != 0) {
2836 							log_print("pf_key_v2_acquire: "
2837 							    "provided user "
2838 							    "name and ID do "
2839 							    "not match (%s != "
2840 							    "%s)",
2841 							    (char *) (dstident + 1),
2842 							    pwd->pw_name);
2843 							/*
2844 							 * String has
2845 							 * precedence, per RF
2846 							 * 2367.
2847 							 */
2848 						}
2849 				}
2850 			}
2851 			if (asprintf(&dstid, "id-%s",
2852 			    slen ? (char *) (dstident + 1) : pwd->pw_name) == -1) {
2853 				log_error("pf_key_v2_acquire: asprintf() failed");
2854 				goto fail;
2855 			}
2856 			pwd = 0;
2857 
2858 			/* Set the section if it doesn't already exist. */
2859 			af = conf_begin();
2860 			if (!conf_get_str(dstid, "ID-type")) {
2861 				if (conf_set(af, dstid, "ID-type", prefstring,
2862 				    1, 0) ||
2863 				    conf_set(af, dstid, "Refcount", "1", 1, 0) ||
2864 				    conf_set(af, dstid, "Name",
2865 					dstid + 3, 1, 0)) {
2866 					conf_end(af, 0);
2867 					goto fail;
2868 				}
2869 			} else
2870 				pf_key_v2_conf_refinc(af, dstid);
2871 			conf_end(af, 1);
2872 			break;
2873 
2874 		default:
2875 			LOG_DBG((LOG_SYSDEP, 20, "pf_key_v2_acquire: "
2876 			    "invalid destination ID type %d",
2877 			    dstident->sadb_ident_type));
2878 			goto fail;
2879 		}
2880 
2881 		LOG_DBG((LOG_SYSDEP, 50,
2882 		    "pf_key_v2_acquire: constructed destination ID \"%s\"",
2883 		    dstid));
2884 	}
2885 	/* Now we've placed the necessary IDs in the configuration space. */
2886 
2887 	/* Get a new connection sequence number. */
2888 	for (;; connection_seq++) {
2889 		snprintf(conn, connlen, "Connection-%u", connection_seq);
2890 
2891 		/* Does it exist ? */
2892 		if (!conf_get_str(conn, "Phase"))
2893 			break;
2894 	}
2895 
2896 	/*
2897 	 * Set the IPsec connection entry. In particular, the following fields:
2898 	 * - Phase
2899 	 * - ISAKMP-peer
2900 	 * - Local-ID/Remote-ID (if provided)
2901 	 * - Acquire-ID (sequence number of kernel message, e.g., PF_KEYv2)
2902 	 * - Configuration
2903 	 *
2904 	 * Also set the following section:
2905 	 *    [peer-dstaddr(-local-srcaddr)]
2906 	 * with these fields:
2907 	 * - Phase
2908 	 * - ID (if provided)
2909 	 * - Remote-ID (if provided)
2910 	 * - Local-address (if provided)
2911 	 * - Address
2912 	 * - Configuration (if an entry phase1-dstaddr-srcadd)
2913 	 *                  exists -- otherwise use the defaults)
2914 	 */
2915 
2916 	/*
2917 	 * The various cases:
2918 	 * - peer-dstaddr
2919 	 * - peer-dstaddr-local-srcaddr
2920 	 */
2921 	if (asprintf(&peer, "peer-%s%s%s", dstbuf, srcaddr ? "-local-" : "",
2922 	    srcaddr ? srcbuf : "") == -1)
2923 		goto fail;
2924 
2925 	/*
2926 	 * Set the IPsec connection section. Refcount is set to 2, because
2927 	 * it will be linked both to the incoming and the outgoing SA.
2928 	 */
2929 	af = conf_begin();
2930 	if (conf_set(af, conn, "Phase", "2", 0, 0) ||
2931 	    conf_set(af, conn, "Flags", "__ondemand", 0, 0) ||
2932 	    conf_set(af, conn, "Refcount", "2", 0, 0) ||
2933 	    conf_set(af, conn, "ISAKMP-peer", peer, 0, 0)) {
2934 		conf_end(af, 0);
2935 		goto fail;
2936 	}
2937 	/* Set the sequence number. */
2938 	snprintf(lname, sizeof lname, "%u", msg->sadb_msg_seq);
2939 	if (conf_set(af, conn, "Acquire-ID", lname, 0, 0)) {
2940 		conf_end(af, 0);
2941 		goto fail;
2942 	}
2943 	/*
2944 	 * Set Phase 2 IDs -- this is the Local-ID section.
2945 	 * - from-address
2946 	 * - from-address=proto
2947 	 * - from-address=proto:port
2948 	 * - from-network/masklen
2949 	 * - from-network/masklen=proto
2950 	 * - from-network/masklen=proto:port
2951 	 */
2952 	phase2id(lname, sizeof lname, "from", ssflow, smasklen, tproto, sport);
2953 	if (conf_set(af, conn, "Local-ID", lname, 0, 0)) {
2954 		conf_end(af, 0);
2955 		goto fail;
2956 	}
2957 	if (!conf_get_str(lname, "ID-type")) {
2958 		if (conf_set(af, lname, "Refcount", "1", 0, 0)) {
2959 			conf_end(af, 0);
2960 			goto fail;
2961 		}
2962 		if (shostflag) {
2963 			if (conf_set(af, lname, "ID-type", sidtype, 0, 0) ||
2964 			    conf_set(af, lname, "Address", ssflow, 0, 0)) {
2965 				conf_end(af, 0);
2966 				goto fail;
2967 			}
2968 		} else {
2969 			if (conf_set(af, lname, "ID-type", sidtype, 0, 0) ||
2970 			    conf_set(af, lname, "Network", ssflow, 0, 0) ||
2971 			    conf_set(af, lname, "Netmask", ssmask, 0, 0)) {
2972 				conf_end(af, 0);
2973 				goto fail;
2974 			}
2975 		}
2976 		if (tproto) {
2977 			snprintf(tmbuf, sizeof sport * 3 + 1, "%u", tproto);
2978 			if (conf_set(af, lname, "Protocol", tmbuf, 0, 0)) {
2979 				conf_end(af, 0);
2980 				goto fail;
2981 			}
2982 			if (sport) {
2983 				snprintf(tmbuf, sizeof sport * 3 + 1, "%u",
2984 				    ntohs(sport));
2985 				if (conf_set(af, lname, "Port", tmbuf, 0, 0)) {
2986 					conf_end(af, 0);
2987 					goto fail;
2988 				}
2989 			}
2990 		}
2991 	} else
2992 		pf_key_v2_conf_refinc(af, lname);
2993 
2994 	/*
2995 	 * Set Remote-ID section.
2996 	 * to-address
2997 	 * to-address=proto
2998 	 * to-address=proto:port
2999 	 * to-network/masklen
3000 	 * to-network/masklen=proto
3001 	 * to-network/masklen=proto:port
3002 	 */
3003 	phase2id(dname, sizeof dname, "to", sdflow, dmasklen, tproto, dport);
3004 	if (conf_set(af, conn, "Remote-ID", dname, 0, 0)) {
3005 		conf_end(af, 0);
3006 		goto fail;
3007 	}
3008 	if (!conf_get_str(dname, "ID-type")) {
3009 		if (conf_set(af, dname, "Refcount", "1", 0, 0)) {
3010 			conf_end(af, 0);
3011 			goto fail;
3012 		}
3013 		if (dhostflag) {
3014 			if (conf_set(af, dname, "ID-type", didtype, 0, 0) ||
3015 			    conf_set(af, dname, "Address", sdflow, 0, 0)) {
3016 				conf_end(af, 0);
3017 				goto fail;
3018 			}
3019 		} else {
3020 			if (conf_set(af, dname, "ID-type", didtype, 0, 0) ||
3021 			    conf_set(af, dname, "Network", sdflow, 0, 0) ||
3022 			    conf_set(af, dname, "Netmask", sdmask, 0, 0)) {
3023 				conf_end(af, 0);
3024 				goto fail;
3025 			}
3026 		}
3027 
3028 		if (tproto) {
3029 			snprintf(tmbuf, sizeof dport * 3 + 1, "%u", tproto);
3030 			if (conf_set(af, dname, "Protocol", tmbuf, 0, 0)) {
3031 				conf_end(af, 0);
3032 				goto fail;
3033 			}
3034 			if (dport) {
3035 				snprintf(tmbuf, sizeof dport * 3 + 1, "%u",
3036 				    ntohs(dport));
3037 				if (conf_set(af, dname, "Port", tmbuf, 0, 0)) {
3038 					conf_end(af, 0);
3039 					goto fail;
3040 				}
3041 			}
3042 		}
3043 	} else
3044 		pf_key_v2_conf_refinc(af, dname);
3045 
3046 	/*
3047 	 * XXX
3048 	 * We should be using information from the proposal to set this up.
3049 	 * At least, we should make this selectable.
3050 	 */
3051 
3052 	/*
3053 	 * Phase 2 configuration.
3054 	 * - phase2-from-address-to-address
3055 	 * - ...
3056 	 * - phase2-from-net/len=proto:port-to-net/len=proto:port
3057 	 */
3058 	snprintf(configname, sizeof configname, "phase2-%s-%s", lname, dname);
3059 	if (conf_set(af, conn, "Configuration", configname, 0, 0)) {
3060 		conf_end(af, 0);
3061 		goto fail;
3062 	}
3063 	if (!conf_get_str(configname, "Exchange_type")) {
3064 		if (conf_set(af, configname, "Exchange_type", "Quick_mode",
3065 		    0, 0) ||
3066 		    conf_set(af, peer, "Refcount", "1", 0, 0) ||
3067 		    conf_set(af, configname, "DOI", "IPSEC", 0, 0)) {
3068 			conf_end(af, 0);
3069 			goto fail;
3070 		}
3071 		if (conf_get_str("General", "Default-phase-2-suites")) {
3072 			if (conf_set(af, configname, "Suites",
3073 			    conf_get_str("General", "Default-phase-2-suites"),
3074 			    0, 0)) {
3075 				conf_end(af, 0);
3076 				goto fail;
3077 			}
3078 		} else {
3079 			if (conf_set(af, configname, "Suites",
3080 			    "QM-ESP-3DES-SHA-PFS-SUITE", 0, 0)) {
3081 				conf_end(af, 0);
3082 				goto fail;
3083 			}
3084 		}
3085 	} else
3086 		pf_key_v2_conf_refinc(af, configname);
3087 
3088 	/* Set the ISAKMP-peer section. */
3089 	if (!conf_get_str(peer, "Phase")) {
3090 		if (conf_set(af, peer, "Phase", "1", 0, 0) ||
3091 		    conf_set(af, peer, "Refcount", "1", 0, 0) ||
3092 		    conf_set(af, peer, "Address", dstbuf, 0, 0)) {
3093 			conf_end(af, 0);
3094 			goto fail;
3095 		}
3096 		if (srcaddr && conf_set(af, peer, "Local-address", srcbuf, 0,
3097 		    0)) {
3098 			conf_end(af, 0);
3099 			goto fail;
3100 		}
3101 		snprintf(confname, sizeof confname, "phase1-%s", peer);
3102 		if (conf_set(af, peer, "Configuration", confname, 0, 0)) {
3103 			conf_end(af, 0);
3104 			goto fail;
3105 		}
3106 
3107 		/* Phase 1 configuration. */
3108 		if (!conf_get_str(confname, "exchange_type")) {
3109 			xform = conf_get_str("Default-phase-1-configuration",
3110 			"Transforms");
3111 			if (conf_set(af, confname, "Transforms", xform ? xform :
3112 			    "3DES-SHA-RSA_SIG", 0, 0)) {
3113 				conf_end(af, 0);
3114 				goto fail;
3115 			}
3116 
3117 			if (conf_set(af, confname, "Exchange_Type", "ID_PROT",
3118 			    0, 0) ||
3119 			    conf_set(af, confname, "DOI", "IPSEC", 0, 0) ||
3120 			    conf_set(af, confname, "Refcount", "1", 0, 0)) {
3121 				conf_end(af, 0);
3122 				goto fail;
3123 			}
3124 		} else
3125 			pf_key_v2_conf_refinc(af, confname);
3126 
3127 		/* The ID we should use in Phase 1. */
3128 		if (srcid && conf_set(af, peer, "ID", srcid, 0, 0)) {
3129 			conf_end(af, 0);
3130 			goto fail;
3131 		}
3132 		/* The ID the other side should use in Phase 1. */
3133 		if (dstid && conf_set(af, peer, "Remote-ID", dstid, 0, 0)) {
3134 			conf_end(af, 0);
3135 			goto fail;
3136 		}
3137 	} else
3138 		pf_key_v2_conf_refinc(af, peer);
3139 
3140 	/* All done. */
3141 	conf_end(af, 1);
3142 
3143 	/* Let's rock 'n roll. */
3144 	connection_record_passive(conn);
3145 	pf_key_v2_connection_check(conn);
3146 	conn = 0;
3147 
3148 	/* Fall-through to cleanup. */
3149 fail:
3150 	if (ret)
3151 		pf_key_v2_msg_free(ret);
3152 	if (askpolicy)
3153 		pf_key_v2_msg_free(askpolicy);
3154 	free(srcid);
3155 	free(dstid);
3156 	free(peer);
3157 	free(conn);
3158 	return;
3159 }
3160 
3161 static void
3162 pf_key_v2_notify(struct pf_key_v2_msg *msg)
3163 {
3164 	switch (((struct sadb_msg *)TAILQ_FIRST(msg)->seg)->sadb_msg_type) {
3165 	case SADB_EXPIRE:
3166 		pf_key_v2_expire(msg);
3167 		break;
3168 
3169 	case SADB_ACQUIRE:
3170 		if (!ui_daemon_passive)
3171 			pf_key_v2_acquire(msg);
3172 		break;
3173 
3174 	default:
3175 		log_print("pf_key_v2_notify: unexpected message type (%d)",
3176 		    ((struct sadb_msg *)TAILQ_FIRST(msg)->seg)->sadb_msg_type);
3177 	}
3178 	pf_key_v2_msg_free(msg);
3179 }
3180 
3181 void
3182 pf_key_v2_handler(int fd)
3183 {
3184 	struct pf_key_v2_msg *msg;
3185 	int		n;
3186 
3187 	/*
3188 	 * As synchronous read/writes to the socket can have taken place
3189 	 * between the select(2) call of the main loop and this handler, we
3190 	 * need to recheck the readability.
3191 	 */
3192 	if (ioctl(pf_key_v2_socket, FIONREAD, &n) == -1) {
3193 		log_error("pf_key_v2_handler: ioctl (%d, FIONREAD, &n) failed",
3194 		    pf_key_v2_socket);
3195 		return;
3196 	}
3197 	if (!n)
3198 		return;
3199 
3200 	msg = pf_key_v2_read(0);
3201 	if (msg)
3202 		pf_key_v2_notify(msg);
3203 }
3204 
3205 /*
3206  * Group 2 IPsec SAs given by the PROTO1 and PROTO2 protocols of the SA IKE
3207  * security association in a chain.
3208  * XXX Assumes OpenBSD GRPSPIS extension.
3209  */
3210 int
3211 pf_key_v2_group_spis(struct sa *sa, struct proto *proto1,
3212     struct proto *proto2, int incoming)
3213 {
3214 	struct sadb_msg msg;
3215 	struct sadb_sa  sa1, sa2;
3216 	struct sadb_address *addr = 0;
3217 	struct sadb_protocol protocol;
3218 	struct pf_key_v2_msg *grpspis = 0, *ret = 0;
3219 	struct sockaddr *saddr;
3220 	int		err;
3221 	size_t		len;
3222 
3223 	msg.sadb_msg_type = SADB_X_GRPSPIS;
3224 	switch (proto1->proto) {
3225 	case IPSEC_PROTO_IPSEC_ESP:
3226 		msg.sadb_msg_satype = SADB_SATYPE_ESP;
3227 		break;
3228 	case IPSEC_PROTO_IPSEC_AH:
3229 		msg.sadb_msg_satype = SADB_SATYPE_AH;
3230 		break;
3231 	case IPSEC_PROTO_IPCOMP:
3232 		msg.sadb_msg_satype = SADB_X_SATYPE_IPCOMP;
3233 		break;
3234 	default:
3235 		log_print("pf_key_v2_group_spis: invalid proto %d",
3236 		    proto1->proto);
3237 		goto cleanup;
3238 	}
3239 	msg.sadb_msg_seq = 0;
3240 	grpspis = pf_key_v2_msg_new(&msg, 0);
3241 	if (!grpspis)
3242 		goto cleanup;
3243 
3244 	/* Setup the SA extensions.  */
3245 	sa1.sadb_sa_exttype = SADB_EXT_SA;
3246 	sa1.sadb_sa_len = sizeof sa1 / PF_KEY_V2_CHUNK;
3247 	memcpy(&sa1.sadb_sa_spi, proto1->spi[incoming],
3248 	    sizeof sa1.sadb_sa_spi);
3249 	sa1.sadb_sa_replay = 0;
3250 	sa1.sadb_sa_state = 0;
3251 	sa1.sadb_sa_auth = 0;
3252 	sa1.sadb_sa_encrypt = 0;
3253 	sa1.sadb_sa_flags = 0;
3254 	if (pf_key_v2_msg_add(grpspis, (struct sadb_ext *)&sa1, 0) == -1)
3255 		goto cleanup;
3256 
3257 	sa2.sadb_sa_exttype = SADB_X_EXT_SA2;
3258 	sa2.sadb_sa_len = sizeof sa2 / PF_KEY_V2_CHUNK;
3259 	memcpy(&sa2.sadb_sa_spi, proto2->spi[incoming],
3260 	    sizeof sa2.sadb_sa_spi);
3261 	sa2.sadb_sa_replay = 0;
3262 	sa2.sadb_sa_state = 0;
3263 	sa2.sadb_sa_auth = 0;
3264 	sa2.sadb_sa_encrypt = 0;
3265 	sa2.sadb_sa_flags = 0;
3266 	if (pf_key_v2_msg_add(grpspis, (struct sadb_ext *)&sa2, 0) == -1)
3267 		goto cleanup;
3268 
3269 	/*
3270 	 * Setup the ADDRESS extensions.
3271 	 */
3272 	if (incoming)
3273 		sa->transport->vtbl->get_src(sa->transport, &saddr);
3274 	else
3275 		sa->transport->vtbl->get_dst(sa->transport, &saddr);
3276 	len = sizeof *addr + PF_KEY_V2_ROUND(SA_LEN(saddr));
3277 	addr = calloc(1, len);
3278 	if (!addr)
3279 		goto cleanup;
3280 	addr->sadb_address_exttype = SADB_EXT_ADDRESS_DST;
3281 	addr->sadb_address_len = len / PF_KEY_V2_CHUNK;
3282 	addr->sadb_address_reserved = 0;
3283 	memcpy(addr + 1, saddr, SA_LEN(saddr));
3284 	((struct sockaddr_in *) (addr + 1))->sin_port = 0;
3285 	if (pf_key_v2_msg_add(grpspis, (struct sadb_ext *) addr,
3286 	    PF_KEY_V2_NODE_MALLOCED) == -1)
3287 		goto cleanup;
3288 	addr = 0;
3289 
3290 	addr = calloc(1, len);
3291 	if (!addr)
3292 		goto cleanup;
3293 	addr->sadb_address_exttype = SADB_X_EXT_DST2;
3294 	addr->sadb_address_len = len / PF_KEY_V2_CHUNK;
3295 	addr->sadb_address_reserved = 0;
3296 	memcpy(addr + 1, saddr, SA_LEN(saddr));
3297 	((struct sockaddr_in *) (addr + 1))->sin_port = 0;
3298 	if (pf_key_v2_msg_add(grpspis, (struct sadb_ext *) addr,
3299 	    PF_KEY_V2_NODE_MALLOCED) == -1)
3300 		goto cleanup;
3301 	addr = 0;
3302 
3303 	/* Setup the sa type extension.  */
3304 	protocol.sadb_protocol_exttype = SADB_X_EXT_SATYPE2;
3305 	protocol.sadb_protocol_len = sizeof protocol / PF_KEY_V2_CHUNK;
3306 	switch (proto2->proto) {
3307 	case IPSEC_PROTO_IPSEC_ESP:
3308 		protocol.sadb_protocol_proto = SADB_SATYPE_ESP;
3309 		break;
3310 	case IPSEC_PROTO_IPSEC_AH:
3311 		protocol.sadb_protocol_proto = SADB_SATYPE_AH;
3312 		break;
3313 	case IPSEC_PROTO_IPCOMP:
3314 		protocol.sadb_protocol_proto = SADB_X_SATYPE_IPCOMP;
3315 		break;
3316 	default:
3317 		log_print("pf_key_v2_group_spis: invalid proto %d",
3318 		    proto2->proto);
3319 		goto cleanup;
3320 	}
3321 	protocol.sadb_protocol_reserved2 = 0;
3322 	if (pf_key_v2_msg_add(grpspis,
3323 	    (struct sadb_ext *)&protocol, 0) == -1)
3324 		goto cleanup;
3325 
3326 	ret = pf_key_v2_call(grpspis);
3327 	pf_key_v2_msg_free(grpspis);
3328 	grpspis = 0;
3329 	if (!ret)
3330 		goto cleanup;
3331 	err = ((struct sadb_msg *)TAILQ_FIRST(ret)->seg)->sadb_msg_errno;
3332 	if (err) {
3333 		log_print("pf_key_v2_group_spis: GRPSPIS: %s", strerror(err));
3334 		goto cleanup;
3335 	}
3336 	pf_key_v2_msg_free(ret);
3337 
3338 	LOG_DBG((LOG_SYSDEP, 50, "pf_key_v2_group_spis: done"));
3339 
3340 	return 0;
3341 
3342 cleanup:
3343 	free(addr);
3344 	if (grpspis)
3345 		pf_key_v2_msg_free(grpspis);
3346 	if (ret)
3347 		pf_key_v2_msg_free(ret);
3348 	return -1;
3349 }
3350