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