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