1 /* $OpenBSD: pfkeyv2.c,v 1.92.2.1 2004/12/14 13:21:06 markus 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 <sys/types.h>
72 #include <sys/param.h>
73 #include <sys/socket.h>
74 #include <sys/systm.h>
75 #include <sys/mbuf.h>
76 #include <sys/kernel.h>
77 #include <sys/proc.h>
78 #include <net/route.h>
79 #include <netinet/ip_ipsp.h>
80 #include <net/pfkeyv2.h>
81 #include <netinet/ip_ah.h>
82 #include <netinet/ip_esp.h>
83 #include <netinet/ip_ipcomp.h>
84 #include <crypto/blf.h>
85 
86 #define PFKEYV2_PROTOCOL 2
87 #define GETSPI_TRIES 10
88 
89 /* Static globals */
90 static struct pfkeyv2_socket *pfkeyv2_sockets = NULL;
91 static struct pfkey_version pfkeyv2_version;
92 static uint32_t pfkeyv2_seq = 1;
93 static int nregistered = 0;
94 static int npromisc = 0;
95 
96 static const struct sadb_alg ealgs[] = {
97 	{ SADB_EALG_DESCBC, 64, 64, 64 },
98 	{ SADB_EALG_3DESCBC, 64, 192, 192 },
99 	{ SADB_X_EALG_BLF, 64, 40, BLF_MAXKEYLEN * 8},
100 	{ SADB_X_EALG_CAST, 64, 40, 128},
101 	{ SADB_X_EALG_SKIPJACK, 64, 80, 80},
102 	{ SADB_X_EALG_AES, 128, 64, 256}
103 };
104 
105 static const struct sadb_alg aalgs[] = {
106 	{ SADB_AALG_SHA1HMAC, 0, 160, 160 },
107 	{ SADB_AALG_MD5HMAC, 0, 128, 128 },
108 	{ SADB_X_AALG_RIPEMD160HMAC, 0, 160, 160 },
109 	{ SADB_X_AALG_SHA2_256, 0, 256, 256 },
110 	{ SADB_X_AALG_SHA2_384, 0, 384, 384 },
111 	{ SADB_X_AALG_SHA2_512, 0, 512, 512 }
112 };
113 
114 static const struct sadb_alg calgs[] = {
115 	{ SADB_X_CALG_DEFLATE, 0, 0, 0},
116 	{ SADB_X_CALG_LZS, 0, 0, 0}
117 };
118 
119 extern uint32_t sadb_exts_allowed_out[SADB_MAX+1];
120 extern uint32_t sadb_exts_required_out[SADB_MAX+1];
121 
122 extern struct pool ipsec_policy_pool;
123 
124 /*
125  * Wrapper around m_devget(); copy data from contiguous buffer to mbuf
126  * chain.
127  */
128 int
pfdatatopacket(void * data,int len,struct mbuf ** packet)129 pfdatatopacket(void *data, int len, struct mbuf **packet) {
130 	if (!(*packet = m_devget(data, len, 0, NULL, NULL)))
131 		return (ENOMEM);
132 	return (0);
133 }
134 
135 /*
136  * Create a new PF_KEYv2 socket.
137  */
138 int
pfkeyv2_create(struct socket * socket)139 pfkeyv2_create(struct socket *socket) {
140 	struct pfkeyv2_socket *pfkeyv2_socket;
141 
142 	if (!(pfkeyv2_socket = malloc(sizeof(struct pfkeyv2_socket),
143 	    M_PFKEY, M_DONTWAIT)))
144 		return (ENOMEM);
145 
146 	bzero(pfkeyv2_socket, sizeof(struct pfkeyv2_socket));
147 	pfkeyv2_socket->next = pfkeyv2_sockets;
148 	pfkeyv2_socket->socket = socket;
149 	pfkeyv2_socket->pid = curproc->p_pid;
150 
151 	pfkeyv2_sockets = pfkeyv2_socket;
152 
153 	return (0);
154 }
155 
156 /*
157  * Close a PF_KEYv2 socket.
158  */
159 int
pfkeyv2_release(struct socket * socket)160 pfkeyv2_release(struct socket *socket)
161 {
162 	struct pfkeyv2_socket **pp;
163 
164 	for (pp = &pfkeyv2_sockets; *pp && ((*pp)->socket != socket);
165 	    pp = &((*pp)->next))
166 		/*EMPTY*/;
167 
168 	if (*pp) {
169 		struct pfkeyv2_socket *pfkeyv2_socket;
170 
171 		pfkeyv2_socket = *pp;
172 		*pp = (*pp)->next;
173 
174 		if (pfkeyv2_socket->flags & PFKEYV2_SOCKETFLAGS_REGISTERED)
175 			nregistered--;
176 
177 		if (pfkeyv2_socket->flags & PFKEYV2_SOCKETFLAGS_PROMISC)
178 			npromisc--;
179 
180 		free(pfkeyv2_socket, M_PFKEY);
181 	}
182 
183 	return (0);
184 }
185 
186 /*
187  * Send a PFKEYv2 message, possibly to many receivers, based on the
188  * satype of the socket (which is set by the REGISTER message), and the
189  * third argument.
190  */
191 int
pfkeyv2_sendmessage(void ** headers,int mode,struct socket * socket,u_int8_t satype,int count)192 pfkeyv2_sendmessage(void **headers, int mode, struct socket *socket,
193     u_int8_t satype, int count)
194 {
195 	int i, j, rval;
196 	void *p, *buffer = NULL;
197 	struct mbuf *packet;
198 	struct pfkeyv2_socket *s;
199 	struct sadb_msg *smsg;
200 
201 	/* Find out how much space we'll need... */
202 	j = sizeof(struct sadb_msg);
203 
204 	for (i = 1; i <= SADB_EXT_MAX; i++)
205 		if (headers[i])
206 			j += ((struct sadb_ext *)headers[i])->sadb_ext_len *
207 			    sizeof(uint64_t);
208 
209 	/* ...and allocate it */
210 	if (!(buffer = malloc(j + sizeof(struct sadb_msg), M_PFKEY,
211 	    M_DONTWAIT))) {
212 		rval = ENOMEM;
213 		goto ret;
214 	}
215 
216 	p = buffer + sizeof(struct sadb_msg);
217 	bcopy(headers[0], p, sizeof(struct sadb_msg));
218 	((struct sadb_msg *) p)->sadb_msg_len = j / sizeof(uint64_t);
219 	p += sizeof(struct sadb_msg);
220 
221 	/* Copy payloads in the packet */
222 	for (i = 1; i <= SADB_EXT_MAX; i++)
223 		if (headers[i]) {
224 			((struct sadb_ext *) headers[i])->sadb_ext_type = i;
225 			bcopy(headers[i], p, EXTLEN(headers[i]));
226 			p += EXTLEN(headers[i]);
227 		}
228 
229 	if ((rval = pfdatatopacket(buffer + sizeof(struct sadb_msg),
230 	    j, &packet)) != 0)
231 		goto ret;
232 
233 	switch (mode) {
234 	case PFKEYV2_SENDMESSAGE_UNICAST:
235 		/*
236 		 * Send message to the specified socket, plus all
237 		 * promiscuous listeners.
238 		 */
239 		pfkey_sendup(socket, packet, 0);
240 
241 		/*
242 		 * Promiscuous messages contain the original message
243 		 * encapsulated in another sadb_msg header.
244 		 */
245 		bzero(buffer, sizeof(struct sadb_msg));
246 		smsg = (struct sadb_msg *) buffer;
247 		smsg->sadb_msg_version = PF_KEY_V2;
248 		smsg->sadb_msg_type = SADB_X_PROMISC;
249 		smsg->sadb_msg_len = (sizeof(struct sadb_msg) + j) /
250 		    sizeof(uint64_t);
251 		smsg->sadb_msg_seq = 0;
252 
253 		/* Copy to mbuf chain */
254 		if ((rval = pfdatatopacket(buffer, sizeof(struct sadb_msg) + j,
255 		    &packet)) != 0)
256 			goto ret;
257 
258 		/*
259 		 * Search for promiscuous listeners, skipping the
260 		 * original destination.
261 		 */
262 		for (s = pfkeyv2_sockets; s; s = s->next)
263 			if ((s->flags & PFKEYV2_SOCKETFLAGS_PROMISC) &&
264 			    (s->socket != socket))
265 				pfkey_sendup(s->socket, packet, 1);
266 
267 		/* Done, let's be a bit paranoid */
268 		m_zero(packet);
269 		m_freem(packet);
270 		break;
271 
272 	case PFKEYV2_SENDMESSAGE_REGISTERED:
273 		/*
274 		 * Send the message to all registered sockets that match
275 		 * the specified satype (e.g., all IPSEC-ESP negotiators)
276 		 */
277 		for (s = pfkeyv2_sockets; s; s = s->next)
278 			if (s->flags & PFKEYV2_SOCKETFLAGS_REGISTERED) {
279 				if (!satype)    /* Just send to everyone registered */
280 					pfkey_sendup(s->socket, packet, 1);
281 				else {
282 					/* Check for specified satype */
283 					if ((1 << satype) & s->registration)
284 						pfkey_sendup(s->socket, packet, 1);
285 				}
286 			}
287 
288 		/* Free last/original copy of the packet */
289 		m_freem(packet);
290 
291 		/* Encapsulate the original message "inside" an sadb_msg header */
292 		bzero(buffer, sizeof(struct sadb_msg));
293 		smsg = (struct sadb_msg *) buffer;
294 		smsg->sadb_msg_version = PF_KEY_V2;
295 		smsg->sadb_msg_type = SADB_X_PROMISC;
296 		smsg->sadb_msg_len = (sizeof(struct sadb_msg) + j) /
297 		    sizeof(uint64_t);
298 		smsg->sadb_msg_seq = 0;
299 
300 		/* Convert to mbuf chain */
301 		if ((rval = pfdatatopacket(buffer, sizeof(struct sadb_msg) + j,
302 		    &packet)) != 0)
303 			goto ret;
304 
305 		/* Send to all registered promiscuous listeners */
306 		for (s = pfkeyv2_sockets; s; s = s->next)
307 			if ((s->flags & PFKEYV2_SOCKETFLAGS_PROMISC) &&
308 			    !(s->flags & PFKEYV2_SOCKETFLAGS_REGISTERED))
309 				pfkey_sendup(s->socket, packet, 1);
310 
311 		m_freem(packet);
312 		break;
313 
314 	case PFKEYV2_SENDMESSAGE_BROADCAST:
315 		/* Send message to all sockets */
316 		for (s = pfkeyv2_sockets; s; s = s->next)
317 			pfkey_sendup(s->socket, packet, 1);
318 
319 		m_freem(packet);
320 		break;
321 	}
322 
323 ret:
324 	if (buffer != NULL) {
325 		bzero(buffer, j + sizeof(struct sadb_msg));
326 		free(buffer, M_PFKEY);
327 	}
328 
329 	return (rval);
330 }
331 
332 /*
333  * Get SPD information for an ACQUIRE. We setup the message such that
334  * the SRC/DST payloads are relative to us (regardless of whether the
335  * SPD rule was for incoming or outgoing packets).
336  */
337 int
pfkeyv2_policy(struct ipsec_acquire * ipa,void ** headers,void ** buffer)338 pfkeyv2_policy(struct ipsec_acquire *ipa, void **headers, void **buffer)
339 {
340 	union sockaddr_union sunion;
341 	struct sadb_protocol *sp;
342 	int rval, i, dir;
343 	void *p;
344 
345 	/* Find out how big a buffer we need */
346 	i = 4 * sizeof(struct sadb_address) + sizeof(struct sadb_protocol);
347 	bzero(&sunion, sizeof(union sockaddr_union));
348 
349 	switch (ipa->ipa_info.sen_type) {
350 #ifdef INET
351 	case SENT_IP4:
352 		i += 4 * PADUP(sizeof(struct sockaddr_in));
353 		sunion.sa.sa_family = AF_INET;
354 		sunion.sa.sa_len = sizeof(struct sockaddr_in);
355 		dir = ipa->ipa_info.sen_direction;
356 		break;
357 #endif /* INET */
358 
359 #ifdef INET6
360 	case SENT_IP6:
361 		i += 4 * PADUP(sizeof(struct sockaddr_in6));
362 		sunion.sa.sa_family = AF_INET6;
363 		sunion.sa.sa_len = sizeof(struct sockaddr_in6);
364 		dir = ipa->ipa_info.sen_ip6_direction;
365 		break;
366 #endif /* INET6 */
367 
368 	default:
369 		return (EINVAL);
370 	}
371 
372 	if (!(p = malloc(i, M_PFKEY, M_DONTWAIT))) {
373 		rval = ENOMEM;
374 		goto ret;
375 	} else {
376 		*buffer = p;
377 		bzero(p, i);
378 	}
379 
380 	if (dir == IPSP_DIRECTION_OUT)
381 		headers[SADB_X_EXT_SRC_FLOW] = p;
382 	else
383 		headers[SADB_X_EXT_DST_FLOW] = p;
384 	switch (sunion.sa.sa_family) {
385 #ifdef INET
386 	case AF_INET:
387 		sunion.sin.sin_addr = ipa->ipa_info.sen_ip_src;
388 		sunion.sin.sin_port = ipa->ipa_info.sen_sport;
389 		break;
390 #endif /* INET */
391 
392 #ifdef INET6
393 	case AF_INET6:
394 		sunion.sin6.sin6_addr = ipa->ipa_info.sen_ip6_src;
395 		sunion.sin6.sin6_port = ipa->ipa_info.sen_ip6_sport;
396 		break;
397 #endif /* INET6 */
398 	}
399 	export_address(&p, (struct sockaddr *) &sunion);
400 
401 	if (dir == IPSP_DIRECTION_OUT)
402 		headers[SADB_X_EXT_SRC_MASK] = p;
403 	else
404 		headers[SADB_X_EXT_DST_MASK] = p;
405 	switch (sunion.sa.sa_family) {
406 #ifdef INET
407 	case AF_INET:
408 		sunion.sin.sin_addr = ipa->ipa_mask.sen_ip_src;
409 		sunion.sin.sin_port = ipa->ipa_mask.sen_sport;
410 		break;
411 #endif /* INET */
412 
413 #ifdef INET6
414 	case AF_INET6:
415 		sunion.sin6.sin6_addr = ipa->ipa_mask.sen_ip6_src;
416 		sunion.sin6.sin6_port = ipa->ipa_mask.sen_ip6_sport;
417 		break;
418 #endif /* INET6 */
419 	}
420 	export_address(&p, (struct sockaddr *) &sunion);
421 
422 	if (dir == IPSP_DIRECTION_OUT)
423 		headers[SADB_X_EXT_DST_FLOW] = p;
424 	else
425 		headers[SADB_X_EXT_SRC_FLOW] = p;
426 	switch (sunion.sa.sa_family) {
427 #ifdef INET
428 	case AF_INET:
429 		sunion.sin.sin_addr = ipa->ipa_info.sen_ip_dst;
430 		sunion.sin.sin_port = ipa->ipa_info.sen_dport;
431 		break;
432 #endif /* INET */
433 
434 #ifdef INET6
435 	case AF_INET6:
436 		sunion.sin6.sin6_addr = ipa->ipa_info.sen_ip6_dst;
437 		sunion.sin6.sin6_port = ipa->ipa_info.sen_ip6_dport;
438 		break;
439 #endif /* INET6 */
440 	}
441 	export_address(&p, (struct sockaddr *) &sunion);
442 
443 	if (dir == IPSP_DIRECTION_OUT)
444 		headers[SADB_X_EXT_DST_MASK] = p;
445 	else
446 		headers[SADB_X_EXT_SRC_MASK] = p;
447 	switch (sunion.sa.sa_family) {
448 #ifdef INET
449 	case AF_INET:
450 		sunion.sin.sin_addr = ipa->ipa_mask.sen_ip_dst;
451 		sunion.sin.sin_port = ipa->ipa_mask.sen_dport;
452 		break;
453 #endif /* INET */
454 
455 #ifdef INET6
456 	case AF_INET6:
457 		sunion.sin6.sin6_addr = ipa->ipa_mask.sen_ip6_dst;
458 		sunion.sin6.sin6_port = ipa->ipa_mask.sen_ip6_dport;
459 		break;
460 #endif /* INET6 */
461 	}
462 	export_address(&p, (struct sockaddr *) &sunion);
463 
464 	headers[SADB_X_EXT_FLOW_TYPE] = p;
465 	sp = p;
466 	sp->sadb_protocol_len = sizeof(struct sadb_protocol) /
467 	    sizeof(u_int64_t);
468 	switch (sunion.sa.sa_family) {
469 #ifdef INET
470 	case AF_INET:
471 		if (ipa->ipa_mask.sen_proto)
472 			sp->sadb_protocol_proto = ipa->ipa_info.sen_proto;
473 		sp->sadb_protocol_direction = ipa->ipa_info.sen_direction;
474 		break;
475 #endif /* INET */
476 
477 #ifdef INET6
478 	case AF_INET6:
479 		if (ipa->ipa_mask.sen_ip6_proto)
480 			sp->sadb_protocol_proto = ipa->ipa_info.sen_ip6_proto;
481 		sp->sadb_protocol_direction = ipa->ipa_info.sen_ip6_direction;
482 		break;
483 #endif /* INET6 */
484 	}
485 
486 	rval = 0;
487 
488 ret:
489 	return (rval);
490 }
491 
492 /*
493  * Get all the information contained in an SA to a PFKEYV2 message.
494  */
495 int
pfkeyv2_get(struct tdb * sa,void ** headers,void ** buffer)496 pfkeyv2_get(struct tdb *sa, void **headers, void **buffer)
497 {
498 	int rval, i;
499 	void *p;
500 
501 	/* Find how much space we need */
502 	i = sizeof(struct sadb_sa) + sizeof(struct sadb_lifetime);
503 
504 	if (sa->tdb_soft_allocations || sa->tdb_soft_bytes ||
505 	    sa->tdb_soft_timeout || sa->tdb_soft_first_use)
506 		i += sizeof(struct sadb_lifetime);
507 
508 	if (sa->tdb_exp_allocations || sa->tdb_exp_bytes ||
509 	    sa->tdb_exp_timeout || sa->tdb_exp_first_use)
510 		i += sizeof(struct sadb_lifetime);
511 
512 	if (sa->tdb_src.sa.sa_family)
513 		i += sizeof(struct sadb_address) + PADUP(SA_LEN(&sa->tdb_src.sa));
514 
515 	if (sa->tdb_dst.sa.sa_family)
516 		i += sizeof(struct sadb_address) + PADUP(SA_LEN(&sa->tdb_dst.sa));
517 
518 	if (sa->tdb_proxy.sa.sa_family)
519 		i += sizeof(struct sadb_address) + PADUP(SA_LEN(&sa->tdb_proxy.sa));
520 
521 	if (sa->tdb_srcid)
522 		i += PADUP(sa->tdb_srcid->ref_len) + sizeof(struct sadb_ident);
523 
524 	if (sa->tdb_dstid)
525 		i += PADUP(sa->tdb_dstid->ref_len) + sizeof(struct sadb_ident);
526 
527 	if (sa->tdb_local_cred)
528 		i += PADUP(sa->tdb_local_cred->ref_len) + sizeof(struct sadb_x_cred);
529 
530 	if (sa->tdb_remote_cred)
531 		i += PADUP(sa->tdb_remote_cred->ref_len) + sizeof(struct sadb_x_cred);
532 
533 	if (sa->tdb_local_auth)
534 		i += PADUP(sa->tdb_local_auth->ref_len) + sizeof(struct sadb_x_cred);
535 
536 	if (sa->tdb_remote_auth)
537 		i += PADUP(sa->tdb_remote_auth->ref_len) + sizeof(struct sadb_x_cred);
538 
539 	if (sa->tdb_amxkey)
540 		i+= PADUP(sa->tdb_amxkeylen) + sizeof(struct sadb_key);
541 
542 	if (sa->tdb_emxkey)
543 		i+= PADUP(sa->tdb_emxkeylen) + sizeof(struct sadb_key);
544 
545 	if (sa->tdb_udpencap_port)
546 		i+= sizeof(struct sadb_x_udpencap);
547 
548 	if (!(p = malloc(i, M_PFKEY, M_DONTWAIT))) {
549 		rval = ENOMEM;
550 		goto ret;
551 	} else {
552 		*buffer = p;
553 		bzero(p, i);
554 	}
555 
556 	headers[SADB_EXT_SA] = p;
557 
558 	export_sa(&p, sa);  /* Export SA information (mostly flags) */
559 
560 	/* Export lifetimes where applicable */
561 	headers[SADB_EXT_LIFETIME_CURRENT] = p;
562 	export_lifetime(&p, sa, PFKEYV2_LIFETIME_CURRENT);
563 
564 	if (sa->tdb_soft_allocations || sa->tdb_soft_bytes ||
565 	    sa->tdb_soft_first_use || sa->tdb_soft_timeout) {
566 		headers[SADB_EXT_LIFETIME_SOFT] = p;
567 		export_lifetime(&p, sa, PFKEYV2_LIFETIME_SOFT);
568 	}
569 
570 	if (sa->tdb_exp_allocations || sa->tdb_exp_bytes ||
571 	    sa->tdb_exp_first_use || sa->tdb_exp_timeout) {
572 		headers[SADB_EXT_LIFETIME_HARD] = p;
573 		export_lifetime(&p, sa, PFKEYV2_LIFETIME_HARD);
574 	}
575 
576 	/* Export TDB source address */
577 	headers[SADB_EXT_ADDRESS_SRC] = p;
578 	export_address(&p, (struct sockaddr *) &sa->tdb_src);
579 
580 	/* Export TDB destination address */
581 	headers[SADB_EXT_ADDRESS_DST] = p;
582 	export_address(&p, (struct sockaddr *) &sa->tdb_dst);
583 
584 	/* Export TDB proxy address, if present */
585 	if (SA_LEN(&sa->tdb_proxy.sa)) {
586 		headers[SADB_EXT_ADDRESS_PROXY] = p;
587 		export_address(&p, (struct sockaddr *) &sa->tdb_proxy);
588 	}
589 
590 	/* Export source identity, if present */
591 	if (sa->tdb_srcid) {
592 		headers[SADB_EXT_IDENTITY_SRC] = p;
593 		export_identity(&p, sa, PFKEYV2_IDENTITY_SRC);
594 	}
595 
596 	/* Export destination identity, if present */
597 	if (sa->tdb_dstid) {
598 		headers[SADB_EXT_IDENTITY_DST] = p;
599 		export_identity(&p, sa, PFKEYV2_IDENTITY_DST);
600 	}
601 
602 	/* Export credentials, if present */
603 	if (sa->tdb_local_cred) {
604 		headers[SADB_X_EXT_LOCAL_CREDENTIALS] = p;
605 		export_credentials(&p, sa, PFKEYV2_CRED_LOCAL);
606 	}
607 
608 	if (sa->tdb_remote_cred) {
609 		headers[SADB_X_EXT_REMOTE_CREDENTIALS] = p;
610 		export_credentials(&p, sa, PFKEYV2_CRED_REMOTE);
611 	}
612 
613 	/* Export authentication information, if present */
614 	if (sa->tdb_local_auth) {
615 		headers[SADB_X_EXT_LOCAL_AUTH] = p;
616 		export_auth(&p, sa, PFKEYV2_AUTH_LOCAL);
617 	}
618 
619 	if (sa->tdb_remote_auth) {
620 		headers[SADB_X_EXT_REMOTE_AUTH] = p;
621 		export_auth(&p, sa, PFKEYV2_AUTH_REMOTE);
622 	}
623 
624 	/* Export authentication key, if present */
625 	if (sa->tdb_amxkey) {
626 		headers[SADB_EXT_KEY_AUTH] = p;
627 		export_key(&p, sa, PFKEYV2_AUTHENTICATION_KEY);
628 	}
629 
630 	/* Export encryption key, if present */
631 	if (sa->tdb_emxkey) {
632 		headers[SADB_EXT_KEY_ENCRYPT] = p;
633 		export_key(&p, sa, PFKEYV2_ENCRYPTION_KEY);
634 	}
635 
636 	/* Export UDP encapsulation port, if present */
637 	if (sa->tdb_udpencap_port) {
638 		headers[SADB_X_EXT_UDPENCAP] = p;
639 		export_udpencap(&p, sa);
640 	}
641 
642 	rval = 0;
643 
644  ret:
645 	return (rval);
646 }
647 
648 /*
649  * Dump a TDB.
650  */
651 int
pfkeyv2_dump_walker(struct tdb * sa,void * state,int last)652 pfkeyv2_dump_walker(struct tdb *sa, void *state, int last)
653 {
654 	struct dump_state *dump_state = (struct dump_state *) state;
655 	void *headers[SADB_EXT_MAX+1], *buffer;
656 	int rval;
657 
658 	/* If not satype was specified, dump all TDBs */
659 	if (!dump_state->sadb_msg->sadb_msg_satype ||
660 	    (sa->tdb_satype == dump_state->sadb_msg->sadb_msg_satype)) {
661 		bzero(headers, sizeof(headers));
662 		headers[0] = (void *) dump_state->sadb_msg;
663 
664 		/* Get the information from the TDB to a PFKEYv2 message */
665 		if ((rval = pfkeyv2_get(sa, headers, &buffer)) != 0)
666 			return (rval);
667 
668 		if (last)
669 			((struct sadb_msg *)headers[0])->sadb_msg_seq = 0;
670 
671 		/* Send the message to the specified socket */
672 		rval = pfkeyv2_sendmessage(headers,
673 		    PFKEYV2_SENDMESSAGE_UNICAST, dump_state->socket, 0, 0);
674 
675 		free(buffer, M_PFKEY);
676 		if (rval)
677 			return (rval);
678 	}
679 
680 	return (0);
681 }
682 
683 /*
684  * Delete an SA.
685  */
686 int
pfkeyv2_flush_walker(struct tdb * sa,void * satype_vp,int last)687 pfkeyv2_flush_walker(struct tdb *sa, void *satype_vp, int last)
688 {
689 	if (!(*((u_int8_t *) satype_vp)) ||
690 	    sa->tdb_satype == *((u_int8_t *) satype_vp))
691 		tdb_delete(sa);
692 	return (0);
693 }
694 
695 /*
696  * Convert between SATYPEs and IPsec protocols, taking into consideration
697  * sysctl variables enabling/disabling ESP/AH and the presence of the old
698  * IPsec transforms.
699  */
700 int
pfkeyv2_get_proto_alg(u_int8_t satype,u_int8_t * sproto,int * alg)701 pfkeyv2_get_proto_alg(u_int8_t satype, u_int8_t *sproto, int *alg)
702 {
703 	switch (satype) {
704 	case SADB_SATYPE_AH:
705 		if (!ah_enable)
706 			return (EOPNOTSUPP);
707 
708 		*sproto = IPPROTO_AH;
709 
710 		if(alg != NULL)
711 			*alg = satype = XF_AH;
712 
713 		break;
714 
715 	case SADB_SATYPE_ESP:
716 		if (!esp_enable)
717 			return (EOPNOTSUPP);
718 
719 		*sproto = IPPROTO_ESP;
720 
721 		if(alg != NULL)
722 			*alg = satype = XF_ESP;
723 
724 		break;
725 
726 	case SADB_X_SATYPE_IPIP:
727 		*sproto = IPPROTO_IPIP;
728 
729 		if (alg != NULL)
730 			*alg = XF_IP4;
731 
732 		break;
733 
734 	case SADB_X_SATYPE_IPCOMP:
735 		if (!ipcomp_enable)
736 			return (EOPNOTSUPP);
737 
738 		*sproto = IPPROTO_IPCOMP;
739 
740 		if(alg != NULL)
741 			*alg = satype = XF_IPCOMP;
742 
743 		break;
744 
745 #ifdef TCP_SIGNATURE
746 	case SADB_X_SATYPE_TCPSIGNATURE:
747 		*sproto = IPPROTO_TCP;
748 
749 		if (alg != NULL)
750 			*alg = XF_TCPSIGNATURE;
751 
752 		break;
753 #endif /* TCP_SIGNATURE */
754 
755 	default: /* Nothing else supported */
756 		return (EOPNOTSUPP);
757 	}
758 
759 	return (0);
760 }
761 
762 /*
763  * Handle all messages from userland to kernel.
764  */
765 int
pfkeyv2_send(struct socket * socket,void * message,int len)766 pfkeyv2_send(struct socket *socket, void *message, int len)
767 {
768 	int i, j, rval = 0, mode = PFKEYV2_SENDMESSAGE_BROADCAST;
769 	int delflag = 0, s;
770 	struct sockaddr_encap encapdst, encapnetmask, encapgw;
771 	struct ipsec_policy *ipo, *tmpipo;
772 	struct ipsec_acquire *ipa;
773 
774 	struct pfkeyv2_socket *pfkeyv2_socket, *so = NULL;
775 
776 	void *freeme = NULL, *bckptr = NULL;
777 	void *headers[SADB_EXT_MAX + 1];
778 
779 	union sockaddr_union *sunionp;
780 
781 	struct tdb sa, *sa2 = NULL;
782 
783 	struct sadb_msg *smsg = NULL;
784 	struct sadb_spirange *sprng;
785 	struct sadb_sa *ssa;
786 	struct sadb_supported *ssup;
787 	struct sadb_ident *sid;
788 
789 	/* Verify that we received this over a legitimate pfkeyv2 socket */
790 	bzero(headers, sizeof(headers));
791 
792 	for (pfkeyv2_socket = pfkeyv2_sockets; pfkeyv2_socket;
793 	    pfkeyv2_socket = pfkeyv2_socket->next)
794 		if (pfkeyv2_socket->socket == socket)
795 			break;
796 
797 	if (!pfkeyv2_socket) {
798 		rval = EINVAL;
799 		goto ret;
800 	}
801 
802 	/* If we have any promiscuous listeners, send them a copy of the message */
803 	if (npromisc) {
804 		struct mbuf *packet;
805 
806 		if (!(freeme = malloc(sizeof(struct sadb_msg) + len, M_PFKEY,
807 		    M_DONTWAIT))) {
808 			rval = ENOMEM;
809 			goto ret;
810 		}
811 
812 		/* Initialize encapsulating header */
813 		bzero(freeme, sizeof(struct sadb_msg));
814 		smsg = (struct sadb_msg *) freeme;
815 		smsg->sadb_msg_version = PF_KEY_V2;
816 		smsg->sadb_msg_type = SADB_X_PROMISC;
817 		smsg->sadb_msg_len = (sizeof(struct sadb_msg) + len) /
818 		    sizeof(uint64_t);
819 		smsg->sadb_msg_seq = curproc->p_pid;
820 
821 		bcopy(message, freeme + sizeof(struct sadb_msg), len);
822 
823 		/* Convert to mbuf chain */
824 		if ((rval = pfdatatopacket(freeme,
825 		    sizeof(struct sadb_msg) + len, &packet)) != 0)
826 			goto ret;
827 
828 		/* Send to all promiscuous listeners */
829 		for (so = pfkeyv2_sockets; so; so = so->next)
830 			if (so->flags & PFKEYV2_SOCKETFLAGS_PROMISC)
831 				pfkey_sendup(so->socket, packet, 1);
832 
833 		/* Paranoid */
834 		m_zero(packet);
835 		m_freem(packet);
836 
837 		/* Even more paranoid */
838 		bzero(freeme, sizeof(struct sadb_msg) + len);
839 		free(freeme, M_PFKEY);
840 		freeme = NULL;
841 	}
842 
843 	/* Validate message format */
844 	if ((rval = pfkeyv2_parsemessage(message, len, headers)) != 0)
845 		goto ret;
846 
847 	smsg = (struct sadb_msg *) headers[0];
848 	switch (smsg->sadb_msg_type) {
849 	case SADB_GETSPI:  /* Reserve an SPI */
850 		bzero(&sa, sizeof(struct tdb));
851 
852 		sa.tdb_satype = smsg->sadb_msg_satype;
853 		if ((rval = pfkeyv2_get_proto_alg(sa.tdb_satype,
854 		    &sa.tdb_sproto, 0)))
855 			goto ret;
856 
857 		import_address((struct sockaddr *) &sa.tdb_src,
858 		    headers[SADB_EXT_ADDRESS_SRC]);
859 		import_address((struct sockaddr *) &sa.tdb_dst,
860 		    headers[SADB_EXT_ADDRESS_DST]);
861 
862 		/* Find an unused SA identifier */
863 		sprng = (struct sadb_spirange *) headers[SADB_EXT_SPIRANGE];
864 		sa.tdb_spi = reserve_spi(sprng->sadb_spirange_min,
865 		    sprng->sadb_spirange_max, &sa.tdb_src, &sa.tdb_dst,
866 		    sa.tdb_sproto, &rval);
867 		if (sa.tdb_spi == 0)
868 			goto ret;
869 
870 		/* Send a message back telling what the SA (the SPI really) is */
871 		if (!(freeme = malloc(sizeof(struct sadb_sa), M_PFKEY,
872 		    M_DONTWAIT))) {
873 			rval = ENOMEM;
874 			goto ret;
875 		}
876 
877 		bzero(freeme, sizeof(struct sadb_sa));
878 		headers[SADB_EXT_SPIRANGE] = NULL;
879 		headers[SADB_EXT_SA] = freeme;
880 		bckptr = freeme;
881 
882 		/* We really only care about the SPI, but we'll export the SA */
883 		export_sa((void **) &bckptr, &sa);
884 		break;
885 
886 	case SADB_UPDATE:
887 		ssa = (struct sadb_sa *) headers[SADB_EXT_SA];
888 		sunionp = (union sockaddr_union *) (headers[SADB_EXT_ADDRESS_DST] +
889 		    sizeof(struct sadb_address));
890 
891 		/* Either all or none of the flow must be included */
892 		if ((headers[SADB_X_EXT_SRC_FLOW] ||
893 		    headers[SADB_X_EXT_PROTOCOL] ||
894 		    headers[SADB_X_EXT_FLOW_TYPE] ||
895 		    headers[SADB_X_EXT_DST_FLOW] ||
896 		    headers[SADB_X_EXT_SRC_MASK] ||
897 		    headers[SADB_X_EXT_DST_MASK]) &&
898 		    !(headers[SADB_X_EXT_SRC_FLOW] &&
899 		    headers[SADB_X_EXT_PROTOCOL] &&
900 		    headers[SADB_X_EXT_FLOW_TYPE] &&
901 		    headers[SADB_X_EXT_DST_FLOW] &&
902 		    headers[SADB_X_EXT_SRC_MASK] &&
903 		    headers[SADB_X_EXT_DST_MASK])) {
904 			rval = EINVAL;
905 			goto ret;
906 		}
907 		/* UDP encapsulation is only supported for ESP */
908 		if (smsg->sadb_msg_satype != SADB_SATYPE_ESP &&
909 		    headers[SADB_X_EXT_UDPENCAP]) {
910 			rval = EINVAL;
911 			goto ret;
912 		}
913 
914 		s = spltdb();
915 
916 		/* Find TDB */
917 		sa2 = gettdb(ssa->sadb_sa_spi, sunionp,
918 		    SADB_X_GETSPROTO(smsg->sadb_msg_satype));
919 
920 		/* If there's no such SA, we're done */
921 		if (sa2 == NULL) {
922 			rval = ESRCH;
923 			goto splxret;
924 		}
925 
926 		/* If this is a reserved SA */
927 		if (sa2->tdb_flags & TDBF_INVALID) {
928 			struct tdb *newsa;
929 			struct ipsecinit ii;
930 			int alg;
931 
932 			/* Create new TDB */
933 			freeme = tdb_alloc();
934 			bzero(&ii, sizeof(struct ipsecinit));
935 
936 			newsa = (struct tdb *) freeme;
937 			newsa->tdb_satype = smsg->sadb_msg_satype;
938 
939 			if ((rval = pfkeyv2_get_proto_alg(newsa->tdb_satype,
940 			    &newsa->tdb_sproto, &alg)))
941 				goto splxret;
942 
943 			/* Initialize SA */
944 			import_sa(newsa, headers[SADB_EXT_SA], &ii);
945 			import_address((struct sockaddr *) &newsa->tdb_src,
946 			    headers[SADB_EXT_ADDRESS_SRC]);
947 			import_address((struct sockaddr *) &newsa->tdb_dst,
948 			    headers[SADB_EXT_ADDRESS_DST]);
949 			import_address((struct sockaddr *) &newsa->tdb_proxy,
950 			    headers[SADB_EXT_ADDRESS_PROXY]);
951 			import_lifetime(newsa,
952 			    headers[SADB_EXT_LIFETIME_CURRENT],
953 			    PFKEYV2_LIFETIME_CURRENT);
954 			import_lifetime(newsa, headers[SADB_EXT_LIFETIME_SOFT],
955 			    PFKEYV2_LIFETIME_SOFT);
956 			import_lifetime(newsa, headers[SADB_EXT_LIFETIME_HARD],
957 			    PFKEYV2_LIFETIME_HARD);
958 			import_key(&ii, headers[SADB_EXT_KEY_AUTH],
959 			    PFKEYV2_AUTHENTICATION_KEY);
960 			import_key(&ii, headers[SADB_EXT_KEY_ENCRYPT],
961 			    PFKEYV2_ENCRYPTION_KEY);
962 			import_identity(newsa, headers[SADB_EXT_IDENTITY_SRC],
963 			    PFKEYV2_IDENTITY_SRC);
964 			import_identity(newsa, headers[SADB_EXT_IDENTITY_DST],
965 			    PFKEYV2_IDENTITY_DST);
966 			import_credentials(newsa,
967 			    headers[SADB_X_EXT_LOCAL_CREDENTIALS],
968 			    PFKEYV2_CRED_LOCAL);
969 			import_credentials(newsa,
970 			    headers[SADB_X_EXT_REMOTE_CREDENTIALS],
971 			    PFKEYV2_CRED_REMOTE);
972 			import_auth(newsa, headers[SADB_X_EXT_LOCAL_AUTH],
973 			    PFKEYV2_AUTH_LOCAL);
974 			import_auth(newsa, headers[SADB_X_EXT_REMOTE_AUTH],
975 			    PFKEYV2_AUTH_REMOTE);
976 			import_flow(&newsa->tdb_filter, &newsa->tdb_filtermask,
977 			    headers[SADB_X_EXT_SRC_FLOW],
978 			    headers[SADB_X_EXT_SRC_MASK],
979 			    headers[SADB_X_EXT_DST_FLOW],
980 			    headers[SADB_X_EXT_DST_MASK],
981 			    headers[SADB_X_EXT_PROTOCOL],
982 			    headers[SADB_X_EXT_FLOW_TYPE]);
983 			import_udpencap(newsa,
984 			    headers[SADB_X_EXT_UDPENCAP]);
985 
986 			headers[SADB_EXT_KEY_AUTH] = NULL;
987 			headers[SADB_EXT_KEY_ENCRYPT] = NULL;
988 			headers[SADB_X_EXT_LOCAL_AUTH] = NULL;
989 
990 			newsa->tdb_seq = smsg->sadb_msg_seq;
991 
992 			rval = tdb_init(newsa, alg, &ii);
993 			if (rval) {
994 				rval = EINVAL;
995 				tdb_delete(freeme);
996 				freeme = NULL;
997 				goto splxret;
998 			}
999 
1000 			newsa->tdb_cur_allocations = sa2->tdb_cur_allocations;
1001 
1002 			/* Delete old version of the SA, insert new one */
1003 			tdb_delete(sa2);
1004 			puttdb((struct tdb *) freeme);
1005 			sa2 = freeme = NULL;
1006 		} else {
1007 			/*
1008 			 * The SA is already initialized, so we're only allowed to
1009 			 * change lifetimes and some other information; we're
1010 			 * not allowed to change keys, addresses or identities.
1011 			 */
1012 			if (headers[SADB_EXT_ADDRESS_PROXY] ||
1013 			    headers[SADB_EXT_KEY_AUTH] ||
1014 			    headers[SADB_EXT_KEY_ENCRYPT] ||
1015 			    headers[SADB_EXT_IDENTITY_SRC] ||
1016 			    headers[SADB_EXT_IDENTITY_DST] ||
1017 			    headers[SADB_EXT_SENSITIVITY]) {
1018 				rval = EINVAL;
1019 				goto splxret;
1020 			}
1021 
1022 			import_sa(sa2, headers[SADB_EXT_SA], NULL);
1023 			import_lifetime(sa2,
1024 			    headers[SADB_EXT_LIFETIME_CURRENT],
1025 			    PFKEYV2_LIFETIME_CURRENT);
1026 			import_lifetime(sa2, headers[SADB_EXT_LIFETIME_SOFT],
1027 			    PFKEYV2_LIFETIME_SOFT);
1028 			import_lifetime(sa2, headers[SADB_EXT_LIFETIME_HARD],
1029 			    PFKEYV2_LIFETIME_HARD);
1030 			import_udpencap(sa2,
1031 			    headers[SADB_X_EXT_UDPENCAP]);
1032 		}
1033 
1034 		splx(s);
1035 		break;
1036 	case SADB_ADD:
1037 		ssa = (struct sadb_sa *) headers[SADB_EXT_SA];
1038 		sunionp = (union sockaddr_union *) (headers[SADB_EXT_ADDRESS_DST] +
1039 		    sizeof(struct sadb_address));
1040 
1041 		/* Either all or none of the flow must be included */
1042 		if ((headers[SADB_X_EXT_SRC_FLOW] ||
1043 		    headers[SADB_X_EXT_PROTOCOL] ||
1044 		    headers[SADB_X_EXT_FLOW_TYPE] ||
1045 		    headers[SADB_X_EXT_DST_FLOW] ||
1046 		    headers[SADB_X_EXT_SRC_MASK] ||
1047 		    headers[SADB_X_EXT_DST_MASK]) &&
1048 		    !(headers[SADB_X_EXT_SRC_FLOW] &&
1049 		    headers[SADB_X_EXT_PROTOCOL] &&
1050 		    headers[SADB_X_EXT_FLOW_TYPE] &&
1051 		    headers[SADB_X_EXT_DST_FLOW] &&
1052 		    headers[SADB_X_EXT_SRC_MASK] &&
1053 		    headers[SADB_X_EXT_DST_MASK])) {
1054 			rval = EINVAL;
1055 			goto ret;
1056 		}
1057 		/* UDP encapsulation is only supported for ESP */
1058 		if (smsg->sadb_msg_satype != SADB_SATYPE_ESP &&
1059 		    headers[SADB_X_EXT_UDPENCAP]) {
1060 			rval = EINVAL;
1061 			goto ret;
1062 		}
1063 
1064 		s = spltdb();
1065 
1066 		sa2 = gettdb(ssa->sadb_sa_spi, sunionp,
1067 		    SADB_X_GETSPROTO(smsg->sadb_msg_satype));
1068 
1069 		/* We can't add an existing SA! */
1070 		if (sa2 != NULL) {
1071 			rval = EEXIST;
1072 			goto splxret;
1073 		}
1074 
1075 		/* We can only add "mature" SAs */
1076 		if (ssa->sadb_sa_state != SADB_SASTATE_MATURE) {
1077 			rval = EINVAL;
1078 			goto splxret;
1079 		}
1080 
1081 		/* Allocate and initialize new TDB */
1082 		freeme = tdb_alloc();
1083 
1084 		{
1085 			struct tdb *newsa = (struct tdb *) freeme;
1086 			struct ipsecinit ii;
1087 			int alg;
1088 
1089 			bzero(&ii, sizeof(struct ipsecinit));
1090 
1091 			newsa->tdb_satype = smsg->sadb_msg_satype;
1092 			if ((rval = pfkeyv2_get_proto_alg(newsa->tdb_satype,
1093 			    &newsa->tdb_sproto, &alg)))
1094 				goto splxret;
1095 
1096 			import_sa(newsa, headers[SADB_EXT_SA], &ii);
1097 			import_address((struct sockaddr *) &newsa->tdb_src,
1098 			    headers[SADB_EXT_ADDRESS_SRC]);
1099 			import_address((struct sockaddr *) &newsa->tdb_dst,
1100 			    headers[SADB_EXT_ADDRESS_DST]);
1101 			import_address((struct sockaddr *) &newsa->tdb_proxy,
1102 			    headers[SADB_EXT_ADDRESS_PROXY]);
1103 
1104 			import_lifetime(newsa,
1105 			    headers[SADB_EXT_LIFETIME_CURRENT],
1106 			    PFKEYV2_LIFETIME_CURRENT);
1107 			import_lifetime(newsa, headers[SADB_EXT_LIFETIME_SOFT],
1108 			    PFKEYV2_LIFETIME_SOFT);
1109 			import_lifetime(newsa, headers[SADB_EXT_LIFETIME_HARD],
1110 			    PFKEYV2_LIFETIME_HARD);
1111 
1112 			import_key(&ii, headers[SADB_EXT_KEY_AUTH],
1113 			    PFKEYV2_AUTHENTICATION_KEY);
1114 			import_key(&ii, headers[SADB_EXT_KEY_ENCRYPT],
1115 			    PFKEYV2_ENCRYPTION_KEY);
1116 
1117 			import_identity(newsa, headers[SADB_EXT_IDENTITY_SRC],
1118 			    PFKEYV2_IDENTITY_SRC);
1119 			import_identity(newsa, headers[SADB_EXT_IDENTITY_DST],
1120 			    PFKEYV2_IDENTITY_DST);
1121 
1122 			import_credentials(newsa,
1123 			    headers[SADB_X_EXT_LOCAL_CREDENTIALS],
1124 			    PFKEYV2_CRED_LOCAL);
1125 			import_credentials(newsa,
1126 			    headers[SADB_X_EXT_REMOTE_CREDENTIALS],
1127 			    PFKEYV2_CRED_REMOTE);
1128 			import_auth(newsa, headers[SADB_X_EXT_LOCAL_AUTH],
1129 			    PFKEYV2_AUTH_LOCAL);
1130 			import_auth(newsa, headers[SADB_X_EXT_REMOTE_AUTH],
1131 			    PFKEYV2_AUTH_REMOTE);
1132 			import_flow(&newsa->tdb_filter, &newsa->tdb_filtermask,
1133 			    headers[SADB_X_EXT_SRC_FLOW],
1134 			    headers[SADB_X_EXT_SRC_MASK],
1135 			    headers[SADB_X_EXT_DST_FLOW],
1136 			    headers[SADB_X_EXT_DST_MASK],
1137 			    headers[SADB_X_EXT_PROTOCOL],
1138 			    headers[SADB_X_EXT_FLOW_TYPE]);
1139 			import_udpencap(newsa,
1140 			    headers[SADB_X_EXT_UDPENCAP]);
1141 
1142 			headers[SADB_EXT_KEY_AUTH] = NULL;
1143 			headers[SADB_EXT_KEY_ENCRYPT] = NULL;
1144 			headers[SADB_X_EXT_LOCAL_AUTH] = NULL;
1145 
1146 			newsa->tdb_seq = smsg->sadb_msg_seq;
1147 
1148 			rval = tdb_init(newsa, alg, &ii);
1149 			if (rval) {
1150 				rval = EINVAL;
1151 				tdb_delete(freeme);
1152 				freeme = NULL;
1153 				goto splxret;
1154 			}
1155 		}
1156 
1157 		/* Add TDB in table */
1158 		puttdb((struct tdb *) freeme);
1159 
1160 		splx(s);
1161 
1162 		freeme = NULL;
1163 		break;
1164 
1165 	case SADB_DELETE:
1166 		ssa = (struct sadb_sa *) headers[SADB_EXT_SA];
1167 		sunionp = (union sockaddr_union *) (headers[SADB_EXT_ADDRESS_DST] +
1168 		    sizeof(struct sadb_address));
1169 		s = spltdb();
1170 
1171 		sa2 = gettdb(ssa->sadb_sa_spi, sunionp,
1172 		    SADB_X_GETSPROTO(smsg->sadb_msg_satype));
1173 		if (sa2 == NULL) {
1174 			rval = ESRCH;
1175 			goto splxret;
1176 		}
1177 
1178 		tdb_delete(sa2);
1179 
1180 		splx(s);
1181 
1182 		sa2 = NULL;
1183 		break;
1184 
1185 	case SADB_X_ASKPOLICY:
1186 		/* Get the relevant policy */
1187 		ipa = ipsec_get_acquire(((struct sadb_x_policy *) headers[SADB_X_EXT_POLICY])->sadb_x_policy_seq);
1188 		if (ipa == NULL) {
1189 			rval = ESRCH;
1190 			goto ret;
1191 		}
1192 
1193 		rval = pfkeyv2_policy(ipa, headers, &freeme);
1194 		if (rval)
1195 			mode = PFKEYV2_SENDMESSAGE_UNICAST;
1196 
1197 		break;
1198 
1199 	case SADB_GET:
1200 		ssa = (struct sadb_sa *) headers[SADB_EXT_SA];
1201 		sunionp = (union sockaddr_union *) (headers[SADB_EXT_ADDRESS_DST] +
1202 		    sizeof(struct sadb_address));
1203 		s = spltdb();
1204 
1205 		sa2 = gettdb(ssa->sadb_sa_spi, sunionp,
1206 		    SADB_X_GETSPROTO(smsg->sadb_msg_satype));
1207 		if (sa2 == NULL) {
1208 			rval = ESRCH;
1209 			goto splxret;
1210 		}
1211 
1212 		rval = pfkeyv2_get(sa2, headers, &freeme);
1213 		if (rval)
1214 			mode = PFKEYV2_SENDMESSAGE_UNICAST;
1215 
1216 		splx(s);
1217 
1218 		break;
1219 
1220 	case SADB_REGISTER:
1221 		pfkeyv2_socket->flags |= PFKEYV2_SOCKETFLAGS_REGISTERED;
1222 		nregistered++;
1223 
1224 		i = sizeof(struct sadb_supported) + sizeof(ealgs);
1225 
1226 		if (!(freeme = malloc(i, M_PFKEY, M_DONTWAIT))) {
1227 			rval = ENOMEM;
1228 			goto ret;
1229 		}
1230 
1231 		bzero(freeme, i);
1232 
1233 		ssup = (struct sadb_supported *) freeme;
1234 		ssup->sadb_supported_len = i / sizeof(uint64_t);
1235 
1236 		{
1237 			void *p = freeme + sizeof(struct sadb_supported);
1238 
1239 			bcopy(&ealgs[0], p, sizeof(ealgs));
1240 		}
1241 
1242 		headers[SADB_EXT_SUPPORTED_ENCRYPT] = freeme;
1243 
1244 		i = sizeof(struct sadb_supported) + sizeof(aalgs);
1245 
1246 		if (!(freeme = malloc(i, M_PFKEY, M_DONTWAIT))) {
1247 			rval = ENOMEM;
1248 			goto ret;
1249 		}
1250 
1251 		/* Keep track what this socket has registered for */
1252 		pfkeyv2_socket->registration |= (1 << ((struct sadb_msg *)message)->sadb_msg_satype);
1253 
1254 		bzero(freeme, i);
1255 
1256 		ssup = (struct sadb_supported *) freeme;
1257 		ssup->sadb_supported_len = i / sizeof(uint64_t);
1258 
1259 		{
1260 			void *p = freeme + sizeof(struct sadb_supported);
1261 
1262 			bcopy(&aalgs[0], p, sizeof(aalgs));
1263 		}
1264 
1265 		headers[SADB_EXT_SUPPORTED_AUTH] = freeme;
1266 
1267 		i = sizeof(struct sadb_supported) + sizeof(calgs);
1268 
1269 		if (!(freeme = malloc(i, M_PFKEY, M_DONTWAIT))) {
1270 			rval = ENOMEM;
1271 			goto ret;
1272 		}
1273 
1274 		bzero(freeme, i);
1275 
1276 		ssup = (struct sadb_supported *) freeme;
1277 		ssup->sadb_supported_len = i / sizeof(uint64_t);
1278 
1279 		{
1280 			void *p = freeme + sizeof(struct sadb_supported);
1281 
1282 			bcopy(&calgs[0], p, sizeof(calgs));
1283 		}
1284 
1285 		headers[SADB_X_EXT_SUPPORTED_COMP] = freeme;
1286 
1287 		break;
1288 
1289 	case SADB_ACQUIRE:
1290 	case SADB_EXPIRE:
1291 		/* Nothing to handle */
1292 		rval = 0;
1293 		break;
1294 
1295 	case SADB_FLUSH:
1296 		rval = 0;
1297 
1298 		switch (smsg->sadb_msg_satype) {
1299 		case SADB_SATYPE_UNSPEC:
1300 			s = spltdb();
1301 
1302 			/*
1303 			 * Go through the list of policies, delete those that
1304 			 * are not socket-attached.
1305 			 */
1306 			for (ipo = TAILQ_FIRST(&ipsec_policy_head);
1307 			    ipo != NULL; ipo = tmpipo) {
1308 				tmpipo = TAILQ_NEXT(ipo, ipo_list);
1309 				if (!(ipo->ipo_flags & IPSP_POLICY_SOCKET))
1310 					ipsec_delete_policy(ipo);
1311 			}
1312 			splx(s);
1313 			/* Fall through */
1314 		case SADB_SATYPE_AH:
1315 		case SADB_SATYPE_ESP:
1316 		case SADB_X_SATYPE_IPIP:
1317 		case SADB_X_SATYPE_IPCOMP:
1318 #ifdef TCP_SIGNATURE
1319 		case SADB_X_SATYPE_TCPSIGNATURE:
1320 #endif /* TCP_SIGNATURE */
1321 			s = spltdb();
1322 
1323 			tdb_walk(pfkeyv2_flush_walker,
1324 			    (u_int8_t *) &(smsg->sadb_msg_satype));
1325 
1326 			splx(s);
1327 			break;
1328 
1329 		default:
1330 			rval = EINVAL; /* Unknown/unsupported type */
1331 		}
1332 
1333 		break;
1334 
1335 	case SADB_DUMP:
1336 	{
1337 		struct dump_state dump_state;
1338 		dump_state.sadb_msg = (struct sadb_msg *) headers[0];
1339 		dump_state.socket = socket;
1340 
1341 		if (!(rval = tdb_walk(pfkeyv2_dump_walker, &dump_state)))
1342 			goto realret;
1343 
1344 		if ((rval == ENOMEM) || (rval == ENOBUFS))
1345 			rval = 0;
1346 	}
1347 	break;
1348 
1349 	case SADB_X_GRPSPIS:
1350 	{
1351 		struct tdb *tdb1, *tdb2, *tdb3;
1352 		struct sadb_protocol *sa_proto;
1353 
1354 		ssa = (struct sadb_sa *) headers[SADB_EXT_SA];
1355 		sunionp = (union sockaddr_union *) (headers[SADB_EXT_ADDRESS_DST] +
1356 		    sizeof(struct sadb_address));
1357 
1358 		s = spltdb();
1359 
1360 		tdb1 = gettdb(ssa->sadb_sa_spi, sunionp,
1361 		    SADB_X_GETSPROTO(smsg->sadb_msg_satype));
1362 		if (tdb1 == NULL) {
1363 			rval = ESRCH;
1364 			goto splxret;
1365 		}
1366 
1367 		ssa = (struct sadb_sa *) headers[SADB_X_EXT_SA2];
1368 		sunionp = (union sockaddr_union *) (headers[SADB_X_EXT_DST2] +
1369 		    sizeof(struct sadb_address));
1370 		sa_proto = ((struct sadb_protocol *) headers[SADB_X_EXT_PROTOCOL]);
1371 
1372 		tdb2 = gettdb(ssa->sadb_sa_spi, sunionp,
1373 		    SADB_X_GETSPROTO(sa_proto->sadb_protocol_proto));
1374 		if (tdb2 == NULL) {
1375 			rval = ESRCH;
1376 			goto splxret;
1377 		}
1378 
1379 		/* Detect cycles */
1380 		for (tdb3 = tdb2; tdb3; tdb3 = tdb3->tdb_onext)
1381 			if (tdb3 == tdb1) {
1382 				rval = ESRCH;
1383 				goto splxret;
1384 			}
1385 
1386 		/* Maintenance */
1387 		if ((tdb1->tdb_onext) &&
1388 		    (tdb1->tdb_onext->tdb_inext == tdb1))
1389 			tdb1->tdb_onext->tdb_inext = NULL;
1390 
1391 		if ((tdb2->tdb_inext) &&
1392 		    (tdb2->tdb_inext->tdb_onext == tdb2))
1393 			tdb2->tdb_inext->tdb_onext = NULL;
1394 
1395 		/* Link them */
1396 		tdb1->tdb_onext = tdb2;
1397 		tdb2->tdb_inext = tdb1;
1398 
1399 		splx(s);
1400 	}
1401 	break;
1402 
1403 	case SADB_X_DELFLOW:
1404 		delflag = 1;
1405 		/*FALLTHROUGH*/
1406 	case SADB_X_ADDFLOW:
1407 	{
1408 		struct sadb_protocol *sab;
1409 		union sockaddr_union *ssrc;
1410 		struct route_enc re;
1411 		int exists = 0;
1412 
1413 		sab = (struct sadb_protocol *) headers[SADB_X_EXT_FLOW_TYPE];
1414 
1415 		if ((sab->sadb_protocol_direction != IPSP_DIRECTION_IN) &&
1416 		    (sab->sadb_protocol_direction != IPSP_DIRECTION_OUT)) {
1417 			rval = EINVAL;
1418 			goto ret;
1419 		}
1420 
1421 		/* If the security protocol wasn't specified, pretend it was ESP */
1422 		if (smsg->sadb_msg_satype == 0)
1423 			smsg->sadb_msg_satype = SADB_SATYPE_ESP;
1424 
1425 		if (headers[SADB_EXT_ADDRESS_DST])
1426 			sunionp = (union sockaddr_union *)
1427 			    (headers[SADB_EXT_ADDRESS_DST] +
1428 				sizeof(struct sadb_address));
1429 		else
1430 			sunionp = NULL;
1431 
1432 		if (headers[SADB_EXT_ADDRESS_SRC])
1433 			ssrc = (union sockaddr_union *)
1434 			    (headers[SADB_EXT_ADDRESS_SRC] +
1435 				sizeof(struct sadb_address));
1436 		else
1437 			ssrc = NULL;
1438 
1439 		import_flow(&encapdst, &encapnetmask,
1440 		    headers[SADB_X_EXT_SRC_FLOW], headers[SADB_X_EXT_SRC_MASK],
1441 		    headers[SADB_X_EXT_DST_FLOW], headers[SADB_X_EXT_DST_MASK],
1442 		    headers[SADB_X_EXT_PROTOCOL], headers[SADB_X_EXT_FLOW_TYPE]);
1443 
1444 		/* Determine whether the exact same SPD entry already exists. */
1445 		bzero(&encapgw, sizeof(struct sockaddr_encap));
1446 		bzero(&re, sizeof(struct route_enc));
1447 		bcopy(&encapdst, &re.re_dst, sizeof(struct sockaddr_encap));
1448 
1449 		s = spltdb();
1450 
1451 		rtalloc((struct route *) &re);
1452 		if (re.re_rt != NULL) {
1453 			ipo = ((struct sockaddr_encap *) re.re_rt->rt_gateway)->sen_ipsp;
1454 			RTFREE(re.re_rt);
1455 
1456 			/* Verify that the entry is identical */
1457 			if (bcmp(&ipo->ipo_addr, &encapdst,
1458 				sizeof(struct sockaddr_encap)) ||
1459 			    bcmp(&ipo->ipo_mask, &encapnetmask,
1460 				sizeof(struct sockaddr_encap)))
1461 				ipo = NULL; /* Fall through */
1462 			else
1463 				exists = 1;
1464 		} else
1465 			ipo = NULL;
1466 
1467 		/*
1468 		 * If the existing policy is static, only delete or update
1469 		 * it if the new one is also static.
1470 		 */
1471 		if (exists && (ipo->ipo_flags & IPSP_POLICY_STATIC)) {
1472 			if (!(sab->sadb_protocol_flags &
1473 				SADB_X_POLICYFLAGS_POLICY)) {
1474 				splx(s);
1475 				goto ret;
1476 			}
1477 		}
1478 
1479 		/* Delete ? */
1480 		if (delflag) {
1481 			if (exists) {
1482 				rval = ipsec_delete_policy(ipo);
1483 				splx(s);
1484 				goto ret;
1485 			}
1486 
1487 			/* If we were asked to delete something non-existant, error. */
1488 			splx(s);
1489 			rval = ESRCH;
1490 			break;
1491 		}
1492 
1493 		if (!exists) {
1494 			if (ipsec_policy_pool_initialized == 0) {
1495 				ipsec_policy_pool_initialized = 1;
1496 				pool_init(&ipsec_policy_pool,
1497 				    sizeof(struct ipsec_policy), 0, 0, 0,
1498 				    "ipsec policy", NULL);
1499 			}
1500 
1501 			/* Allocate policy entry */
1502 			ipo = pool_get(&ipsec_policy_pool, 0);
1503 			if (ipo == NULL) {
1504 				splx(s);
1505 				rval = ENOMEM;
1506 				goto ret;
1507 			}
1508 
1509 			bzero(ipo, sizeof(struct ipsec_policy));
1510 			ipo->ipo_ref_count = 1;
1511 			TAILQ_INIT(&ipo->ipo_acquires);
1512 
1513 			/* Finish initialization of SPD entry */
1514 			encapgw.sen_len = SENT_LEN;
1515 			encapgw.sen_family = PF_KEY;
1516 			encapgw.sen_type = SENT_IPSP;
1517 			encapgw.sen_ipsp = ipo;
1518 
1519 			/* Initialize policy entry */
1520 			bcopy(&encapdst, &ipo->ipo_addr,
1521 			    sizeof(struct sockaddr_encap));
1522 			bcopy(&encapnetmask, &ipo->ipo_mask,
1523 			    sizeof(struct sockaddr_encap));
1524 		}
1525 
1526 		switch (((struct sadb_protocol *) headers[SADB_X_EXT_FLOW_TYPE])->sadb_protocol_proto) {
1527 		case SADB_X_FLOW_TYPE_USE:
1528 			ipo->ipo_type = IPSP_IPSEC_USE;
1529 			break;
1530 
1531 		case SADB_X_FLOW_TYPE_ACQUIRE:
1532 			ipo->ipo_type = IPSP_IPSEC_ACQUIRE;
1533 			break;
1534 
1535 		case SADB_X_FLOW_TYPE_REQUIRE:
1536 			ipo->ipo_type = IPSP_IPSEC_REQUIRE;
1537 			break;
1538 
1539 		case SADB_X_FLOW_TYPE_DENY:
1540 			ipo->ipo_type = IPSP_DENY;
1541 			break;
1542 
1543 		case SADB_X_FLOW_TYPE_BYPASS:
1544 			ipo->ipo_type = IPSP_PERMIT;
1545 			break;
1546 
1547 		case SADB_X_FLOW_TYPE_DONTACQ:
1548 			ipo->ipo_type = IPSP_IPSEC_DONTACQ;
1549 			break;
1550 
1551 		default:
1552 			if (!exists)
1553 				pool_put(&ipsec_policy_pool, ipo);
1554 			else
1555 				ipsec_delete_policy(ipo);
1556 
1557 			splx(s);
1558 			rval = EINVAL;
1559 			goto ret;
1560 		}
1561 
1562 		if (sab->sadb_protocol_flags & SADB_X_POLICYFLAGS_POLICY)
1563 			ipo->ipo_flags |= IPSP_POLICY_STATIC;
1564 
1565 		if (sunionp)
1566 			bcopy(sunionp, &ipo->ipo_dst,
1567 			    sizeof(union sockaddr_union));
1568 		else
1569 			bzero(&ipo->ipo_dst, sizeof(union sockaddr_union));
1570 
1571 		if (ssrc)
1572 			bcopy(ssrc, &ipo->ipo_src,
1573 			    sizeof(union sockaddr_union));
1574 		else
1575 			bzero(&ipo->ipo_src, sizeof(union sockaddr_union));
1576 
1577 		ipo->ipo_sproto = SADB_X_GETSPROTO(smsg->sadb_msg_satype);
1578 
1579 		if (ipo->ipo_srcid) {
1580 			ipsp_reffree(ipo->ipo_srcid);
1581 			ipo->ipo_srcid = NULL;
1582 		}
1583 
1584 		if (ipo->ipo_dstid) {
1585 			ipsp_reffree(ipo->ipo_dstid);
1586 			ipo->ipo_dstid = NULL;
1587 		}
1588 
1589 		if ((sid = headers[SADB_EXT_IDENTITY_SRC]) != NULL) {
1590 			int clen =  (sid->sadb_ident_len * sizeof(u_int64_t)) -
1591 			    sizeof(struct sadb_ident);
1592 
1593 			MALLOC(ipo->ipo_srcid, struct ipsec_ref *, clen +
1594 			    sizeof(struct ipsec_ref), M_CREDENTIALS, M_DONTWAIT);
1595 			if (ipo->ipo_srcid == NULL) {
1596 				if (exists)
1597 					ipsec_delete_policy(ipo);
1598 				else
1599 					pool_put(&ipsec_policy_pool, ipo);
1600 				splx(s);
1601 				rval = ENOBUFS;
1602 				goto ret;
1603 			}
1604 			ipo->ipo_srcid->ref_type = sid->sadb_ident_type;
1605 			ipo->ipo_srcid->ref_len = clen;
1606 			ipo->ipo_srcid->ref_count = 1;
1607 			ipo->ipo_srcid->ref_malloctype = M_CREDENTIALS;
1608 			bcopy(sid + 1, ipo->ipo_srcid + 1, ipo->ipo_srcid->ref_len);
1609 		}
1610 
1611 		if ((sid = headers[SADB_EXT_IDENTITY_DST]) != NULL) {
1612 			int clen =  (sid->sadb_ident_len * sizeof(u_int64_t)) -
1613 			    sizeof(struct sadb_ident);
1614 
1615 			MALLOC(ipo->ipo_dstid, struct ipsec_ref *,
1616 			    clen + sizeof(struct ipsec_ref),
1617 			    M_CREDENTIALS, M_DONTWAIT);
1618 			if (ipo->ipo_dstid == NULL) {
1619 				if (exists)
1620 					ipsec_delete_policy(ipo);
1621 				else {
1622 					if (ipo->ipo_dstid)
1623 						ipsp_reffree(ipo->ipo_dstid);
1624 					pool_put(&ipsec_policy_pool, ipo);
1625 				}
1626 
1627 				splx(s);
1628 				rval = ENOBUFS;
1629 				goto ret;
1630 			}
1631 			ipo->ipo_dstid->ref_type = sid->sadb_ident_type;
1632 			ipo->ipo_dstid->ref_len = clen;
1633 			ipo->ipo_dstid->ref_count = 1;
1634 			ipo->ipo_dstid->ref_malloctype = M_CREDENTIALS;
1635 			bcopy(sid + 1, ipo->ipo_dstid + 1,
1636 			    ipo->ipo_dstid->ref_len);
1637 		}
1638 
1639 		/* Flow type */
1640 		if (!exists) {
1641 			/* Add SPD entry */
1642 			if ((rval = rtrequest(RTM_ADD,
1643 				 (struct sockaddr *) &encapdst,
1644 				 (struct sockaddr *) &encapgw,
1645 				 (struct sockaddr *) &encapnetmask,
1646 				 RTF_UP | RTF_GATEWAY | RTF_STATIC,
1647 				 (struct rtentry **) 0)) != 0) {
1648 				/* Remove from linked list of policies on TDB */
1649 				if (ipo->ipo_tdb)
1650 					TAILQ_REMOVE(&ipo->ipo_tdb->tdb_policy_head,
1651 					    ipo, ipo_tdb_next);
1652 
1653 				if (ipo->ipo_srcid)
1654 					ipsp_reffree(ipo->ipo_srcid);
1655 				if (ipo->ipo_dstid)
1656 					ipsp_reffree(ipo->ipo_dstid);
1657 				pool_put(&ipsec_policy_pool, ipo);
1658 
1659 				splx(s);
1660 				goto ret;
1661 			}
1662 
1663 			TAILQ_INSERT_HEAD(&ipsec_policy_head, ipo, ipo_list);
1664 			ipsec_in_use++;
1665 		} else {
1666 			ipo->ipo_last_searched = ipo->ipo_flags = 0;
1667 		}
1668 
1669 		splx(s);
1670 	}
1671 	break;
1672 
1673 	case SADB_X_PROMISC:
1674 		if (len >= 2 * sizeof(struct sadb_msg)) {
1675 			struct mbuf *packet;
1676 
1677 			if ((rval = pfdatatopacket(message, len, &packet)) != 0)
1678 				goto ret;
1679 
1680 			for (so = pfkeyv2_sockets; so; so = so->next)
1681 				if ((so != pfkeyv2_socket) &&
1682 				    (!smsg->sadb_msg_seq ||
1683 				    (smsg->sadb_msg_seq == pfkeyv2_socket->pid)))
1684 					pfkey_sendup(so->socket, packet, 1);
1685 
1686 			m_freem(packet);
1687 		} else {
1688 			if (len != sizeof(struct sadb_msg)) {
1689 				rval = EINVAL;
1690 				goto ret;
1691 			}
1692 
1693 			i = (pfkeyv2_socket->flags &
1694 			    PFKEYV2_SOCKETFLAGS_PROMISC) ? 1 : 0;
1695 			j = smsg->sadb_msg_satype ? 1 : 0;
1696 
1697 			if (i ^ j) {
1698 				if (j) {
1699 					pfkeyv2_socket->flags |=
1700 					    PFKEYV2_SOCKETFLAGS_PROMISC;
1701 					npromisc++;
1702 				}
1703 			} else {
1704 				pfkeyv2_socket->flags &=
1705 				    ~PFKEYV2_SOCKETFLAGS_PROMISC;
1706 				npromisc--;
1707 			}
1708 		}
1709 
1710 
1711 		break;
1712 
1713 	default:
1714 		rval = EINVAL;
1715 		goto ret;
1716 	}
1717 
1718 ret:
1719 	if (rval) {
1720 		if ((rval == EINVAL) || (rval == ENOMEM) || (rval == ENOBUFS))
1721 			goto realret;
1722 
1723 		for (i = 1; i <= SADB_EXT_MAX; i++)
1724 			headers[i] = NULL;
1725 
1726 		smsg->sadb_msg_errno = abs(rval);
1727 	} else {
1728 		uint32_t seen = 0;
1729 
1730 		for (i = 1; i <= SADB_EXT_MAX; i++)
1731 			if (headers[i])
1732 				seen |= (1 << i);
1733 
1734 		if ((seen & sadb_exts_allowed_out[smsg->sadb_msg_type])
1735 		    != seen)
1736 			goto realret;
1737 
1738 		if ((seen & sadb_exts_required_out[smsg->sadb_msg_type]) !=
1739 		    sadb_exts_required_out[smsg->sadb_msg_type])
1740 			goto realret;
1741 	}
1742 
1743 	rval = pfkeyv2_sendmessage(headers, mode, socket, 0, 0);
1744 
1745 realret:
1746 	if (freeme)
1747 		free(freeme, M_PFKEY);
1748 
1749 	free(message, M_PFKEY);
1750 
1751 	return (rval);
1752 
1753 splxret:
1754 	splx(s);
1755 	goto ret;
1756 }
1757 
1758 /*
1759  * Send an ACQUIRE message to key management, to get a new SA.
1760  */
1761 int
pfkeyv2_acquire(struct ipsec_policy * ipo,union sockaddr_union * gw,union sockaddr_union * laddr,u_int32_t * seq,struct sockaddr_encap * ddst)1762 pfkeyv2_acquire(struct ipsec_policy *ipo, union sockaddr_union *gw,
1763 		union sockaddr_union *laddr, u_int32_t *seq,
1764 		struct sockaddr_encap *ddst)
1765 {
1766 	void *p, *headers[SADB_EXT_MAX + 1], *buffer = NULL;
1767 	struct sadb_ident *srcid, *dstid;
1768 	struct sadb_x_cred *lcred, *lauth;
1769 	struct sadb_comb *sadb_comb;
1770 	struct sadb_address *sadd;
1771 	struct sadb_prop *sa_prop;
1772 	struct sadb_msg *smsg;
1773 	int rval = 0;
1774 	int i, j;
1775 
1776 	*seq = pfkeyv2_seq++;
1777 
1778 	if (!nregistered) {
1779 		rval = ESRCH;
1780 		goto ret;
1781 	}
1782 
1783 	/* How large a buffer do we need... XXX we only do one proposal for now */
1784 	i = sizeof(struct sadb_msg) +
1785 	    (laddr == NULL ? 0 : sizeof(struct sadb_address) +
1786 		PADUP(SA_LEN(&ipo->ipo_src.sa))) +
1787 	    sizeof(struct sadb_address) + PADUP(SA_LEN(&gw->sa)) +
1788 	    sizeof(struct sadb_prop) + 1 * sizeof(struct sadb_comb);
1789 
1790 	if (ipo->ipo_srcid)
1791 		i += sizeof(struct sadb_ident) + PADUP(ipo->ipo_srcid->ref_len);
1792 
1793 	if (ipo->ipo_dstid)
1794 		i += sizeof(struct sadb_ident) + PADUP(ipo->ipo_dstid->ref_len);
1795 
1796 	if (ipo->ipo_local_cred)
1797 		i += sizeof(struct sadb_x_cred) + PADUP(ipo->ipo_local_cred->ref_len);
1798 
1799 	if (ipo->ipo_local_auth)
1800 		i += sizeof(struct sadb_x_cred) + PADUP(ipo->ipo_local_auth->ref_len);
1801 
1802 	/* Allocate */
1803 	if (!(p = malloc(i, M_PFKEY, M_DONTWAIT))) {
1804 		rval = ENOMEM;
1805 		goto ret;
1806 	}
1807 
1808 	bzero(headers, sizeof(headers));
1809 
1810 	buffer = p;
1811 	bzero(p, i);
1812 
1813 	headers[0] = p;
1814 	p += sizeof(struct sadb_msg);
1815 
1816 	smsg = (struct sadb_msg *) headers[0];
1817 	smsg->sadb_msg_version = PF_KEY_V2;
1818 	smsg->sadb_msg_type = SADB_ACQUIRE;
1819 	smsg->sadb_msg_len = i / sizeof(uint64_t);
1820 	smsg->sadb_msg_seq = *seq;
1821 
1822 	if (ipo->ipo_sproto == IPPROTO_ESP)
1823 		smsg->sadb_msg_satype = SADB_SATYPE_ESP;
1824 	else if (ipo->ipo_sproto == IPPROTO_AH)
1825 		smsg->sadb_msg_satype = SADB_SATYPE_AH;
1826 	else if (ipo->ipo_sproto == IPPROTO_IPCOMP)
1827 		smsg->sadb_msg_satype = SADB_X_SATYPE_IPCOMP;
1828 
1829 	if (laddr) {
1830 		headers[SADB_EXT_ADDRESS_SRC] = p;
1831 		p += sizeof(struct sadb_address) + PADUP(SA_LEN(&laddr->sa));
1832 		sadd = (struct sadb_address *) headers[SADB_EXT_ADDRESS_SRC];
1833 		sadd->sadb_address_len = (sizeof(struct sadb_address) +
1834 		    SA_LEN(&laddr->sa) + sizeof(uint64_t) - 1) /
1835 		    sizeof(uint64_t);
1836 		bcopy(laddr, headers[SADB_EXT_ADDRESS_SRC] +
1837 		    sizeof(struct sadb_address), SA_LEN(&laddr->sa));
1838 	}
1839 
1840 	headers[SADB_EXT_ADDRESS_DST] = p;
1841 	p += sizeof(struct sadb_address) + PADUP(SA_LEN(&gw->sa));
1842 	sadd = (struct sadb_address *) headers[SADB_EXT_ADDRESS_DST];
1843 	sadd->sadb_address_len = (sizeof(struct sadb_address) +
1844 	    SA_LEN(&gw->sa) + sizeof(uint64_t) - 1) / sizeof(uint64_t);
1845 	bcopy(gw, headers[SADB_EXT_ADDRESS_DST] + sizeof(struct sadb_address),
1846 	    SA_LEN(&gw->sa));
1847 
1848 	if (ipo->ipo_srcid) {
1849 		headers[SADB_EXT_IDENTITY_SRC] = p;
1850 		p += sizeof(struct sadb_ident) + PADUP(ipo->ipo_srcid->ref_len);
1851 		srcid = (struct sadb_ident *) headers[SADB_EXT_IDENTITY_SRC];
1852 		srcid->sadb_ident_len = (sizeof(struct sadb_ident) +
1853 		    PADUP(ipo->ipo_srcid->ref_len)) / sizeof(u_int64_t);
1854 		srcid->sadb_ident_type = ipo->ipo_srcid->ref_type;
1855 		bcopy(ipo->ipo_srcid + 1, headers[SADB_EXT_IDENTITY_SRC] +
1856 		    sizeof(struct sadb_ident), ipo->ipo_srcid->ref_len);
1857 	}
1858 
1859 	if (ipo->ipo_dstid) {
1860 		headers[SADB_EXT_IDENTITY_DST] = p;
1861 		p += sizeof(struct sadb_ident) + PADUP(ipo->ipo_dstid->ref_len);
1862 		dstid = (struct sadb_ident *) headers[SADB_EXT_IDENTITY_DST];
1863 		dstid->sadb_ident_len = (sizeof(struct sadb_ident) +
1864 		    PADUP(ipo->ipo_dstid->ref_len)) / sizeof(u_int64_t);
1865 		dstid->sadb_ident_type = ipo->ipo_dstid->ref_type;
1866 		bcopy(ipo->ipo_dstid + 1, headers[SADB_EXT_IDENTITY_DST] +
1867 		    sizeof(struct sadb_ident), ipo->ipo_dstid->ref_len);
1868 	}
1869 
1870 	if (ipo->ipo_local_cred) {
1871 		headers[SADB_X_EXT_LOCAL_CREDENTIALS] = p;
1872 		p += sizeof(struct sadb_x_cred) + PADUP(ipo->ipo_local_cred->ref_len);
1873 		lcred = (struct sadb_x_cred *) headers[SADB_X_EXT_LOCAL_CREDENTIALS];
1874 		lcred->sadb_x_cred_len = (sizeof(struct sadb_x_cred) +
1875 		    PADUP(ipo->ipo_local_cred->ref_len)) / sizeof(u_int64_t);
1876 		switch (ipo->ipo_local_cred->ref_type) {
1877 		case IPSP_CRED_KEYNOTE:
1878 			lcred->sadb_x_cred_type = SADB_X_CREDTYPE_KEYNOTE;
1879 			break;
1880 		case IPSP_CRED_X509:
1881 			lcred->sadb_x_cred_type = SADB_X_CREDTYPE_X509;
1882 			break;
1883 		}
1884 		bcopy(ipo->ipo_local_cred + 1, headers[SADB_X_EXT_LOCAL_CREDENTIALS] +
1885 		    sizeof(struct sadb_x_cred), ipo->ipo_local_cred->ref_len);
1886 	}
1887 
1888 	if (ipo->ipo_local_auth) {
1889 		headers[SADB_X_EXT_LOCAL_AUTH] = p;
1890 		p += sizeof(struct sadb_x_cred) + PADUP(ipo->ipo_local_auth->ref_len);
1891 		lauth = (struct sadb_x_cred *) headers[SADB_X_EXT_LOCAL_AUTH];
1892 		lauth->sadb_x_cred_len = (sizeof(struct sadb_x_cred) +
1893 		    PADUP(ipo->ipo_local_auth->ref_len)) / sizeof(u_int64_t);
1894 		switch (ipo->ipo_local_auth->ref_type) {
1895 		case IPSP_AUTH_PASSPHRASE:
1896 			lauth->sadb_x_cred_type = SADB_X_AUTHTYPE_PASSPHRASE;
1897 			break;
1898 		case IPSP_AUTH_RSA:
1899 			lauth->sadb_x_cred_type = SADB_X_AUTHTYPE_RSA;
1900 			break;
1901 		}
1902 
1903 		bcopy(ipo->ipo_local_auth + 1, headers[SADB_X_EXT_LOCAL_AUTH] +
1904 		    sizeof(struct sadb_x_cred), ipo->ipo_local_auth->ref_len);
1905 	}
1906 
1907 	headers[SADB_EXT_PROPOSAL] = p;
1908 	p += sizeof(struct sadb_prop);
1909 	sa_prop = (struct sadb_prop *) headers[SADB_EXT_PROPOSAL];
1910 	sa_prop->sadb_prop_num = 1; /* XXX One proposal only */
1911 	sa_prop->sadb_prop_len = (sizeof(struct sadb_prop) +
1912 	    (sizeof(struct sadb_comb) * sa_prop->sadb_prop_num)) /
1913 	    sizeof(uint64_t);
1914 
1915 	sadb_comb = p;
1916 
1917 	/* XXX Should actually ask the crypto layer what's supported */
1918 	for (j = 0; j < sa_prop->sadb_prop_num; j++) {
1919 		sadb_comb->sadb_comb_flags = 0;
1920 
1921 		if (ipsec_require_pfs)
1922 			sadb_comb->sadb_comb_flags |= SADB_SAFLAGS_PFS;
1923 
1924 		/* Set the encryption algorithm */
1925 		if (ipo->ipo_sproto == IPPROTO_ESP) {
1926 			if (!strncasecmp(ipsec_def_enc, "aes",
1927 			    sizeof("aes"))) {
1928 				sadb_comb->sadb_comb_encrypt = SADB_X_EALG_AES;
1929 				sadb_comb->sadb_comb_encrypt_minbits = 64;
1930 				sadb_comb->sadb_comb_encrypt_maxbits = 256;
1931 			} else if (!strncasecmp(ipsec_def_enc, "3des",
1932 			    sizeof("3des"))) {
1933 				sadb_comb->sadb_comb_encrypt = SADB_EALG_3DESCBC;
1934 				sadb_comb->sadb_comb_encrypt_minbits = 192;
1935 				sadb_comb->sadb_comb_encrypt_maxbits = 192;
1936 			} else if (!strncasecmp(ipsec_def_enc, "des",
1937 			    sizeof("des"))) {
1938 				sadb_comb->sadb_comb_encrypt = SADB_EALG_DESCBC;
1939 				sadb_comb->sadb_comb_encrypt_minbits = 64;
1940 				sadb_comb->sadb_comb_encrypt_maxbits = 64;
1941 			} else if (!strncasecmp(ipsec_def_enc, "blowfish",
1942 			    sizeof("blowfish"))) {
1943 				sadb_comb->sadb_comb_encrypt = SADB_X_EALG_BLF;
1944 				sadb_comb->sadb_comb_encrypt_minbits = 40;
1945 				sadb_comb->sadb_comb_encrypt_maxbits = BLF_MAXKEYLEN * 8;
1946 			} else if (!strncasecmp(ipsec_def_enc, "skipjack",
1947 			    sizeof("skipjack"))) {
1948 				sadb_comb->sadb_comb_encrypt = SADB_X_EALG_SKIPJACK;
1949 				sadb_comb->sadb_comb_encrypt_minbits = 80;
1950 				sadb_comb->sadb_comb_encrypt_maxbits = 80;
1951 			} else if (!strncasecmp(ipsec_def_enc, "cast128",
1952 			    sizeof("cast128"))) {
1953 				sadb_comb->sadb_comb_encrypt = SADB_X_EALG_CAST;
1954 				sadb_comb->sadb_comb_encrypt_minbits = 40;
1955 				sadb_comb->sadb_comb_encrypt_maxbits = 128;
1956 			}
1957 		} else if (ipo->ipo_sproto == IPPROTO_IPCOMP) {
1958 			/* Set the compression algorithm */
1959 			if (!strncasecmp(ipsec_def_comp, "deflate",
1960 			    sizeof("deflate"))) {
1961 				sadb_comb->sadb_comb_encrypt = SADB_X_CALG_DEFLATE;
1962 				sadb_comb->sadb_comb_encrypt_minbits = 0;
1963 				sadb_comb->sadb_comb_encrypt_maxbits = 0;
1964 			} else if (!strncasecmp(ipsec_def_comp, "lzs",
1965 			    sizeof("lzs"))) {
1966 				sadb_comb->sadb_comb_encrypt = SADB_X_CALG_LZS;
1967 				sadb_comb->sadb_comb_encrypt_minbits = 0;
1968 				sadb_comb->sadb_comb_encrypt_maxbits = 0;
1969 			}
1970 		}
1971 
1972 		/* Set the authentication algorithm */
1973 		if (!strncasecmp(ipsec_def_auth, "hmac-sha1",
1974 		    sizeof("hmac-sha1"))) {
1975 			sadb_comb->sadb_comb_auth = SADB_AALG_SHA1HMAC;
1976 			sadb_comb->sadb_comb_auth_minbits = 160;
1977 			sadb_comb->sadb_comb_auth_maxbits = 160;
1978 		} else if (!strncasecmp(ipsec_def_auth, "hmac-ripemd160",
1979 		    sizeof("hmac_ripemd160"))) {
1980 			sadb_comb->sadb_comb_auth = SADB_X_AALG_RIPEMD160HMAC;
1981 			sadb_comb->sadb_comb_auth_minbits = 160;
1982 			sadb_comb->sadb_comb_auth_maxbits = 160;
1983 		} else if (!strncasecmp(ipsec_def_auth, "hmac-md5",
1984 		    sizeof("hmac-md5"))) {
1985 			sadb_comb->sadb_comb_auth = SADB_AALG_MD5HMAC;
1986 			sadb_comb->sadb_comb_auth_minbits = 128;
1987 			sadb_comb->sadb_comb_auth_maxbits = 128;
1988 		} else if (!strncasecmp(ipsec_def_auth, "hmac-sha2-256",
1989 		    sizeof("hmac-sha2-256"))) {
1990 			sadb_comb->sadb_comb_auth = SADB_X_AALG_SHA2_256;
1991 			sadb_comb->sadb_comb_auth_minbits = 256;
1992 			sadb_comb->sadb_comb_auth_maxbits = 256;
1993 		} else if (!strncasecmp(ipsec_def_auth, "hmac-sha2-384",
1994 		    sizeof("hmac-sha2-384"))) {
1995 			sadb_comb->sadb_comb_auth = SADB_X_AALG_SHA2_384;
1996 			sadb_comb->sadb_comb_auth_minbits = 384;
1997 			sadb_comb->sadb_comb_auth_maxbits = 384;
1998 		} else if (!strncasecmp(ipsec_def_auth, "hmac-sha2-512",
1999 		    sizeof("hmac-sha2-512"))) {
2000 			sadb_comb->sadb_comb_auth = SADB_X_AALG_SHA2_512;
2001 			sadb_comb->sadb_comb_auth_minbits = 512;
2002 			sadb_comb->sadb_comb_auth_maxbits = 512;
2003 		}
2004 
2005 		sadb_comb->sadb_comb_soft_allocations = ipsec_soft_allocations;
2006 		sadb_comb->sadb_comb_hard_allocations = ipsec_exp_allocations;
2007 
2008 		sadb_comb->sadb_comb_soft_bytes = ipsec_soft_bytes;
2009 		sadb_comb->sadb_comb_hard_bytes = ipsec_exp_bytes;
2010 
2011 		sadb_comb->sadb_comb_soft_addtime = ipsec_soft_timeout;
2012 		sadb_comb->sadb_comb_hard_addtime = ipsec_exp_timeout;
2013 
2014 		sadb_comb->sadb_comb_soft_usetime = ipsec_soft_first_use;
2015 		sadb_comb->sadb_comb_hard_usetime = ipsec_exp_first_use;
2016 		sadb_comb++;
2017 	}
2018 
2019     /* Send the ACQUIRE message to all compliant registered listeners. */
2020 	if ((rval = pfkeyv2_sendmessage(headers,
2021 	    PFKEYV2_SENDMESSAGE_REGISTERED, NULL, smsg->sadb_msg_satype, 0))
2022 	    != 0)
2023 		goto ret;
2024 
2025 	rval = 0;
2026 ret:
2027 	if (buffer != NULL) {
2028 		bzero(buffer, i);
2029 		free(buffer, M_PFKEY);
2030 	}
2031 
2032 	return (rval);
2033 }
2034 
2035 /*
2036  * Notify key management that an expiration went off. The second argument
2037  * specifies the type of expiration (soft or hard).
2038  */
2039 int
pfkeyv2_expire(struct tdb * sa,u_int16_t type)2040 pfkeyv2_expire(struct tdb *sa, u_int16_t type)
2041 {
2042 	void *p, *headers[SADB_EXT_MAX+1], *buffer = NULL;
2043 	struct sadb_msg *smsg;
2044 	int rval = 0;
2045 	int i;
2046 
2047 	switch (sa->tdb_sproto) {
2048 	case IPPROTO_AH:
2049 	case IPPROTO_ESP:
2050 	case IPPROTO_IPIP:
2051 	case IPPROTO_IPCOMP:
2052 #ifdef TCP_SIGNATURE
2053 	case IPPROTO_TCP:
2054 #endif /* TCP_SIGNATURE */
2055 		break;
2056 
2057 	default:
2058 		rval = EOPNOTSUPP;
2059 		goto ret;
2060 	}
2061 
2062 	i = sizeof(struct sadb_msg) + sizeof(struct sadb_sa) +
2063 	    2 * sizeof(struct sadb_lifetime) +
2064 	    sizeof(struct sadb_address) + PADUP(SA_LEN(&sa->tdb_src.sa)) +
2065 	    sizeof(struct sadb_address) + PADUP(SA_LEN(&sa->tdb_dst.sa));
2066 
2067 	if (!(p = malloc(i, M_PFKEY, M_DONTWAIT))) {
2068 		rval = ENOMEM;
2069 		goto ret;
2070 	}
2071 
2072 	bzero(headers, sizeof(headers));
2073 
2074 	buffer = p;
2075 	bzero(p, i);
2076 
2077 	headers[0] = p;
2078 	p += sizeof(struct sadb_msg);
2079 
2080 	smsg = (struct sadb_msg *) headers[0];
2081 	smsg->sadb_msg_version = PF_KEY_V2;
2082 	smsg->sadb_msg_type = SADB_EXPIRE;
2083 	smsg->sadb_msg_satype = sa->tdb_satype;
2084 	smsg->sadb_msg_len = i / sizeof(uint64_t);
2085 	smsg->sadb_msg_seq = pfkeyv2_seq++;
2086 
2087 	headers[SADB_EXT_SA] = p;
2088 	export_sa(&p, sa);
2089 
2090 	headers[SADB_EXT_LIFETIME_CURRENT] = p;
2091 	export_lifetime(&p, sa, 2);
2092 
2093 	headers[type] = p;
2094 	type = (SADB_EXT_LIFETIME_SOFT ? PFKEYV2_LIFETIME_SOFT :
2095 	    PFKEYV2_LIFETIME_HARD);
2096 	export_lifetime(&p, sa, type);
2097 
2098 	headers[SADB_EXT_ADDRESS_SRC] = p;
2099 	export_address(&p, (struct sockaddr *) &sa->tdb_src);
2100 
2101 	headers[SADB_EXT_ADDRESS_DST] = p;
2102 	export_address(&p, (struct sockaddr *) &sa->tdb_dst);
2103 
2104 	if ((rval = pfkeyv2_sendmessage(headers, PFKEYV2_SENDMESSAGE_BROADCAST,
2105 	    NULL, 0, 0)) != 0)
2106 		goto ret;
2107 
2108 	rval = 0;
2109 
2110  ret:
2111 	if (buffer != NULL) {
2112 		bzero(buffer, i);
2113 		free(buffer, M_PFKEY);
2114 	}
2115 
2116 	return (rval);
2117 }
2118 
2119 int
pfkeyv2_init(void)2120 pfkeyv2_init(void)
2121 {
2122 	int rval;
2123 
2124 	bzero(&pfkeyv2_version, sizeof(struct pfkey_version));
2125 	pfkeyv2_version.protocol = PFKEYV2_PROTOCOL;
2126 	pfkeyv2_version.create = &pfkeyv2_create;
2127 	pfkeyv2_version.release = &pfkeyv2_release;
2128 	pfkeyv2_version.send = &pfkeyv2_send;
2129 
2130 	rval = pfkey_register(&pfkeyv2_version);
2131 	return (rval);
2132 }
2133 
2134 int
pfkeyv2_cleanup(void)2135 pfkeyv2_cleanup(void)
2136 {
2137 	pfkey_unregister(&pfkeyv2_version);
2138 	return (0);
2139 }
2140