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