xref: /openbsd-src/sys/net/pfkeyv2.c (revision 46035553bfdd96e63c94e32da0210227ec2e3cf1)
1 /* $OpenBSD: pfkeyv2.c,v 1.208 2020/12/14 20:20:06 tobhe Exp $ */
2 
3 /*
4  *	@(#)COPYRIGHT	1.1 (NRL) 17 January 1995
5  *
6  * NRL grants permission for redistribution and use in source and binary
7  * forms, with or without modification, of the software and documentation
8  * created at NRL provided that the following conditions are met:
9  *
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. All advertising materials mentioning features or use of this software
16  *    must display the following acknowledgements:
17  *	This product includes software developed by the University of
18  *	California, Berkeley and its contributors.
19  *	This product includes software developed at the Information
20  *	Technology Division, US Naval Research Laboratory.
21  * 4. Neither the name of the NRL nor the names of its contributors
22  *    may be used to endorse or promote products derived from this software
23  *    without specific prior written permission.
24  *
25  * THE SOFTWARE PROVIDED BY NRL IS PROVIDED BY NRL AND CONTRIBUTORS ``AS
26  * IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
27  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
28  * PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL NRL OR
29  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
30  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
31  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
32  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
33  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
34  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
35  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36  *
37  * The views and conclusions contained in the software and documentation
38  * are those of the authors and should not be interpreted as representing
39  * official policies, either expressed or implied, of the US Naval
40  * Research Laboratory (NRL).
41  */
42 
43 /*
44  * Copyright (c) 1995, 1996, 1997, 1998, 1999 Craig Metz. All rights reserved.
45  *
46  * Redistribution and use in source and binary forms, with or without
47  * modification, are permitted provided that the following conditions
48  * are met:
49  * 1. Redistributions of source code must retain the above copyright
50  *    notice, this list of conditions and the following disclaimer.
51  * 2. Redistributions in binary form must reproduce the above copyright
52  *    notice, this list of conditions and the following disclaimer in the
53  *    documentation and/or other materials provided with the distribution.
54  * 3. Neither the name of the author nor the names of any contributors
55  *    may be used to endorse or promote products derived from this software
56  *    without specific prior written permission.
57  *
58  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
59  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
60  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
61  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
62  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
63  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
64  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
65  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
66  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
67  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
68  * SUCH DAMAGE.
69  */
70 
71 #include "pf.h"
72 
73 #include <sys/param.h>
74 #include <sys/socket.h>
75 #include <sys/socketvar.h>
76 #include <sys/protosw.h>
77 #include <sys/domain.h>
78 #include <sys/systm.h>
79 #include <sys/mbuf.h>
80 #include <sys/kernel.h>
81 #include <sys/proc.h>
82 #include <sys/pool.h>
83 #include <sys/mutex.h>
84 
85 #include <net/route.h>
86 #include <netinet/ip_ipsp.h>
87 #include <net/pfkeyv2.h>
88 #include <net/radix.h>
89 #include <netinet/ip_ah.h>
90 #include <netinet/ip_esp.h>
91 #include <netinet/ip_ipcomp.h>
92 #include <crypto/blf.h>
93 
94 #if NPF > 0
95 #include <net/if.h>
96 #include <net/pfvar.h>
97 #endif
98 
99 #define	PFKEYSNDQ	8192
100 #define	PFKEYRCVQ	8192
101 
102 static const struct sadb_alg ealgs[] = {
103 	{ SADB_EALG_NULL, 0, 0, 0 },
104 	{ SADB_EALG_3DESCBC, 64, 192, 192 },
105 	{ SADB_X_EALG_BLF, 64, 40, BLF_MAXKEYLEN * 8},
106 	{ SADB_X_EALG_CAST, 64, 40, 128},
107 	{ SADB_X_EALG_AES, 128, 128, 256},
108 	{ SADB_X_EALG_AESCTR, 128, 128 + 32, 256 + 32}
109 };
110 
111 static const struct sadb_alg aalgs[] = {
112 	{ SADB_AALG_SHA1HMAC, 0, 160, 160 },
113 	{ SADB_AALG_MD5HMAC, 0, 128, 128 },
114 	{ SADB_X_AALG_RIPEMD160HMAC, 0, 160, 160 },
115 	{ SADB_X_AALG_SHA2_256, 0, 256, 256 },
116 	{ SADB_X_AALG_SHA2_384, 0, 384, 384 },
117 	{ SADB_X_AALG_SHA2_512, 0, 512, 512 }
118 };
119 
120 static const struct sadb_alg calgs[] = {
121 	{ SADB_X_CALG_DEFLATE, 0, 0, 0},
122 	{ SADB_X_CALG_LZS, 0, 0, 0}
123 };
124 
125 extern uint64_t sadb_exts_allowed_out[SADB_MAX+1];
126 extern uint64_t sadb_exts_required_out[SADB_MAX+1];
127 
128 extern struct pool ipsec_policy_pool;
129 
130 extern struct radix_node_head **spd_tables;
131 
132 struct pool pkpcb_pool;
133 #define PFKEY_MSG_MAXSZ 4096
134 const struct sockaddr pfkey_addr = { 2, PF_KEY, };
135 struct domain pfkeydomain;
136 
137 /*
138  * pfkey PCB
139  *
140  *  Locks used to protect struct members in this file:
141  *	I	immutable after creation
142  *	a	atomic operations
143  *	l	pkptable's lock
144  *	s	socket lock
145  */
146 struct pkpcb {
147 	struct socket		*kcb_socket;	/* [I] associated socket */
148 
149 	SRPL_ENTRY(pkpcb)	kcb_list;	/* [l] */
150 	struct refcnt		kcb_refcnt;	/* [a] */
151 	int			kcb_flags;	/* [s] */
152 	uint32_t		kcb_reg;	/* [s] Inc if SATYPE_MAX > 31 */
153 	uint32_t		kcb_pid;	/* [I] */
154 	unsigned int		kcb_rdomain;	/* [I] routing domain */
155 };
156 #define sotokeycb(so)		((struct pkpcb *)(so)->so_pcb)
157 #define keylock(kp)		solock((kp)->kcb_socket)
158 #define keyunlock(kp, s)	sounlock((kp)->kcb_socket, s)
159 
160 
161 struct dump_state {
162 	struct sadb_msg *sadb_msg;
163 	struct socket *socket;
164 };
165 
166 struct pkptable {
167 	SRPL_HEAD(, pkpcb)	pkp_list;
168 	struct srpl_rc		pkp_rc;
169 	struct rwlock		pkp_lk;
170 };
171 
172 struct pkptable pkptable;
173 struct mutex pfkeyv2_mtx = MUTEX_INITIALIZER(IPL_MPFLOOR);
174 static uint32_t pfkeyv2_seq = 1;
175 static int nregistered = 0;
176 static int npromisc = 0;
177 
178 void pfkey_init(void);
179 
180 int pfkeyv2_attach(struct socket *, int);
181 int pfkeyv2_detach(struct socket *);
182 int pfkeyv2_usrreq(struct socket *, int, struct mbuf *, struct mbuf *,
183     struct mbuf *, struct proc *);
184 int pfkeyv2_output(struct mbuf *, struct socket *, struct sockaddr *,
185     struct mbuf *);
186 int pfkey_sendup(struct pkpcb *, struct mbuf *, int);
187 int pfkeyv2_sa_flush(struct tdb *, void *, int);
188 int pfkeyv2_policy_flush(struct ipsec_policy *, void *, unsigned int);
189 int pfkeyv2_sysctl_policydumper(struct ipsec_policy *, void *, unsigned int);
190 
191 void	keycb_ref(void *, void *);
192 void	keycb_unref(void *, void *);
193 
194 /*
195  * Wrapper around m_devget(); copy data from contiguous buffer to mbuf
196  * chain.
197  */
198 int
199 pfdatatopacket(void *data, int len, struct mbuf **packet)
200 {
201 	if (!(*packet = m_devget(data, len, 0)))
202 		return (ENOMEM);
203 
204 	/* Make sure, all data gets zeroized on free */
205 	(*packet)->m_flags |= M_ZEROIZE;
206 
207 	return (0);
208 }
209 
210 static struct protosw pfkeysw[] = {
211 {
212   .pr_type      = SOCK_RAW,
213   .pr_domain    = &pfkeydomain,
214   .pr_protocol  = PF_KEY_V2,
215   .pr_flags     = PR_ATOMIC | PR_ADDR,
216   .pr_output    = pfkeyv2_output,
217   .pr_usrreq    = pfkeyv2_usrreq,
218   .pr_attach    = pfkeyv2_attach,
219   .pr_detach    = pfkeyv2_detach,
220   .pr_sysctl    = pfkeyv2_sysctl,
221 }
222 };
223 
224 struct domain pfkeydomain = {
225   .dom_family = PF_KEY,
226   .dom_name = "PF_KEY",
227   .dom_init = pfkey_init,
228   .dom_protosw = pfkeysw,
229   .dom_protoswNPROTOSW = &pfkeysw[nitems(pfkeysw)],
230 };
231 
232 void
233 keycb_ref(void *null, void *v)
234 {
235 	struct pkpcb *kp = v;
236 
237 	refcnt_take(&kp->kcb_refcnt);
238 }
239 
240 void
241 keycb_unref(void *null, void *v)
242 {
243 	struct pkpcb *kp = v;
244 
245 	refcnt_rele_wake(&kp->kcb_refcnt);
246 }
247 
248 void
249 pfkey_init(void)
250 {
251 	rn_init(sizeof(struct sockaddr_encap));
252 	srpl_rc_init(&pkptable.pkp_rc, keycb_ref, keycb_unref, NULL);
253 	rw_init(&pkptable.pkp_lk, "pfkey");
254 	SRPL_INIT(&pkptable.pkp_list);
255 	pool_init(&pkpcb_pool, sizeof(struct pkpcb), 0,
256 	    IPL_NONE, PR_WAITOK, "pkpcb", NULL);
257 }
258 
259 
260 /*
261  * Attach a new PF_KEYv2 socket.
262  */
263 int
264 pfkeyv2_attach(struct socket *so, int proto)
265 {
266 	struct pkpcb *kp;
267 	int error;
268 
269 	if ((so->so_state & SS_PRIV) == 0)
270 		return EACCES;
271 
272 	kp = pool_get(&pkpcb_pool, PR_WAITOK|PR_ZERO);
273 	so->so_pcb = kp;
274 	refcnt_init(&kp->kcb_refcnt);
275 
276 	error = soreserve(so, PFKEYSNDQ, PFKEYRCVQ);
277 	if (error) {
278 		pool_put(&pkpcb_pool, kp);
279 		return (error);
280 	}
281 
282 	kp->kcb_socket = so;
283 
284 	so->so_options |= SO_USELOOPBACK;
285 	soisconnected(so);
286 
287 	kp->kcb_pid = curproc->p_p->ps_pid;
288 	kp->kcb_rdomain = rtable_l2(curproc->p_p->ps_rtableid);
289 
290 	rw_enter(&pkptable.pkp_lk, RW_WRITE);
291 	SRPL_INSERT_HEAD_LOCKED(&pkptable.pkp_rc, &pkptable.pkp_list, kp, kcb_list);
292 	rw_exit(&pkptable.pkp_lk);
293 
294 	return (0);
295 }
296 
297 /*
298  * Close a PF_KEYv2 socket.
299  */
300 int
301 pfkeyv2_detach(struct socket *so)
302 {
303 	struct pkpcb *kp;
304 
305 	soassertlocked(so);
306 
307 	kp = sotokeycb(so);
308 	if (kp == NULL)
309 		return ENOTCONN;
310 
311 	if (kp->kcb_flags &
312 	    (PFKEYV2_SOCKETFLAGS_REGISTERED|PFKEYV2_SOCKETFLAGS_PROMISC)) {
313 		mtx_enter(&pfkeyv2_mtx);
314 		if (kp->kcb_flags & PFKEYV2_SOCKETFLAGS_REGISTERED)
315 			nregistered--;
316 
317 		if (kp->kcb_flags & PFKEYV2_SOCKETFLAGS_PROMISC)
318 			npromisc--;
319 		mtx_leave(&pfkeyv2_mtx);
320 	}
321 
322 	rw_enter(&pkptable.pkp_lk, RW_WRITE);
323 	SRPL_REMOVE_LOCKED(&pkptable.pkp_rc, &pkptable.pkp_list, kp, pkpcb,
324 	    kcb_list);
325 	rw_exit(&pkptable.pkp_lk);
326 
327 	/* wait for all references to drop */
328 	refcnt_finalize(&kp->kcb_refcnt, "pfkeyrefs");
329 
330 	so->so_pcb = NULL;
331 	KASSERT((so->so_state & SS_NOFDREF) == 0);
332 	pool_put(&pkpcb_pool, kp);
333 
334 	return (0);
335 }
336 
337 int
338 pfkeyv2_usrreq(struct socket *so, int req, struct mbuf *m,
339     struct mbuf *nam, struct mbuf *control, struct proc *p)
340 {
341 	struct pkpcb *kp;
342 	int error = 0;
343 
344 	if (req == PRU_CONTROL)
345 		return (EOPNOTSUPP);
346 
347 	soassertlocked(so);
348 
349 	if (control && control->m_len) {
350 		error = EOPNOTSUPP;
351 		goto release;
352 	}
353 
354 	kp = sotokeycb(so);
355 	if (kp == NULL) {
356 		error = EINVAL;
357 		goto release;
358 	}
359 
360 	switch (req) {
361 	/* no connect, bind, accept. Socket is connected from the start */
362 	case PRU_CONNECT:
363 	case PRU_BIND:
364 	case PRU_CONNECT2:
365 	case PRU_LISTEN:
366 	case PRU_ACCEPT:
367 		error = EOPNOTSUPP;
368 		break;
369 
370 	case PRU_DISCONNECT:
371 	case PRU_ABORT:
372 		soisdisconnected(so);
373 		break;
374 	case PRU_SHUTDOWN:
375 		socantsendmore(so);
376 		break;
377 	case PRU_SENSE:
378 		/* stat: don't bother with a blocksize. */
379 		break;
380 
381 	/* minimal support, just implement a fake peer address */
382 	case PRU_SOCKADDR:
383 		error = EINVAL;
384 		break;
385 	case PRU_PEERADDR:
386 		bcopy(&pfkey_addr, mtod(nam, caddr_t), pfkey_addr.sa_len);
387 		nam->m_len = pfkey_addr.sa_len;
388 		break;
389 
390 	case PRU_RCVOOB:
391 	case PRU_RCVD:
392 	case PRU_SENDOOB:
393 		error = EOPNOTSUPP;
394 		break;
395 	case PRU_SEND:
396 		if (nam) {
397 			error = EISCONN;
398 			break;
399 		}
400 		error = (*so->so_proto->pr_output)(m, so, NULL, NULL);
401 		m = NULL;
402 		break;
403 	default:
404 		panic("pfkeyv2_usrreq");
405 	}
406 
407  release:
408 	if (req != PRU_RCVD && req != PRU_RCVOOB && req != PRU_SENSE) {
409 		m_freem(control);
410 		m_freem(m);
411 	}
412 	return (error);
413 }
414 
415 int
416 pfkeyv2_output(struct mbuf *mbuf, struct socket *so,
417     struct sockaddr *dstaddr, struct mbuf *control)
418 {
419 	void *message;
420 	int error = 0;
421 
422 #ifdef DIAGNOSTIC
423 	if (!mbuf || !(mbuf->m_flags & M_PKTHDR)) {
424 		error = EINVAL;
425 		goto ret;
426 	}
427 #endif /* DIAGNOSTIC */
428 
429 	if (mbuf->m_pkthdr.len > PFKEY_MSG_MAXSZ) {
430 		error = EMSGSIZE;
431 		goto ret;
432 	}
433 
434 	if (!(message = malloc((unsigned long) mbuf->m_pkthdr.len,
435 	    M_PFKEY, M_DONTWAIT))) {
436 		error = ENOMEM;
437 		goto ret;
438 	}
439 
440 	m_copydata(mbuf, 0, mbuf->m_pkthdr.len, message);
441 
442 	error = pfkeyv2_send(so, message, mbuf->m_pkthdr.len);
443 
444 ret:
445 	m_freem(mbuf);
446 	return (error);
447 }
448 
449 int
450 pfkey_sendup(struct pkpcb *kp, struct mbuf *m0, int more)
451 {
452 	struct socket *so = kp->kcb_socket;
453 	struct mbuf *m;
454 
455 	soassertlocked(so);
456 
457 	if (more) {
458 		if (!(m = m_dup_pkt(m0, 0, M_DONTWAIT)))
459 			return (ENOMEM);
460 	} else
461 		m = m0;
462 
463 	if (!sbappendaddr(so, &so->so_rcv, &pfkey_addr, m, NULL)) {
464 		m_freem(m);
465 		return (ENOBUFS);
466 	}
467 
468 	sorwakeup(so);
469 	return (0);
470 }
471 
472 /*
473  * Send a PFKEYv2 message, possibly to many receivers, based on the
474  * satype of the socket (which is set by the REGISTER message), and the
475  * third argument.
476  */
477 int
478 pfkeyv2_sendmessage(void **headers, int mode, struct socket *so,
479     u_int8_t satype, int count, u_int rdomain)
480 {
481 	int i, j, rval, s;
482 	void *p, *buffer = NULL;
483 	struct mbuf *packet;
484 	struct pkpcb *kp;
485 	struct sadb_msg *smsg;
486 	struct srp_ref sr;
487 
488 	/* Find out how much space we'll need... */
489 	j = sizeof(struct sadb_msg);
490 
491 	for (i = 1; i <= SADB_EXT_MAX; i++)
492 		if (headers[i])
493 			j += ((struct sadb_ext *)headers[i])->sadb_ext_len *
494 			    sizeof(uint64_t);
495 
496 	/* ...and allocate it */
497 	if (!(buffer = malloc(j + sizeof(struct sadb_msg), M_PFKEY,
498 	    M_NOWAIT))) {
499 		rval = ENOMEM;
500 		goto ret;
501 	}
502 
503 	p = buffer + sizeof(struct sadb_msg);
504 	bcopy(headers[0], p, sizeof(struct sadb_msg));
505 	((struct sadb_msg *) p)->sadb_msg_len = j / sizeof(uint64_t);
506 	p += sizeof(struct sadb_msg);
507 
508 	/* Copy payloads in the packet */
509 	for (i = 1; i <= SADB_EXT_MAX; i++)
510 		if (headers[i]) {
511 			((struct sadb_ext *) headers[i])->sadb_ext_type = i;
512 			bcopy(headers[i], p, EXTLEN(headers[i]));
513 			p += EXTLEN(headers[i]);
514 		}
515 
516 	if ((rval = pfdatatopacket(buffer + sizeof(struct sadb_msg),
517 	    j, &packet)) != 0)
518 		goto ret;
519 
520 	switch (mode) {
521 	case PFKEYV2_SENDMESSAGE_UNICAST:
522 		/*
523 		 * Send message to the specified socket, plus all
524 		 * promiscuous listeners.
525 		 */
526 		s = solock(so);
527 		pfkey_sendup(sotokeycb(so), packet, 0);
528 		sounlock(so, s);
529 
530 		/*
531 		 * Promiscuous messages contain the original message
532 		 * encapsulated in another sadb_msg header.
533 		 */
534 		bzero(buffer, sizeof(struct sadb_msg));
535 		smsg = (struct sadb_msg *) buffer;
536 		smsg->sadb_msg_version = PF_KEY_V2;
537 		smsg->sadb_msg_type = SADB_X_PROMISC;
538 		smsg->sadb_msg_len = (sizeof(struct sadb_msg) + j) /
539 		    sizeof(uint64_t);
540 		smsg->sadb_msg_seq = 0;
541 
542 		/* Copy to mbuf chain */
543 		if ((rval = pfdatatopacket(buffer, sizeof(struct sadb_msg) + j,
544 		    &packet)) != 0)
545 			goto ret;
546 
547 		/*
548 		 * Search for promiscuous listeners, skipping the
549 		 * original destination.
550 		 */
551 		SRPL_FOREACH(kp, &sr, &pkptable.pkp_list, kcb_list) {
552 			if (kp->kcb_socket == so || kp->kcb_rdomain != rdomain)
553 				continue;
554 
555 			s = keylock(kp);
556 			if (kp->kcb_flags & PFKEYV2_SOCKETFLAGS_PROMISC)
557 				pfkey_sendup(kp, packet, 1);
558 			keyunlock(kp, s);
559 		}
560 		SRPL_LEAVE(&sr);
561 		m_freem(packet);
562 		break;
563 
564 	case PFKEYV2_SENDMESSAGE_REGISTERED:
565 		/*
566 		 * Send the message to all registered sockets that match
567 		 * the specified satype (e.g., all IPSEC-ESP negotiators)
568 		 */
569 		SRPL_FOREACH(kp, &sr, &pkptable.pkp_list, kcb_list) {
570 			if (kp->kcb_rdomain != rdomain)
571 				continue;
572 
573 			s = keylock(kp);
574 			if (kp->kcb_flags & PFKEYV2_SOCKETFLAGS_REGISTERED) {
575 				if (!satype) {
576 					/* Just send to everyone registered */
577 					pfkey_sendup(kp, packet, 1);
578 				} else {
579 					/* Check for specified satype */
580 					if ((1 << satype) & kp->kcb_reg)
581 						pfkey_sendup(kp, packet, 1);
582 				}
583 			}
584 			keyunlock(kp, s);
585 		}
586 		SRPL_LEAVE(&sr);
587 		/* Free last/original copy of the packet */
588 		m_freem(packet);
589 
590 		/* Encapsulate the original message "inside" an sadb_msg header */
591 		bzero(buffer, sizeof(struct sadb_msg));
592 		smsg = (struct sadb_msg *) buffer;
593 		smsg->sadb_msg_version = PF_KEY_V2;
594 		smsg->sadb_msg_type = SADB_X_PROMISC;
595 		smsg->sadb_msg_len = (sizeof(struct sadb_msg) + j) /
596 		    sizeof(uint64_t);
597 		smsg->sadb_msg_seq = 0;
598 
599 		/* Convert to mbuf chain */
600 		if ((rval = pfdatatopacket(buffer, sizeof(struct sadb_msg) + j,
601 		    &packet)) != 0)
602 			goto ret;
603 
604 		/* Send to all registered promiscuous listeners */
605 		SRPL_FOREACH(kp, &sr, &pkptable.pkp_list, kcb_list) {
606 			if (kp->kcb_rdomain != rdomain)
607 				continue;
608 
609 			s = keylock(kp);
610 			if ((kp->kcb_flags & PFKEYV2_SOCKETFLAGS_PROMISC) &&
611 			    !(kp->kcb_flags & PFKEYV2_SOCKETFLAGS_REGISTERED))
612 				pfkey_sendup(kp, packet, 1);
613 			keyunlock(kp, s);
614 		}
615 		SRPL_LEAVE(&sr);
616 		m_freem(packet);
617 		break;
618 
619 	case PFKEYV2_SENDMESSAGE_BROADCAST:
620 		/* Send message to all sockets */
621 		SRPL_FOREACH(kp, &sr, &pkptable.pkp_list, kcb_list) {
622 			if (kp->kcb_rdomain != rdomain)
623 				continue;
624 
625 			s = keylock(kp);
626 			pfkey_sendup(kp, packet, 1);
627 			keyunlock(kp, s);
628 		}
629 		SRPL_LEAVE(&sr);
630 		m_freem(packet);
631 		break;
632 	}
633 
634 ret:
635 	if (buffer != NULL) {
636 		explicit_bzero(buffer, j + sizeof(struct sadb_msg));
637 		free(buffer, M_PFKEY, j + sizeof(struct sadb_msg));
638 	}
639 
640 	return (rval);
641 }
642 
643 /*
644  * Get SPD information for an ACQUIRE. We setup the message such that
645  * the SRC/DST payloads are relative to us (regardless of whether the
646  * SPD rule was for incoming or outgoing packets).
647  */
648 int
649 pfkeyv2_policy(struct ipsec_acquire *ipa, void **headers, void **buffer,
650     int *bufferlen)
651 {
652 	union sockaddr_union sunion;
653 	struct sadb_protocol *sp;
654 	int rval, i, dir;
655 	void *p;
656 
657 	/* Find out how big a buffer we need */
658 	i = 4 * sizeof(struct sadb_address) + sizeof(struct sadb_protocol);
659 	bzero(&sunion, sizeof(union sockaddr_union));
660 
661 	switch (ipa->ipa_info.sen_type) {
662 	case SENT_IP4:
663 		i += 4 * PADUP(sizeof(struct sockaddr_in));
664 		sunion.sa.sa_family = AF_INET;
665 		sunion.sa.sa_len = sizeof(struct sockaddr_in);
666 		dir = ipa->ipa_info.sen_direction;
667 		break;
668 
669 #ifdef INET6
670 	case SENT_IP6:
671 		i += 4 * PADUP(sizeof(struct sockaddr_in6));
672 		sunion.sa.sa_family = AF_INET6;
673 		sunion.sa.sa_len = sizeof(struct sockaddr_in6);
674 		dir = ipa->ipa_info.sen_ip6_direction;
675 		break;
676 #endif /* INET6 */
677 
678 	default:
679 		return (EINVAL);
680 	}
681 
682 	if (!(p = malloc(i, M_PFKEY, M_NOWAIT | M_ZERO))) {
683 		rval = ENOMEM;
684 		goto ret;
685 	} else {
686 		*buffer = p;
687 		*bufferlen = i;
688 	}
689 
690 	if (dir == IPSP_DIRECTION_OUT)
691 		headers[SADB_X_EXT_SRC_FLOW] = p;
692 	else
693 		headers[SADB_X_EXT_DST_FLOW] = p;
694 	switch (sunion.sa.sa_family) {
695 	case AF_INET:
696 		sunion.sin.sin_addr = ipa->ipa_info.sen_ip_src;
697 		sunion.sin.sin_port = ipa->ipa_info.sen_sport;
698 		break;
699 
700 #ifdef INET6
701 	case AF_INET6:
702 		sunion.sin6.sin6_addr = ipa->ipa_info.sen_ip6_src;
703 		sunion.sin6.sin6_port = ipa->ipa_info.sen_ip6_sport;
704 		break;
705 #endif /* INET6 */
706 	}
707 	export_address(&p, &sunion.sa);
708 
709 	if (dir == IPSP_DIRECTION_OUT)
710 		headers[SADB_X_EXT_SRC_MASK] = p;
711 	else
712 		headers[SADB_X_EXT_DST_MASK] = p;
713 	switch (sunion.sa.sa_family) {
714 	case AF_INET:
715 		sunion.sin.sin_addr = ipa->ipa_mask.sen_ip_src;
716 		sunion.sin.sin_port = ipa->ipa_mask.sen_sport;
717 		break;
718 
719 #ifdef INET6
720 	case AF_INET6:
721 		sunion.sin6.sin6_addr = ipa->ipa_mask.sen_ip6_src;
722 		sunion.sin6.sin6_port = ipa->ipa_mask.sen_ip6_sport;
723 		break;
724 #endif /* INET6 */
725 	}
726 	export_address(&p, &sunion.sa);
727 
728 	if (dir == IPSP_DIRECTION_OUT)
729 		headers[SADB_X_EXT_DST_FLOW] = p;
730 	else
731 		headers[SADB_X_EXT_SRC_FLOW] = p;
732 	switch (sunion.sa.sa_family) {
733 	case AF_INET:
734 		sunion.sin.sin_addr = ipa->ipa_info.sen_ip_dst;
735 		sunion.sin.sin_port = ipa->ipa_info.sen_dport;
736 		break;
737 
738 #ifdef INET6
739 	case AF_INET6:
740 		sunion.sin6.sin6_addr = ipa->ipa_info.sen_ip6_dst;
741 		sunion.sin6.sin6_port = ipa->ipa_info.sen_ip6_dport;
742 		break;
743 #endif /* INET6 */
744 	}
745 	export_address(&p, &sunion.sa);
746 
747 	if (dir == IPSP_DIRECTION_OUT)
748 		headers[SADB_X_EXT_DST_MASK] = p;
749 	else
750 		headers[SADB_X_EXT_SRC_MASK] = p;
751 	switch (sunion.sa.sa_family) {
752 	case AF_INET:
753 		sunion.sin.sin_addr = ipa->ipa_mask.sen_ip_dst;
754 		sunion.sin.sin_port = ipa->ipa_mask.sen_dport;
755 		break;
756 
757 #ifdef INET6
758 	case AF_INET6:
759 		sunion.sin6.sin6_addr = ipa->ipa_mask.sen_ip6_dst;
760 		sunion.sin6.sin6_port = ipa->ipa_mask.sen_ip6_dport;
761 		break;
762 #endif /* INET6 */
763 	}
764 	export_address(&p, &sunion.sa);
765 
766 	headers[SADB_X_EXT_FLOW_TYPE] = p;
767 	sp = p;
768 	sp->sadb_protocol_len = sizeof(struct sadb_protocol) /
769 	    sizeof(u_int64_t);
770 	switch (sunion.sa.sa_family) {
771 	case AF_INET:
772 		if (ipa->ipa_mask.sen_proto)
773 			sp->sadb_protocol_proto = ipa->ipa_info.sen_proto;
774 		sp->sadb_protocol_direction = ipa->ipa_info.sen_direction;
775 		break;
776 
777 #ifdef INET6
778 	case AF_INET6:
779 		if (ipa->ipa_mask.sen_ip6_proto)
780 			sp->sadb_protocol_proto = ipa->ipa_info.sen_ip6_proto;
781 		sp->sadb_protocol_direction = ipa->ipa_info.sen_ip6_direction;
782 		break;
783 #endif /* INET6 */
784 	}
785 
786 	rval = 0;
787 
788 ret:
789 	return (rval);
790 }
791 
792 /*
793  * Get all the information contained in an SA to a PFKEYV2 message.
794  */
795 int
796 pfkeyv2_get(struct tdb *tdb, void **headers, void **buffer, int *lenp,
797     int *lenused)
798 {
799 	int rval, i;
800 	void *p;
801 
802 	/* Find how much space we need */
803 	i = sizeof(struct sadb_sa) + sizeof(struct sadb_lifetime) +
804 	    sizeof(struct sadb_x_counter);
805 
806 	if (tdb->tdb_soft_allocations || tdb->tdb_soft_bytes ||
807 	    tdb->tdb_soft_timeout || tdb->tdb_soft_first_use)
808 		i += sizeof(struct sadb_lifetime);
809 
810 	if (tdb->tdb_exp_allocations || tdb->tdb_exp_bytes ||
811 	    tdb->tdb_exp_timeout || tdb->tdb_exp_first_use)
812 		i += sizeof(struct sadb_lifetime);
813 
814 	if (tdb->tdb_last_used)
815 		i += sizeof(struct sadb_lifetime);
816 
817 	i += sizeof(struct sadb_address) + PADUP(tdb->tdb_src.sa.sa_len);
818 	i += sizeof(struct sadb_address) + PADUP(tdb->tdb_dst.sa.sa_len);
819 
820 	if (tdb->tdb_ids) {
821 		i += sizeof(struct sadb_ident) + PADUP(tdb->tdb_ids->id_local->len);
822 		i += sizeof(struct sadb_ident) + PADUP(tdb->tdb_ids->id_remote->len);
823 	}
824 
825 	if (tdb->tdb_amxkey)
826 		i += sizeof(struct sadb_key) + PADUP(tdb->tdb_amxkeylen);
827 
828 	if (tdb->tdb_emxkey)
829 		i += sizeof(struct sadb_key) + PADUP(tdb->tdb_emxkeylen);
830 
831 	if (tdb->tdb_filter.sen_type) {
832 		i += 2 * sizeof(struct sadb_protocol);
833 
834 		/* We'll need four of them: src, src mask, dst, dst mask. */
835 		switch (tdb->tdb_filter.sen_type) {
836 		case SENT_IP4:
837 			i += 4 * PADUP(sizeof(struct sockaddr_in));
838 			i += 4 * sizeof(struct sadb_address);
839 			break;
840 #ifdef INET6
841 		case SENT_IP6:
842 			i += 4 * PADUP(sizeof(struct sockaddr_in6));
843 			i += 4 * sizeof(struct sadb_address);
844 			break;
845 #endif /* INET6 */
846 		default:
847 			rval = EINVAL;
848 			goto ret;
849 		}
850 	}
851 
852 	if (tdb->tdb_onext) {
853 		i += sizeof(struct sadb_sa);
854 		i += sizeof(struct sadb_address) +
855 		    PADUP(tdb->tdb_onext->tdb_dst.sa.sa_len);
856 		i += sizeof(struct sadb_protocol);
857 	}
858 
859 	if (tdb->tdb_udpencap_port)
860 		i += sizeof(struct sadb_x_udpencap);
861 
862 	if (tdb->tdb_rdomain != tdb->tdb_rdomain_post)
863 		i += sizeof(struct sadb_x_rdomain);
864 
865 #if NPF > 0
866 	if (tdb->tdb_tag)
867 		i += sizeof(struct sadb_x_tag) + PADUP(PF_TAG_NAME_SIZE);
868 	if (tdb->tdb_tap)
869 		i += sizeof(struct sadb_x_tap);
870 #endif
871 
872 	if (lenp)
873 		*lenp = i;
874 
875 	if (buffer == NULL) {
876 		rval = 0;
877 		goto ret;
878 	}
879 
880 	if (!(p = malloc(i, M_PFKEY, M_NOWAIT | M_ZERO))) {
881 		rval = ENOMEM;
882 		goto ret;
883 	} else
884 		*buffer = p;
885 
886 	headers[SADB_EXT_SA] = p;
887 
888 	export_sa(&p, tdb);  /* Export SA information (mostly flags) */
889 
890 	/* Export lifetimes where applicable */
891 	headers[SADB_EXT_LIFETIME_CURRENT] = p;
892 	export_lifetime(&p, tdb, PFKEYV2_LIFETIME_CURRENT);
893 
894 	if (tdb->tdb_soft_allocations || tdb->tdb_soft_bytes ||
895 	    tdb->tdb_soft_first_use || tdb->tdb_soft_timeout) {
896 		headers[SADB_EXT_LIFETIME_SOFT] = p;
897 		export_lifetime(&p, tdb, PFKEYV2_LIFETIME_SOFT);
898 	}
899 
900 	if (tdb->tdb_exp_allocations || tdb->tdb_exp_bytes ||
901 	    tdb->tdb_exp_first_use || tdb->tdb_exp_timeout) {
902 		headers[SADB_EXT_LIFETIME_HARD] = p;
903 		export_lifetime(&p, tdb, PFKEYV2_LIFETIME_HARD);
904 	}
905 
906 	if (tdb->tdb_last_used) {
907 		headers[SADB_X_EXT_LIFETIME_LASTUSE] = p;
908 		export_lifetime(&p, tdb, PFKEYV2_LIFETIME_LASTUSE);
909 	}
910 
911 	/* Export TDB source address */
912 	headers[SADB_EXT_ADDRESS_SRC] = p;
913 	export_address(&p, &tdb->tdb_src.sa);
914 
915 	/* Export TDB destination address */
916 	headers[SADB_EXT_ADDRESS_DST] = p;
917 	export_address(&p, &tdb->tdb_dst.sa);
918 
919 	/* Export source/destination identities, if present */
920 	if (tdb->tdb_ids)
921 		export_identities(&p, tdb->tdb_ids, tdb->tdb_ids_swapped, headers);
922 
923 	/* Export authentication key, if present */
924 	if (tdb->tdb_amxkey) {
925 		headers[SADB_EXT_KEY_AUTH] = p;
926 		export_key(&p, tdb, PFKEYV2_AUTHENTICATION_KEY);
927 	}
928 
929 	/* Export encryption key, if present */
930 	if (tdb->tdb_emxkey) {
931 		headers[SADB_EXT_KEY_ENCRYPT] = p;
932 		export_key(&p, tdb, PFKEYV2_ENCRYPTION_KEY);
933 	}
934 
935 	/* Export flow/filter, if present */
936 	if (tdb->tdb_filter.sen_type)
937 		export_flow(&p, IPSP_IPSEC_USE, &tdb->tdb_filter,
938 		    &tdb->tdb_filtermask, headers);
939 
940 	if (tdb->tdb_onext) {
941 		headers[SADB_X_EXT_SA2] = p;
942 		export_sa(&p, tdb->tdb_onext);
943 		headers[SADB_X_EXT_DST2] = p;
944 		export_address(&p, &tdb->tdb_onext->tdb_dst.sa);
945 		headers[SADB_X_EXT_SATYPE2] = p;
946 		export_satype(&p, tdb->tdb_onext);
947 	}
948 
949 	/* Export UDP encapsulation port, if present */
950 	if (tdb->tdb_udpencap_port) {
951 		headers[SADB_X_EXT_UDPENCAP] = p;
952 		export_udpencap(&p, tdb);
953 	}
954 
955 	/* Export rdomain switch, if present */
956 	if (tdb->tdb_rdomain != tdb->tdb_rdomain_post) {
957 		headers[SADB_X_EXT_RDOMAIN] = p;
958 		export_rdomain(&p, tdb);
959 	}
960 
961 #if NPF > 0
962 	/* Export tag information, if present */
963 	if (tdb->tdb_tag) {
964 		headers[SADB_X_EXT_TAG] = p;
965 		export_tag(&p, tdb);
966 	}
967 
968 	/* Export tap enc(4) device information, if present */
969 	if (tdb->tdb_tap) {
970 		headers[SADB_X_EXT_TAP] = p;
971 		export_tap(&p, tdb);
972 	}
973 #endif
974 
975 	headers[SADB_X_EXT_COUNTER] = p;
976 	export_counter(&p, tdb);
977 
978 	if (lenused)
979 		*lenused = p - *buffer;
980 	rval = 0;
981 
982  ret:
983 	return (rval);
984 }
985 
986 /*
987  * Dump a TDB.
988  */
989 int
990 pfkeyv2_dump_walker(struct tdb *tdb, void *state, int last)
991 {
992 	struct dump_state *dump_state = (struct dump_state *) state;
993 	void *headers[SADB_EXT_MAX+1], *buffer;
994 	int buflen;
995 	int rval;
996 
997 	/* If not satype was specified, dump all TDBs */
998 	if (!dump_state->sadb_msg->sadb_msg_satype ||
999 	    (tdb->tdb_satype == dump_state->sadb_msg->sadb_msg_satype)) {
1000 		bzero(headers, sizeof(headers));
1001 		headers[0] = (void *) dump_state->sadb_msg;
1002 
1003 		/* Get the information from the TDB to a PFKEYv2 message */
1004 		if ((rval = pfkeyv2_get(tdb, headers, &buffer, &buflen, NULL)) != 0)
1005 			return (rval);
1006 
1007 		if (last)
1008 			((struct sadb_msg *)headers[0])->sadb_msg_seq = 0;
1009 
1010 		/* Send the message to the specified socket */
1011 		rval = pfkeyv2_sendmessage(headers,
1012 		    PFKEYV2_SENDMESSAGE_UNICAST, dump_state->socket, 0, 0,
1013 		    tdb->tdb_rdomain);
1014 
1015 		explicit_bzero(buffer, buflen);
1016 		free(buffer, M_PFKEY, buflen);
1017 		if (rval)
1018 			return (rval);
1019 	}
1020 
1021 	return (0);
1022 }
1023 
1024 /*
1025  * Delete an SA.
1026  */
1027 int
1028 pfkeyv2_sa_flush(struct tdb *tdb, void *satype_vp, int last)
1029 {
1030 	if (!(*((u_int8_t *) satype_vp)) ||
1031 	    tdb->tdb_satype == *((u_int8_t *) satype_vp))
1032 		tdb_delete(tdb);
1033 	return (0);
1034 }
1035 
1036 /*
1037  * Convert between SATYPEs and IPsec protocols, taking into consideration
1038  * sysctl variables enabling/disabling ESP/AH and the presence of the old
1039  * IPsec transforms.
1040  */
1041 int
1042 pfkeyv2_get_proto_alg(u_int8_t satype, u_int8_t *sproto, int *alg)
1043 {
1044 	switch (satype) {
1045 #ifdef IPSEC
1046 	case SADB_SATYPE_AH:
1047 		if (!ah_enable)
1048 			return (EOPNOTSUPP);
1049 
1050 		*sproto = IPPROTO_AH;
1051 
1052 		if(alg != NULL)
1053 			*alg = satype = XF_AH;
1054 
1055 		break;
1056 
1057 	case SADB_SATYPE_ESP:
1058 		if (!esp_enable)
1059 			return (EOPNOTSUPP);
1060 
1061 		*sproto = IPPROTO_ESP;
1062 
1063 		if(alg != NULL)
1064 			*alg = satype = XF_ESP;
1065 
1066 		break;
1067 
1068 	case SADB_X_SATYPE_IPIP:
1069 		*sproto = IPPROTO_IPIP;
1070 
1071 		if (alg != NULL)
1072 			*alg = XF_IP4;
1073 
1074 		break;
1075 
1076 	case SADB_X_SATYPE_IPCOMP:
1077 		if (!ipcomp_enable)
1078 			return (EOPNOTSUPP);
1079 
1080 		*sproto = IPPROTO_IPCOMP;
1081 
1082 		if(alg != NULL)
1083 			*alg = satype = XF_IPCOMP;
1084 
1085 		break;
1086 #endif /* IPSEC */
1087 #ifdef TCP_SIGNATURE
1088 	case SADB_X_SATYPE_TCPSIGNATURE:
1089 		*sproto = IPPROTO_TCP;
1090 
1091 		if (alg != NULL)
1092 			*alg = XF_TCPSIGNATURE;
1093 
1094 		break;
1095 #endif /* TCP_SIGNATURE */
1096 
1097 	default: /* Nothing else supported */
1098 		return (EOPNOTSUPP);
1099 	}
1100 
1101 	return (0);
1102 }
1103 
1104 /*
1105  * Handle all messages from userland to kernel.
1106  */
1107 int
1108 pfkeyv2_send(struct socket *so, void *message, int len)
1109 {
1110 	int i, j, rval = 0, mode = PFKEYV2_SENDMESSAGE_BROADCAST;
1111 	int delflag = 0;
1112 	struct sockaddr_encap encapdst, encapnetmask;
1113 	struct ipsec_policy *ipo;
1114 	struct ipsec_acquire *ipa;
1115 	struct radix_node_head *rnh;
1116 	struct radix_node *rn = NULL;
1117 	struct pkpcb *kp, *bkp;
1118 	void *freeme = NULL, *freeme2 = NULL, *freeme3 = NULL;
1119 	int freeme_sz = 0, freeme2_sz = 0, freeme3_sz = 0;
1120 	void *bckptr = NULL;
1121 	void *headers[SADB_EXT_MAX + 1];
1122 	union sockaddr_union *sunionp;
1123 	struct tdb *sa1 = NULL, *sa2 = NULL;
1124 	struct sadb_msg *smsg;
1125 	struct sadb_spirange *sprng;
1126 	struct sadb_sa *ssa;
1127 	struct sadb_supported *ssup;
1128 	struct sadb_ident *sid, *did;
1129 	struct srp_ref sr;
1130 	struct sadb_x_rdomain *srdomain;
1131 	u_int rdomain = 0;
1132 	int promisc, s;
1133 
1134 	mtx_enter(&pfkeyv2_mtx);
1135 	promisc = npromisc;
1136 	mtx_leave(&pfkeyv2_mtx);
1137 
1138 	/* Verify that we received this over a legitimate pfkeyv2 socket */
1139 	bzero(headers, sizeof(headers));
1140 
1141 	kp = sotokeycb(so);
1142 	if (!kp) {
1143 		rval = EINVAL;
1144 		goto ret;
1145 	}
1146 
1147 	rdomain = kp->kcb_rdomain;
1148 
1149 	/* If we have any promiscuous listeners, send them a copy of the message */
1150 	if (promisc) {
1151 		struct mbuf *packet;
1152 
1153 		freeme_sz = sizeof(struct sadb_msg) + len;
1154 		if (!(freeme = malloc(freeme_sz, M_PFKEY, M_NOWAIT))) {
1155 			rval = ENOMEM;
1156 			goto ret;
1157 		}
1158 
1159 		/* Initialize encapsulating header */
1160 		bzero(freeme, sizeof(struct sadb_msg));
1161 		smsg = (struct sadb_msg *) freeme;
1162 		smsg->sadb_msg_version = PF_KEY_V2;
1163 		smsg->sadb_msg_type = SADB_X_PROMISC;
1164 		smsg->sadb_msg_len = (sizeof(struct sadb_msg) + len) /
1165 		    sizeof(uint64_t);
1166 		smsg->sadb_msg_seq = curproc->p_p->ps_pid;
1167 
1168 		bcopy(message, freeme + sizeof(struct sadb_msg), len);
1169 
1170 		/* Convert to mbuf chain */
1171 		if ((rval = pfdatatopacket(freeme, freeme_sz, &packet)) != 0)
1172 			goto ret;
1173 
1174 		/* Send to all promiscuous listeners */
1175 		SRPL_FOREACH(bkp, &sr, &pkptable.pkp_list, kcb_list) {
1176 			if (bkp->kcb_rdomain != kp->kcb_rdomain)
1177 				continue;
1178 
1179 			s = keylock(bkp);
1180 			if (bkp->kcb_flags & PFKEYV2_SOCKETFLAGS_PROMISC)
1181 				pfkey_sendup(bkp, packet, 1);
1182 			keyunlock(bkp, s);
1183 		}
1184 		SRPL_LEAVE(&sr);
1185 
1186 		m_freem(packet);
1187 
1188 		/* Paranoid */
1189 		explicit_bzero(freeme, freeme_sz);
1190 		free(freeme, M_PFKEY, freeme_sz);
1191 		freeme = NULL;
1192 		freeme_sz = 0;
1193 	}
1194 
1195 	/* Validate message format */
1196 	if ((rval = pfkeyv2_parsemessage(message, len, headers)) != 0)
1197 		goto ret;
1198 
1199 	/* use specified rdomain */
1200 	srdomain = (struct sadb_x_rdomain *) headers[SADB_X_EXT_RDOMAIN];
1201 	if (srdomain) {
1202 		if (!rtable_exists(srdomain->sadb_x_rdomain_dom1) ||
1203 		    !rtable_exists(srdomain->sadb_x_rdomain_dom2)) {
1204 			rval = EINVAL;
1205 			goto ret;
1206 		}
1207 		rdomain = srdomain->sadb_x_rdomain_dom1;
1208 	}
1209 
1210 	smsg = (struct sadb_msg *) headers[0];
1211 	switch (smsg->sadb_msg_type) {
1212 	case SADB_GETSPI:  /* Reserve an SPI */
1213 		sa1 = malloc(sizeof (*sa1), M_PFKEY, M_NOWAIT | M_ZERO);
1214 		if (sa1 == NULL) {
1215 			rval = ENOMEM;
1216 			goto ret;
1217 		}
1218 
1219 		sa1->tdb_satype = smsg->sadb_msg_satype;
1220 		if ((rval = pfkeyv2_get_proto_alg(sa1->tdb_satype,
1221 		    &sa1->tdb_sproto, 0)))
1222 			goto ret;
1223 
1224 		import_address(&sa1->tdb_src.sa, headers[SADB_EXT_ADDRESS_SRC]);
1225 		import_address(&sa1->tdb_dst.sa, headers[SADB_EXT_ADDRESS_DST]);
1226 
1227 		/* Find an unused SA identifier */
1228 		sprng = (struct sadb_spirange *) headers[SADB_EXT_SPIRANGE];
1229 		NET_LOCK();
1230 		sa1->tdb_spi = reserve_spi(rdomain,
1231 		    sprng->sadb_spirange_min, sprng->sadb_spirange_max,
1232 		    &sa1->tdb_src, &sa1->tdb_dst, sa1->tdb_sproto, &rval);
1233 		if (sa1->tdb_spi == 0) {
1234 			NET_UNLOCK();
1235 			goto ret;
1236 		}
1237 
1238 		/* Send a message back telling what the SA (the SPI really) is */
1239 		freeme_sz = sizeof(struct sadb_sa);
1240 		if (!(freeme = malloc(freeme_sz, M_PFKEY, M_NOWAIT | M_ZERO))) {
1241 			rval = ENOMEM;
1242 			NET_UNLOCK();
1243 			goto ret;
1244 		}
1245 
1246 		headers[SADB_EXT_SPIRANGE] = NULL;
1247 		headers[SADB_EXT_SA] = freeme;
1248 		bckptr = freeme;
1249 
1250 		/* We really only care about the SPI, but we'll export the SA */
1251 		export_sa((void **) &bckptr, sa1);
1252 		NET_UNLOCK();
1253 		break;
1254 
1255 	case SADB_UPDATE:
1256 		ssa = (struct sadb_sa *) headers[SADB_EXT_SA];
1257 		sunionp = (union sockaddr_union *) (headers[SADB_EXT_ADDRESS_DST] +
1258 		    sizeof(struct sadb_address));
1259 
1260 		/* Either all or none of the flow must be included */
1261 		if ((headers[SADB_X_EXT_SRC_FLOW] ||
1262 		    headers[SADB_X_EXT_PROTOCOL] ||
1263 		    headers[SADB_X_EXT_FLOW_TYPE] ||
1264 		    headers[SADB_X_EXT_DST_FLOW] ||
1265 		    headers[SADB_X_EXT_SRC_MASK] ||
1266 		    headers[SADB_X_EXT_DST_MASK]) &&
1267 		    !(headers[SADB_X_EXT_SRC_FLOW] &&
1268 		    headers[SADB_X_EXT_PROTOCOL] &&
1269 		    headers[SADB_X_EXT_FLOW_TYPE] &&
1270 		    headers[SADB_X_EXT_DST_FLOW] &&
1271 		    headers[SADB_X_EXT_SRC_MASK] &&
1272 		    headers[SADB_X_EXT_DST_MASK])) {
1273 			rval = EINVAL;
1274 			goto ret;
1275 		}
1276 #ifdef IPSEC
1277 		/* UDP encap has to be enabled and is only supported for ESP */
1278 		if (headers[SADB_X_EXT_UDPENCAP] &&
1279 		    (!udpencap_enable ||
1280 		    smsg->sadb_msg_satype != SADB_SATYPE_ESP)) {
1281 			rval = EINVAL;
1282 			goto ret;
1283 		}
1284 #endif /* IPSEC */
1285 
1286 		/* Find TDB */
1287 		NET_LOCK();
1288 		sa2 = gettdb(rdomain, ssa->sadb_sa_spi, sunionp,
1289 		    SADB_X_GETSPROTO(smsg->sadb_msg_satype));
1290 
1291 		/* If there's no such SA, we're done */
1292 		if (sa2 == NULL) {
1293 			rval = ESRCH;
1294 			NET_UNLOCK();
1295 			goto ret;
1296 		}
1297 
1298 		/* If this is a reserved SA */
1299 		if (sa2->tdb_flags & TDBF_INVALID) {
1300 			struct tdb *newsa;
1301 			struct ipsecinit ii;
1302 			int alg;
1303 
1304 			/* Create new TDB */
1305 			freeme_sz = 0;
1306 			freeme = tdb_alloc(rdomain);
1307 			bzero(&ii, sizeof(struct ipsecinit));
1308 
1309 			newsa = (struct tdb *) freeme;
1310 			newsa->tdb_satype = smsg->sadb_msg_satype;
1311 
1312 			if ((rval = pfkeyv2_get_proto_alg(newsa->tdb_satype,
1313 			    &newsa->tdb_sproto, &alg))) {
1314 				tdb_free(freeme);
1315 				freeme = NULL;
1316 				NET_UNLOCK();
1317 				goto ret;
1318 			}
1319 
1320 			/* Initialize SA */
1321 			import_sa(newsa, headers[SADB_EXT_SA], &ii);
1322 			import_address(&newsa->tdb_src.sa,
1323 			    headers[SADB_EXT_ADDRESS_SRC]);
1324 			import_address(&newsa->tdb_dst.sa,
1325 			    headers[SADB_EXT_ADDRESS_DST]);
1326 			import_lifetime(newsa,
1327 			    headers[SADB_EXT_LIFETIME_CURRENT],
1328 			    PFKEYV2_LIFETIME_CURRENT);
1329 			import_lifetime(newsa, headers[SADB_EXT_LIFETIME_SOFT],
1330 			    PFKEYV2_LIFETIME_SOFT);
1331 			import_lifetime(newsa, headers[SADB_EXT_LIFETIME_HARD],
1332 			    PFKEYV2_LIFETIME_HARD);
1333 			import_key(&ii, headers[SADB_EXT_KEY_AUTH],
1334 			    PFKEYV2_AUTHENTICATION_KEY);
1335 			import_key(&ii, headers[SADB_EXT_KEY_ENCRYPT],
1336 			    PFKEYV2_ENCRYPTION_KEY);
1337 			newsa->tdb_ids_swapped = 1; /* only on TDB_UPDATE */
1338 			import_identities(&newsa->tdb_ids,
1339 			    newsa->tdb_ids_swapped,
1340 			    headers[SADB_EXT_IDENTITY_SRC],
1341 			    headers[SADB_EXT_IDENTITY_DST]);
1342 			if ((rval = import_flow(&newsa->tdb_filter,
1343 			    &newsa->tdb_filtermask,
1344 			    headers[SADB_X_EXT_SRC_FLOW],
1345 			    headers[SADB_X_EXT_SRC_MASK],
1346 			    headers[SADB_X_EXT_DST_FLOW],
1347 			    headers[SADB_X_EXT_DST_MASK],
1348 			    headers[SADB_X_EXT_PROTOCOL],
1349 			    headers[SADB_X_EXT_FLOW_TYPE]))) {
1350 				tdb_free(freeme);
1351 				freeme = NULL;
1352 				NET_UNLOCK();
1353 				goto ret;
1354 			}
1355 			import_udpencap(newsa, headers[SADB_X_EXT_UDPENCAP]);
1356 			import_rdomain(newsa, headers[SADB_X_EXT_RDOMAIN]);
1357 #if NPF > 0
1358 			import_tag(newsa, headers[SADB_X_EXT_TAG]);
1359 			import_tap(newsa, headers[SADB_X_EXT_TAP]);
1360 #endif
1361 
1362 			/* Exclude sensitive data from reply message. */
1363 			headers[SADB_EXT_KEY_AUTH] = NULL;
1364 			headers[SADB_EXT_KEY_ENCRYPT] = NULL;
1365 			headers[SADB_X_EXT_LOCAL_AUTH] = NULL;
1366 			headers[SADB_X_EXT_REMOTE_AUTH] = NULL;
1367 
1368 			newsa->tdb_seq = smsg->sadb_msg_seq;
1369 
1370 			rval = tdb_init(newsa, alg, &ii);
1371 			if (rval) {
1372 				rval = EINVAL;
1373 				tdb_free(freeme);
1374 				freeme = NULL;
1375 				NET_UNLOCK();
1376 				goto ret;
1377 			}
1378 
1379 			newsa->tdb_cur_allocations = sa2->tdb_cur_allocations;
1380 
1381 			/* Delete old version of the SA, insert new one */
1382 			tdb_delete(sa2);
1383 			puttdb((struct tdb *) freeme);
1384 			sa2 = freeme = NULL;
1385 		} else {
1386 			/*
1387 			 * The SA is already initialized, so we're only allowed to
1388 			 * change lifetimes and some other information; we're
1389 			 * not allowed to change keys, addresses or identities.
1390 			 */
1391 			if (headers[SADB_EXT_KEY_AUTH] ||
1392 			    headers[SADB_EXT_KEY_ENCRYPT] ||
1393 			    headers[SADB_EXT_IDENTITY_SRC] ||
1394 			    headers[SADB_EXT_IDENTITY_DST] ||
1395 			    headers[SADB_EXT_SENSITIVITY]) {
1396 				rval = EINVAL;
1397 				NET_UNLOCK();
1398 				goto ret;
1399 			}
1400 
1401 			import_sa(sa2, headers[SADB_EXT_SA], NULL);
1402 			import_lifetime(sa2,
1403 			    headers[SADB_EXT_LIFETIME_CURRENT],
1404 			    PFKEYV2_LIFETIME_CURRENT);
1405 			import_lifetime(sa2, headers[SADB_EXT_LIFETIME_SOFT],
1406 			    PFKEYV2_LIFETIME_SOFT);
1407 			import_lifetime(sa2, headers[SADB_EXT_LIFETIME_HARD],
1408 			    PFKEYV2_LIFETIME_HARD);
1409 			import_udpencap(sa2, headers[SADB_X_EXT_UDPENCAP]);
1410 #if NPF > 0
1411 			import_tag(sa2, headers[SADB_X_EXT_TAG]);
1412 			import_tap(sa2, headers[SADB_X_EXT_TAP]);
1413 #endif
1414 			if (headers[SADB_EXT_ADDRESS_SRC] ||
1415 			    headers[SADB_EXT_ADDRESS_PROXY]) {
1416 				tdb_unlink(sa2);
1417 				import_address((struct sockaddr *)&sa2->tdb_src,
1418 				    headers[SADB_EXT_ADDRESS_SRC]);
1419 				import_address((struct sockaddr *)&sa2->tdb_dst,
1420 				    headers[SADB_EXT_ADDRESS_PROXY]);
1421 				puttdb(sa2);
1422 			}
1423 		}
1424 		NET_UNLOCK();
1425 
1426 		break;
1427 	case SADB_ADD:
1428 		ssa = (struct sadb_sa *) headers[SADB_EXT_SA];
1429 		sunionp = (union sockaddr_union *) (headers[SADB_EXT_ADDRESS_DST] +
1430 		    sizeof(struct sadb_address));
1431 
1432 		/* Either all or none of the flow must be included */
1433 		if ((headers[SADB_X_EXT_SRC_FLOW] ||
1434 		    headers[SADB_X_EXT_PROTOCOL] ||
1435 		    headers[SADB_X_EXT_FLOW_TYPE] ||
1436 		    headers[SADB_X_EXT_DST_FLOW] ||
1437 		    headers[SADB_X_EXT_SRC_MASK] ||
1438 		    headers[SADB_X_EXT_DST_MASK]) &&
1439 		    !(headers[SADB_X_EXT_SRC_FLOW] &&
1440 		    headers[SADB_X_EXT_PROTOCOL] &&
1441 		    headers[SADB_X_EXT_FLOW_TYPE] &&
1442 		    headers[SADB_X_EXT_DST_FLOW] &&
1443 		    headers[SADB_X_EXT_SRC_MASK] &&
1444 		    headers[SADB_X_EXT_DST_MASK])) {
1445 			rval = EINVAL;
1446 			goto ret;
1447 		}
1448 #ifdef IPSEC
1449 		/* UDP encap has to be enabled and is only supported for ESP */
1450 		if (headers[SADB_X_EXT_UDPENCAP] &&
1451 		    (!udpencap_enable ||
1452 		    smsg->sadb_msg_satype != SADB_SATYPE_ESP)) {
1453 			rval = EINVAL;
1454 			goto ret;
1455 		}
1456 #endif /* IPSEC */
1457 
1458 		NET_LOCK();
1459 		sa2 = gettdb(rdomain, ssa->sadb_sa_spi, sunionp,
1460 		    SADB_X_GETSPROTO(smsg->sadb_msg_satype));
1461 
1462 		/* We can't add an existing SA! */
1463 		if (sa2 != NULL) {
1464 			rval = EEXIST;
1465 			NET_UNLOCK();
1466 			goto ret;
1467 		}
1468 
1469 		/* We can only add "mature" SAs */
1470 		if (ssa->sadb_sa_state != SADB_SASTATE_MATURE) {
1471 			rval = EINVAL;
1472 			NET_UNLOCK();
1473 			goto ret;
1474 		}
1475 
1476 		/* Allocate and initialize new TDB */
1477 		freeme_sz = 0;
1478 		freeme = tdb_alloc(rdomain);
1479 
1480 		{
1481 			struct tdb *newsa = (struct tdb *) freeme;
1482 			struct ipsecinit ii;
1483 			int alg;
1484 
1485 			bzero(&ii, sizeof(struct ipsecinit));
1486 
1487 			newsa->tdb_satype = smsg->sadb_msg_satype;
1488 			if ((rval = pfkeyv2_get_proto_alg(newsa->tdb_satype,
1489 			    &newsa->tdb_sproto, &alg))) {
1490 				tdb_free(freeme);
1491 				freeme = NULL;
1492 				NET_UNLOCK();
1493 				goto ret;
1494 			}
1495 
1496 			import_sa(newsa, headers[SADB_EXT_SA], &ii);
1497 			import_address(&newsa->tdb_src.sa,
1498 			    headers[SADB_EXT_ADDRESS_SRC]);
1499 			import_address(&newsa->tdb_dst.sa,
1500 			    headers[SADB_EXT_ADDRESS_DST]);
1501 
1502 			import_lifetime(newsa,
1503 			    headers[SADB_EXT_LIFETIME_CURRENT],
1504 			    PFKEYV2_LIFETIME_CURRENT);
1505 			import_lifetime(newsa, headers[SADB_EXT_LIFETIME_SOFT],
1506 			    PFKEYV2_LIFETIME_SOFT);
1507 			import_lifetime(newsa, headers[SADB_EXT_LIFETIME_HARD],
1508 			    PFKEYV2_LIFETIME_HARD);
1509 
1510 			import_key(&ii, headers[SADB_EXT_KEY_AUTH],
1511 			    PFKEYV2_AUTHENTICATION_KEY);
1512 			import_key(&ii, headers[SADB_EXT_KEY_ENCRYPT],
1513 			    PFKEYV2_ENCRYPTION_KEY);
1514 
1515 			import_identities(&newsa->tdb_ids,
1516 			    newsa->tdb_ids_swapped,
1517 			    headers[SADB_EXT_IDENTITY_SRC],
1518 			    headers[SADB_EXT_IDENTITY_DST]);
1519 
1520 			if ((rval = import_flow(&newsa->tdb_filter,
1521 			    &newsa->tdb_filtermask,
1522 			    headers[SADB_X_EXT_SRC_FLOW],
1523 			    headers[SADB_X_EXT_SRC_MASK],
1524 			    headers[SADB_X_EXT_DST_FLOW],
1525 			    headers[SADB_X_EXT_DST_MASK],
1526 			    headers[SADB_X_EXT_PROTOCOL],
1527 			    headers[SADB_X_EXT_FLOW_TYPE]))) {
1528 				tdb_free(freeme);
1529 				freeme = NULL;
1530 				NET_UNLOCK();
1531 				goto ret;
1532 			}
1533 			import_udpencap(newsa, headers[SADB_X_EXT_UDPENCAP]);
1534 			import_rdomain(newsa, headers[SADB_X_EXT_RDOMAIN]);
1535 #if NPF > 0
1536 			import_tag(newsa, headers[SADB_X_EXT_TAG]);
1537 			import_tap(newsa, headers[SADB_X_EXT_TAP]);
1538 #endif
1539 
1540 			/* Exclude sensitive data from reply message. */
1541 			headers[SADB_EXT_KEY_AUTH] = NULL;
1542 			headers[SADB_EXT_KEY_ENCRYPT] = NULL;
1543 			headers[SADB_X_EXT_LOCAL_AUTH] = NULL;
1544 			headers[SADB_X_EXT_REMOTE_AUTH] = NULL;
1545 
1546 			newsa->tdb_seq = smsg->sadb_msg_seq;
1547 
1548 			rval = tdb_init(newsa, alg, &ii);
1549 			if (rval) {
1550 				rval = EINVAL;
1551 				tdb_free(freeme);
1552 				freeme = NULL;
1553 				NET_UNLOCK();
1554 				goto ret;
1555 			}
1556 		}
1557 
1558 		/* Add TDB in table */
1559 		puttdb((struct tdb *) freeme);
1560 		NET_UNLOCK();
1561 
1562 		freeme = NULL;
1563 		break;
1564 
1565 	case SADB_DELETE:
1566 		ssa = (struct sadb_sa *) headers[SADB_EXT_SA];
1567 		sunionp =
1568 		    (union sockaddr_union *)(headers[SADB_EXT_ADDRESS_DST] +
1569 			sizeof(struct sadb_address));
1570 
1571 		NET_LOCK();
1572 		sa2 = gettdb(rdomain, ssa->sadb_sa_spi, sunionp,
1573 		    SADB_X_GETSPROTO(smsg->sadb_msg_satype));
1574 		if (sa2 == NULL) {
1575 			rval = ESRCH;
1576 			NET_UNLOCK();
1577 			goto ret;
1578 		}
1579 
1580 		tdb_delete(sa2);
1581 		NET_UNLOCK();
1582 
1583 		sa2 = NULL;
1584 		break;
1585 
1586 	case SADB_X_ASKPOLICY:
1587 		/* Get the relevant policy */
1588 		NET_LOCK();
1589 		ipa = ipsec_get_acquire(((struct sadb_x_policy *) headers[SADB_X_EXT_POLICY])->sadb_x_policy_seq);
1590 		if (ipa == NULL) {
1591 			rval = ESRCH;
1592 			NET_UNLOCK();
1593 			goto ret;
1594 		}
1595 
1596 		rval = pfkeyv2_policy(ipa, headers, &freeme, &freeme_sz);
1597 		NET_UNLOCK();
1598 		if (rval)
1599 			mode = PFKEYV2_SENDMESSAGE_UNICAST;
1600 
1601 		break;
1602 
1603 	case SADB_GET:
1604 		ssa = (struct sadb_sa *) headers[SADB_EXT_SA];
1605 		sunionp =
1606 		    (union sockaddr_union *)(headers[SADB_EXT_ADDRESS_DST] +
1607 			sizeof(struct sadb_address));
1608 
1609 		NET_LOCK();
1610 		sa2 = gettdb(rdomain, ssa->sadb_sa_spi, sunionp,
1611 		    SADB_X_GETSPROTO(smsg->sadb_msg_satype));
1612 		if (sa2 == NULL) {
1613 			rval = ESRCH;
1614 			NET_UNLOCK();
1615 			goto ret;
1616 		}
1617 
1618 		rval = pfkeyv2_get(sa2, headers, &freeme, &freeme_sz, NULL);
1619 		NET_UNLOCK();
1620 		if (rval)
1621 			mode = PFKEYV2_SENDMESSAGE_UNICAST;
1622 
1623 		break;
1624 
1625 	case SADB_REGISTER:
1626 		s = keylock(kp);
1627 		if (!(kp->kcb_flags & PFKEYV2_SOCKETFLAGS_REGISTERED)) {
1628 			kp->kcb_flags |= PFKEYV2_SOCKETFLAGS_REGISTERED;
1629 			mtx_enter(&pfkeyv2_mtx);
1630 			nregistered++;
1631 			mtx_leave(&pfkeyv2_mtx);
1632 		}
1633 		keyunlock(kp, s);
1634 
1635 		freeme_sz = sizeof(struct sadb_supported) + sizeof(ealgs);
1636 		if (!(freeme = malloc(freeme_sz, M_PFKEY, M_NOWAIT | M_ZERO))) {
1637 			rval = ENOMEM;
1638 			goto ret;
1639 		}
1640 
1641 		ssup = (struct sadb_supported *) freeme;
1642 		ssup->sadb_supported_len = freeme_sz / sizeof(uint64_t);
1643 
1644 		{
1645 			void *p = freeme + sizeof(struct sadb_supported);
1646 
1647 			bcopy(&ealgs[0], p, sizeof(ealgs));
1648 		}
1649 
1650 		headers[SADB_EXT_SUPPORTED_ENCRYPT] = freeme;
1651 
1652 		freeme2_sz = sizeof(struct sadb_supported) + sizeof(aalgs);
1653 		if (!(freeme2 = malloc(freeme2_sz, M_PFKEY,
1654 		    M_NOWAIT | M_ZERO))) {
1655 			rval = ENOMEM;
1656 			goto ret;
1657 		}
1658 
1659 		/* Keep track what this socket has registered for */
1660 		s = keylock(kp);
1661 		kp->kcb_reg |=
1662 		    (1 << ((struct sadb_msg *)message)->sadb_msg_satype);
1663 		keyunlock(kp, s);
1664 
1665 		ssup = (struct sadb_supported *) freeme2;
1666 		ssup->sadb_supported_len = freeme2_sz / sizeof(uint64_t);
1667 
1668 		{
1669 			void *p = freeme2 + sizeof(struct sadb_supported);
1670 
1671 			bcopy(&aalgs[0], p, sizeof(aalgs));
1672 		}
1673 
1674 		headers[SADB_EXT_SUPPORTED_AUTH] = freeme2;
1675 
1676 		freeme3_sz = sizeof(struct sadb_supported) + sizeof(calgs);
1677 		if (!(freeme3 = malloc(freeme3_sz, M_PFKEY,
1678 		    M_NOWAIT | M_ZERO))) {
1679 			rval = ENOMEM;
1680 			goto ret;
1681 		}
1682 
1683 		ssup = (struct sadb_supported *) freeme3;
1684 		ssup->sadb_supported_len = freeme3_sz / sizeof(uint64_t);
1685 
1686 		{
1687 			void *p = freeme3 + sizeof(struct sadb_supported);
1688 
1689 			bcopy(&calgs[0], p, sizeof(calgs));
1690 		}
1691 
1692 		headers[SADB_X_EXT_SUPPORTED_COMP] = freeme3;
1693 
1694 		break;
1695 
1696 	case SADB_ACQUIRE:
1697 	case SADB_EXPIRE:
1698 		/* Nothing to handle */
1699 		rval = 0;
1700 		break;
1701 
1702 	case SADB_FLUSH:
1703 		rval = 0;
1704 
1705 		NET_LOCK();
1706 		switch (smsg->sadb_msg_satype) {
1707 		case SADB_SATYPE_UNSPEC:
1708 			spd_table_walk(rdomain, pfkeyv2_policy_flush, NULL);
1709 			/* FALLTHROUGH */
1710 		case SADB_SATYPE_AH:
1711 		case SADB_SATYPE_ESP:
1712 		case SADB_X_SATYPE_IPIP:
1713 		case SADB_X_SATYPE_IPCOMP:
1714 #ifdef TCP_SIGNATURE
1715 		case SADB_X_SATYPE_TCPSIGNATURE:
1716 #endif /* TCP_SIGNATURE */
1717 			tdb_walk(rdomain, pfkeyv2_sa_flush,
1718 			    (u_int8_t *) &(smsg->sadb_msg_satype));
1719 
1720 			break;
1721 
1722 		default:
1723 			rval = EINVAL; /* Unknown/unsupported type */
1724 		}
1725 		NET_UNLOCK();
1726 
1727 		break;
1728 
1729 	case SADB_DUMP:
1730 	{
1731 		struct dump_state dump_state;
1732 		dump_state.sadb_msg = (struct sadb_msg *) headers[0];
1733 		dump_state.socket = so;
1734 
1735 		NET_LOCK();
1736 		rval = tdb_walk(rdomain, pfkeyv2_dump_walker, &dump_state);
1737 		NET_UNLOCK();
1738 		if (!rval)
1739 			goto realret;
1740 		if ((rval == ENOMEM) || (rval == ENOBUFS))
1741 			rval = 0;
1742 	}
1743 	break;
1744 
1745 	case SADB_X_GRPSPIS:
1746 	{
1747 		struct tdb *tdb1, *tdb2, *tdb3;
1748 		struct sadb_protocol *sa_proto;
1749 
1750 		ssa = (struct sadb_sa *) headers[SADB_EXT_SA];
1751 		sunionp = (union sockaddr_union *) (headers[SADB_EXT_ADDRESS_DST] +
1752 		    sizeof(struct sadb_address));
1753 
1754 		NET_LOCK();
1755 		tdb1 = gettdb(rdomain, ssa->sadb_sa_spi, sunionp,
1756 		    SADB_X_GETSPROTO(smsg->sadb_msg_satype));
1757 		if (tdb1 == NULL) {
1758 			rval = ESRCH;
1759 			NET_UNLOCK();
1760 			goto ret;
1761 		}
1762 
1763 		ssa = (struct sadb_sa *) headers[SADB_X_EXT_SA2];
1764 		sunionp = (union sockaddr_union *) (headers[SADB_X_EXT_DST2] +
1765 		    sizeof(struct sadb_address));
1766 		sa_proto = (struct sadb_protocol *) headers[SADB_X_EXT_SATYPE2];
1767 
1768 		/* optionally fetch tdb2 from rdomain2 */
1769 		tdb2 = gettdb(srdomain ? srdomain->sadb_x_rdomain_dom2 : rdomain,
1770 		    ssa->sadb_sa_spi, sunionp,
1771 		    SADB_X_GETSPROTO(sa_proto->sadb_protocol_proto));
1772 		if (tdb2 == NULL) {
1773 			rval = ESRCH;
1774 			NET_UNLOCK();
1775 			goto ret;
1776 		}
1777 
1778 		/* Detect cycles */
1779 		for (tdb3 = tdb2; tdb3; tdb3 = tdb3->tdb_onext)
1780 			if (tdb3 == tdb1) {
1781 				rval = ESRCH;
1782 				NET_UNLOCK();
1783 				goto ret;
1784 			}
1785 
1786 		/* Maintenance */
1787 		if ((tdb1->tdb_onext) &&
1788 		    (tdb1->tdb_onext->tdb_inext == tdb1))
1789 			tdb1->tdb_onext->tdb_inext = NULL;
1790 
1791 		if ((tdb2->tdb_inext) &&
1792 		    (tdb2->tdb_inext->tdb_onext == tdb2))
1793 			tdb2->tdb_inext->tdb_onext = NULL;
1794 
1795 		/* Link them */
1796 		tdb1->tdb_onext = tdb2;
1797 		tdb2->tdb_inext = tdb1;
1798 		NET_UNLOCK();
1799 	}
1800 	break;
1801 
1802 	case SADB_X_DELFLOW:
1803 		delflag = 1;
1804 		/*FALLTHROUGH*/
1805 	case SADB_X_ADDFLOW:
1806 	{
1807 		struct sadb_protocol *sab;
1808 		union sockaddr_union *ssrc;
1809 		int exists = 0;
1810 
1811 		NET_LOCK();
1812 		if ((rnh = spd_table_add(rdomain)) == NULL) {
1813 			rval = ENOMEM;
1814 			NET_UNLOCK();
1815 			goto ret;
1816 		}
1817 
1818 		sab = (struct sadb_protocol *) headers[SADB_X_EXT_FLOW_TYPE];
1819 
1820 		if ((sab->sadb_protocol_direction != IPSP_DIRECTION_IN) &&
1821 		    (sab->sadb_protocol_direction != IPSP_DIRECTION_OUT)) {
1822 			rval = EINVAL;
1823 			NET_UNLOCK();
1824 			goto ret;
1825 		}
1826 
1827 		/* If the security protocol wasn't specified, pretend it was ESP */
1828 		if (smsg->sadb_msg_satype == 0)
1829 			smsg->sadb_msg_satype = SADB_SATYPE_ESP;
1830 
1831 		if (headers[SADB_EXT_ADDRESS_DST])
1832 			sunionp = (union sockaddr_union *)
1833 			    (headers[SADB_EXT_ADDRESS_DST] +
1834 				sizeof(struct sadb_address));
1835 		else
1836 			sunionp = NULL;
1837 
1838 		if (headers[SADB_EXT_ADDRESS_SRC])
1839 			ssrc = (union sockaddr_union *)
1840 			    (headers[SADB_EXT_ADDRESS_SRC] +
1841 				sizeof(struct sadb_address));
1842 		else
1843 			ssrc = NULL;
1844 
1845 		if ((rval = import_flow(&encapdst, &encapnetmask,
1846 		    headers[SADB_X_EXT_SRC_FLOW], headers[SADB_X_EXT_SRC_MASK],
1847 		    headers[SADB_X_EXT_DST_FLOW], headers[SADB_X_EXT_DST_MASK],
1848 		    headers[SADB_X_EXT_PROTOCOL],
1849 		    headers[SADB_X_EXT_FLOW_TYPE]))) {
1850 			NET_UNLOCK();
1851 			goto ret;
1852 		}
1853 
1854 		/* Determine whether the exact same SPD entry already exists. */
1855 		if ((rn = rn_match(&encapdst, rnh)) != NULL) {
1856 			ipo = (struct ipsec_policy *)rn;
1857 
1858 			/* Verify that the entry is identical */
1859 			if (bcmp(&ipo->ipo_addr, &encapdst,
1860 				sizeof(struct sockaddr_encap)) ||
1861 			    bcmp(&ipo->ipo_mask, &encapnetmask,
1862 				sizeof(struct sockaddr_encap)))
1863 				ipo = NULL; /* Fall through */
1864 			else
1865 				exists = 1;
1866 		} else
1867 			ipo = NULL;
1868 
1869 		/*
1870 		 * If the existing policy is static, only delete or update
1871 		 * it if the new one is also static.
1872 		 */
1873 		if (exists && (ipo->ipo_flags & IPSP_POLICY_STATIC)) {
1874 			if (!(sab->sadb_protocol_flags &
1875 				SADB_X_POLICYFLAGS_POLICY)) {
1876 				NET_UNLOCK();
1877 				goto ret;
1878 			}
1879 		}
1880 
1881 		/* Delete ? */
1882 		if (delflag) {
1883 			if (exists) {
1884 				rval = ipsec_delete_policy(ipo);
1885 				NET_UNLOCK();
1886 				goto ret;
1887 			}
1888 
1889 			/* If we were asked to delete something non-existent, error. */
1890 			rval = ESRCH;
1891 			NET_UNLOCK();
1892 			break;
1893 		}
1894 
1895 		if (!exists) {
1896 			if (ipsec_policy_pool_initialized == 0) {
1897 				ipsec_policy_pool_initialized = 1;
1898 				pool_init(&ipsec_policy_pool,
1899 				    sizeof(struct ipsec_policy), 0,
1900 				    IPL_NONE, 0, "ipsec policy", NULL);
1901 			}
1902 
1903 			/* Allocate policy entry */
1904 			ipo = pool_get(&ipsec_policy_pool, PR_NOWAIT|PR_ZERO);
1905 			if (ipo == NULL) {
1906 				rval = ENOMEM;
1907 				NET_UNLOCK();
1908 				goto ret;
1909 			}
1910 		}
1911 
1912 		switch (sab->sadb_protocol_proto) {
1913 		case SADB_X_FLOW_TYPE_USE:
1914 			ipo->ipo_type = IPSP_IPSEC_USE;
1915 			break;
1916 
1917 		case SADB_X_FLOW_TYPE_ACQUIRE:
1918 			ipo->ipo_type = IPSP_IPSEC_ACQUIRE;
1919 			break;
1920 
1921 		case SADB_X_FLOW_TYPE_REQUIRE:
1922 			ipo->ipo_type = IPSP_IPSEC_REQUIRE;
1923 			break;
1924 
1925 		case SADB_X_FLOW_TYPE_DENY:
1926 			ipo->ipo_type = IPSP_DENY;
1927 			break;
1928 
1929 		case SADB_X_FLOW_TYPE_BYPASS:
1930 			ipo->ipo_type = IPSP_PERMIT;
1931 			break;
1932 
1933 		case SADB_X_FLOW_TYPE_DONTACQ:
1934 			ipo->ipo_type = IPSP_IPSEC_DONTACQ;
1935 			break;
1936 
1937 		default:
1938 			if (!exists)
1939 				pool_put(&ipsec_policy_pool, ipo);
1940 			else
1941 				ipsec_delete_policy(ipo);
1942 
1943 			rval = EINVAL;
1944 			NET_UNLOCK();
1945 			goto ret;
1946 		}
1947 
1948 		if (sab->sadb_protocol_flags & SADB_X_POLICYFLAGS_POLICY)
1949 			ipo->ipo_flags |= IPSP_POLICY_STATIC;
1950 
1951 		if (sunionp)
1952 			bcopy(sunionp, &ipo->ipo_dst,
1953 			    sizeof(union sockaddr_union));
1954 		else
1955 			bzero(&ipo->ipo_dst, sizeof(union sockaddr_union));
1956 
1957 		if (ssrc)
1958 			bcopy(ssrc, &ipo->ipo_src,
1959 			    sizeof(union sockaddr_union));
1960 		else
1961 			bzero(&ipo->ipo_src, sizeof(union sockaddr_union));
1962 
1963 		ipo->ipo_sproto = SADB_X_GETSPROTO(smsg->sadb_msg_satype);
1964 
1965 		if (ipo->ipo_ids) {
1966 			ipsp_ids_free(ipo->ipo_ids);
1967 			ipo->ipo_ids = NULL;
1968 		}
1969 
1970 		if ((sid = headers[SADB_EXT_IDENTITY_SRC]) != NULL &&
1971 		    (did = headers[SADB_EXT_IDENTITY_DST]) != NULL) {
1972 			import_identities(&ipo->ipo_ids, 0, sid, did);
1973 			if (ipo->ipo_ids == NULL) {
1974 				if (exists)
1975 					ipsec_delete_policy(ipo);
1976 				else
1977 					pool_put(&ipsec_policy_pool, ipo);
1978 				rval = ENOBUFS;
1979 				NET_UNLOCK();
1980 				goto ret;
1981 			}
1982 		}
1983 
1984 		/* Flow type */
1985 		if (!exists) {
1986 			/* Initialize policy entry */
1987 			bcopy(&encapdst, &ipo->ipo_addr,
1988 			    sizeof(struct sockaddr_encap));
1989 			bcopy(&encapnetmask, &ipo->ipo_mask,
1990 			    sizeof(struct sockaddr_encap));
1991 
1992 			TAILQ_INIT(&ipo->ipo_acquires);
1993 			ipo->ipo_rdomain = rdomain;
1994 			ipo->ipo_ref_count = 1;
1995 
1996 			/* Add SPD entry */
1997 			if ((rnh = spd_table_get(rdomain)) == NULL ||
1998 			    (rn = rn_addroute((caddr_t)&ipo->ipo_addr,
1999 				(caddr_t)&ipo->ipo_mask, rnh,
2000 				ipo->ipo_nodes, 0)) == NULL) {
2001 				/* Remove from linked list of policies on TDB */
2002 				if (ipo->ipo_tdb)
2003 					TAILQ_REMOVE(&ipo->ipo_tdb->tdb_policy_head,
2004 					    ipo, ipo_tdb_next);
2005 
2006 				if (ipo->ipo_ids)
2007 					ipsp_ids_free(ipo->ipo_ids);
2008 				pool_put(&ipsec_policy_pool, ipo);
2009 				NET_UNLOCK();
2010 				goto ret;
2011 			}
2012 			TAILQ_INSERT_HEAD(&ipsec_policy_head, ipo, ipo_list);
2013 			ipsec_in_use++;
2014 			/*
2015 			 * XXXSMP IPsec data structures are not ready to be
2016 			 * accessed by multiple Network threads in parallel,
2017 			 * so force all packets to be processed by the first
2018 			 * one.
2019 			 */
2020 			extern int nettaskqs;
2021 			nettaskqs = 1;
2022 		} else {
2023 			ipo->ipo_last_searched = ipo->ipo_flags = 0;
2024 		}
2025 		NET_UNLOCK();
2026 	}
2027 	break;
2028 
2029 	case SADB_X_PROMISC:
2030 		if (len >= 2 * sizeof(struct sadb_msg)) {
2031 			struct mbuf *packet;
2032 
2033 			if ((rval = pfdatatopacket(message, len, &packet)) != 0)
2034 				goto ret;
2035 
2036 			SRPL_FOREACH(bkp, &sr, &pkptable.pkp_list, kcb_list) {
2037 				if (bkp == kp || bkp->kcb_rdomain != kp->kcb_rdomain)
2038 					continue;
2039 
2040 				if (!smsg->sadb_msg_seq ||
2041 				    (smsg->sadb_msg_seq == kp->kcb_pid)) {
2042 					s = keylock(bkp);
2043 					pfkey_sendup(bkp, packet, 1);
2044 					keyunlock(bkp, s);
2045 				}
2046 			}
2047 			SRPL_LEAVE(&sr);
2048 
2049 			m_freem(packet);
2050 		} else {
2051 			if (len != sizeof(struct sadb_msg)) {
2052 				rval = EINVAL;
2053 				goto ret;
2054 			}
2055 
2056 			s = keylock(kp);
2057 			i = (kp->kcb_flags &
2058 			    PFKEYV2_SOCKETFLAGS_PROMISC) ? 1 : 0;
2059 			j = smsg->sadb_msg_satype ? 1 : 0;
2060 
2061 			if (i ^ j) {
2062 				if (j) {
2063 					kp->kcb_flags |=
2064 					    PFKEYV2_SOCKETFLAGS_PROMISC;
2065 					mtx_enter(&pfkeyv2_mtx);
2066 					npromisc++;
2067 					mtx_leave(&pfkeyv2_mtx);
2068 				} else {
2069 					kp->kcb_flags &=
2070 					    ~PFKEYV2_SOCKETFLAGS_PROMISC;
2071 					mtx_enter(&pfkeyv2_mtx);
2072 					npromisc--;
2073 					mtx_leave(&pfkeyv2_mtx);
2074 				}
2075 			}
2076 			keyunlock(kp, s);
2077 		}
2078 
2079 		break;
2080 
2081 	default:
2082 		rval = EINVAL;
2083 		goto ret;
2084 	}
2085 
2086 ret:
2087 	if (rval) {
2088 		if ((rval == EINVAL) || (rval == ENOMEM) || (rval == ENOBUFS))
2089 			goto realret;
2090 
2091 		for (i = 1; i <= SADB_EXT_MAX; i++)
2092 			headers[i] = NULL;
2093 
2094 		smsg->sadb_msg_errno = abs(rval);
2095 	} else {
2096 		uint64_t seen = 0LL;
2097 
2098 		for (i = 1; i <= SADB_EXT_MAX; i++)
2099 			if (headers[i])
2100 				seen |= (1LL << i);
2101 
2102 		if ((seen & sadb_exts_allowed_out[smsg->sadb_msg_type])
2103 		    != seen) {
2104 		    	rval = EPERM;
2105 			goto realret;
2106 		}
2107 
2108 		if ((seen & sadb_exts_required_out[smsg->sadb_msg_type]) !=
2109 		    sadb_exts_required_out[smsg->sadb_msg_type]) {
2110 		    	rval = EPERM;
2111 			goto realret;
2112 		}
2113 	}
2114 
2115 	rval = pfkeyv2_sendmessage(headers, mode, so, 0, 0, kp->kcb_rdomain);
2116 
2117 realret:
2118 
2119 	if (freeme != NULL)
2120 		explicit_bzero(freeme, freeme_sz);
2121 	free(freeme, M_PFKEY, freeme_sz);
2122 	free(freeme2, M_PFKEY, freeme2_sz);
2123 	free(freeme3, M_PFKEY, freeme3_sz);
2124 
2125 	explicit_bzero(message, len);
2126 	free(message, M_PFKEY, len);
2127 
2128 	free(sa1, M_PFKEY, sizeof(*sa1));
2129 
2130 	return (rval);
2131 }
2132 
2133 /*
2134  * Send an ACQUIRE message to key management, to get a new SA.
2135  */
2136 int
2137 pfkeyv2_acquire(struct ipsec_policy *ipo, union sockaddr_union *gw,
2138     union sockaddr_union *laddr, u_int32_t *seq, struct sockaddr_encap *ddst)
2139 {
2140 	void *p, *headers[SADB_EXT_MAX + 1], *buffer = NULL;
2141 	struct sadb_comb *sadb_comb;
2142 	struct sadb_address *sadd;
2143 	struct sadb_prop *sa_prop;
2144 	struct sadb_msg *smsg;
2145 	int rval = 0;
2146 	int i, j, registered;
2147 
2148 	mtx_enter(&pfkeyv2_mtx);
2149 	*seq = pfkeyv2_seq++;
2150 
2151 	registered = nregistered;
2152 	mtx_leave(&pfkeyv2_mtx);
2153 
2154 	if (!registered) {
2155 		rval = ESRCH;
2156 		goto ret;
2157 	}
2158 
2159 	/* How large a buffer do we need... XXX we only do one proposal for now */
2160 	i = sizeof(struct sadb_msg) +
2161 	    (laddr == NULL ? 0 : sizeof(struct sadb_address) +
2162 		PADUP(ipo->ipo_src.sa.sa_len)) +
2163 	    sizeof(struct sadb_address) + PADUP(gw->sa.sa_len) +
2164 	    sizeof(struct sadb_prop) + 1 * sizeof(struct sadb_comb);
2165 
2166 	if (ipo->ipo_ids) {
2167 		i += sizeof(struct sadb_ident) + PADUP(ipo->ipo_ids->id_local->len);
2168 		i += sizeof(struct sadb_ident) + PADUP(ipo->ipo_ids->id_remote->len);
2169 	}
2170 
2171 	/* Allocate */
2172 	if (!(p = malloc(i, M_PFKEY, M_NOWAIT | M_ZERO))) {
2173 		rval = ENOMEM;
2174 		goto ret;
2175 	}
2176 
2177 	bzero(headers, sizeof(headers));
2178 
2179 	buffer = p;
2180 
2181 	headers[0] = p;
2182 	p += sizeof(struct sadb_msg);
2183 
2184 	smsg = (struct sadb_msg *) headers[0];
2185 	smsg->sadb_msg_version = PF_KEY_V2;
2186 	smsg->sadb_msg_type = SADB_ACQUIRE;
2187 	smsg->sadb_msg_len = i / sizeof(uint64_t);
2188 	smsg->sadb_msg_seq = *seq;
2189 
2190 	if (ipo->ipo_sproto == IPPROTO_ESP)
2191 		smsg->sadb_msg_satype = SADB_SATYPE_ESP;
2192 	else if (ipo->ipo_sproto == IPPROTO_AH)
2193 		smsg->sadb_msg_satype = SADB_SATYPE_AH;
2194 	else if (ipo->ipo_sproto == IPPROTO_IPCOMP)
2195 		smsg->sadb_msg_satype = SADB_X_SATYPE_IPCOMP;
2196 
2197 	if (laddr) {
2198 		headers[SADB_EXT_ADDRESS_SRC] = p;
2199 		p += sizeof(struct sadb_address) + PADUP(laddr->sa.sa_len);
2200 		sadd = (struct sadb_address *) headers[SADB_EXT_ADDRESS_SRC];
2201 		sadd->sadb_address_len = (sizeof(struct sadb_address) +
2202 		    laddr->sa.sa_len + sizeof(uint64_t) - 1) /
2203 		    sizeof(uint64_t);
2204 		bcopy(laddr, headers[SADB_EXT_ADDRESS_SRC] +
2205 		    sizeof(struct sadb_address), laddr->sa.sa_len);
2206 	}
2207 
2208 	headers[SADB_EXT_ADDRESS_DST] = p;
2209 	p += sizeof(struct sadb_address) + PADUP(gw->sa.sa_len);
2210 	sadd = (struct sadb_address *) headers[SADB_EXT_ADDRESS_DST];
2211 	sadd->sadb_address_len = (sizeof(struct sadb_address) +
2212 	    gw->sa.sa_len + sizeof(uint64_t) - 1) / sizeof(uint64_t);
2213 	bcopy(gw, headers[SADB_EXT_ADDRESS_DST] + sizeof(struct sadb_address),
2214 	    gw->sa.sa_len);
2215 
2216 	if (ipo->ipo_ids)
2217 		export_identities(&p, ipo->ipo_ids, 0, headers);
2218 
2219 	headers[SADB_EXT_PROPOSAL] = p;
2220 	p += sizeof(struct sadb_prop);
2221 	sa_prop = (struct sadb_prop *) headers[SADB_EXT_PROPOSAL];
2222 	sa_prop->sadb_prop_num = 1; /* XXX One proposal only */
2223 	sa_prop->sadb_prop_len = (sizeof(struct sadb_prop) +
2224 	    (sizeof(struct sadb_comb) * sa_prop->sadb_prop_num)) /
2225 	    sizeof(uint64_t);
2226 
2227 	sadb_comb = p;
2228 
2229 	/* XXX Should actually ask the crypto layer what's supported */
2230 	for (j = 0; j < sa_prop->sadb_prop_num; j++) {
2231 		sadb_comb->sadb_comb_flags = 0;
2232 #ifdef IPSEC
2233 		if (ipsec_require_pfs)
2234 			sadb_comb->sadb_comb_flags |= SADB_SAFLAGS_PFS;
2235 
2236 		/* Set the encryption algorithm */
2237 		if (ipo->ipo_sproto == IPPROTO_ESP) {
2238 			if (!strncasecmp(ipsec_def_enc, "aes",
2239 			    sizeof("aes"))) {
2240 				sadb_comb->sadb_comb_encrypt = SADB_X_EALG_AES;
2241 				sadb_comb->sadb_comb_encrypt_minbits = 128;
2242 				sadb_comb->sadb_comb_encrypt_maxbits = 256;
2243 			} else if (!strncasecmp(ipsec_def_enc, "aesctr",
2244 			    sizeof("aesctr"))) {
2245 				sadb_comb->sadb_comb_encrypt = SADB_X_EALG_AESCTR;
2246 				sadb_comb->sadb_comb_encrypt_minbits = 128+32;
2247 				sadb_comb->sadb_comb_encrypt_maxbits = 256+32;
2248 			} else if (!strncasecmp(ipsec_def_enc, "3des",
2249 			    sizeof("3des"))) {
2250 				sadb_comb->sadb_comb_encrypt = SADB_EALG_3DESCBC;
2251 				sadb_comb->sadb_comb_encrypt_minbits = 192;
2252 				sadb_comb->sadb_comb_encrypt_maxbits = 192;
2253 			} else if (!strncasecmp(ipsec_def_enc, "blowfish",
2254 			    sizeof("blowfish"))) {
2255 				sadb_comb->sadb_comb_encrypt = SADB_X_EALG_BLF;
2256 				sadb_comb->sadb_comb_encrypt_minbits = 40;
2257 				sadb_comb->sadb_comb_encrypt_maxbits = BLF_MAXKEYLEN * 8;
2258 			} else if (!strncasecmp(ipsec_def_enc, "cast128",
2259 			    sizeof("cast128"))) {
2260 				sadb_comb->sadb_comb_encrypt = SADB_X_EALG_CAST;
2261 				sadb_comb->sadb_comb_encrypt_minbits = 40;
2262 				sadb_comb->sadb_comb_encrypt_maxbits = 128;
2263 			}
2264 		} else if (ipo->ipo_sproto == IPPROTO_IPCOMP) {
2265 			/* Set the compression algorithm */
2266 			if (!strncasecmp(ipsec_def_comp, "deflate",
2267 			    sizeof("deflate"))) {
2268 				sadb_comb->sadb_comb_encrypt = SADB_X_CALG_DEFLATE;
2269 				sadb_comb->sadb_comb_encrypt_minbits = 0;
2270 				sadb_comb->sadb_comb_encrypt_maxbits = 0;
2271 			} else if (!strncasecmp(ipsec_def_comp, "lzs",
2272 			    sizeof("lzs"))) {
2273 				sadb_comb->sadb_comb_encrypt = SADB_X_CALG_LZS;
2274 				sadb_comb->sadb_comb_encrypt_minbits = 0;
2275 				sadb_comb->sadb_comb_encrypt_maxbits = 0;
2276 			}
2277 		}
2278 
2279 		/* Set the authentication algorithm */
2280 		if (!strncasecmp(ipsec_def_auth, "hmac-sha1",
2281 		    sizeof("hmac-sha1"))) {
2282 			sadb_comb->sadb_comb_auth = SADB_AALG_SHA1HMAC;
2283 			sadb_comb->sadb_comb_auth_minbits = 160;
2284 			sadb_comb->sadb_comb_auth_maxbits = 160;
2285 		} else if (!strncasecmp(ipsec_def_auth, "hmac-ripemd160",
2286 		    sizeof("hmac_ripemd160"))) {
2287 			sadb_comb->sadb_comb_auth = SADB_X_AALG_RIPEMD160HMAC;
2288 			sadb_comb->sadb_comb_auth_minbits = 160;
2289 			sadb_comb->sadb_comb_auth_maxbits = 160;
2290 		} else if (!strncasecmp(ipsec_def_auth, "hmac-md5",
2291 		    sizeof("hmac-md5"))) {
2292 			sadb_comb->sadb_comb_auth = SADB_AALG_MD5HMAC;
2293 			sadb_comb->sadb_comb_auth_minbits = 128;
2294 			sadb_comb->sadb_comb_auth_maxbits = 128;
2295 		} else if (!strncasecmp(ipsec_def_auth, "hmac-sha2-256",
2296 		    sizeof("hmac-sha2-256"))) {
2297 			sadb_comb->sadb_comb_auth = SADB_X_AALG_SHA2_256;
2298 			sadb_comb->sadb_comb_auth_minbits = 256;
2299 			sadb_comb->sadb_comb_auth_maxbits = 256;
2300 		} else if (!strncasecmp(ipsec_def_auth, "hmac-sha2-384",
2301 		    sizeof("hmac-sha2-384"))) {
2302 			sadb_comb->sadb_comb_auth = SADB_X_AALG_SHA2_384;
2303 			sadb_comb->sadb_comb_auth_minbits = 384;
2304 			sadb_comb->sadb_comb_auth_maxbits = 384;
2305 		} else if (!strncasecmp(ipsec_def_auth, "hmac-sha2-512",
2306 		    sizeof("hmac-sha2-512"))) {
2307 			sadb_comb->sadb_comb_auth = SADB_X_AALG_SHA2_512;
2308 			sadb_comb->sadb_comb_auth_minbits = 512;
2309 			sadb_comb->sadb_comb_auth_maxbits = 512;
2310 		}
2311 
2312 		sadb_comb->sadb_comb_soft_allocations = ipsec_soft_allocations;
2313 		sadb_comb->sadb_comb_hard_allocations = ipsec_exp_allocations;
2314 
2315 		sadb_comb->sadb_comb_soft_bytes = ipsec_soft_bytes;
2316 		sadb_comb->sadb_comb_hard_bytes = ipsec_exp_bytes;
2317 
2318 		sadb_comb->sadb_comb_soft_addtime = ipsec_soft_timeout;
2319 		sadb_comb->sadb_comb_hard_addtime = ipsec_exp_timeout;
2320 
2321 		sadb_comb->sadb_comb_soft_usetime = ipsec_soft_first_use;
2322 		sadb_comb->sadb_comb_hard_usetime = ipsec_exp_first_use;
2323 #endif
2324 		sadb_comb++;
2325 	}
2326 
2327 	/* Send the ACQUIRE message to all compliant registered listeners. */
2328 	if ((rval = pfkeyv2_sendmessage(headers,
2329 	    PFKEYV2_SENDMESSAGE_REGISTERED, NULL, smsg->sadb_msg_satype, 0,
2330 	    ipo->ipo_rdomain)) != 0)
2331 		goto ret;
2332 
2333 	rval = 0;
2334 ret:
2335 	if (buffer != NULL) {
2336 		explicit_bzero(buffer, i);
2337 		free(buffer, M_PFKEY, i);
2338 	}
2339 
2340 	return (rval);
2341 }
2342 
2343 /*
2344  * Notify key management that an expiration went off. The second argument
2345  * specifies the type of expiration (soft or hard).
2346  */
2347 int
2348 pfkeyv2_expire(struct tdb *tdb, u_int16_t type)
2349 {
2350 	void *p, *headers[SADB_EXT_MAX+1], *buffer = NULL;
2351 	struct sadb_msg *smsg;
2352 	int rval = 0;
2353 	int i;
2354 
2355 	switch (tdb->tdb_sproto) {
2356 	case IPPROTO_AH:
2357 	case IPPROTO_ESP:
2358 	case IPPROTO_IPIP:
2359 	case IPPROTO_IPCOMP:
2360 #ifdef TCP_SIGNATURE
2361 	case IPPROTO_TCP:
2362 #endif /* TCP_SIGNATURE */
2363 		break;
2364 
2365 	default:
2366 		rval = EOPNOTSUPP;
2367 		goto ret;
2368 	}
2369 
2370 	i = sizeof(struct sadb_msg) + sizeof(struct sadb_sa) +
2371 	    2 * sizeof(struct sadb_lifetime) +
2372 	    sizeof(struct sadb_address) + PADUP(tdb->tdb_src.sa.sa_len) +
2373 	    sizeof(struct sadb_address) + PADUP(tdb->tdb_dst.sa.sa_len);
2374 
2375 	if (!(p = malloc(i, M_PFKEY, M_NOWAIT | M_ZERO))) {
2376 		rval = ENOMEM;
2377 		goto ret;
2378 	}
2379 
2380 	bzero(headers, sizeof(headers));
2381 
2382 	buffer = p;
2383 
2384 	headers[0] = p;
2385 	p += sizeof(struct sadb_msg);
2386 
2387 	smsg = (struct sadb_msg *) headers[0];
2388 	smsg->sadb_msg_version = PF_KEY_V2;
2389 	smsg->sadb_msg_type = SADB_EXPIRE;
2390 	smsg->sadb_msg_satype = tdb->tdb_satype;
2391 	smsg->sadb_msg_len = i / sizeof(uint64_t);
2392 
2393 	mtx_enter(&pfkeyv2_mtx);
2394 	smsg->sadb_msg_seq = pfkeyv2_seq++;
2395 	mtx_leave(&pfkeyv2_mtx);
2396 
2397 	headers[SADB_EXT_SA] = p;
2398 	export_sa(&p, tdb);
2399 
2400 	headers[SADB_EXT_LIFETIME_CURRENT] = p;
2401 	export_lifetime(&p, tdb, PFKEYV2_LIFETIME_CURRENT);
2402 
2403 	headers[type] = p;
2404 	export_lifetime(&p, tdb, type == SADB_EXT_LIFETIME_SOFT ?
2405 	    PFKEYV2_LIFETIME_SOFT : PFKEYV2_LIFETIME_HARD);
2406 
2407 	headers[SADB_EXT_ADDRESS_SRC] = p;
2408 	export_address(&p, &tdb->tdb_src.sa);
2409 
2410 	headers[SADB_EXT_ADDRESS_DST] = p;
2411 	export_address(&p, &tdb->tdb_dst.sa);
2412 
2413 	if ((rval = pfkeyv2_sendmessage(headers, PFKEYV2_SENDMESSAGE_BROADCAST,
2414 	    NULL, 0, 0, tdb->tdb_rdomain)) != 0)
2415 		goto ret;
2416 	/* XXX */
2417 	if (tdb->tdb_rdomain != tdb->tdb_rdomain_post)
2418 		if ((rval = pfkeyv2_sendmessage(headers,
2419 		    PFKEYV2_SENDMESSAGE_BROADCAST, NULL, 0, 0,
2420 		    tdb->tdb_rdomain_post)) != 0)
2421 			goto ret;
2422 
2423 	rval = 0;
2424 
2425  ret:
2426 	if (buffer != NULL) {
2427 		explicit_bzero(buffer, i);
2428 		free(buffer, M_PFKEY, i);
2429 	}
2430 
2431 	return (rval);
2432 }
2433 
2434 struct pfkeyv2_sysctl_walk {
2435 	void		*w_where;
2436 	size_t		 w_len;
2437 	int		 w_op;
2438 	u_int8_t	 w_satype;
2439 };
2440 
2441 int
2442 pfkeyv2_sysctl_walker(struct tdb *tdb, void *arg, int last)
2443 {
2444 	struct pfkeyv2_sysctl_walk *w = (struct pfkeyv2_sysctl_walk *)arg;
2445 	void *buffer = NULL;
2446 	int error = 0;
2447 	int usedlen, buflen, i;
2448 
2449 	if (w->w_satype != SADB_SATYPE_UNSPEC &&
2450 	    w->w_satype != tdb->tdb_satype)
2451 		return (0);
2452 
2453 	if (w->w_where) {
2454 		void *headers[SADB_EXT_MAX+1];
2455 		struct sadb_msg msg;
2456 
2457 		bzero(headers, sizeof(headers));
2458 		if ((error = pfkeyv2_get(tdb, headers, &buffer, &buflen,
2459 		    &usedlen)) != 0)
2460 			goto done;
2461 		if (w->w_len < sizeof(msg) + usedlen) {
2462 			error = ENOMEM;
2463 			goto done;
2464 		}
2465 		/* prepend header */
2466 		bzero(&msg, sizeof(msg));
2467 		msg.sadb_msg_version = PF_KEY_V2;
2468 		msg.sadb_msg_satype = tdb->tdb_satype;
2469 		msg.sadb_msg_type = SADB_DUMP;
2470 		msg.sadb_msg_len = (sizeof(msg) + usedlen) / sizeof(uint64_t);
2471 		if ((error = copyout(&msg, w->w_where, sizeof(msg))) != 0)
2472 			goto done;
2473 		w->w_where += sizeof(msg);
2474 		w->w_len -= sizeof(msg);
2475 		/* set extension type */
2476 		for (i = 1; i <= SADB_EXT_MAX; i++)
2477 			if (headers[i])
2478 				((struct sadb_ext *)
2479 				    headers[i])->sadb_ext_type = i;
2480 		if ((error = copyout(buffer, w->w_where, usedlen)) != 0)
2481 			goto done;
2482 		w->w_where += usedlen;
2483 		w->w_len -= usedlen;
2484 	} else {
2485 		if ((error = pfkeyv2_get(tdb, NULL, NULL, &buflen, NULL)) != 0)
2486 			return (error);
2487 		w->w_len += buflen;
2488 		w->w_len += sizeof(struct sadb_msg);
2489 	}
2490 
2491 done:
2492 	if (buffer != NULL) {
2493 		explicit_bzero(buffer, buflen);
2494 		free(buffer, M_PFKEY, buflen);
2495 	}
2496 	return (error);
2497 }
2498 
2499 int
2500 pfkeyv2_dump_policy(struct ipsec_policy *ipo, void **headers, void **buffer,
2501     int *lenp)
2502 {
2503 	int i, rval, perm;
2504 	void *p;
2505 
2506 	/* Find how much space we need. */
2507 	i = 2 * sizeof(struct sadb_protocol);
2508 
2509 	/* We'll need four of them: src, src mask, dst, dst mask. */
2510 	switch (ipo->ipo_addr.sen_type) {
2511 	case SENT_IP4:
2512 		i += 4 * PADUP(sizeof(struct sockaddr_in));
2513 		i += 4 * sizeof(struct sadb_address);
2514 		break;
2515 #ifdef INET6
2516 	case SENT_IP6:
2517 		i += 4 * PADUP(sizeof(struct sockaddr_in6));
2518 		i += 4 * sizeof(struct sadb_address);
2519 		break;
2520 #endif /* INET6 */
2521 	default:
2522 		return (EINVAL);
2523 	}
2524 
2525 	/* Local address, might be zeroed. */
2526 	switch (ipo->ipo_src.sa.sa_family) {
2527 	case 0:
2528 		break;
2529 	case AF_INET:
2530 		i += PADUP(sizeof(struct sockaddr_in));
2531 		i += sizeof(struct sadb_address);
2532 		break;
2533 #ifdef INET6
2534 	case AF_INET6:
2535 		i += PADUP(sizeof(struct sockaddr_in6));
2536 		i += sizeof(struct sadb_address);
2537 		break;
2538 #endif /* INET6 */
2539 	default:
2540 		return (EINVAL);
2541 	}
2542 
2543 	/* Remote address, might be zeroed. XXX ??? */
2544 	switch (ipo->ipo_dst.sa.sa_family) {
2545 	case 0:
2546 		break;
2547 	case AF_INET:
2548 		i += PADUP(sizeof(struct sockaddr_in));
2549 		i += sizeof(struct sadb_address);
2550 		break;
2551 #ifdef INET6
2552 	case AF_INET6:
2553 		i += PADUP(sizeof(struct sockaddr_in6));
2554 		i += sizeof(struct sadb_address);
2555 		break;
2556 #endif /* INET6 */
2557 	default:
2558 		return (EINVAL);
2559 	}
2560 
2561 	if (ipo->ipo_ids) {
2562 		i += sizeof(struct sadb_ident) + PADUP(ipo->ipo_ids->id_local->len);
2563 		i += sizeof(struct sadb_ident) + PADUP(ipo->ipo_ids->id_remote->len);
2564 	}
2565 
2566 	if (lenp)
2567 		*lenp = i;
2568 
2569 	if (buffer == NULL) {
2570 		rval = 0;
2571 		goto ret;
2572 	}
2573 
2574 	if (!(p = malloc(i, M_PFKEY, M_NOWAIT | M_ZERO))) {
2575 		rval = ENOMEM;
2576 		goto ret;
2577 	} else
2578 		*buffer = p;
2579 
2580 	/* Local address. */
2581 	if (ipo->ipo_src.sa.sa_family) {
2582 		headers[SADB_EXT_ADDRESS_SRC] = p;
2583 		export_address(&p, &ipo->ipo_src.sa);
2584 	}
2585 
2586 	/* Remote address. */
2587 	if (ipo->ipo_dst.sa.sa_family) {
2588 		headers[SADB_EXT_ADDRESS_DST] = p;
2589 		export_address(&p, &ipo->ipo_dst.sa);
2590 	}
2591 
2592 	/* Get actual flow. */
2593 	export_flow(&p, ipo->ipo_type, &ipo->ipo_addr, &ipo->ipo_mask,
2594 	    headers);
2595 
2596 	/* Add ids only when we are root. */
2597 	perm = suser(curproc);
2598 	if (perm == 0 && ipo->ipo_ids)
2599 		export_identities(&p, ipo->ipo_ids, 0, headers);
2600 
2601 	rval = 0;
2602 ret:
2603 	return (rval);
2604 }
2605 
2606 int
2607 pfkeyv2_sysctl_policydumper(struct ipsec_policy *ipo, void *arg,
2608     unsigned int tableid)
2609 {
2610 	struct pfkeyv2_sysctl_walk *w = (struct pfkeyv2_sysctl_walk *)arg;
2611 	void *buffer = 0;
2612 	int i, buflen, error = 0;
2613 
2614 	if (w->w_where) {
2615 		void *headers[SADB_EXT_MAX + 1];
2616 		struct sadb_msg msg;
2617 
2618 		bzero(headers, sizeof(headers));
2619 		if ((error = pfkeyv2_dump_policy(ipo, headers, &buffer,
2620 		    &buflen)) != 0)
2621 			goto done;
2622 		if (w->w_len < buflen) {
2623 			error = ENOMEM;
2624 			goto done;
2625 		}
2626 		/* prepend header */
2627 		bzero(&msg, sizeof(msg));
2628 		msg.sadb_msg_version = PF_KEY_V2;
2629 		if (ipo->ipo_sproto == IPPROTO_ESP)
2630 			msg.sadb_msg_satype = SADB_SATYPE_ESP;
2631 		else if (ipo->ipo_sproto == IPPROTO_AH)
2632 			msg.sadb_msg_satype = SADB_SATYPE_AH;
2633 		else if (ipo->ipo_sproto == IPPROTO_IPCOMP)
2634 			msg.sadb_msg_satype = SADB_X_SATYPE_IPCOMP;
2635 		else if (ipo->ipo_sproto == IPPROTO_IPIP)
2636 			msg.sadb_msg_satype = SADB_X_SATYPE_IPIP;
2637 		msg.sadb_msg_type = SADB_X_SPDDUMP;
2638 		msg.sadb_msg_len = (sizeof(msg) + buflen) / sizeof(uint64_t);
2639 		if ((error = copyout(&msg, w->w_where, sizeof(msg))) != 0)
2640 			goto done;
2641 		w->w_where += sizeof(msg);
2642 		w->w_len -= sizeof(msg);
2643 		/* set extension type */
2644 		for (i = 1; i <= SADB_EXT_MAX; i++)
2645 			if (headers[i])
2646 				((struct sadb_ext *)
2647 				    headers[i])->sadb_ext_type = i;
2648 		if ((error = copyout(buffer, w->w_where, buflen)) != 0)
2649 			goto done;
2650 		w->w_where += buflen;
2651 		w->w_len -= buflen;
2652 	} else {
2653 		if ((error = pfkeyv2_dump_policy(ipo, NULL, NULL,
2654 		    &buflen)) != 0)
2655 			goto done;
2656 		w->w_len += buflen;
2657 		w->w_len += sizeof(struct sadb_msg);
2658 	}
2659 
2660 done:
2661 	if (buffer)
2662 		free(buffer, M_PFKEY, buflen);
2663 	return (error);
2664 }
2665 
2666 int
2667 pfkeyv2_policy_flush(struct ipsec_policy *ipo, void *arg, unsigned int tableid)
2668 {
2669 	int error;
2670 
2671 	error = ipsec_delete_policy(ipo);
2672 	if (error == 0)
2673 		error = EAGAIN;
2674 
2675 	return (error);
2676 }
2677 
2678 int
2679 pfkeyv2_sysctl(int *name, u_int namelen, void *oldp, size_t *oldlenp,
2680     void *new, size_t newlen)
2681 {
2682 	struct pfkeyv2_sysctl_walk w;
2683 	int error = EINVAL;
2684 	u_int rdomain;
2685 	u_int tableid;
2686 
2687 	if (new)
2688 		return (EPERM);
2689 	if (namelen < 1)
2690 		return (EINVAL);
2691 	w.w_op = name[0];
2692 	w.w_satype = name[1];
2693 	w.w_where = oldp;
2694 	w.w_len = oldp ? *oldlenp : 0;
2695 
2696 	if (namelen == 3) {
2697 		tableid = name[2];
2698 		if (!rtable_exists(tableid))
2699 			return (ENOENT);
2700 	} else
2701 		tableid = curproc->p_p->ps_rtableid;
2702 	rdomain = rtable_l2(tableid);
2703 
2704 	switch(w.w_op) {
2705 	case NET_KEY_SADB_DUMP:
2706 		if ((error = suser(curproc)) != 0)
2707 			return (error);
2708 		NET_LOCK();
2709 		error = tdb_walk(rdomain, pfkeyv2_sysctl_walker, &w);
2710 		NET_UNLOCK();
2711 		if (oldp)
2712 			*oldlenp = w.w_where - oldp;
2713 		else
2714 			*oldlenp = w.w_len;
2715 		break;
2716 
2717 	case NET_KEY_SPD_DUMP:
2718 		NET_LOCK();
2719 		error = spd_table_walk(rdomain,
2720 		    pfkeyv2_sysctl_policydumper, &w);
2721 		NET_UNLOCK();
2722 		if (oldp)
2723 			*oldlenp = w.w_where - oldp;
2724 		else
2725 			*oldlenp = w.w_len;
2726 		break;
2727 	}
2728 
2729 	return (error);
2730 }
2731