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