xref: /openbsd/sbin/isakmpd/pf_key_v2.c (revision 1821443c)
1 /*      $OpenBSD: pf_key_v2.c,v 1.136 2003/08/08 08:37:36 ho Exp $  */
2 /*	$EOM: pf_key_v2.c,v 1.79 2000/12/12 00:33:19 niklas Exp $	*/
3 
4 /*
5  * Copyright (c) 1999, 2000, 2001 Niklas Hallqvist.  All rights reserved.
6  * Copyright (c) 1999, 2000, 2001 Angelos D. Keromytis.  All rights reserved.
7  * Copyright (c) 2001 H�kan Olsson.  All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
19  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
20  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
21  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
22  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
23  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
27  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28  */
29 
30 /*
31  * This code was written under funding by Ericsson Radio Systems.
32  */
33 
34 #include <sys/types.h>
35 #include <sys/ioctl.h>
36 #include <sys/queue.h>
37 #include <sys/socket.h>
38 #include <sys/time.h>
39 #include <sys/uio.h>
40 
41 #include "sysdep.h"
42 
43 #if !defined (LINUX_IPSEC)
44 #include <net/pfkeyv2.h>
45 #endif
46 #include <netinet/in.h>
47 #ifdef SADB_X_EXT_FLOW_TYPE
48 #include <sys/mbuf.h>
49 #include <netinet/ip_ipsp.h>
50 #endif
51 #include <arpa/inet.h>
52 #include <stdlib.h>
53 #include <string.h>
54 #include <unistd.h>
55 #include <pwd.h>
56 #include <errno.h>
57 #include <bitstring.h>
58 
59 #include "cert.h"
60 #include "conf.h"
61 #include "exchange.h"
62 #include "ipsec.h"
63 #include "ipsec_num.h"
64 #include "key.h"
65 #include "log.h"
66 #include "monitor.h"
67 #include "pf_key_v2.h"
68 #include "sa.h"
69 #include "timer.h"
70 #include "transport.h"
71 #include "util.h"
72 
73 #ifdef USE_KEYNOTE
74 #include "policy.h"
75 #endif
76 
77 #define IN6_IS_ADDR_FULL(a)						\
78   ((*(u_int32_t *)(void *)(&(a)->s6_addr[0]) == 0xffff)			\
79    && (*(u_int32_t *)(void *)(&(a)->s6_addr[4]) == 0xffff)		\
80    && (*(u_int32_t *)(void *)(&(a)->s6_addr[8]) == 0xffff)		\
81    && (*(u_int32_t *)(void *)(&(a)->s6_addr[12]) == 0xffff))
82 
83 #define ADDRESS_MAX sizeof "ffff:ffff:ffff:ffff:ffff:ffff:255.255.255.255"
84 
85 /*
86  * PF_KEY v2 always work with 64-bit entities and aligns on 64-bit boundaries.
87  */
88 #define PF_KEY_V2_CHUNK 8
89 #define PF_KEY_V2_ROUND(x)						\
90   (((x) + PF_KEY_V2_CHUNK - 1) & ~(PF_KEY_V2_CHUNK - 1))
91 
92 /* How many microseconds we will wait for a reply from the PF_KEY socket.  */
93 #define PF_KEY_REPLY_TIMEOUT 1000
94 
95 struct pf_key_v2_node {
96   TAILQ_ENTRY (pf_key_v2_node) link;
97   void *seg;
98   size_t sz;
99   int cnt;
100   u_int16_t type;
101   u_int8_t flags;
102 };
103 
104 TAILQ_HEAD (pf_key_v2_msg, pf_key_v2_node);
105 
106 #define PF_KEY_V2_NODE_MALLOCED 1
107 #define PF_KEY_V2_NODE_MARK 2
108 
109 /* Used to derive "unique" connection identifiers. */
110 int connection_seq = 0;
111 
112 #ifdef KAME
113 /*
114  * KAME requires the sadb_msg_seq of an UPDATE be the same of that of the
115  * GETSPI creating the larval SA.
116  */
117 struct pf_key_v2_sa_seq {
118   TAILQ_ENTRY (pf_key_v2_sa_seq) link;
119   u_int8_t *spi;
120   size_t sz;
121   u_int8_t proto;
122   struct sockaddr *dst;
123   int dstlen;
124   u_int32_t seq;
125 };
126 
127 TAILQ_HEAD (, pf_key_v2_sa_seq) pf_key_v2_sa_seq_map;
128 #endif
129 
130 #ifndef KAME
131 static u_int8_t *pf_key_v2_convert_id (u_int8_t *, int, size_t *, int *);
132 #endif
133 static struct pf_key_v2_msg *pf_key_v2_call (struct pf_key_v2_msg *);
134 static struct pf_key_v2_node *pf_key_v2_find_ext (struct pf_key_v2_msg *,
135 						  u_int16_t);
136 static void pf_key_v2_notify (struct pf_key_v2_msg *);
137 static struct pf_key_v2_msg *pf_key_v2_read (u_int32_t);
138 static u_int32_t pf_key_v2_seq (void);
139 static u_int32_t pf_key_v2_write (struct pf_key_v2_msg *);
140 static int pf_key_v2_remove_conf (char *);
141 static int pf_key_v2_conf_refhandle (int, char *);
142 
143 #ifdef SADB_X_ASKPOLICY
144 static int pf_key_v2_conf_refinc (int, char *);
145 #endif
146 
147 /* The socket to use for PF_KEY interactions.  */
148 static int pf_key_v2_socket;
149 
150 #ifdef KAME
151 static int
152 pf_key_v2_register_sa_seq (u_int8_t *spi, size_t sz, u_int8_t proto,
153 			   struct sockaddr *dst, int dstlen, u_int32_t seq)
154 {
155   struct pf_key_v2_sa_seq *node = 0;
156 
157   node = malloc (sizeof *node);
158   if (!node)
159     goto cleanup;
160   memset (node, '0', sizeof *node);
161   node->spi = malloc (sz);
162   if (!node->spi)
163     goto cleanup;
164   node->dst = malloc (sysdep_sa_len (dst));
165   if (!node->dst)
166     goto cleanup;
167   memcpy (node->dst, dst, sysdep_sa_len (dst));
168   node->dstlen = sysdep_sa_len (dst);
169   memcpy (node->spi, spi, sz);
170   node->sz = sz;
171   node->proto = proto;
172   node->seq = seq;
173   TAILQ_INSERT_TAIL (&pf_key_v2_sa_seq_map, node, link);
174   return 1;
175 
176  cleanup:
177   if (node->dst)
178     free (node->dst);
179   if (node)
180     free (node);
181   return 0;
182 }
183 
184 static u_int32_t
185 pf_key_v2_seq_by_sa (u_int8_t *spi, size_t sz, u_int8_t proto,
186 		     struct sockaddr *dst, int dstlen)
187 {
188   struct pf_key_v2_sa_seq *node;
189 
190   for (node = TAILQ_FIRST (&pf_key_v2_sa_seq_map); node;
191        node = TAILQ_NEXT (node, link))
192     if (node->proto == proto
193 	&& node->sz == sz && memcmp (node->spi, spi, sz) == 0
194 	&& node->dstlen == sysdep_sa_len (dst)
195 	&& memcmp (node->dst, dst, sysdep_sa_len (dst)) == 0)
196       return node->seq;
197   return 0;
198 }
199 #endif
200 
201 static struct pf_key_v2_msg *
202 pf_key_v2_msg_new (struct sadb_msg *msg, int flags)
203 {
204   struct pf_key_v2_node *node = 0;
205   struct pf_key_v2_msg *ret;
206 
207   node = malloc (sizeof *node);
208   if (!node)
209     goto cleanup;
210   ret = malloc (sizeof *ret);
211   if (!ret)
212     goto cleanup;
213   TAILQ_INIT (ret);
214   node->seg = msg;
215   node->sz = sizeof *msg;
216   node->type = 0;
217   node->cnt = 1;
218   node->flags = flags;
219   TAILQ_INSERT_HEAD (ret, node, link);
220   return ret;
221 
222  cleanup:
223   if (node)
224     free (node);
225   return 0;
226 }
227 
228 /* Add a SZ sized segment SEG to the PF_KEY message MSG.  */
229 static int
230 pf_key_v2_msg_add (struct pf_key_v2_msg *msg, struct sadb_ext *ext, int flags)
231 {
232   struct pf_key_v2_node *node;
233 
234   node = malloc (sizeof *node);
235   if (!node)
236     return -1;
237   node->seg = ext;
238   node->sz = ext->sadb_ext_len * PF_KEY_V2_CHUNK;
239   node->type = ext->sadb_ext_type;
240   node->flags = flags;
241   TAILQ_FIRST (msg)->cnt++;
242   TAILQ_INSERT_TAIL (msg, node, link);
243   return 0;
244 }
245 
246 /* Deallocate the PF_KEY message MSG.  */
247 static void
248 pf_key_v2_msg_free (struct pf_key_v2_msg *msg)
249 {
250   struct pf_key_v2_node *np;
251 
252   np = TAILQ_FIRST (msg);
253   while (np)
254     {
255       TAILQ_REMOVE (msg, np, link);
256       if (np->flags & PF_KEY_V2_NODE_MALLOCED)
257 	free (np->seg);
258       free (np);
259       np = TAILQ_FIRST (msg);
260     }
261   free (msg);
262 }
263 
264 /* Just return a new sequence number.  */
265 static u_int32_t
266 pf_key_v2_seq (void)
267 {
268   static u_int32_t seq = 0;
269 
270   return ++seq;
271 }
272 
273 /*
274  * Read a PF_KEY packet with SEQ as the sequence number, looping if necessary.
275  * If SEQ is zero just read the first message we see, otherwise we queue
276  * messages up until both the PID and the sequence number match.
277  */
278 static struct pf_key_v2_msg *
279 pf_key_v2_read (u_int32_t seq)
280 {
281   ssize_t n;
282   u_int8_t *buf = 0;
283   struct pf_key_v2_msg *ret = 0;
284   struct sadb_msg *msg;
285   struct sadb_msg hdr;
286   struct sadb_ext *ext;
287   struct timeval tv;
288   fd_set *fds;
289 
290   while (1)
291     {
292       /*
293        * If this is a read of a reply we should actually expect the reply to
294        * get lost as PF_KEY is an unreliable service per the specs.
295        * Currently we do this by setting a short timeout, and if it is not
296        * readable in that time, we fail the read.
297        */
298       if (seq)
299 	{
300 	  fds = calloc (howmany (pf_key_v2_socket + 1, NFDBITS),
301 			sizeof (fd_mask));
302 	  if (!fds)
303 	    {
304 	      log_error ("pf_key_v2_read: calloc (%lu, %lu) failed",
305 			 (unsigned long)howmany (pf_key_v2_socket + 1,
306 						 NFDBITS),
307 			 (unsigned long)sizeof (fd_mask));
308 	      goto cleanup;
309 	    }
310 	  FD_SET (pf_key_v2_socket, fds);
311 	  tv.tv_sec = 0;
312 	  tv.tv_usec = PF_KEY_REPLY_TIMEOUT;
313 	  n = select (pf_key_v2_socket + 1, fds, 0, 0, &tv);
314 	  free (fds);
315 	  if (n == -1)
316 	    {
317 	      log_error ("pf_key_v2_read: select (%d, fds, 0, 0, &tv) failed",
318 			 pf_key_v2_socket + 1);
319 	      goto cleanup;
320 	    }
321 	  if (!n)
322 	    {
323 	      log_print ("pf_key_v2_read: no reply from PF_KEY");
324 	      goto cleanup;
325 	    }
326 	}
327       n = recv (pf_key_v2_socket, &hdr, sizeof hdr, MSG_PEEK);
328       if (n == -1)
329 	{
330 	  log_error ("pf_key_v2_read: recv (%d, ...) failed",
331 		     pf_key_v2_socket);
332 	  goto cleanup;
333 	}
334       if (n != sizeof hdr)
335 	{
336 	  log_error ("pf_key_v2_read: recv (%d, ...) returned short packet "
337 		     "(%lu bytes)", pf_key_v2_socket, (unsigned long)n);
338 	  goto cleanup;
339 	}
340 
341       n = hdr.sadb_msg_len * PF_KEY_V2_CHUNK;
342       buf = malloc (n);
343       if (!buf)
344 	{
345 	  log_error ("pf_key_v2_read: malloc (%lu) failed", (unsigned long)n);
346 	  goto cleanup;
347 	}
348 
349       n = read (pf_key_v2_socket, buf, n);
350       if (n == -1)
351 	{
352 	  log_error ("pf_key_v2_read: read (%d, ...) failed",
353 		     pf_key_v2_socket);
354 	  goto cleanup;
355 	}
356 
357       if ((size_t)n != hdr.sadb_msg_len * PF_KEY_V2_CHUNK)
358 	{
359 	  log_print ("pf_key_v2_read: read (%d, ...) returned short packet "
360 		     "(%lu bytes)", pf_key_v2_socket, (unsigned long)n);
361 	  goto cleanup;
362 	}
363 
364       LOG_DBG_BUF ((LOG_SYSDEP, 80, "pf_key_v2_read: msg", buf, n));
365 
366       /* We drop all messages that is not what we expect.  */
367       msg = (struct sadb_msg *)buf;
368       if (msg->sadb_msg_version != PF_KEY_V2
369 	  || (msg->sadb_msg_pid != 0 && msg->sadb_msg_pid != getpid ()))
370 	{
371 	  if (seq)
372 	    {
373 	      free (buf);
374 	      buf = 0;
375 	      continue;
376 	    }
377 	  else
378 	    {
379 	      LOG_DBG ((LOG_SYSDEP, 90,
380 			"pf_key_v2_read:"
381 			"bad version (%d) or PID (%d, mine is %ld), ignored",
382 			msg->sadb_msg_version, msg->sadb_msg_pid,
383 			(long)getpid ()));
384 	      goto cleanup;
385 	    }
386 	}
387 
388       /* Parse the message.  */
389       ret = pf_key_v2_msg_new (msg, PF_KEY_V2_NODE_MALLOCED);
390       if (!ret)
391 	goto cleanup;
392       buf = 0;
393       for (ext = (struct sadb_ext *)(msg + 1);
394 	   (u_int8_t *)ext - (u_int8_t *)msg
395 	     < msg->sadb_msg_len * PF_KEY_V2_CHUNK;
396 	   ext = (struct sadb_ext *)((u_int8_t *)ext
397 				     + ext->sadb_ext_len * PF_KEY_V2_CHUNK))
398 	pf_key_v2_msg_add (ret, ext, 0);
399 
400       /* If the message is not the one we are waiting for, queue it up.  */
401       if (seq && (msg->sadb_msg_pid != getpid () || msg->sadb_msg_seq != seq))
402 	{
403 	  gettimeofday (&tv, 0);
404 	  timer_add_event ("pf_key_v2_notify",
405 			   (void (*) (void *))pf_key_v2_notify, ret, &tv);
406 	  ret = 0;
407 	  continue;
408 	}
409 
410       return ret;
411     }
412 
413  cleanup:
414   if (buf)
415     free (buf);
416   if (ret)
417     pf_key_v2_msg_free (ret);
418   return 0;
419 }
420 
421 /* Write the message in PMSG to the PF_KEY socket.  */
422 u_int32_t
423 pf_key_v2_write (struct pf_key_v2_msg *pmsg)
424 {
425   struct iovec *iov = 0;
426   ssize_t n;
427   size_t len;
428   int i, cnt = TAILQ_FIRST (pmsg)->cnt;
429   char header[80];
430   struct sadb_msg *msg = TAILQ_FIRST (pmsg)->seg;
431   struct pf_key_v2_node *np = TAILQ_FIRST (pmsg);
432 
433   iov = (struct iovec *)malloc (cnt * sizeof *iov);
434   if (!iov)
435     {
436       log_error ("pf_key_v2_write: malloc (%lu) failed",
437 		 cnt * (unsigned long)sizeof *iov);
438       return 0;
439     }
440 
441   msg->sadb_msg_version = PF_KEY_V2;
442   msg->sadb_msg_errno = 0;
443   msg->sadb_msg_reserved = 0;
444   msg->sadb_msg_pid = getpid ();
445   if (!msg->sadb_msg_seq)
446     msg->sadb_msg_seq = pf_key_v2_seq ();
447 
448   /* Compute the iovec segments as well as the message length.  */
449   len = 0;
450   for (i = 0; i < cnt; i++)
451     {
452       iov[i].iov_base = np->seg;
453       len += iov[i].iov_len = np->sz;
454 
455       /*
456        * XXX One can envision setting specific extension fields, like
457        * *_reserved ones here.  For now we require them to be set by the
458        * caller.
459        */
460 
461       np = TAILQ_NEXT (np, link);
462     }
463   msg->sadb_msg_len = len / PF_KEY_V2_CHUNK;
464 
465   for (i = 0; i < cnt; i++)
466     {
467       snprintf (header, sizeof header, "pf_key_v2_write: iov[%d]", i);
468       LOG_DBG_BUF ((LOG_SYSDEP, 80, header, (u_int8_t *)iov[i].iov_base,
469 		    iov[i].iov_len));
470     }
471 
472   n = writev (pf_key_v2_socket, iov, cnt);
473   if (n == -1)
474     {
475       log_error ("pf_key_v2_write: writev (%d, %p, %d) failed",
476 		 pf_key_v2_socket, iov, cnt);
477       goto cleanup;
478     }
479   if ((size_t)n != len)
480     {
481       log_error ("pf_key_v2_write: writev (%d, ...) returned prematurely "
482 		 "(%lu)", pf_key_v2_socket, (unsigned long)n);
483       goto cleanup;
484     }
485   free (iov);
486   return msg->sadb_msg_seq;
487 
488  cleanup:
489   if (iov)
490     free (iov);
491   return 0;
492 }
493 
494 /*
495  * Do a PF_KEY "call", i.e. write a message MSG, read the reply and return
496  * it to the caller.
497  */
498 static struct pf_key_v2_msg *
499 pf_key_v2_call (struct pf_key_v2_msg *msg)
500 {
501   u_int32_t seq;
502 
503   seq = pf_key_v2_write (msg);
504   if (!seq)
505     return 0;
506   return pf_key_v2_read (seq);
507 }
508 
509 /* Find the TYPE extension in MSG.  Return zero if none found.  */
510 static struct pf_key_v2_node *
511 pf_key_v2_find_ext (struct pf_key_v2_msg *msg, u_int16_t type)
512 {
513   struct pf_key_v2_node *ext;
514 
515   for (ext = TAILQ_NEXT (TAILQ_FIRST (msg), link); ext;
516        ext = TAILQ_NEXT (ext, link))
517     if (ext->type == type)
518       return ext;
519   return 0;
520 }
521 
522 /*
523  * Open the PF_KEYv2 sockets and return the descriptor used for notifies.
524  * Return -1 for failure and -2 if no notifies will show up.
525  */
526 int
527 pf_key_v2_open (void)
528 {
529   int fd = -1, err;
530   struct sadb_msg msg;
531   struct pf_key_v2_msg *regmsg = 0, *ret = 0;
532 
533   /* Open the socket we use to speak to IPsec. */
534   pf_key_v2_socket = -1;
535   fd = monitor_socket (PF_KEY, SOCK_RAW, PF_KEY_V2);
536   if (fd == -1)
537     {
538       log_error ("pf_key_v2_open: "
539 		 "socket (PF_KEY, SOCK_RAW, PF_KEY_V2) failed");
540       goto cleanup;
541     }
542   pf_key_v2_socket = fd;
543 
544   /* Register it to get ESP and AH acquires from the kernel.  */
545   msg.sadb_msg_seq = 0;
546   msg.sadb_msg_type = SADB_REGISTER;
547   msg.sadb_msg_satype = SADB_SATYPE_ESP;
548   regmsg = pf_key_v2_msg_new (&msg, 0);
549   if (!regmsg)
550     goto cleanup;
551   ret = pf_key_v2_call (regmsg);
552   pf_key_v2_msg_free (regmsg);
553   if (!ret)
554     goto cleanup;
555   err = ((struct sadb_msg *)TAILQ_FIRST (ret)->seg)->sadb_msg_errno;
556   if (err)
557     {
558       log_print ("pf_key_v2_open: REGISTER: %s", strerror (err));
559       goto cleanup;
560     }
561 
562   /* XXX Register the accepted transforms.  */
563 
564   pf_key_v2_msg_free (ret);
565   ret = 0;
566 
567   msg.sadb_msg_seq = 0;
568   msg.sadb_msg_type = SADB_REGISTER;
569   msg.sadb_msg_satype = SADB_SATYPE_AH;
570   regmsg = pf_key_v2_msg_new (&msg, 0);
571   if (!regmsg)
572     goto cleanup;
573   ret = pf_key_v2_call (regmsg);
574   pf_key_v2_msg_free (regmsg);
575   if (!ret)
576     goto cleanup;
577   err = ((struct sadb_msg *)TAILQ_FIRST (ret)->seg)->sadb_msg_errno;
578   if (err)
579     {
580       log_print ("pf_key_v2_open: REGISTER: %s", strerror (err));
581       goto cleanup;
582     }
583 
584   /* XXX Register the accepted transforms.  */
585 
586   pf_key_v2_msg_free (ret);
587   ret = 0;
588 
589 #ifdef SADB_X_SATYPE_IPCOMP
590   msg.sadb_msg_seq = 0;
591   msg.sadb_msg_type = SADB_REGISTER;
592   msg.sadb_msg_satype = SADB_X_SATYPE_IPCOMP;
593   regmsg = pf_key_v2_msg_new (&msg, 0);
594   if (!regmsg)
595     goto cleanup;
596   ret = pf_key_v2_call (regmsg);
597   pf_key_v2_msg_free (regmsg);
598   if (!ret)
599     goto cleanup;
600   err = ((struct sadb_msg *)TAILQ_FIRST (ret)->seg)->sadb_msg_errno;
601   if (err)
602     {
603       log_print ("pf_key_v2_open: REGISTER: %s", strerror (err));
604       goto cleanup;
605     }
606 
607   /* XXX Register the accepted transforms.  */
608 
609   pf_key_v2_msg_free (ret);
610 #endif /* SADB_X_SATYPE_IPCOMP */
611 
612 #ifdef KAME
613   TAILQ_INIT (&pf_key_v2_sa_seq_map);
614 #endif
615 
616   return fd;
617 
618  cleanup:
619   if (pf_key_v2_socket != -1)
620     {
621       close (pf_key_v2_socket);
622       pf_key_v2_socket = -1;
623     }
624   if (ret)
625     pf_key_v2_msg_free (ret);
626   return -1;
627 }
628 
629 /*
630  * Generate a SPI for protocol PROTO and the source/destination pair given by
631  * SRC, SRCLEN, DST & DSTLEN.  Stash the SPI size in SZ.
632  */
633 u_int8_t *
634 pf_key_v2_get_spi (size_t *sz, u_int8_t proto, struct sockaddr *src,
635 		   struct sockaddr *dst, u_int32_t seq)
636 {
637   struct sadb_msg msg;
638   struct sadb_sa *sa;
639   struct sadb_address *addr = 0;
640   struct sadb_spirange spirange;
641   struct pf_key_v2_msg *getspi = 0, *ret = 0;
642   struct pf_key_v2_node *ext;
643   u_int8_t *spi = 0;
644   int len, err;
645 #ifdef KAME
646   struct sadb_x_sa2 ssa2;
647 #endif
648 
649   msg.sadb_msg_type = SADB_GETSPI;
650   switch (proto)
651     {
652     case IPSEC_PROTO_IPSEC_ESP:
653       msg.sadb_msg_satype = SADB_SATYPE_ESP;
654       break;
655     case IPSEC_PROTO_IPSEC_AH:
656       msg.sadb_msg_satype = SADB_SATYPE_AH;
657       break;
658 #ifdef SADB_X_SATYPE_IPCOMP
659     case IPSEC_PROTO_IPCOMP:
660       msg.sadb_msg_satype = SADB_X_SATYPE_IPCOMP;
661       break;
662 #endif
663     default:
664       log_print ("pf_key_v2_get_spi: invalid proto %d", proto);
665       goto cleanup;
666     }
667 
668   /* Set the sequence number from the ACQUIRE message. */
669   msg.sadb_msg_seq = seq;
670   getspi = pf_key_v2_msg_new (&msg, 0);
671   if (!getspi)
672     goto cleanup;
673 
674 #ifdef KAME
675   memset (&ssa2, 0, sizeof ssa2);
676   ssa2.sadb_x_sa2_exttype = SADB_X_EXT_SA2;
677   ssa2.sadb_x_sa2_len = sizeof ssa2 / PF_KEY_V2_CHUNK;
678   ssa2.sadb_x_sa2_mode = 0;
679   if (pf_key_v2_msg_add (getspi, (struct sadb_ext *)&ssa2, 0) == -1)
680     goto cleanup;
681 #endif
682 
683   /* Setup the ADDRESS extensions.  */
684   len = sizeof (struct sadb_address) + PF_KEY_V2_ROUND (sysdep_sa_len (src));
685   addr = calloc (1, len);
686   if (!addr)
687     goto cleanup;
688   addr->sadb_address_exttype = SADB_EXT_ADDRESS_SRC;
689   addr->sadb_address_len = len / PF_KEY_V2_CHUNK;
690 #ifndef __OpenBSD__
691   addr->sadb_address_proto = 0;
692   addr->sadb_address_prefixlen = 0;
693 #endif
694   addr->sadb_address_reserved = 0;
695   memcpy (addr + 1, src, sysdep_sa_len (src));
696   switch (((struct sockaddr *)(addr + 1))->sa_family)
697     {
698     case AF_INET:
699       ((struct sockaddr_in *)(addr + 1))->sin_port = 0;
700       break;
701     case AF_INET6:
702       ((struct sockaddr_in6 *)(addr + 1))->sin6_port = 0;
703       break;
704     }
705   if (pf_key_v2_msg_add (getspi, (struct sadb_ext *)addr,
706 			 PF_KEY_V2_NODE_MALLOCED) == -1)
707     goto cleanup;
708   addr = 0;
709 
710   len = sizeof (struct sadb_address) + PF_KEY_V2_ROUND (sysdep_sa_len (dst));
711   addr = calloc (1, len);
712   if (!addr)
713     goto cleanup;
714   addr->sadb_address_exttype = SADB_EXT_ADDRESS_DST;
715   addr->sadb_address_len = len / PF_KEY_V2_CHUNK;
716 #ifndef __OpenBSD__
717   addr->sadb_address_proto = 0;
718   addr->sadb_address_prefixlen = 0;
719 #endif
720   addr->sadb_address_reserved = 0;
721   memcpy (addr + 1, dst, sysdep_sa_len (dst));
722   switch (((struct sockaddr *)(addr + 1))->sa_family)
723     {
724     case AF_INET:
725       ((struct sockaddr_in *)(addr + 1))->sin_port = 0;
726       break;
727     case AF_INET6:
728       ((struct sockaddr_in6 *)(addr + 1))->sin6_port = 0;
729       break;
730     }
731   if (pf_key_v2_msg_add (getspi, (struct sadb_ext *)addr,
732 			 PF_KEY_V2_NODE_MALLOCED) == -1)
733     goto cleanup;
734   addr = 0;
735 
736   /* Setup the SPIRANGE extension.  */
737   spirange.sadb_spirange_exttype = SADB_EXT_SPIRANGE;
738   spirange.sadb_spirange_len = sizeof spirange / PF_KEY_V2_CHUNK;
739   if (proto == IPSEC_PROTO_IPCOMP)
740     {
741       spirange.sadb_spirange_min = CPI_RESERVED_MAX + 1;
742       spirange.sadb_spirange_max = CPI_PRIVATE_MIN - 1;
743     }
744   else
745     {
746       spirange.sadb_spirange_min = IPSEC_SPI_LOW;
747       spirange.sadb_spirange_max = 0xffffffff;
748     }
749   spirange.sadb_spirange_reserved = 0;
750   if (pf_key_v2_msg_add (getspi, (struct sadb_ext *)&spirange, 0) == -1)
751     goto cleanup;
752 
753   ret = pf_key_v2_call (getspi);
754   pf_key_v2_msg_free (getspi);
755   getspi = 0;
756   if (!ret)
757     goto cleanup;
758   err = ((struct sadb_msg *)TAILQ_FIRST (ret)->seg)->sadb_msg_errno;
759   if (err)
760     {
761       log_print ("pf_key_v2_get_spi: GETSPI: %s", strerror (err));
762       goto cleanup;
763     }
764 
765   ext = pf_key_v2_find_ext (ret, SADB_EXT_SA);
766   if (!ext)
767     {
768       log_print ("pf_key_v2_get_spi: no SA extension found");
769       goto cleanup;
770     }
771   sa = ext->seg;
772 
773   /* IPCOMP CPIs are only 16 bits long.  */
774   *sz = (proto == IPSEC_PROTO_IPCOMP) ? sizeof (u_int16_t)
775     : sizeof sa->sadb_sa_spi;
776   spi = malloc (*sz);
777   if (!spi)
778     goto cleanup;
779   /* XXX This is ugly.  */
780   if (proto == IPSEC_PROTO_IPCOMP)
781     {
782       u_int32_t tspi = ntohl (sa->sadb_sa_spi);
783       *(u_int16_t *)spi = htons ((u_int16_t)tspi);
784     }
785   else
786     memcpy (spi, &sa->sadb_sa_spi, *sz);
787 
788 #ifdef KAME
789   if (!pf_key_v2_register_sa_seq (spi, *sz, proto, dst, sysdep_sa_len (dst),
790 				  ((struct sadb_msg *)(TAILQ_FIRST (ret)->seg))
791 				  ->sadb_msg_seq))
792     goto cleanup;
793 #endif
794   pf_key_v2_msg_free (ret);
795 
796   LOG_DBG_BUF ((LOG_SYSDEP, 50, "pf_key_v2_get_spi: spi", spi, *sz));
797 
798   return spi;
799 
800  cleanup:
801   if (spi)
802     free (spi);
803   if (addr)
804     free (addr);
805   if (getspi)
806     pf_key_v2_msg_free (getspi);
807   if (ret)
808     pf_key_v2_msg_free (ret);
809   return 0;
810 }
811 
812 static void
813 pf_key_v2_setup_sockaddr (void *res, struct sockaddr *src,
814 			  struct sockaddr *dst, in_port_t port, int ingress)
815 {
816   struct sockaddr_in *ip4_sa;
817   struct sockaddr_in6 *ip6_sa;
818   u_int8_t *p;
819 
820   switch (src->sa_family)
821     {
822     case AF_INET:
823       ip4_sa = (struct sockaddr_in *)res;
824       ip4_sa->sin_family = AF_INET;
825 #ifndef USE_OLD_SOCKADDR
826       ip4_sa->sin_len = sizeof *ip4_sa;
827 #endif
828       ip4_sa->sin_port = port;
829       if (dst)
830 	p = (u_int8_t *)(ingress
831 			 ? &((struct sockaddr_in *)src)->sin_addr.s_addr
832 			 : &((struct sockaddr_in *)dst)->sin_addr.s_addr);
833       else
834 	p = (u_int8_t *)&((struct sockaddr_in *)src)->sin_addr.s_addr;
835       ip4_sa->sin_addr.s_addr = *((in_addr_t *)p);
836       break;
837 
838     case AF_INET6:
839       ip6_sa = (struct sockaddr_in6 *)res;
840       ip6_sa->sin6_family = AF_INET6;
841 #ifndef USE_OLD_SOCKADDR
842       ip6_sa->sin6_len = sizeof *ip6_sa;
843 #endif
844       ip6_sa->sin6_port = port;
845       if (dst)
846 	p = (u_int8_t *)(ingress
847 			 ? &((struct sockaddr_in6 *)src)->sin6_addr.s6_addr
848 			 : &((struct sockaddr_in6 *)dst)->sin6_addr.s6_addr);
849       else
850 	p = (u_int8_t *)&((struct sockaddr_in6 *)src)->sin6_addr.s6_addr;
851       memcpy (ip6_sa->sin6_addr.s6_addr, p, sizeof (struct in6_addr));
852       break;
853 
854     default:
855       log_print ("pf_key_v2_setup_sockaddr: unknown family %d\n",
856 		 src->sa_family);
857       break;
858     }
859 }
860 
861 /*
862  * Store/update a PF_KEY_V2 security association with full information from the
863  * IKE SA and PROTO into the kernel.  INCOMING is set if we are setting the
864  * parameters for the incoming SA, and cleared otherwise.
865  */
866 int
867 pf_key_v2_set_spi (struct sa *sa, struct proto *proto, int incoming,
868 		   struct sa *isakmp_sa)
869 {
870   struct sadb_msg msg;
871   struct sadb_sa ssa;
872   struct sadb_lifetime *life = 0;
873   struct sadb_address *addr = 0;
874   struct sadb_key *key = 0;
875   struct sadb_ident *sid = 0;
876   struct sockaddr *src, *dst;
877   struct pf_key_v2_msg *update = 0, *ret = 0;
878   struct ipsec_proto *iproto = proto->data;
879   size_t len;
880   int keylen, hashlen, err;
881 #ifndef KAME
882   u_int8_t *pp;
883   int idtype;
884 #else /* KAME */
885   struct sadb_x_sa2 ssa2;
886 #endif
887 #if defined (SADB_X_CREDTYPE_NONE) || defined (SADB_X_AUTHTYPE_NONE)
888   struct ipsec_sa *isa = sa->data;
889   struct sadb_x_cred *cred;
890   struct sadb_protocol flowtype, tprotocol;
891 #endif
892 #ifdef USE_DEBUG
893   char *addr_str;
894 #endif
895 
896   msg.sadb_msg_type = incoming ? SADB_UPDATE : SADB_ADD;
897   switch (proto->proto)
898     {
899     case IPSEC_PROTO_IPSEC_ESP:
900       msg.sadb_msg_satype = SADB_SATYPE_ESP;
901       keylen = ipsec_esp_enckeylength (proto);
902       hashlen = ipsec_esp_authkeylength (proto);
903 
904       switch (proto->id)
905 	{
906 	case IPSEC_ESP_DES:
907 	case IPSEC_ESP_DES_IV32:
908 	case IPSEC_ESP_DES_IV64:
909 	  ssa.sadb_sa_encrypt = SADB_EALG_DESCBC;
910 	  break;
911 
912 	case IPSEC_ESP_3DES:
913 	  ssa.sadb_sa_encrypt = SADB_EALG_3DESCBC;
914 	  break;
915 
916 #ifdef SADB_X_EALG_AES
917 	case IPSEC_ESP_AES:
918 	/* case IPSEC_ESP_AES_128_CTR: */
919 	  ssa.sadb_sa_encrypt = SADB_X_EALG_AES;
920 	  break;
921 #endif
922 
923 #ifdef SADB_X_EALG_CAST
924 	case IPSEC_ESP_CAST:
925 	  ssa.sadb_sa_encrypt = SADB_X_EALG_CAST;
926 	  break;
927 #endif
928 
929 #ifdef SADB_X_EALG_BLF
930 	case IPSEC_ESP_BLOWFISH:
931 	  ssa.sadb_sa_encrypt = SADB_X_EALG_BLF;
932 	  break;
933 #endif
934 
935 	default:
936 	  LOG_DBG ((LOG_SYSDEP, 50,
937 		    "pf_key_v2_set_spi: unknown encryption algorithm %d",
938 		    proto->id));
939 	  return -1;
940 	}
941 
942       switch (iproto->auth)
943 	{
944 	case IPSEC_AUTH_HMAC_MD5:
945 #ifdef SADB_AALG_MD5HMAC96
946 	  ssa.sadb_sa_auth = SADB_AALG_MD5HMAC96;
947 #else
948 	  ssa.sadb_sa_auth = SADB_AALG_MD5HMAC;
949 #endif
950 	  break;
951 
952 	case IPSEC_AUTH_HMAC_SHA:
953 #ifdef SADB_AALG_SHA1HMAC96
954 	  ssa.sadb_sa_auth = SADB_AALG_SHA1HMAC96;
955 #else
956 	  ssa.sadb_sa_auth = SADB_AALG_SHA1HMAC;
957 #endif
958 	  break;
959 
960 #ifndef KAME
961         case IPSEC_AUTH_HMAC_RIPEMD:
962 #ifdef SADB_X_AALG_RIPEMD160HMAC96
963 	  ssa.sadb_sa_auth = SADB_X_AALG_RIPEMD160HMAC96;
964 #elif defined(SADB_X_AALG_RIPEMD160HMAC)
965 	  ssa.sadb_sa_auth = SADB_X_AALG_RIPEMD160HMAC;
966 #elif defined(SADB_X_AALG_RIPEMD160)
967 	  ssa.sadb_sa_auth = SADB_X_AALG_RIPEMD160;
968 #else
969 	  ssa.sadb_sa_auth = SADB_AALG_RIPEMD160HMAC;
970 #endif
971 	  break;
972 #endif
973 
974 #ifdef SADB_X_AALG_SHA2_256
975 	case IPSEC_AUTH_HMAC_SHA2_256:
976 	  ssa.sadb_sa_auth = SADB_X_AALG_SHA2_256;
977 	  break;
978 #endif
979 
980 #ifdef SADB_X_AALG_SHA2_384
981 	case IPSEC_AUTH_HMAC_SHA2_384:
982 	  ssa.sadb_sa_auth = SADB_X_AALG_SHA2_384;
983 	  break;
984 #endif
985 
986 #ifdef SADB_X_AALG_SHA2_512
987 	case IPSEC_AUTH_HMAC_SHA2_512:
988 	  ssa.sadb_sa_auth = SADB_X_AALG_SHA2_512;
989 	  break;
990 #endif
991 
992 	case IPSEC_AUTH_DES_MAC:
993 	case IPSEC_AUTH_KPDK:
994 	  /* XXX We should be supporting KPDK */
995 	  LOG_DBG ((LOG_SYSDEP, 50,
996 		    "pf_key_v2_set_spi: unknown authentication algorithm %d",
997 		    iproto->auth));
998 	  return -1;
999 
1000 	default:
1001 	  ssa.sadb_sa_auth = SADB_AALG_NONE;
1002 	}
1003       break;
1004 
1005     case IPSEC_PROTO_IPSEC_AH:
1006       msg.sadb_msg_satype = SADB_SATYPE_AH;
1007       hashlen = ipsec_ah_keylength (proto);
1008       keylen = 0;
1009 
1010       ssa.sadb_sa_encrypt = SADB_EALG_NONE;
1011       switch (proto->id)
1012 	{
1013 	case IPSEC_AH_MD5:
1014 #ifdef SADB_AALG_MD5HMAC96
1015 	  ssa.sadb_sa_auth = SADB_AALG_MD5HMAC96;
1016 #else
1017 	  ssa.sadb_sa_auth = SADB_AALG_MD5HMAC;
1018 #endif
1019 	  break;
1020 
1021 	case IPSEC_AH_SHA:
1022 #ifdef SADB_AALG_SHA1HMAC96
1023 	  ssa.sadb_sa_auth = SADB_AALG_SHA1HMAC96;
1024 #else
1025 	  ssa.sadb_sa_auth = SADB_AALG_SHA1HMAC;
1026 #endif
1027 	  break;
1028 
1029 #ifndef KAME
1030 	case IPSEC_AH_RIPEMD:
1031 #ifdef SADB_X_AALG_RIPEMD160HMAC96
1032 	  ssa.sadb_sa_auth = SADB_X_AALG_RIPEMD160HMAC96;
1033 #elif defined(SADB_X_AALG_RIPEMD160HMAC)
1034 	  ssa.sadb_sa_auth = SADB_X_AALG_RIPEMD160HMAC;
1035 #elif defined(SADB_X_AALG_RIPEMD160)
1036 	  ssa.sadb_sa_auth = SADB_X_AALG_RIPEMD160;
1037 #else
1038 	  ssa.sadb_sa_auth = SADB_AALG_RIPEMD160HMAC;
1039 #endif
1040 	  break;
1041 #endif
1042 
1043 #ifdef SADB_X_AALG_SHA2_256
1044 	case IPSEC_AH_SHA2_256:
1045 	  ssa.sadb_sa_auth = SADB_X_AALG_SHA2_256;
1046 	  break;
1047 #endif
1048 
1049 #ifdef SADB_X_AALG_SHA2_384
1050 	case IPSEC_AH_SHA2_384:
1051 	  ssa.sadb_sa_auth = SADB_X_AALG_SHA2_384;
1052 	  break;
1053 #endif
1054 
1055 #ifdef SADB_X_AALG_SHA2_512
1056 	case IPSEC_AH_SHA2_512:
1057 	  ssa.sadb_sa_auth = SADB_X_AALG_SHA2_512;
1058 	  break;
1059 #endif
1060 
1061 	default:
1062 	  LOG_DBG ((LOG_SYSDEP, 50,
1063 		    "pf_key_v2_set_spi: unknown authentication algorithm %d",
1064 		    proto->id));
1065 	  goto cleanup;
1066 	}
1067       break;
1068 
1069 #ifdef SADB_X_SATYPE_IPCOMP
1070     case IPSEC_PROTO_IPCOMP:
1071       msg.sadb_msg_satype = SADB_X_SATYPE_IPCOMP;
1072       ssa.sadb_sa_auth = SADB_AALG_NONE;
1073       keylen = 0;
1074       hashlen = 0;
1075 
1076       /* Put compression algorithm type in the sadb_sa_encrypt field.  */
1077       switch (proto->id)
1078 	{
1079 #ifdef SADB_X_CALG_OUI
1080 	case IPSEC_IPCOMP_OUI:
1081 	  ssa.sadb_sa_encrypt = SADB_X_CALG_OUI;
1082 	  break;
1083 #endif
1084 
1085 #ifdef SADB_X_CALG_DEFLATE
1086 	case IPSEC_IPCOMP_DEFLATE:
1087 	  ssa.sadb_sa_encrypt = SADB_X_CALG_DEFLATE;
1088 	  break;
1089 #endif
1090 
1091 #ifdef SADB_X_CALG_LZS
1092 	case IPSEC_IPCOMP_LZS:
1093 	  ssa.sadb_sa_encrypt = SADB_X_CALG_LZS;
1094 	  break;
1095 #endif
1096 
1097 #ifdef SADB_X_CALG_V42BIS
1098 	case IPSEC_IPCOMP_V42BIS:
1099 	  ssa.sadb_sa_encrypt = SADB_X_CALG_V42BIS;
1100 	  break;
1101 #endif
1102 
1103 	default:
1104 	  break;
1105 	}
1106       break;
1107 #endif /* SADB_X_SATYPE_IPCOMP */
1108 
1109     default:
1110       log_print ("pf_key_v2_set_spi: invalid proto %d", proto->proto);
1111       goto cleanup;
1112     }
1113   if (incoming)
1114     sa->transport->vtbl->get_src (sa->transport, &dst);
1115   else
1116     sa->transport->vtbl->get_dst (sa->transport, &dst);
1117 #ifdef KAME
1118   msg.sadb_msg_seq
1119     = (incoming ? pf_key_v2_seq_by_sa (proto->spi[incoming],
1120 				       sizeof ssa.sadb_sa_spi, proto->proto,
1121 				       dst, sysdep_sa_len (dst))
1122        : 0);
1123 #else
1124   msg.sadb_msg_seq = sa->seq;
1125 #endif
1126   update = pf_key_v2_msg_new (&msg, 0);
1127   if (!update)
1128     goto cleanup;
1129 
1130 #ifdef KAME
1131   memset (&ssa2, 0, sizeof ssa2);
1132   ssa2.sadb_x_sa2_exttype = SADB_X_EXT_SA2;
1133   ssa2.sadb_x_sa2_len = sizeof ssa2 / PF_KEY_V2_CHUNK;
1134 #if defined (LINUX_IPSEC)
1135   if (iproto->encap_mode == IPSEC_ENCAP_TUNNEL)
1136     ssa2.sadb_x_sa2_mode = IPSEC_MODE_TUNNEL;
1137   else
1138     ssa2.sadb_x_sa2_mode = IPSEC_MODE_TRANSPORT;
1139 #else
1140   ssa2.sadb_x_sa2_mode = 0;
1141 #endif
1142   if (pf_key_v2_msg_add (update, (struct sadb_ext *)&ssa2, 0) == -1)
1143     goto cleanup;
1144 #endif
1145 
1146   /* Setup the rest of the SA extension.  */
1147   ssa.sadb_sa_exttype = SADB_EXT_SA;
1148   ssa.sadb_sa_len = sizeof ssa / PF_KEY_V2_CHUNK;
1149   if (proto->spi_sz[incoming] == 2) /* IPCOMP uses 16bit CPIs.  */
1150     ssa.sadb_sa_spi = htonl(proto->spi[incoming][0] << 8
1151 			    | proto->spi[incoming][1]);
1152   else
1153     memcpy (&ssa.sadb_sa_spi, proto->spi[incoming], sizeof ssa.sadb_sa_spi);
1154   ssa.sadb_sa_replay
1155     = conf_get_str ("General", "Shared-SADB") ? 0 : iproto->replay_window;
1156   ssa.sadb_sa_state = SADB_SASTATE_MATURE;
1157 #ifdef SADB_X_SAFLAGS_TUNNEL
1158   ssa.sadb_sa_flags
1159     = iproto->encap_mode == IPSEC_ENCAP_TUNNEL ? SADB_X_SAFLAGS_TUNNEL : 0;
1160 #else
1161   ssa.sadb_sa_flags = 0;
1162 #endif
1163   if (pf_key_v2_msg_add (update, (struct sadb_ext *)&ssa, 0) == -1)
1164     goto cleanup;
1165 
1166   if (sa->seconds || sa->kilobytes)
1167     {
1168       /* Setup the hard limits.  */
1169       life = malloc (sizeof *life);
1170       if (!life)
1171 	goto cleanup;
1172       life->sadb_lifetime_len = sizeof *life / PF_KEY_V2_CHUNK;
1173       life->sadb_lifetime_exttype = SADB_EXT_LIFETIME_HARD;
1174       life->sadb_lifetime_allocations = 0;
1175       life->sadb_lifetime_bytes = sa->kilobytes * 1024;
1176       /*
1177        * XXX I am not sure which one is best in security respect.  Maybe the
1178        * RFCs actually mandate what a lifetime really is.
1179        */
1180 #if 0
1181       life->sadb_lifetime_addtime = 0;
1182       life->sadb_lifetime_usetime = sa->seconds;
1183 #else
1184       life->sadb_lifetime_addtime = sa->seconds;
1185       life->sadb_lifetime_usetime = 0;
1186 #endif
1187       if (pf_key_v2_msg_add (update, (struct sadb_ext *)life,
1188 			     PF_KEY_V2_NODE_MALLOCED) == -1)
1189 	goto cleanup;
1190       life = 0;
1191 
1192       /*
1193        * Setup the soft limits, we use 90 % of the hard ones.
1194        * XXX A configurable ratio would be better.
1195        */
1196       life = malloc (sizeof *life);
1197       if (!life)
1198 	goto cleanup;
1199       life->sadb_lifetime_len = sizeof *life / PF_KEY_V2_CHUNK;
1200       life->sadb_lifetime_exttype = SADB_EXT_LIFETIME_SOFT;
1201       life->sadb_lifetime_allocations = 0;
1202       life->sadb_lifetime_bytes = sa->kilobytes * 1024 * 9 / 10;
1203       /*
1204        * XXX I am not sure which one is best in security respect.  Maybe the
1205        * RFCs actually mandate what a lifetime really is.
1206        */
1207 #if 0
1208       life->sadb_lifetime_addtime = 0;
1209       life->sadb_lifetime_usetime = sa->seconds * 9 / 10;
1210 #else
1211       life->sadb_lifetime_addtime = sa->seconds * 9 / 10;
1212       life->sadb_lifetime_usetime = 0;
1213 #endif
1214       if (pf_key_v2_msg_add (update, (struct sadb_ext *)life,
1215 			     PF_KEY_V2_NODE_MALLOCED) == -1)
1216 	goto cleanup;
1217       life = 0;
1218     }
1219 
1220   /*
1221    * Setup the ADDRESS extensions.
1222    */
1223   if (incoming)
1224     sa->transport->vtbl->get_dst (sa->transport, &src);
1225   else
1226     sa->transport->vtbl->get_src (sa->transport, &src);
1227   len = sizeof *addr + PF_KEY_V2_ROUND (sysdep_sa_len (src));
1228   addr = calloc (1, len);
1229   if (!addr)
1230     goto cleanup;
1231   addr->sadb_address_exttype = SADB_EXT_ADDRESS_SRC;
1232   addr->sadb_address_len = len / PF_KEY_V2_CHUNK;
1233 #ifndef __OpenBSD__
1234   addr->sadb_address_proto = 0;
1235   addr->sadb_address_prefixlen = 0;
1236 #endif
1237   addr->sadb_address_reserved = 0;
1238   memcpy (addr + 1, src, sysdep_sa_len (src));
1239   switch (((struct sockaddr *)(addr + 1))->sa_family)
1240     {
1241     case AF_INET:
1242       ((struct sockaddr_in *)(addr + 1))->sin_port = 0;
1243       break;
1244     case AF_INET6:
1245       ((struct sockaddr_in6 *)(addr + 1))->sin6_port = 0;
1246       break;
1247     }
1248   if (pf_key_v2_msg_add (update, (struct sadb_ext *)addr,
1249 			 PF_KEY_V2_NODE_MALLOCED) == -1)
1250     goto cleanup;
1251   addr = 0;
1252 
1253   len = sizeof *addr + PF_KEY_V2_ROUND (sysdep_sa_len (dst));
1254   addr = calloc (1, len);
1255   if (!addr)
1256     goto cleanup;
1257   addr->sadb_address_exttype = SADB_EXT_ADDRESS_DST;
1258   addr->sadb_address_len = len / PF_KEY_V2_CHUNK;
1259 #ifndef __OpenBSD__
1260   addr->sadb_address_proto = 0;
1261   addr->sadb_address_prefixlen = 0;
1262 #endif
1263   addr->sadb_address_reserved = 0;
1264   memcpy (addr + 1, dst, sysdep_sa_len (dst));
1265   switch (((struct sockaddr *)(addr + 1))->sa_family)
1266     {
1267     case AF_INET:
1268       ((struct sockaddr_in *)(addr + 1))->sin_port = 0;
1269       break;
1270     case AF_INET6:
1271       ((struct sockaddr_in6 *)(addr + 1))->sin6_port = 0;
1272       break;
1273     }
1274   if (pf_key_v2_msg_add (update, (struct sadb_ext *)addr,
1275 			 PF_KEY_V2_NODE_MALLOCED) == -1)
1276     goto cleanup;
1277   addr = 0;
1278 
1279 #if 0
1280   /* XXX I am not sure about what to do here just yet.  */
1281   if (iproto->encap_mode == IPSEC_ENCAP_TUNNEL)
1282     {
1283       len = sizeof *addr + PF_KEY_V2_ROUND (sysdep_sa_len (dst));
1284       addr = calloc (1, len);
1285       if (!addr)
1286 	goto cleanup;
1287       addr->sadb_address_exttype = SADB_EXT_ADDRESS_PROXY;
1288       addr->sadb_address_len = len / PF_KEY_V2_CHUNK;
1289 #ifndef __OpenBSD__
1290       addr->sadb_address_proto = 0;
1291       addr->sadb_address_prefixlen = 0;
1292 #endif
1293       addr->sadb_address_reserved = 0;
1294       memcpy (addr + 1, dst, sysdep_sa_len (dst));
1295       switch (((struct sockaddr *)(addr + 1))->sa_family)
1296 	{
1297 	case AF_INET:
1298 	  ((struct sockaddr_in *)(addr + 1))->sin_port = 0;
1299 	  break;
1300 	case AF_INET6:
1301 	  ((struct sockaddr_in6 *)(addr + 1))->sin6_port = 0;
1302 	  break;
1303 	}
1304       if (pf_key_v2_msg_add (update, (struct sadb_ext *)addr,
1305 			     PF_KEY_V2_NODE_MALLOCED) == -1)
1306 	goto cleanup;
1307       addr = 0;
1308 #if 0
1309       msg->em_odst = msg->em_dst;
1310       msg->em_osrc = msg->em_src;
1311 #endif
1312     }
1313 #endif
1314 
1315   if (proto->proto != IPSEC_PROTO_IPCOMP)
1316     {
1317       /* Setup the KEY extensions.  */
1318       len = sizeof *key + PF_KEY_V2_ROUND (hashlen);
1319       key = malloc (len);
1320       if (!key)
1321 	goto cleanup;
1322       key->sadb_key_exttype = SADB_EXT_KEY_AUTH;
1323       key->sadb_key_len = len / PF_KEY_V2_CHUNK;
1324       key->sadb_key_bits = hashlen * 8;
1325       key->sadb_key_reserved = 0;
1326       memcpy (key + 1,
1327 	      iproto->keymat[incoming]
1328 	      + (proto->proto == IPSEC_PROTO_IPSEC_ESP ? keylen : 0),
1329 	      hashlen);
1330       if (pf_key_v2_msg_add (update, (struct sadb_ext *)key,
1331 			     PF_KEY_V2_NODE_MALLOCED) == -1)
1332 	goto cleanup;
1333       key = 0;
1334 
1335       if (keylen)
1336 	{
1337 	  len = sizeof *key + PF_KEY_V2_ROUND (keylen);
1338 	  key = malloc (len);
1339 	  if (!key)
1340 	    goto cleanup;
1341 	  key->sadb_key_exttype = SADB_EXT_KEY_ENCRYPT;
1342 	  key->sadb_key_len = len / PF_KEY_V2_CHUNK;
1343 	  key->sadb_key_bits = keylen * 8;
1344 	  key->sadb_key_reserved = 0;
1345 	  memcpy (key + 1, iproto->keymat[incoming], keylen);
1346 	  if (pf_key_v2_msg_add (update, (struct sadb_ext *)key,
1347 				 PF_KEY_V2_NODE_MALLOCED) == -1)
1348 	    goto cleanup;
1349 	  key = 0;
1350 	}
1351     }
1352 
1353 #ifndef KAME
1354   /* Setup identity extensions. */
1355   if (isakmp_sa->id_i)
1356     {
1357       pp = pf_key_v2_convert_id (isakmp_sa->id_i, isakmp_sa->id_i_len,
1358 				 &len, &idtype);
1359       if (!pp)
1360 	goto nosid;
1361 
1362       sid = calloc (PF_KEY_V2_ROUND (len + 1) + sizeof *sid, sizeof (u_int8_t));
1363       if (!sid)
1364 	{
1365 	  free (pp);
1366 	  goto cleanup;
1367 	}
1368 
1369       sid->sadb_ident_type = idtype;
1370       sid->sadb_ident_len = ((sizeof *sid) / PF_KEY_V2_CHUNK)
1371 			    + PF_KEY_V2_ROUND (len + 1) / PF_KEY_V2_CHUNK;
1372       if ((isakmp_sa->initiator && !incoming)
1373 	  || (!isakmp_sa->initiator && incoming))
1374 	sid->sadb_ident_exttype = SADB_EXT_IDENTITY_SRC;
1375       else
1376 	sid->sadb_ident_exttype = SADB_EXT_IDENTITY_DST;
1377 
1378       memcpy(sid + 1, pp, len);
1379       free (pp);
1380 
1381       if (pf_key_v2_msg_add (update, (struct sadb_ext *)sid,
1382 			      PF_KEY_V2_NODE_MALLOCED) == -1)
1383 	goto cleanup;
1384       sid = 0;
1385 
1386  nosid:
1387       if (sid)
1388 	free (sid);
1389       sid = 0;
1390     }
1391 
1392   if (isakmp_sa->id_r)
1393     {
1394       pp = pf_key_v2_convert_id (isakmp_sa->id_r, isakmp_sa->id_r_len,
1395 				 &len, &idtype);
1396       if (!pp)
1397 	goto nodid;
1398 
1399       sid = calloc (PF_KEY_V2_ROUND (len + 1) + sizeof *sid, sizeof (u_int8_t));
1400       if (!sid)
1401 	{
1402 	  free (pp);
1403 	  goto cleanup;
1404 	}
1405 
1406       sid->sadb_ident_type = idtype;
1407       sid->sadb_ident_len = ((sizeof *sid) / PF_KEY_V2_CHUNK)
1408 			    + PF_KEY_V2_ROUND (len + 1) / PF_KEY_V2_CHUNK;
1409       if ((isakmp_sa->initiator && !incoming)
1410 	  || (!isakmp_sa->initiator && incoming))
1411 	sid->sadb_ident_exttype = SADB_EXT_IDENTITY_DST;
1412       else
1413 	sid->sadb_ident_exttype = SADB_EXT_IDENTITY_SRC;
1414 
1415       memcpy (sid + 1, pp, len);
1416       free (pp);
1417 
1418       if (pf_key_v2_msg_add (update, (struct sadb_ext *)sid,
1419 			      PF_KEY_V2_NODE_MALLOCED) == -1)
1420 	goto cleanup;
1421       sid = 0;
1422 
1423  nodid:
1424       if (sid)
1425 	free (sid);
1426       sid = 0;
1427     }
1428 #endif /* KAME */
1429 
1430 #ifdef SADB_X_CREDTYPE_NONE
1431   /*
1432    * Send received credentials to the kernel. We don't bother with
1433    * our credentials, since the process either knows them (if it specified
1434    * them with setsockopt()), or has no business looking at them (e.g.,
1435    * system wide certs).
1436    */
1437   if (isakmp_sa->recv_cert)
1438     {
1439       switch (isakmp_sa->recv_certtype)
1440 	{
1441 	case ISAKMP_CERTENC_NONE:
1442 	  /* Nothing to be done here. */
1443 	  break;
1444 
1445 #if defined (USE_KEYNOTE) && defined (SADB_X_EXT_REMOTE_CREDENTIALS)
1446 	case ISAKMP_CERTENC_KEYNOTE:
1447 	  len = strlen (isakmp_sa->recv_cert);
1448 	  cred = calloc (PF_KEY_V2_ROUND (len) + sizeof *cred,
1449 			 sizeof (u_int8_t));
1450 	  if (!cred)
1451 	    goto cleanup;
1452 
1453 	  cred->sadb_x_cred_len = ((sizeof *cred) / PF_KEY_V2_CHUNK) +
1454 	    PF_KEY_V2_ROUND (len) / PF_KEY_V2_CHUNK;
1455 	  cred->sadb_x_cred_exttype = SADB_X_EXT_REMOTE_CREDENTIALS;
1456 	  cred->sadb_x_cred_type = SADB_X_CREDTYPE_KEYNOTE;
1457 	  memcpy (cred + 1, isakmp_sa->recv_cert, len);
1458 
1459 	  if (pf_key_v2_msg_add (update, (struct sadb_ext *)cred,
1460 				 PF_KEY_V2_NODE_MALLOCED) == -1)
1461 	    goto cleanup;
1462 	  break;
1463 #endif /* USE_KEYNOTE */
1464 
1465 #if defined (USE_X509) && defined (SADB_X_EXT_REMOTE_CREDENTIALS)
1466 	case ISAKMP_CERTENC_X509_SIG:
1467 	  {
1468 	    u_int8_t *data;
1469 	    u_int32_t datalen;
1470 	    struct cert_handler *handler;
1471 
1472 	    /* We do it this way to avoid weird includes. */
1473 	    handler = cert_get (ISAKMP_CERTENC_X509_SIG);
1474 	    if (!handler)
1475 	      break;
1476 	    handler->cert_serialize (isakmp_sa->recv_cert, &data, &datalen);
1477 	    if (!data)
1478 	      break;
1479 
1480 	    len = datalen;
1481 	    cred = calloc (PF_KEY_V2_ROUND (len) + sizeof *cred,
1482 			   sizeof (u_int8_t));
1483 	    if (!cred)
1484 	      {
1485 		free (data);
1486 		goto cleanup;
1487 	      }
1488 
1489 	    cred->sadb_x_cred_len = ((sizeof *cred) / PF_KEY_V2_CHUNK) +
1490 	      PF_KEY_V2_ROUND (len) / PF_KEY_V2_CHUNK;
1491 	    cred->sadb_x_cred_exttype = SADB_X_EXT_REMOTE_CREDENTIALS;
1492 	    cred->sadb_x_cred_type = SADB_X_CREDTYPE_X509;
1493 	    memcpy (cred + 1, data, len);
1494 	    free (data);
1495 
1496 	    if (pf_key_v2_msg_add (update, (struct sadb_ext *)cred,
1497 				   PF_KEY_V2_NODE_MALLOCED) == -1)
1498 	      goto cleanup;
1499 	  }
1500 	  break;
1501 #endif /* USE_X509 */
1502 	}
1503     }
1504 #endif /* SADB_X_CREDTYPE_NONE */
1505 
1506 #ifdef SADB_X_AUTHTYPE_NONE
1507   /*
1508    * Tell the kernel what the peer used to authenticate, unless it was a
1509    * passphrase.
1510    */
1511   if (isakmp_sa->recv_key)
1512     {
1513       u_int8_t *data;
1514 
1515       /*
1516        * If it's a private key, we shouldn't pass it to the kernel for
1517        * processes to see; successful authentication of Phase 1 implies
1518        * that the process already knew the passphrase. On the other hand,
1519        * we don't want to reveal to processes any system-wide passphrases
1520        * used for authentication with remote systems. Same reason we don't
1521        * send up the key (private or passphrase) we used to authenticate
1522        * with the peer.
1523        */
1524       if (isakmp_sa->recv_keytype == ISAKMP_KEY_PASSPHRASE)
1525 	goto doneauth;
1526 
1527       key_serialize (isakmp_sa->recv_keytype, ISAKMP_KEYTYPE_PUBLIC,
1528 		     isakmp_sa->recv_key, &data, &len);
1529       if (!data)
1530 	goto cleanup;
1531 
1532       cred = calloc (PF_KEY_V2_ROUND (len) + sizeof *cred, sizeof (u_int8_t));
1533       if (!cred)
1534 	{
1535 	  free (data);
1536 	  goto cleanup;
1537 	}
1538 
1539       cred->sadb_x_cred_len = ((sizeof *cred) / PF_KEY_V2_CHUNK) +
1540 	PF_KEY_V2_ROUND (len) / PF_KEY_V2_CHUNK;
1541       cred->sadb_x_cred_exttype = SADB_X_EXT_REMOTE_AUTH;
1542       memcpy (cred + 1, data, len);
1543       free (data);
1544 
1545       switch (isakmp_sa->recv_keytype)
1546 	{
1547 	case ISAKMP_KEY_RSA:
1548 	  cred->sadb_x_cred_type = SADB_X_AUTHTYPE_RSA;
1549 	  break;
1550 
1551 	default:
1552 	  log_print ("pf_key_v2_set_spi: unknown received key type %d",
1553 		     isakmp_sa->recv_keytype);
1554 	  free (cred);
1555 	  goto cleanup;
1556 	}
1557 
1558       if (pf_key_v2_msg_add (update, (struct sadb_ext *)cred,
1559 			     PF_KEY_V2_NODE_MALLOCED) == -1)
1560 	goto cleanup;
1561     }
1562  doneauth:
1563 #endif /* SADB_X_AUTHTYPE_NONE */
1564 
1565 #ifdef SADB_X_EXT_FLOW_TYPE
1566   /* Setup the flow type extension.  */
1567   bzero (&flowtype, sizeof flowtype);
1568   flowtype.sadb_protocol_exttype = SADB_X_EXT_FLOW_TYPE;
1569   flowtype.sadb_protocol_len = sizeof flowtype / PF_KEY_V2_CHUNK;
1570   flowtype.sadb_protocol_direction
1571     = incoming ? IPSP_DIRECTION_IN : IPSP_DIRECTION_OUT;
1572 
1573   if (pf_key_v2_msg_add (update, (struct sadb_ext *)&flowtype, 0) == -1)
1574     goto cleanup;
1575 
1576   bzero (&tprotocol, sizeof tprotocol);
1577   tprotocol.sadb_protocol_exttype = SADB_X_EXT_PROTOCOL;
1578   tprotocol.sadb_protocol_len = sizeof tprotocol / PF_KEY_V2_CHUNK;
1579   tprotocol.sadb_protocol_proto = isa->tproto;
1580 
1581   if (pf_key_v2_msg_add (update, (struct sadb_ext *)&tprotocol, 0) == -1)
1582     goto cleanup;
1583 
1584   len = sizeof *addr + PF_KEY_V2_ROUND (sysdep_sa_len (isa->src_net));
1585   addr = calloc (1, len);
1586   if (!addr)
1587     goto cleanup;
1588   addr->sadb_address_exttype =
1589       incoming ? SADB_X_EXT_DST_FLOW : SADB_X_EXT_SRC_FLOW;
1590   addr->sadb_address_len = len / PF_KEY_V2_CHUNK;
1591   addr->sadb_address_reserved = 0;
1592   pf_key_v2_setup_sockaddr (addr + 1, isa->src_net, 0, isa->sport, 0);
1593   if (pf_key_v2_msg_add (update, (struct sadb_ext *)addr,
1594 			 PF_KEY_V2_NODE_MALLOCED) == -1)
1595     goto cleanup;
1596   addr = 0;
1597 
1598   addr = calloc (1, len);
1599   if (!addr)
1600     goto cleanup;
1601   addr->sadb_address_exttype =
1602       incoming ? SADB_X_EXT_DST_MASK : SADB_X_EXT_SRC_MASK;
1603   addr->sadb_address_len = len / PF_KEY_V2_CHUNK;
1604   addr->sadb_address_reserved = 0;
1605   pf_key_v2_setup_sockaddr (addr + 1, isa->src_mask, 0,
1606       isa->sport ? 0xffff : 0, 0);
1607   if (pf_key_v2_msg_add (update, (struct sadb_ext *)addr,
1608 			 PF_KEY_V2_NODE_MALLOCED) == -1)
1609     goto cleanup;
1610   addr = 0;
1611 
1612   addr = calloc (1, len);
1613   if (!addr)
1614     goto cleanup;
1615   addr->sadb_address_exttype =
1616       incoming ? SADB_X_EXT_SRC_FLOW : SADB_X_EXT_DST_FLOW;
1617   addr->sadb_address_len = len / PF_KEY_V2_CHUNK;
1618   addr->sadb_address_reserved = 0;
1619   pf_key_v2_setup_sockaddr (addr + 1, isa->dst_net, 0, isa->dport, 0);
1620   if (pf_key_v2_msg_add (update, (struct sadb_ext *)addr,
1621 			 PF_KEY_V2_NODE_MALLOCED) == -1)
1622     goto cleanup;
1623   addr = 0;
1624 
1625   addr = calloc (1, len);
1626   if (!addr)
1627     goto cleanup;
1628   addr->sadb_address_exttype =
1629       incoming ? SADB_X_EXT_SRC_MASK : SADB_X_EXT_DST_MASK;
1630   addr->sadb_address_len = len / PF_KEY_V2_CHUNK;
1631   addr->sadb_address_reserved = 0;
1632   pf_key_v2_setup_sockaddr (addr + 1, isa->dst_mask, 0,
1633       isa->dport ? 0xffff : 0, 0);
1634   if (pf_key_v2_msg_add (update, (struct sadb_ext *)addr,
1635 			 PF_KEY_V2_NODE_MALLOCED) == -1)
1636     goto cleanup;
1637   addr = 0;
1638 #endif /* SADB_X_EXT_FLOW_TYPE */
1639 
1640   /* XXX Here can sensitivity extensions be setup.  */
1641 
1642 #ifdef USE_DEBUG
1643   if (sockaddr2text (dst, &addr_str, 0))
1644     addr_str = 0;
1645 
1646   LOG_DBG ((LOG_SYSDEP, 10, "pf_key_v2_set_spi: satype %d dst %s SPI 0x%x",
1647 	    msg.sadb_msg_satype, addr_str ? addr_str : "unknown",
1648 	    ntohl (ssa.sadb_sa_spi)));
1649 
1650   if (addr_str)
1651     free (addr_str);
1652 #endif /* USE_DEBUG */
1653 
1654   /*
1655    * Although PF_KEY knows about expirations, it is unreliable per the specs
1656    * thus we need to do them inside isakmpd as well.
1657    */
1658   if (sa->seconds)
1659     if (sa_setup_expirations (sa))
1660       goto cleanup;
1661 
1662   ret = pf_key_v2_call (update);
1663   pf_key_v2_msg_free (update);
1664   update = 0;
1665   if (!ret)
1666     goto cleanup;
1667   err = ((struct sadb_msg *)TAILQ_FIRST (ret)->seg)->sadb_msg_errno;
1668   pf_key_v2_msg_free (ret);
1669   ret = 0;
1670 
1671   /*
1672    * If we are doing an addition into an SADB shared with our peer, errors
1673    * here are to be expected as the peer will already have created the SA,
1674    * and can thus be ignored.
1675    */
1676   if (err && !(msg.sadb_msg_type == SADB_ADD
1677 	       && conf_get_str ("General", "Shared-SADB")))
1678     {
1679       log_print ("pf_key_v2_set_spi: %s: %s",
1680 		 msg.sadb_msg_type == SADB_ADD ? "ADD" : "UPDATE",
1681 		 strerror (err));
1682       goto cleanup;
1683     }
1684 
1685   LOG_DBG ((LOG_SYSDEP, 50, "pf_key_v2_set_spi: done"));
1686 
1687   return 0;
1688 
1689  cleanup:
1690   if (sid)
1691     free (sid);
1692   if (addr)
1693     free (addr);
1694   if (life)
1695     free (life);
1696   if (key)
1697     free (key);
1698   if (update)
1699     pf_key_v2_msg_free (update);
1700   if (ret)
1701     pf_key_v2_msg_free (ret);
1702   return -1;
1703 }
1704 
1705 static __inline__ int
1706 pf_key_v2_mask_to_bits (u_int32_t mask)
1707 {
1708   u_int32_t hmask = ntohl (mask);
1709   return (33 - ffs (~hmask + 1)) % 33;
1710 }
1711 
1712 static int
1713 pf_key_v2_mask6_to_bits (u_int8_t *mask)
1714 {
1715   int n;
1716   bit_ffc (mask, 128, &n);
1717   return n == -1 ? 128 : n;
1718 }
1719 
1720 /*
1721  * Enable/disable a flow.
1722  * XXX Assumes OpenBSD {ADD,DEL}FLOW extensions.
1723  * Should probably be moved to sysdep.c
1724  */
1725 static int
1726 pf_key_v2_flow (struct sockaddr *laddr, struct sockaddr *lmask,
1727 		struct sockaddr *raddr,	struct sockaddr *rmask,
1728 		u_int8_t tproto, u_int16_t sport, u_int16_t dport,
1729 		u_int8_t *spi, u_int8_t proto, struct sockaddr *dst,
1730 		struct sockaddr *src, int delete, int ingress,
1731 		u_int8_t srcid_type, u_int8_t *srcid, int srcid_len,
1732 		u_int8_t dstid_type, u_int8_t *dstid, int dstid_len,
1733 		struct ipsec_proto *iproto)
1734 {
1735 #ifdef USE_DEBUG
1736   char *laddr_str, *lmask_str, *raddr_str, *rmask_str;
1737 #endif
1738 
1739 #if defined (SADB_X_ADDFLOW) && defined (SADB_X_DELFLOW)
1740   struct sadb_msg msg;
1741 #if defined (SADB_X_EXT_FLOW_TYPE)
1742   struct sadb_protocol flowtype;
1743   struct sadb_ident *sid = 0;
1744 #else
1745   struct sadb_sa ssa;
1746 #endif
1747   struct sadb_address *addr = 0;
1748   struct sadb_protocol tprotocol;
1749   struct pf_key_v2_msg *flow = 0, *ret = 0;
1750   size_t len;
1751   int err;
1752 
1753 #if !defined (SADB_X_SAFLAGS_INGRESS_FLOW) && !defined (SADB_X_EXT_FLOW_TYPE)
1754   if (ingress)
1755     return 0;
1756 #endif
1757 
1758   msg.sadb_msg_type = delete ? SADB_X_DELFLOW : SADB_X_ADDFLOW;
1759   switch (proto)
1760     {
1761     case IPSEC_PROTO_IPSEC_ESP:
1762       msg.sadb_msg_satype = SADB_SATYPE_ESP;
1763       break;
1764     case IPSEC_PROTO_IPSEC_AH:
1765       msg.sadb_msg_satype = SADB_SATYPE_AH;
1766       break;
1767     case IPSEC_PROTO_IPCOMP:
1768       msg.sadb_msg_satype = SADB_X_SATYPE_IPCOMP;
1769       break;
1770     default:
1771       log_print ("pf_key_v2_flow: invalid proto %d", proto);
1772       goto cleanup;
1773     }
1774   msg.sadb_msg_seq = 0;
1775   flow = pf_key_v2_msg_new (&msg, 0);
1776   if (!flow)
1777     goto cleanup;
1778 
1779 #if defined (SADB_X_EXT_FLOW_TYPE)
1780   if (!delete)
1781     {
1782       /* Setup the source ID, if provided. */
1783       if (srcid)
1784         {
1785 	  sid = calloc (PF_KEY_V2_ROUND (srcid_len + 1) + sizeof *sid,
1786 			sizeof (u_int8_t));
1787 	  if (!sid)
1788 	    goto cleanup;
1789 
1790 	  sid->sadb_ident_len = ((sizeof *sid) / PF_KEY_V2_CHUNK)
1791 	    + PF_KEY_V2_ROUND (srcid_len + 1) / PF_KEY_V2_CHUNK;
1792 	  sid->sadb_ident_exttype = SADB_EXT_IDENTITY_SRC;
1793 	  sid->sadb_ident_type = srcid_type;
1794 
1795 	  memcpy (sid + 1, srcid, srcid_len);
1796 
1797 	  if (pf_key_v2_msg_add (flow, (struct sadb_ext *)sid,
1798 				 PF_KEY_V2_NODE_MALLOCED) == -1)
1799 	    goto cleanup;
1800 
1801 	  sid = 0;
1802 	}
1803 
1804       /* Setup the destination ID, if provided. */
1805       if (dstid)
1806         {
1807 	  sid = calloc (PF_KEY_V2_ROUND (dstid_len + 1) + sizeof *sid,
1808 			sizeof (u_int8_t));
1809 	  if (!sid)
1810 	    goto cleanup;
1811 
1812 	  sid->sadb_ident_len = ((sizeof *sid) / PF_KEY_V2_CHUNK)
1813 	    + PF_KEY_V2_ROUND (dstid_len + 1) / PF_KEY_V2_CHUNK;
1814 	  sid->sadb_ident_exttype = SADB_EXT_IDENTITY_DST;
1815 	  sid->sadb_ident_type = dstid_type;
1816 
1817 	  memcpy (sid + 1, dstid, dstid_len);
1818 
1819 	  if (pf_key_v2_msg_add (flow, (struct sadb_ext *)sid,
1820 				 PF_KEY_V2_NODE_MALLOCED) == -1)
1821 	    goto cleanup;
1822 
1823 	  sid = 0;
1824 	}
1825     }
1826 
1827   /* Setup the flow type extension.  */
1828   bzero (&flowtype, sizeof flowtype);
1829   flowtype.sadb_protocol_exttype = SADB_X_EXT_FLOW_TYPE;
1830   flowtype.sadb_protocol_len = sizeof flowtype / PF_KEY_V2_CHUNK;
1831   flowtype.sadb_protocol_direction
1832     = ingress ? IPSP_DIRECTION_IN : IPSP_DIRECTION_OUT;
1833   flowtype.sadb_protocol_proto
1834     = ingress ? SADB_X_FLOW_TYPE_USE : SADB_X_FLOW_TYPE_REQUIRE;
1835 
1836   if (pf_key_v2_msg_add (flow, (struct sadb_ext *)&flowtype, 0) == -1)
1837     goto cleanup;
1838 #else /* SADB_X_EXT_FLOW_TYPE */
1839   /* Setup the SA extension.  */
1840   ssa.sadb_sa_exttype = SADB_EXT_SA;
1841   ssa.sadb_sa_len = sizeof ssa / PF_KEY_V2_CHUNK;
1842   memcpy (&ssa.sadb_sa_spi, spi, sizeof ssa.sadb_sa_spi);
1843   ssa.sadb_sa_replay = 0;
1844   ssa.sadb_sa_state = 0;
1845   ssa.sadb_sa_auth = 0;
1846   ssa.sadb_sa_encrypt = 0;
1847   ssa.sadb_sa_flags = 0;
1848 #if defined (SADB_X_SAFLAGS_INGRESS_FLOW)
1849   if (ingress)
1850     ssa.sadb_sa_flags |= SADB_X_SAFLAGS_INGRESS_FLOW;
1851 #endif
1852 #if defined (SADB_X_SAFLAGS_REPLACEFLOW)
1853   if (!delete && !ingress)
1854     ssa.sadb_sa_flags |= SADB_X_SAFLAGS_REPLACEFLOW;
1855 #endif
1856 
1857   if (pf_key_v2_msg_add (flow, (struct sadb_ext *)&ssa, 0) == -1)
1858     goto cleanup;
1859 #endif /* SADB_X_EXT_FLOW_TYPE */
1860 
1861   /*
1862    * Setup the ADDRESS extensions.
1863    */
1864   len = sizeof *addr + PF_KEY_V2_ROUND (sysdep_sa_len (src));
1865 #if !defined (SADB_X_EXT_FLOW_TYPE)
1866   if (!delete || ingress)
1867 #else
1868   if (!delete)
1869 #endif /* SADB_X_EXT_FLOW_TYPE */
1870     {
1871       addr = calloc (1, len);
1872       if (!addr)
1873 	goto cleanup;
1874       addr->sadb_address_exttype = SADB_EXT_ADDRESS_DST;
1875       addr->sadb_address_len = len / PF_KEY_V2_CHUNK;
1876       addr->sadb_address_reserved = 0;
1877 #if defined (SADB_X_EXT_FLOW_TYPE)
1878       pf_key_v2_setup_sockaddr (addr + 1, src, dst, 0, ingress);
1879 #else
1880       pf_key_v2_setup_sockaddr (addr + 1, dst, 0, 0, 0);
1881 #endif
1882       if (pf_key_v2_msg_add (flow, (struct sadb_ext *)addr,
1883 			     PF_KEY_V2_NODE_MALLOCED) == -1)
1884 	goto cleanup;
1885       addr = 0;
1886     }
1887 
1888   len = sizeof *addr + PF_KEY_V2_ROUND (sysdep_sa_len (laddr));
1889   addr = calloc (1, len);
1890   if (!addr)
1891     goto cleanup;
1892   addr->sadb_address_exttype = SADB_X_EXT_SRC_FLOW;
1893   addr->sadb_address_len = len / PF_KEY_V2_CHUNK;
1894   addr->sadb_address_reserved = 0;
1895   pf_key_v2_setup_sockaddr (addr + 1, laddr, 0, sport, 0);
1896   if (pf_key_v2_msg_add (flow, (struct sadb_ext *)addr,
1897 			 PF_KEY_V2_NODE_MALLOCED) == -1)
1898     goto cleanup;
1899   addr = 0;
1900 
1901   addr = calloc (1, len);
1902   if (!addr)
1903     goto cleanup;
1904   addr->sadb_address_exttype = SADB_X_EXT_SRC_MASK;
1905   addr->sadb_address_len = len / PF_KEY_V2_CHUNK;
1906   addr->sadb_address_reserved = 0;
1907   pf_key_v2_setup_sockaddr (addr + 1, lmask, 0, sport ? 0xffff : 0, 0);
1908   if (pf_key_v2_msg_add (flow, (struct sadb_ext *)addr,
1909 			 PF_KEY_V2_NODE_MALLOCED) == -1)
1910     goto cleanup;
1911   addr = 0;
1912 
1913   addr = calloc (1, len);
1914   if (!addr)
1915     goto cleanup;
1916   addr->sadb_address_exttype = SADB_X_EXT_DST_FLOW;
1917   addr->sadb_address_len = len / PF_KEY_V2_CHUNK;
1918   addr->sadb_address_reserved = 0;
1919   pf_key_v2_setup_sockaddr (addr + 1, raddr, 0, dport, 0);
1920   if (pf_key_v2_msg_add (flow, (struct sadb_ext *)addr,
1921 			 PF_KEY_V2_NODE_MALLOCED) == -1)
1922     goto cleanup;
1923   addr = 0;
1924 
1925   addr = calloc (1, len);
1926   if (!addr)
1927     goto cleanup;
1928   addr->sadb_address_exttype = SADB_X_EXT_DST_MASK;
1929   addr->sadb_address_len = len / PF_KEY_V2_CHUNK;
1930   addr->sadb_address_reserved = 0;
1931   pf_key_v2_setup_sockaddr (addr + 1, rmask, 0, dport ? 0xffff : 0, 0);
1932   if (pf_key_v2_msg_add (flow, (struct sadb_ext *)addr,
1933 			 PF_KEY_V2_NODE_MALLOCED) == -1)
1934     goto cleanup;
1935   addr = 0;
1936 
1937   /* Setup the protocol extension.  */
1938   bzero (&tprotocol, sizeof tprotocol);
1939   tprotocol.sadb_protocol_exttype = SADB_X_EXT_PROTOCOL;
1940   tprotocol.sadb_protocol_len = sizeof tprotocol / PF_KEY_V2_CHUNK;
1941   tprotocol.sadb_protocol_proto = tproto;
1942 
1943   if (pf_key_v2_msg_add (flow, (struct sadb_ext *)&tprotocol, 0) == -1)
1944     goto cleanup;
1945 
1946 #ifdef USE_DEBUG
1947   if (sockaddr2text (laddr, &laddr_str, 0))
1948     laddr_str = 0;
1949   if (sockaddr2text (lmask, &lmask_str, 0))
1950     lmask_str = 0;
1951   if (sockaddr2text (raddr, &raddr_str, 0))
1952     raddr_str = 0;
1953   if (sockaddr2text (rmask, &rmask_str, 0))
1954     rmask_str = 0;
1955 
1956   LOG_DBG ((LOG_SYSDEP, 50,
1957 	    "pf_key_v2_flow: src %s %s dst %s %s proto %u sport %u dport %u",
1958 	    laddr_str ? laddr_str : "<??\?>", lmask_str ? lmask_str : "<??\?>",
1959 	    raddr_str ? raddr_str : "<??\?>", rmask_str ? rmask_str : "<??\?>",
1960 	    tproto, ntohs (sport), ntohs (dport)));
1961 
1962   if (laddr_str)
1963     free (laddr_str);
1964   if (lmask_str)
1965     free (lmask_str);
1966   if (raddr_str)
1967     free (raddr_str);
1968   if (rmask_str)
1969     free (rmask_str);
1970 #endif /* USE_DEBUG */
1971 
1972   ret = pf_key_v2_call (flow);
1973   pf_key_v2_msg_free (flow);
1974   flow = 0;
1975   if (!ret)
1976     goto cleanup;
1977   err = ((struct sadb_msg *)TAILQ_FIRST (ret)->seg)->sadb_msg_errno;
1978   if (err)
1979     {
1980       if (err == ESRCH) /* These are common and usually harmless.  */
1981 	LOG_DBG ((LOG_SYSDEP, 10, "pf_key_v2_flow: %sFLOW: %s",
1982 		  delete ? "DEL" : "ADD", strerror (err)));
1983       else
1984 	log_print ("pf_key_v2_flow: %sFLOW: %s", delete ? "DEL" : "ADD",
1985 		   strerror (err));
1986       goto cleanup;
1987     }
1988   pf_key_v2_msg_free (ret);
1989 
1990   LOG_DBG ((LOG_MISC, 50, "pf_key_v2_flow: %sFLOW: done",
1991 	    delete ? "DEL" : "ADD"));
1992 
1993   return 0;
1994 
1995  cleanup:
1996 #if defined (SADB_X_EXT_FLOW_TYPE)
1997   if (sid)
1998     free (sid);
1999 #endif /* SADB_X_EXT_FLOW_TYPE */
2000   if (addr)
2001     free (addr);
2002   if (flow)
2003     pf_key_v2_msg_free (flow);
2004   if (ret)
2005     pf_key_v2_msg_free (ret);
2006   return -1;
2007 
2008 #elif defined (SADB_X_SPDADD) && defined (SADB_X_SPDDELETE)
2009   struct sadb_msg msg;
2010   struct sadb_x_policy *policy = 0;
2011   struct sadb_x_ipsecrequest *ipsecrequest;
2012   struct sadb_x_sa2 ssa2;
2013   struct sadb_address *addr = 0;
2014   struct sockaddr *saddr;
2015   struct pf_key_v2_msg *flow = 0, *ret = 0;
2016   u_int8_t *policy_buf;
2017   size_t len;
2018   int err;
2019   struct sockaddr_in *ip4_sa;
2020   struct sockaddr_in6 *ip6_sa;
2021 
2022   msg.sadb_msg_type = delete ? SADB_X_SPDDELETE : SADB_X_SPDADD;
2023   msg.sadb_msg_satype = SADB_SATYPE_UNSPEC;
2024   msg.sadb_msg_seq = 0;
2025   flow = pf_key_v2_msg_new (&msg, 0);
2026   if (!flow)
2027     goto cleanup;
2028 
2029   memset (&ssa2, 0, sizeof ssa2);
2030   ssa2.sadb_x_sa2_exttype = SADB_X_EXT_SA2;
2031   ssa2.sadb_x_sa2_len = sizeof ssa2 / PF_KEY_V2_CHUNK;
2032   ssa2.sadb_x_sa2_mode = 0;
2033   if (pf_key_v2_msg_add (flow, (struct sadb_ext *)&ssa2, 0) == -1)
2034     goto cleanup;
2035 
2036   /*
2037    * Setup the ADDRESS extensions.
2038    */
2039   len = sizeof *addr + PF_KEY_V2_ROUND (sysdep_sa_len (src));
2040   addr = calloc (1, len);
2041   if (!addr)
2042     goto cleanup;
2043   addr->sadb_address_exttype = SADB_EXT_ADDRESS_SRC;
2044   addr->sadb_address_len = len / PF_KEY_V2_CHUNK;
2045 #ifdef LINUX_IPSEC
2046   addr->sadb_address_proto = tproto;
2047 #else
2048   addr->sadb_address_proto = IPSEC_ULPROTO_ANY;
2049 #endif
2050   addr->sadb_address_reserved = 0;
2051 #ifdef LINUX_IPSEC
2052   pf_key_v2_setup_sockaddr (addr + 1, laddr, 0, sport, 0);
2053 #else
2054   pf_key_v2_setup_sockaddr (addr + 1, laddr, 0, IPSEC_PORT_ANY, 0);
2055 #endif
2056   switch (laddr->sa_family)
2057     {
2058     case AF_INET:
2059       ip4_sa = (struct sockaddr_in *)lmask;
2060       addr->sadb_address_prefixlen
2061 	= pf_key_v2_mask_to_bits (ip4_sa->sin_addr.s_addr);
2062       break;
2063     case AF_INET6:
2064       ip6_sa = (struct sockaddr_in6 *)lmask;
2065       addr->sadb_address_prefixlen
2066 	= pf_key_v2_mask6_to_bits (&ip6_sa->sin6_addr.s6_addr[0]);
2067       break;
2068     }
2069   if (pf_key_v2_msg_add (flow, (struct sadb_ext *)addr,
2070 			 PF_KEY_V2_NODE_MALLOCED) == -1)
2071     goto cleanup;
2072   addr = 0;
2073 
2074   len = sizeof *addr + PF_KEY_V2_ROUND (sysdep_sa_len (raddr));
2075   addr = calloc (1, len);
2076   if (!addr)
2077     goto cleanup;
2078   addr->sadb_address_exttype = SADB_EXT_ADDRESS_DST;
2079   addr->sadb_address_len = len / PF_KEY_V2_CHUNK;
2080 #ifdef LINUX_IPSEC
2081   addr->sadb_address_proto = tproto;
2082 #else
2083   addr->sadb_address_proto = IPSEC_ULPROTO_ANY;
2084 #endif
2085   addr->sadb_address_reserved = 0;
2086 #ifdef LINUX_IPSEC
2087   pf_key_v2_setup_sockaddr (addr + 1, raddr, 0, dport, 0);
2088 #else
2089   pf_key_v2_setup_sockaddr (addr + 1, raddr, 0, IPSEC_PORT_ANY, 0);
2090 #endif
2091   switch (raddr->sa_family)
2092     {
2093     case AF_INET:
2094       ip4_sa = (struct sockaddr_in *)rmask;
2095       addr->sadb_address_prefixlen
2096 	= pf_key_v2_mask_to_bits (ip4_sa->sin_addr.s_addr);
2097       break;
2098     case AF_INET6:
2099       ip6_sa = (struct sockaddr_in6 *)rmask;
2100       addr->sadb_address_prefixlen
2101 	= pf_key_v2_mask6_to_bits (&ip6_sa->sin6_addr.s6_addr[0]);
2102       break;
2103     }
2104   if (pf_key_v2_msg_add (flow, (struct sadb_ext *)addr,
2105 			 PF_KEY_V2_NODE_MALLOCED) == -1)
2106     goto cleanup;
2107   addr = 0;
2108 
2109   /* Setup the POLICY extension.  */
2110   len = sizeof *policy + sizeof *ipsecrequest +
2111     2 * PF_KEY_V2_ROUND (sysdep_sa_len (src));
2112   policy_buf = (u_int8_t *)calloc (1, len);
2113   if (!policy_buf)
2114     {
2115       log_error ("pf_key_v2_flow: calloc %lu failed", (unsigned long)len);
2116       goto cleanup;
2117     }
2118 
2119   policy = (struct sadb_x_policy *)policy_buf;
2120   policy->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
2121   policy->sadb_x_policy_len = len / PF_KEY_V2_CHUNK;
2122   policy->sadb_x_policy_type = IPSEC_POLICY_IPSEC;
2123   if (ingress)
2124 	policy->sadb_x_policy_dir = IPSEC_DIR_INBOUND;
2125   else
2126 	policy->sadb_x_policy_dir = IPSEC_DIR_OUTBOUND;
2127   policy->sadb_x_policy_reserved = 0;
2128 
2129   /* Setup the IPSECREQUEST extension part.  */
2130   ipsecrequest = (struct sadb_x_ipsecrequest *)(policy + 1);
2131   ipsecrequest->sadb_x_ipsecrequest_len = len - sizeof *policy;
2132   switch (proto)
2133     {
2134     case IPSEC_PROTO_IPSEC_ESP:
2135       ipsecrequest->sadb_x_ipsecrequest_proto = IPPROTO_ESP;
2136       break;
2137     case IPSEC_PROTO_IPSEC_AH:
2138       ipsecrequest->sadb_x_ipsecrequest_proto = IPPROTO_AH;
2139       break;
2140     default:
2141       log_print ("pf_key_v2_flow: invalid proto %d", proto);
2142       goto cleanup;
2143   }
2144 #if defined (LINUX_IPSEC)
2145   if (iproto->encap_mode == IPSEC_ENCAP_TUNNEL)
2146     ipsecrequest->sadb_x_ipsecrequest_mode = IPSEC_MODE_TUNNEL;
2147   else
2148     ipsecrequest->sadb_x_ipsecrequest_mode = IPSEC_MODE_TRANSPORT;
2149 #else
2150   ipsecrequest->sadb_x_ipsecrequest_mode = IPSEC_MODE_TUNNEL;	/* XXX */
2151 #endif
2152   ipsecrequest->sadb_x_ipsecrequest_level
2153     = ingress ? IPSEC_LEVEL_USE : IPSEC_LEVEL_REQUIRE;
2154   ipsecrequest->sadb_x_ipsecrequest_reqid = 0;	/* XXX */
2155 
2156   /* Add source and destination addresses. */
2157   saddr = (struct sockaddr *)(ipsecrequest + 1);
2158   pf_key_v2_setup_sockaddr (saddr, src, 0, 0, 0);
2159   switch (src->sa_family)
2160     {
2161     case AF_INET:
2162       saddr = (struct sockaddr *)((struct sockaddr_in *)saddr + 1);
2163       break;
2164     case AF_INET6:
2165       saddr = (struct sockaddr *)((struct sockaddr_in6 *)saddr + 1);
2166       break;
2167     }
2168   pf_key_v2_setup_sockaddr (saddr, dst, 0, 0, 0);
2169   if (pf_key_v2_msg_add (flow, (struct sadb_ext *)policy, 0) == -1)
2170     goto cleanup;
2171 
2172 #ifdef USE_DEBUG
2173   if (sockaddr2text (laddr, &laddr_str, 0))
2174     laddr_str = 0;
2175   if (sockaddr2text (lmask, &lmask_str, 0))
2176     lmask_str = 0;
2177   if (sockaddr2text (raddr, &raddr_str, 0))
2178     raddr_str = 0;
2179   if (sockaddr2text (rmask, &rmask_str, 0))
2180     rmask_str = 0;
2181 
2182   LOG_DBG ((LOG_SYSDEP, 50, "pf_key_v2_flow: src %s %s dst %s %s",
2183 	    laddr_str ? laddr_str : "<??\?>", lmask_str ? lmask_str : "<??\?>",
2184 	    raddr_str ? raddr_str : "<??\?>",
2185 	    rmask_str ? rmask_str : "<??\?>"));
2186 
2187   if (laddr_str)
2188     free (laddr_str);
2189   if (lmask_str)
2190     free (lmask_str);
2191   if (raddr_str)
2192     free (raddr_str);
2193   if (rmask_str)
2194     free (rmask_str);
2195 #endif
2196 
2197   ret = pf_key_v2_call (flow);
2198   pf_key_v2_msg_free (flow);
2199   flow = 0;
2200   if (!ret)
2201     goto cleanup;
2202   err = ((struct sadb_msg *)TAILQ_FIRST (ret)->seg)->sadb_msg_errno;
2203   if (!delete && err == EEXIST)
2204     {
2205       LOG_DBG ((LOG_SYSDEP, 50, "pf_key_v2_flow: SPDADD returns EEXIST"));
2206     }
2207   else if (err)
2208     {
2209       log_print ("pf_key_v2_flow: SPD%s: %s", delete ? "DELETE" : "ADD",
2210 		 strerror (err));
2211       goto cleanup;
2212     }
2213   pf_key_v2_msg_free (ret);
2214 
2215   LOG_DBG ((LOG_SYSDEP, 50, "pf_key_v2_flow: SPD%s: done",
2216 	    delete ? "DELETE" : "ADD"));
2217 
2218   return 0;
2219 
2220  cleanup:
2221   if (addr)
2222     free (addr);
2223   if (policy)
2224     free (policy);
2225   if (flow)
2226     pf_key_v2_msg_free (flow);
2227   if (ret)
2228     pf_key_v2_msg_free (ret);
2229   return -1;
2230 
2231 #else
2232   log_print ("pf_key_v2_flow: not supported in pure PF_KEYv2");
2233   return -1;
2234 #endif
2235 }
2236 
2237 #ifndef KAME
2238 static u_int8_t *
2239 pf_key_v2_convert_id (u_int8_t *id, int idlen, size_t *reslen, int *idtype)
2240 {
2241   u_int8_t *addr, *res = 0;
2242   char addrbuf[ADDRESS_MAX + 5];
2243 
2244   switch (id[0])
2245     {
2246     case IPSEC_ID_FQDN:
2247       res = calloc (idlen - ISAKMP_ID_DATA_OFF + ISAKMP_GEN_SZ,
2248 		    sizeof (u_int8_t));
2249       if (!res)
2250 	return 0;
2251 
2252       *reslen = idlen - ISAKMP_ID_DATA_OFF + ISAKMP_GEN_SZ;
2253       memcpy (res, id + ISAKMP_ID_DATA_OFF - ISAKMP_GEN_SZ, *reslen);
2254       *idtype = SADB_IDENTTYPE_FQDN;
2255       LOG_DBG ((LOG_SYSDEP, 40, "pf_key_v2_convert_id: FQDN %.*s",
2256 		   (int)*reslen, res));
2257       return res;
2258 
2259     case IPSEC_ID_USER_FQDN:
2260       res = calloc (idlen - ISAKMP_ID_DATA_OFF + ISAKMP_GEN_SZ,
2261 		    sizeof (u_int8_t));
2262       if (!res)
2263 	return 0;
2264 
2265       *reslen = idlen - ISAKMP_ID_DATA_OFF + ISAKMP_GEN_SZ;
2266       memcpy (res, id + ISAKMP_ID_DATA_OFF - ISAKMP_GEN_SZ, *reslen);
2267       *idtype = SADB_IDENTTYPE_USERFQDN;
2268       LOG_DBG ((LOG_SYSDEP, 40, "pf_key_v2_convert_id: UFQDN %.*s",
2269 		   (int)*reslen, res));
2270       return res;
2271 
2272     case IPSEC_ID_IPV4_ADDR: /* XXX CONNECTION ? */
2273       if (inet_ntop (AF_INET, id + ISAKMP_ID_DATA_OFF - ISAKMP_GEN_SZ,
2274 		     addrbuf, ADDRESS_MAX) == NULL)
2275 	return 0;
2276       *reslen = strlen (addrbuf) + 3;
2277       strlcat (addrbuf, "/32", ADDRESS_MAX + 5);
2278       res = (u_int8_t *)strdup (addrbuf);
2279       if (!res)
2280 	return 0;
2281       *idtype = SADB_IDENTTYPE_PREFIX;
2282       LOG_DBG ((LOG_SYSDEP, 40, "pf_key_v2_convert_id: IPv4 address %s", res));
2283       return res;
2284 
2285     case IPSEC_ID_IPV6_ADDR: /* XXX CONNECTION ? */
2286       if (inet_ntop (AF_INET6, id + ISAKMP_ID_DATA_OFF - ISAKMP_GEN_SZ,
2287 		     addrbuf, ADDRESS_MAX) == NULL)
2288 	return 0;
2289       *reslen = strlen (addrbuf) + 4;
2290       strlcat (addrbuf, "/128", ADDRESS_MAX + 5);
2291       res = (u_int8_t *)strdup (addrbuf);
2292       if (!res)
2293 	return 0;
2294       LOG_DBG ((LOG_SYSDEP, 40, "pf_key_v2_convert_id: IPv6 address %s", res));
2295       *idtype = SADB_IDENTTYPE_PREFIX;
2296       return res;
2297 
2298     case IPSEC_ID_IPV4_ADDR_SUBNET: /* XXX PREFIX */
2299       addr = id + ISAKMP_ID_DATA_OFF - ISAKMP_GEN_SZ;
2300       if (inet_ntop (AF_INET, addr, addrbuf, ADDRESS_MAX) == NULL)
2301 	return 0;
2302       snprintf (addrbuf + strlen (addrbuf), ADDRESS_MAX - strlen (addrbuf),
2303 		"/%d", pf_key_v2_mask_to_bits ((u_int32_t)
2304 					       *(addr +
2305 						 sizeof (struct in_addr))));
2306       *reslen = strlen (addrbuf);
2307       res = (u_int8_t *)strdup (addrbuf);
2308       if (!res)
2309 	return 0;
2310       *idtype = SADB_IDENTTYPE_PREFIX;
2311       LOG_DBG ((LOG_SYSDEP, 40, "pf_key_v2_convert_id: IPv4 subnet %s", res));
2312       return res;
2313 
2314     case IPSEC_ID_IPV6_ADDR_SUBNET: /* XXX PREFIX */
2315       addr = id + ISAKMP_ID_DATA_OFF - ISAKMP_GEN_SZ;
2316       if (inet_ntop (AF_INET6, addr, addrbuf, ADDRESS_MAX) == NULL)
2317 	return 0;
2318       snprintf (addrbuf + strlen (addrbuf), ADDRESS_MAX - strlen (addrbuf),
2319 		"/%d", pf_key_v2_mask6_to_bits (addr +
2320 						sizeof (struct in6_addr)));
2321       *reslen = strlen (addrbuf);
2322       res = (u_int8_t *)strdup (addrbuf);
2323       if (!res)
2324 	return 0;
2325       LOG_DBG ((LOG_SYSDEP, 40, "pf_key_v2_convert_id: IPv6 subnet %s", res));
2326       *idtype = SADB_IDENTTYPE_PREFIX;
2327       return res;
2328 
2329     case IPSEC_ID_IPV4_RANGE:
2330     case IPSEC_ID_IPV6_RANGE:
2331     case IPSEC_ID_DER_ASN1_DN:
2332     case IPSEC_ID_DER_ASN1_GN:
2333     case IPSEC_ID_KEY_ID:
2334       /* XXX Not implemented yet.  */
2335       return 0;
2336     }
2337 
2338   return 0;
2339 }
2340 #endif
2341 
2342 /* Enable a flow given an SA.  */
2343 int
2344 pf_key_v2_enable_sa (struct sa *sa, struct sa *isakmp_sa)
2345 {
2346   struct ipsec_sa *isa = sa->data;
2347   struct sockaddr *dst, *src;
2348   int error;
2349   struct proto *proto = TAILQ_FIRST (&sa->protos);
2350   int sidtype = 0, didtype = 0;
2351   size_t sidlen = 0, didlen = 0;
2352   u_int8_t *sid = 0, *did = 0;
2353 #if !defined (SADB_X_EXT_FLOW_TYPE)
2354   struct sockaddr_storage hostmask_storage;
2355   struct sockaddr *hostmask = (struct sockaddr *)&hostmask_storage;
2356 #endif /* SADB_X_EXT_FLOW_TYPE */
2357 
2358   sa->transport->vtbl->get_dst (sa->transport, &dst);
2359   sa->transport->vtbl->get_src (sa->transport, &src);
2360 
2361 #if defined (SADB_X_EXT_FLOW_TYPE)
2362   if (isakmp_sa->id_i)
2363     {
2364       if (isakmp_sa->initiator)
2365 	sid = pf_key_v2_convert_id (isakmp_sa->id_i, isakmp_sa->id_i_len,
2366 				    &sidlen, &sidtype);
2367       else
2368 	did = pf_key_v2_convert_id (isakmp_sa->id_i, isakmp_sa->id_i_len,
2369 				    &didlen, &didtype);
2370     }
2371 
2372   if (isakmp_sa->id_r)
2373     {
2374       if (isakmp_sa->initiator)
2375 	did = pf_key_v2_convert_id (isakmp_sa->id_r, isakmp_sa->id_r_len,
2376 				    &didlen, &didtype);
2377       else
2378 	sid = pf_key_v2_convert_id (isakmp_sa->id_r, isakmp_sa->id_r_len,
2379 				    &sidlen, &sidtype);
2380     }
2381 #endif /* SADB_X_EXT_FLOW_TYPE */
2382 
2383   error = pf_key_v2_flow (isa->src_net, isa->src_mask, isa->dst_net,
2384 			  isa->dst_mask, isa->tproto, isa->sport, isa->dport,
2385 			  proto->spi[0], proto->proto, dst, src, 0, 0,
2386 			  sidtype, sid, sidlen, didtype, did, didlen,
2387 			  proto->data);
2388   if (error)
2389     goto cleanup;
2390 
2391 #if !defined (SADB_X_EXT_FLOW_TYPE)
2392   /* Set hostmask to '-1'. */
2393   switch (dst->sa_family)
2394     {
2395     case AF_INET:
2396       ((struct sockaddr_in *)hostmask)->sin_family = AF_INET;
2397 #ifndef USE_OLD_SOCKADDR
2398       ((struct sockaddr_in *)hostmask)->sin_len = sizeof (struct in_addr);
2399 #endif
2400       memset (&((struct sockaddr_in *)hostmask)->sin_addr.s_addr, 0xff,
2401 	      sizeof (struct in_addr));
2402       break;
2403     case AF_INET6:
2404       ((struct sockaddr_in6 *)hostmask)->sin6_family = AF_INET6;
2405 #ifndef USE_OLD_SOCKADDR
2406       ((struct sockaddr_in6 *)hostmask)->sin6_len = sizeof (struct in6_addr);
2407 #endif
2408       memset (&((struct sockaddr_in6 *)hostmask)->sin6_addr.s6_addr, 0xff,
2409 	      sizeof (struct in6_addr));
2410       break;
2411     }
2412 
2413   /* Ingress flows, handling SA bundles. */
2414   while (TAILQ_NEXT (proto, link))
2415     {
2416       error = pf_key_v2_flow (dst, hostmask, src, hostmask, 0, 0, 0,
2417 			      proto->spi[1], proto->proto, src, dst,
2418 			      0, 1, 0, 0, 0, 0, 0, 0, proto->data);
2419       if (error)
2420 	goto cleanup;
2421       proto = TAILQ_NEXT (proto, link);
2422     }
2423 #endif /* SADB_X_EXT_FLOW_TYPE */
2424 
2425   error = pf_key_v2_flow (isa->dst_net, isa->dst_mask, isa->src_net,
2426 			  isa->src_mask, isa->tproto, isa->dport, isa->sport,
2427 			  proto->spi[1], proto->proto, src, dst, 0, 1,
2428 			  sidtype, sid, sidlen, didtype, did, didlen,
2429 			  proto->data);
2430 
2431  cleanup:
2432 #if defined (SADB_X_EXT_FLOW_TYPE)
2433   if (sid)
2434     free (sid);
2435   if (did)
2436     free (did);
2437 #endif /* SADB_X_EXT_FLOW_TYPE */
2438 
2439   return error;
2440 }
2441 
2442 #if defined (SADB_X_ASKPOLICY)
2443 /* Increase reference count of refcounted sections. */
2444 static int
2445 pf_key_v2_conf_refinc (int af, char *section)
2446 {
2447   char conn[22];
2448   int num;
2449 
2450   if (!section)
2451     return 0;
2452 
2453   num = conf_get_num (section, "Refcount", 0);
2454   if (num == 0)
2455     return 0;
2456 
2457   snprintf (conn, sizeof conn, "%d", num + 1);
2458   conf_set (af, section, "Refcount", conn, 1, 0);
2459   return 0;
2460 }
2461 #endif
2462 
2463 /*
2464  * Return 0 if the section didn't exist or was removed, non-zero otherwise.
2465  * Don't touch non-refcounted (statically defined) sections.
2466  */
2467 static int
2468 pf_key_v2_conf_refhandle (int af, char *section)
2469 {
2470   char conn[22];
2471   int num;
2472 
2473   if (!section)
2474     return 0;
2475 
2476   num = conf_get_num (section, "Refcount", 0);
2477   if (num == 1)
2478     {
2479       conf_remove_section (af, section);
2480       num--;
2481     }
2482   else
2483     if (num != 0)
2484       {
2485 	snprintf (conn, sizeof conn, "%d", num - 1);
2486 	conf_set (af, section, "Refcount", conn, 1, 0);
2487       }
2488 
2489   return num;
2490 }
2491 
2492 /* Remove all dynamically-established configuration entries.  */
2493 static int
2494 pf_key_v2_remove_conf (char *section)
2495 {
2496   char *ikepeer, *localid, *remoteid, *configname;
2497   struct conf_list_node *attr;
2498   struct conf_list *attrs;
2499   int af;
2500 
2501   if (!section)
2502     return 0;
2503 
2504   if (!conf_get_str (section, "Phase"))
2505     return 0;
2506 
2507   /* Only remove dynamically-established entries. */
2508   attrs = conf_get_list (section, "Flags");
2509   if (attrs)
2510     {
2511       for (attr = TAILQ_FIRST (&attrs->fields); attr;
2512 	   attr = TAILQ_NEXT (attr, link))
2513 	if (!strcasecmp (attr->field, "__ondemand"))
2514 	  goto passed;
2515 
2516       conf_free_list (attrs);
2517     }
2518 
2519   return 0;
2520 
2521  passed:
2522   conf_free_list (attrs);
2523 
2524   af = conf_begin ();
2525 
2526   configname = conf_get_str (section, "Configuration");
2527   conf_remove_section (af, configname);
2528 
2529   /* These are the Phase 2 Local/Remote IDs. */
2530   localid = conf_get_str (section, "Local-ID");
2531   pf_key_v2_conf_refhandle (af, localid);
2532 
2533   remoteid = conf_get_str (section, "Remote-ID");
2534   pf_key_v2_conf_refhandle (af, remoteid);
2535 
2536   ikepeer = conf_get_str (section, "ISAKMP-peer");
2537 
2538   pf_key_v2_conf_refhandle (af, section);
2539 
2540   if (ikepeer)
2541     {
2542       remoteid = conf_get_str (ikepeer, "Remote-ID");
2543       localid = conf_get_str (ikepeer, "ID");
2544       configname = conf_get_str (ikepeer, "Configuration");
2545 
2546       pf_key_v2_conf_refhandle (af, ikepeer);
2547       pf_key_v2_conf_refhandle (af, configname);
2548 
2549       /* Phase 1 IDs */
2550       pf_key_v2_conf_refhandle (af, localid);
2551       pf_key_v2_conf_refhandle (af, remoteid);
2552     }
2553 
2554   conf_end (af, 1);
2555   return 0;
2556 }
2557 
2558 /* Disable a flow given a SA.  */
2559 static int
2560 pf_key_v2_disable_sa (struct sa *sa, int incoming)
2561 {
2562   struct ipsec_sa *isa = sa->data;
2563   struct sockaddr *dst, *src;
2564   struct proto *proto = TAILQ_FIRST (&sa->protos);
2565 #if !defined (SADB_X_EXT_FLOW_TYPE)
2566   struct sockaddr_storage hostmask_storage;
2567   struct sockaddr *hostmask = (struct sockaddr *)&hostmask_storage;
2568   int error;
2569 #endif /* SADB_X_EXT_FLOW_TYPE */
2570 
2571   sa->transport->vtbl->get_dst (sa->transport, &dst);
2572   sa->transport->vtbl->get_src (sa->transport, &src);
2573 
2574   if (!incoming)
2575     return pf_key_v2_flow (isa->src_net, isa->src_mask, isa->dst_net,
2576 			   isa->dst_mask, isa->tproto, isa->sport, isa->dport,
2577 			   proto->spi[0], proto->proto, src, dst, 1, 0,
2578 			   0, 0, 0, 0, 0, 0, proto->data);
2579   else
2580     {
2581 #if !defined (SADB_X_EXT_FLOW_TYPE)
2582       /* Set hostmask to '-1'. */
2583       switch (dst->sa_family)
2584 	{
2585 	case AF_INET:
2586 	  ((struct sockaddr_in *)hostmask)->sin_family = AF_INET;
2587 #ifndef USE_OLD_SOCKADDR
2588 	  ((struct sockaddr_in *)hostmask)->sin_len = sizeof (struct in_addr);
2589 #endif
2590 	  memset (&((struct sockaddr_in *)hostmask)->sin_addr.s_addr, 0xff,
2591 		  sizeof (struct in_addr));
2592 	  break;
2593 	case AF_INET6:
2594 	  ((struct sockaddr_in6 *)hostmask)->sin6_family = AF_INET6;
2595 #ifndef USE_OLD_SOCKADDR
2596 	  ((struct sockaddr_in6 *)hostmask)->sin6_len =
2597 	    sizeof (struct in6_addr);
2598 #endif
2599 	  memset (&((struct sockaddr_in6 *)hostmask)->sin6_addr.s6_addr, 0xff,
2600 		  sizeof (struct in6_addr));
2601 	  break;
2602 	}
2603 
2604       /* Ingress flow --- SA bundles */
2605       while (TAILQ_NEXT (proto, link))
2606 	{
2607           error = pf_key_v2_flow (dst, hostmask, src, hostmask, 0, 0, 0,
2608 				  proto->spi[1], proto->proto, src, dst,
2609 				  1, 1, 0, 0, 0, 0, 0, 0, proto->data);
2610           if (error)
2611 	    return error;
2612           proto = TAILQ_NEXT (proto, link);
2613 	}
2614 #endif /* SADB_X_EXT_FLOW_TYPE */
2615 
2616       return pf_key_v2_flow (isa->dst_net, isa->dst_mask, isa->src_net,
2617 			     isa->src_mask, isa->tproto, isa->dport,
2618 			     isa->sport, proto->spi[1], proto->proto,
2619 			     src, dst, 1, 1, 0, 0, 0, 0, 0, 0, proto->data);
2620     }
2621 }
2622 
2623 /*
2624  * Delete the IPsec SA represented by the INCOMING direction in protocol PROTO
2625  * of the IKE security association SA.  Also delete potential flows tied to it.
2626  */
2627 int
2628 pf_key_v2_delete_spi (struct sa *sa, struct proto *proto, int incoming)
2629 {
2630   struct sadb_msg msg;
2631   struct sadb_sa ssa;
2632   struct sadb_address *addr = 0;
2633   struct sockaddr *saddr;
2634   int len, err;
2635   struct pf_key_v2_msg *delete = 0, *ret = 0;
2636 #ifdef KAME
2637   struct sadb_x_sa2 ssa2;
2638 #endif
2639 
2640   /* If it's not an established SA, don't proceed. */
2641   if (!(sa->flags & SA_FLAG_READY))
2642     return 0;
2643 
2644   /*
2645    * If the SA was not replaced and was not one acquired through the
2646    * kernel (ACQUIRE message), remove the flow associated with it.
2647    * We ignore any errors from the disabling of the flow.
2648    */
2649   if (!(sa->flags & SA_FLAG_REPLACED)
2650       && !(sa->flags & SA_FLAG_ONDEMAND))
2651     pf_key_v2_disable_sa (sa, incoming);
2652 
2653   if (sa->name && !(sa->flags & SA_FLAG_REPLACED))
2654     {
2655       LOG_DBG ((LOG_SYSDEP, 50,
2656 		"pf_key_v2_delete_spi: removing configuration %s",
2657 		sa->name));
2658       pf_key_v2_remove_conf (sa->name);
2659     }
2660 
2661   msg.sadb_msg_type = SADB_DELETE;
2662   switch (proto->proto)
2663     {
2664     case IPSEC_PROTO_IPSEC_ESP:
2665       msg.sadb_msg_satype = SADB_SATYPE_ESP;
2666       break;
2667     case IPSEC_PROTO_IPSEC_AH:
2668       msg.sadb_msg_satype = SADB_SATYPE_AH;
2669       break;
2670 #if defined (SADB_X_SATYPE_IPCOMP)
2671     case IPSEC_PROTO_IPCOMP:
2672       msg.sadb_msg_satype = SADB_X_SATYPE_IPCOMP;
2673       break;
2674 #endif
2675     default:
2676       log_print ("pf_key_v2_delete_spi: invalid proto %d", proto->proto);
2677       goto cleanup;
2678     }
2679   msg.sadb_msg_seq = 0;
2680   delete = pf_key_v2_msg_new (&msg, 0);
2681   if (!delete)
2682     goto cleanup;
2683 
2684   /* Setup the SA extension.  */
2685   ssa.sadb_sa_exttype = SADB_EXT_SA;
2686   ssa.sadb_sa_len = sizeof ssa / PF_KEY_V2_CHUNK;
2687   memcpy (&ssa.sadb_sa_spi, proto->spi[incoming], sizeof ssa.sadb_sa_spi);
2688   ssa.sadb_sa_replay = 0;
2689   ssa.sadb_sa_state = 0;
2690   ssa.sadb_sa_auth = 0;
2691   ssa.sadb_sa_encrypt = 0;
2692   ssa.sadb_sa_flags = 0;
2693   if (pf_key_v2_msg_add (delete, (struct sadb_ext *)&ssa, 0) == -1)
2694     goto cleanup;
2695 
2696 #ifdef KAME
2697   memset (&ssa2, 0, sizeof ssa2);
2698   ssa2.sadb_x_sa2_exttype = SADB_X_EXT_SA2;
2699   ssa2.sadb_x_sa2_len = sizeof ssa2 / PF_KEY_V2_CHUNK;
2700   ssa2.sadb_x_sa2_mode = 0;
2701   if (pf_key_v2_msg_add (delete, (struct sadb_ext *)&ssa2, 0) == -1)
2702     goto cleanup;
2703 #endif
2704 
2705   /*
2706    * Setup the ADDRESS extensions.
2707    */
2708   if (incoming)
2709     sa->transport->vtbl->get_dst (sa->transport, &saddr);
2710   else
2711     sa->transport->vtbl->get_src (sa->transport, &saddr);
2712   len = sizeof *addr + PF_KEY_V2_ROUND (sysdep_sa_len (saddr));
2713   addr = calloc (1, len);
2714   if (!addr)
2715     goto cleanup;
2716   addr->sadb_address_exttype = SADB_EXT_ADDRESS_SRC;
2717   addr->sadb_address_len = len / PF_KEY_V2_CHUNK;
2718 #ifndef __OpenBSD__
2719   addr->sadb_address_proto = 0;
2720   addr->sadb_address_prefixlen = 0;
2721 #endif
2722   addr->sadb_address_reserved = 0;
2723   memcpy (addr + 1, saddr, sysdep_sa_len (saddr));
2724   switch (saddr->sa_family)
2725     {
2726     case AF_INET:
2727       ((struct sockaddr_in *)(addr + 1))->sin_port = 0;
2728       break;
2729     case AF_INET6:
2730       ((struct sockaddr_in6 *)(addr + 1))->sin6_port = 0;
2731       break;
2732     }
2733   if (pf_key_v2_msg_add (delete, (struct sadb_ext *)addr,
2734 			 PF_KEY_V2_NODE_MALLOCED) == -1)
2735     goto cleanup;
2736   addr = 0;
2737 
2738   if (incoming)
2739     sa->transport->vtbl->get_src (sa->transport, &saddr);
2740   else
2741     sa->transport->vtbl->get_dst (sa->transport, &saddr);
2742   len = sizeof *addr + PF_KEY_V2_ROUND (sysdep_sa_len (saddr));
2743   addr = calloc (1, len);
2744   if (!addr)
2745     goto cleanup;
2746   addr->sadb_address_exttype = SADB_EXT_ADDRESS_DST;
2747   addr->sadb_address_len = len / PF_KEY_V2_CHUNK;
2748 #ifndef __OpenBSD__
2749   addr->sadb_address_proto = 0;
2750   addr->sadb_address_prefixlen = 0;
2751 #endif
2752   addr->sadb_address_reserved = 0;
2753   memcpy (addr + 1, saddr, sysdep_sa_len (saddr));
2754   switch (saddr->sa_family)
2755     {
2756     case AF_INET:
2757       ((struct sockaddr_in *)(addr + 1))->sin_port = 0;
2758       break;
2759     case AF_INET6:
2760       ((struct sockaddr_in6 *)(addr + 1))->sin6_port = 0;
2761       break;
2762     }
2763   if (pf_key_v2_msg_add (delete, (struct sadb_ext *)addr,
2764 			 PF_KEY_V2_NODE_MALLOCED) == -1)
2765     goto cleanup;
2766   addr = 0;
2767 
2768   ret = pf_key_v2_call (delete);
2769   pf_key_v2_msg_free (delete);
2770   delete = 0;
2771   if (!ret)
2772     goto cleanup;
2773   err = ((struct sadb_msg *)TAILQ_FIRST (ret)->seg)->sadb_msg_errno;
2774   if (err)
2775     {
2776       LOG_DBG ((LOG_SYSDEP, 10, "pf_key_v2_delete_spi: DELETE: %s",
2777 		strerror (err)));
2778       goto cleanup;
2779     }
2780   pf_key_v2_msg_free (ret);
2781 
2782   LOG_DBG ((LOG_SYSDEP, 50, "pf_key_v2_delete_spi: done"));
2783 
2784   return 0;
2785 
2786  cleanup:
2787   if (addr)
2788     free (addr);
2789   if (delete)
2790     pf_key_v2_msg_free (delete);
2791   if (ret)
2792     pf_key_v2_msg_free (ret);
2793   return -1;
2794 }
2795 
2796 static void
2797 pf_key_v2_stayalive (struct exchange *exchange, void *vconn, int fail)
2798 {
2799   char *conn = vconn;
2800   struct sa *sa;
2801 
2802   /* XXX What if it is phase 1 ? */
2803   sa = sa_lookup_by_name (conn, 2);
2804   if (sa)
2805     sa->flags |= SA_FLAG_STAYALIVE;
2806 
2807   /*
2808    * Remove failed configuration entry -- call twice because it is
2809    * created with a Refcount of 2.
2810    */
2811   if (fail && (!exchange || exchange->name))
2812     {
2813       pf_key_v2_remove_conf (conn);
2814       pf_key_v2_remove_conf (conn);
2815     }
2816 }
2817 
2818 /* Check if a connection CONN exists, otherwise establish it.  */
2819 void
2820 pf_key_v2_connection_check (char *conn)
2821 {
2822   if (!sa_lookup_by_name (conn, 2))
2823     {
2824       LOG_DBG ((LOG_SYSDEP, 70,
2825 		"pf_key_v2_connection_check: SA for %s missing", conn));
2826       exchange_establish (conn, pf_key_v2_stayalive, conn);
2827     }
2828   else
2829     LOG_DBG ((LOG_SYSDEP, 70, "pf_key_v2_connection_check: SA for %s exists",
2830 	      conn));
2831 }
2832 
2833 /* Handle a PF_KEY lifetime expiration message PMSG.  */
2834 static void
2835 pf_key_v2_expire (struct pf_key_v2_msg *pmsg)
2836 {
2837   struct sadb_msg *msg;
2838   struct sadb_sa *ssa;
2839   struct sadb_address *dst;
2840   struct sockaddr *dstaddr;
2841   struct sadb_lifetime *life, *lifecurrent;
2842   struct sa *sa;
2843   struct pf_key_v2_node *lifenode, *ext;
2844   char *dst_str;
2845 
2846   msg = (struct sadb_msg *)TAILQ_FIRST (pmsg)->seg;
2847   ext = pf_key_v2_find_ext (pmsg, SADB_EXT_SA);
2848   if (!ext)
2849     {
2850       log_print ("pf_key_v2_expire: no SA extension found");
2851       return;
2852     }
2853   ssa = ext->seg;
2854   ext = pf_key_v2_find_ext (pmsg, SADB_EXT_ADDRESS_DST);
2855   if (!ext)
2856     {
2857       log_print ("pf_key_v2_expire: no destination address extension found");
2858       return;
2859     }
2860   dst = ext->seg;
2861   dstaddr = (struct sockaddr *)(dst + 1);
2862   lifenode = pf_key_v2_find_ext (pmsg, SADB_EXT_LIFETIME_HARD);
2863   if (!lifenode)
2864     lifenode = pf_key_v2_find_ext (pmsg, SADB_EXT_LIFETIME_SOFT);
2865   if (!lifenode)
2866     {
2867       log_print ("pf_key_v2_expire: no lifetime extension found");
2868       return;
2869     }
2870   life = lifenode->seg;
2871 
2872   lifenode = pf_key_v2_find_ext (pmsg, SADB_EXT_LIFETIME_CURRENT);
2873   if (!lifenode)
2874     {
2875       log_print ("pf_key_v2_expire: no current lifetime extension found");
2876       return;
2877     }
2878   lifecurrent = lifenode->seg;
2879 
2880 #ifdef USE_DEBUG
2881 
2882   if (sockaddr2text (dstaddr, &dst_str, 0))
2883     dst_str = 0;
2884 
2885   LOG_DBG ((LOG_SYSDEP, 20, "pf_key_v2_expire: %s dst %s SPI %x sproto %d",
2886 	    life->sadb_lifetime_exttype == SADB_EXT_LIFETIME_SOFT ? "SOFT"
2887 	    : "HARD", dst_str ? dst_str : "<unknown>",
2888 	    ntohl (ssa->sadb_sa_spi), msg->sadb_msg_satype));
2889 
2890   if (dst_str)
2891     free (dst_str);
2892 
2893 #endif /* USE_DEBUG */
2894 
2895   /*
2896    * Find the IPsec SA.  The IPsec stack has two SAs for every IKE SA,
2897    * one outgoing and one incoming, we regard expirations for any of
2898    * them as an expiration of the full IKE SA.  Likewise, in
2899    * protection suites consisting of more than one protocol, any
2900    * expired individual IPsec stack SA will be seen as an expiration
2901    * of the full suite.
2902    */
2903   switch (msg->sadb_msg_satype)
2904     {
2905     case SADB_SATYPE_ESP:
2906       sa = ipsec_sa_lookup (dstaddr, ssa->sadb_sa_spi, IPSEC_PROTO_IPSEC_ESP);
2907       break;
2908 
2909     case SADB_SATYPE_AH:
2910       sa = ipsec_sa_lookup (dstaddr, ssa->sadb_sa_spi, IPSEC_PROTO_IPSEC_AH);
2911       break;
2912 
2913 #ifdef SADB_X_SATYPE_IPCOMP
2914     case SADB_X_SATYPE_IPCOMP:
2915       sa = ipsec_sa_lookup (dstaddr, ssa->sadb_sa_spi, IPSEC_PROTO_IPCOMP);
2916       break;
2917 #endif
2918 
2919     default:
2920       /* XXX Log? */
2921       sa = 0;
2922       break;
2923     }
2924 
2925   /* If the SA is already gone, don't do anything.  */
2926   if (!sa)
2927     return;
2928 
2929   /*
2930    * If we got a notification, try to renegotiate the SA -- unless of
2931    * course it has already been replaced by another.
2932    * Also, ignore SAs that were not dynamically established, or that
2933    * did not see any use.
2934    */
2935   if (!(sa->flags & SA_FLAG_REPLACED) && (sa->flags & SA_FLAG_ONDEMAND) &&
2936       lifecurrent->sadb_lifetime_bytes)
2937     exchange_establish (sa->name, 0, 0);
2938 
2939   if (life->sadb_lifetime_exttype == SADB_EXT_LIFETIME_HARD)
2940     {
2941       /* Remove the old SA, it isn't useful anymore.  */
2942       sa_free (sa);
2943     }
2944 }
2945 
2946 /* Handle a PF_KEY SA ACQUIRE message PMSG.  */
2947 static void
2948 pf_key_v2_acquire (struct pf_key_v2_msg *pmsg)
2949 {
2950 #if defined (SADB_X_ASKPOLICY)
2951   struct sadb_msg *msg, askpolicy_msg;
2952   struct pf_key_v2_msg *askpolicy = 0, *ret = 0;
2953   struct sadb_x_policy policy;
2954   struct sadb_address *dst = 0, *src = 0;
2955   struct sockaddr *dstaddr, *srcaddr = 0;
2956   struct sadb_comb *scmb = 0;
2957   struct sadb_prop *sprp = 0;
2958   struct sadb_ident *srcident = 0, *dstident = 0;
2959   char dstbuf[ADDRESS_MAX], srcbuf[ADDRESS_MAX], *peer = 0, *conn = 0;
2960   char confname[120];
2961   char *srcid = 0, *dstid = 0, *prefstring = 0;
2962   int slen, af, afamily, masklen, buflen;
2963   struct sockaddr *smask, *sflow, *dmask, *dflow;
2964   struct sadb_protocol *sproto;
2965   char ssflow[ADDRESS_MAX], sdflow[ADDRESS_MAX];
2966   char sdmask[ADDRESS_MAX], ssmask[ADDRESS_MAX];
2967   char *sidtype = 0, *didtype = 0;
2968   char lname[100], dname[100], configname[30];
2969   int shostflag = 0, dhostflag = 0;
2970   struct pf_key_v2_node *ext;
2971   struct passwd *pwd = 0;
2972   u_int16_t sport = 0, dport = 0;
2973   u_int8_t tproto = 0;
2974   char tmbuf[sizeof sport * 3 + 1], *xform;
2975   int connlen;
2976 #if defined (SADB_X_CREDTYPE_NONE)
2977   struct sadb_x_cred *cred = 0, *sauth = 0;
2978 #endif
2979 
2980   /* This needs to be dynamically allocated. */
2981   connlen = 22;
2982   conn = malloc (connlen);
2983   if (!conn)
2984     {
2985       log_error ("pf_key_v2_acquire: malloc (%d) failed", connlen);
2986       return;
2987     }
2988 
2989   msg = (struct sadb_msg *)TAILQ_FIRST (pmsg)->seg;
2990 
2991   ext = pf_key_v2_find_ext (pmsg, SADB_EXT_ADDRESS_DST);
2992   if (!ext)
2993     {
2994       log_print ("pf_key_v2_acquire: no destination address specified");
2995       return;
2996     }
2997   dst = ext->seg;
2998 
2999   ext = pf_key_v2_find_ext (pmsg, SADB_EXT_ADDRESS_SRC);
3000   if (ext)
3001     src = ext->seg;
3002 
3003   ext = pf_key_v2_find_ext (pmsg, SADB_EXT_PROPOSAL);
3004   if (ext)
3005     {
3006       sprp = ext->seg;
3007       scmb = (struct sadb_comb *)(sprp + 1);
3008     }
3009 
3010   ext = pf_key_v2_find_ext (pmsg, SADB_EXT_IDENTITY_SRC);
3011   if (ext)
3012     srcident = ext->seg;
3013 
3014   ext = pf_key_v2_find_ext (pmsg, SADB_EXT_IDENTITY_DST);
3015   if (ext)
3016     dstident = ext->seg;
3017 
3018   /* Ask the kernel for the matching policy. */
3019   bzero (&askpolicy_msg, sizeof askpolicy_msg);
3020   askpolicy_msg.sadb_msg_type = SADB_X_ASKPOLICY;
3021   askpolicy = pf_key_v2_msg_new (&askpolicy_msg, 0);
3022   if (!askpolicy)
3023     goto fail;
3024 
3025   policy.sadb_x_policy_exttype = SADB_X_EXT_POLICY;
3026   policy.sadb_x_policy_len = sizeof policy / PF_KEY_V2_CHUNK;
3027   policy.sadb_x_policy_seq = msg->sadb_msg_seq;
3028   if (pf_key_v2_msg_add (askpolicy, (struct sadb_ext *)&policy, 0) == -1)
3029     goto fail;
3030 
3031   ret = pf_key_v2_call (askpolicy);
3032   if (!ret)
3033     goto fail;
3034 
3035   /* Now we have all the information needed. */
3036 
3037   ext = pf_key_v2_find_ext (ret, SADB_X_EXT_SRC_FLOW);
3038   if (!ext)
3039     {
3040       log_print ("pf_key_v2_acquire: no source flow extension found");
3041       goto fail;
3042     }
3043   sflow = (struct sockaddr *)(((struct sadb_address *)ext->seg) + 1);
3044 
3045   ext = pf_key_v2_find_ext (ret, SADB_X_EXT_DST_FLOW);
3046   if (!ext)
3047     {
3048       log_print ("pf_key_v2_acquire: no destination flow extension found");
3049       goto fail;
3050     }
3051   dflow = (struct sockaddr *)(((struct sadb_address *)ext->seg) + 1);
3052   ext = pf_key_v2_find_ext (ret, SADB_X_EXT_SRC_MASK);
3053   if (!ext)
3054     {
3055       log_print ("pf_key_v2_acquire: no source mask extension found");
3056       goto fail;
3057     }
3058   smask = (struct sockaddr *)(((struct sadb_address *)ext->seg) + 1);
3059 
3060   ext = pf_key_v2_find_ext (ret, SADB_X_EXT_DST_MASK);
3061   if (!ext)
3062     {
3063       log_print ("pf_key_v2_acquire: no destination mask extension found");
3064       goto fail;
3065     }
3066   dmask = (struct sockaddr *)(((struct sadb_address *)ext->seg) + 1);
3067 
3068   ext = pf_key_v2_find_ext (ret, SADB_X_EXT_FLOW_TYPE);
3069   if (!ext)
3070     {
3071       log_print ("pf_key_v2_acquire: no flow type extension found");
3072       goto fail;
3073     }
3074   sproto = ext->seg;
3075   tproto = sproto->sadb_protocol_proto;
3076 
3077 #if defined (SADB_X_EXT_LOCAL_CREDENTIALS)
3078   ext = pf_key_v2_find_ext (pmsg, SADB_X_EXT_LOCAL_CREDENTIALS);
3079   if (ext)
3080     cred = (struct sadb_x_cred *) ext->seg;
3081   else
3082     cred = 0;
3083 #endif
3084 
3085 #if defined (SADB_X_EXT_LOCAL_AUTH)
3086   ext = pf_key_v2_find_ext (pmsg, SADB_X_EXT_LOCAL_AUTH);
3087   if (ext)
3088     sauth = (struct sadb_x_cred *) ext->seg;
3089   else
3090     sauth = 0;
3091 #endif
3092 
3093   bzero (ssflow, sizeof ssflow);
3094   bzero (sdflow, sizeof sdflow);
3095   bzero (ssmask, sizeof ssmask);
3096   bzero (sdmask, sizeof sdmask);
3097 
3098   sidtype = didtype = "IPV4_ADDR_SUBNET"; /* default */
3099 
3100   switch (sflow->sa_family)
3101     {
3102     case AF_INET:
3103       if (inet_ntop (AF_INET, &((struct sockaddr_in *)sflow)->sin_addr, ssflow,
3104 		     ADDRESS_MAX) == NULL)
3105 	{
3106 	  log_print ("pf_key_v2_acquire: inet_ntop failed");
3107 	  goto fail;
3108 	}
3109       sport = ((struct sockaddr_in *)sflow)->sin_port;
3110       if (inet_ntop (AF_INET, &((struct sockaddr_in *)dflow)->sin_addr, sdflow,
3111 		     ADDRESS_MAX) == NULL)
3112 	{
3113 	  log_print ("pf_key_v2_acquire: inet_ntop failed");
3114 	  goto fail;
3115 	}
3116       dport = ((struct sockaddr_in *)dflow)->sin_port;
3117       if (inet_ntop (AF_INET, &((struct sockaddr_in *)smask)->sin_addr, ssmask,
3118 		     ADDRESS_MAX) == NULL)
3119 	{
3120 	  log_print ("pf_key_v2_acquire: inet_ntop failed");
3121 	  goto fail;
3122 	}
3123       if (inet_ntop (AF_INET, &((struct sockaddr_in *)dmask)->sin_addr, sdmask,
3124 		     ADDRESS_MAX) == NULL)
3125 	{
3126 	  log_print ("pf_key_v2_acquire: inet_ntop failed");
3127 	  goto fail;
3128 	}
3129       if (((struct sockaddr_in *)smask)->sin_addr.s_addr == INADDR_BROADCAST)
3130 	{
3131 	  shostflag = 1;
3132 	  sidtype = "IPV4_ADDR";
3133 	}
3134       if (((struct sockaddr_in *)dmask)->sin_addr.s_addr == INADDR_BROADCAST)
3135 	{
3136 	  dhostflag = 1;
3137 	  didtype = "IPV4_ADDR";
3138 	}
3139       break;
3140 
3141     case AF_INET6:
3142       if (inet_ntop (AF_INET6, &((struct sockaddr_in6 *)sflow)->sin6_addr,
3143 		     ssflow, ADDRESS_MAX) == NULL)
3144 	{
3145 	  log_print ("pf_key_v2_acquire: inet_ntop failed");
3146 	  goto fail;
3147 	}
3148       sport = ((struct sockaddr_in6 *)sflow)->sin6_port;
3149       if (inet_ntop (AF_INET6, &((struct sockaddr_in6 *)dflow)->sin6_addr,
3150 		     sdflow, ADDRESS_MAX) == NULL)
3151 	{
3152 	  log_print ("pf_key_v2_acquire: inet_ntop failed");
3153 	  goto fail;
3154 	}
3155       dport = ((struct sockaddr_in6 *)dflow)->sin6_port;
3156       if (inet_ntop (AF_INET6, &((struct sockaddr_in6 *)smask)->sin6_addr,
3157 		     ssmask, ADDRESS_MAX) == NULL)
3158 	{
3159 	  log_print ("pf_key_v2_acquire: inet_ntop failed");
3160 	  goto fail;
3161 	}
3162       if (inet_ntop (AF_INET6, &((struct sockaddr_in6 *)dmask)->sin6_addr,
3163 		     sdmask, ADDRESS_MAX) == NULL)
3164 	{
3165 	  log_print ("pf_key_v2_acquire: inet_ntop failed");
3166 	  goto fail;
3167 	}
3168       sidtype = didtype = "IPV6_ADDR_SUBNET";
3169       if (IN6_IS_ADDR_FULL (&((struct sockaddr_in6 *)smask)->sin6_addr))
3170 	{
3171 	  shostflag = 1;
3172 	  sidtype = "IPV6_ADDR";
3173 	}
3174       if (IN6_IS_ADDR_FULL (&((struct sockaddr_in6 *)dmask)->sin6_addr))
3175 	{
3176 	  dhostflag = 1;
3177 	  didtype = "IPV6_ADDR";
3178 	}
3179       break;
3180     }
3181 
3182   dstaddr = (struct sockaddr *)(dst + 1);
3183   bzero (dstbuf, sizeof dstbuf);
3184   bzero (srcbuf, sizeof srcbuf);
3185 
3186   if (dstaddr->sa_family == 0)
3187     {
3188       /* Destination was not specified in the flow -- can we derive it? */
3189       if (dhostflag == 0)
3190 	{
3191           log_print("pf_key_v2_acquire: Cannot determine precise destination");
3192           goto fail;
3193         }
3194       dstaddr = dflow;
3195     }
3196   switch (dstaddr->sa_family)
3197     {
3198     case AF_INET:
3199       if (inet_ntop (AF_INET, &((struct sockaddr_in *)dstaddr)->sin_addr,
3200 		     dstbuf, ADDRESS_MAX) == NULL)
3201 	{
3202 	  log_print ("pf_key_v2_acquire: inet_ntop failed");
3203 	  goto fail;
3204 	}
3205       LOG_DBG ((LOG_SYSDEP, 20, "pf_key_v2_acquire: dst=%s sproto %d", dstbuf,
3206 		msg->sadb_msg_satype));
3207       break;
3208 
3209     case AF_INET6:
3210       if (inet_ntop (AF_INET6, &((struct sockaddr_in6 *)dstaddr)->sin6_addr,
3211 		     dstbuf, ADDRESS_MAX) == NULL)
3212 	{
3213 	  log_print ("pf_key_v2_acquire: inet_ntop failed");
3214 	  goto fail;
3215 	}
3216       LOG_DBG ((LOG_SYSDEP, 20, "pf_key_v2_acquire: dst=%s sproto %d", dstbuf,
3217 		msg->sadb_msg_satype));
3218       break;
3219     }
3220 
3221   if (src)
3222     {
3223       srcaddr = (struct sockaddr *)(src + 1);
3224 
3225       switch (srcaddr->sa_family)
3226         {
3227 	case AF_INET:
3228 	  if (inet_ntop (AF_INET, &((struct sockaddr_in *)srcaddr)->sin_addr,
3229 			 srcbuf, ADDRESS_MAX) == NULL)
3230 	    {
3231 	      log_print ("pf_key_v2_acquire: inet_ntop failed");
3232 	      goto fail;
3233 	    }
3234 	  break;
3235 
3236 	case AF_INET6:
3237 	  if (inet_ntop (AF_INET6,
3238 			 &((struct sockaddr_in6 *)srcaddr)->sin6_addr, srcbuf,
3239 			 ADDRESS_MAX) == NULL)
3240 	    {
3241 	      log_print ("pf_key_v2_acquire: inet_ntop failed");
3242 	      goto fail;
3243 	    }
3244           break;
3245 
3246 	default:
3247 	  /*
3248 	   * The kernel will pass an all '0' EXT_ADDRESS_SRC if it wasn't
3249 	   * specified for the flow. In that case, do NOT specify the srcaddr
3250 	   * in the Peer- name below
3251 	   */
3252 	  srcbuf[0] = 0;
3253 	  srcaddr = NULL;
3254 	  break;
3255 	}
3256     }
3257 
3258   /* Insert source ID. */
3259   if (srcident)
3260     {
3261       slen = (srcident->sadb_ident_len * sizeof (u_int64_t))
3262 	- sizeof (struct sadb_ident);
3263       if (((unsigned char *)(srcident + 1))[slen - 1] != '\0')
3264 	{
3265 	  log_print ("pf_key_v2_acquire: source identity not NUL-terminated");
3266 	  goto fail;
3267 	}
3268 
3269       /* Check for valid type. */
3270       switch (srcident->sadb_ident_type)
3271         {
3272 #if defined (SADB_X_IDENTTYPE_CONNECTION)
3273 	case SADB_X_IDENTTYPE_CONNECTION:
3274 	  /* XXX */
3275 	  break;
3276 #endif
3277 
3278 	case SADB_IDENTTYPE_PREFIX:
3279 	  /* Determine what the address family is. */
3280 	  srcid = memchr (srcident + 1, ':', slen);
3281 	  if (srcid)
3282 	    afamily = AF_INET6;
3283 	  else
3284 	    afamily = AF_INET;
3285 
3286 	  srcid = memchr (srcident + 1, '/', slen);
3287 	  if (!srcid)
3288 	    {
3289 	      log_print ("pf_key_v2_acquire: badly formatted PREFIX identity");
3290 	      goto fail;
3291 	    }
3292 
3293 	  masklen = atoi (srcid + 1);
3294 
3295 	  /* XXX We only support host addresses. */
3296 	  if ((afamily == AF_INET6 && masklen != 128)
3297 	      || (afamily == AF_INET && masklen != 32))
3298 	    {
3299 	      log_print ("pf_key_v2_acquire: non-host address specified in "
3300 			 "source identity (mask length %d), ignoring request",
3301 			 masklen);
3302 	      goto fail;
3303 	    }
3304 
3305 	  /* NUL-terminate the PREFIX string at the separator, then dup. */
3306 	  *srcid = '\0';
3307 	  slen = strlen ((char *)(srcident + 1)) + sizeof "ID:Address/";
3308 	  srcid = malloc (slen);
3309 	  if (!srcid)
3310 	    {
3311 	      log_error ("pf_key_v2_acquire: malloc (%d) failed", slen);
3312 	      goto fail;
3313 	    }
3314 
3315 	  snprintf (srcid, slen, "ID:Address/%s", (char *)(srcident + 1));
3316 
3317 	  /* Set the section if it doesn't already exist. */
3318 	  af = conf_begin ();
3319 	  if (!conf_get_str (srcid, "ID-type"))
3320 	    {
3321 	      if (conf_set (af, srcid, "ID-type",
3322 			    afamily == AF_INET ? "IPV4_ADDR" : "IPV6_ADDR",
3323 			    1, 0)
3324 		  || conf_set (af, srcid, "Refcount", "1", 1, 0)
3325 		  || conf_set (af, srcid, "Address", (char *)(srcident + 1),
3326 			       1, 0))
3327 		{
3328 		  conf_end (af, 0);
3329 		  goto fail;
3330 		}
3331 	    }
3332 	  else
3333 	    pf_key_v2_conf_refinc (af, srcid);
3334 	  conf_end (af, 1);
3335 	  break;
3336 
3337 	case SADB_IDENTTYPE_FQDN:
3338 	  prefstring = "FQDN";
3339 	  /* Fall through */
3340 	case SADB_IDENTTYPE_USERFQDN:
3341 	  if (!prefstring)
3342 	    {
3343 	      prefstring = "USER_FQDN";
3344 
3345 	      /*
3346 	       * Check whether there is a string following the header;
3347 	       * if no, that there is a user ID (and acquire the login
3348 	       * name). If there is both a string and a user ID, check
3349 	       * that they match.
3350 	       */
3351 	      if ((slen == 0) && (srcident->sadb_ident_id == 0))
3352 	        {
3353 		  log_print ("pf_key_v2_acquire: no user FQDN or ID provided");
3354 		  goto fail;
3355 		}
3356 
3357 	      if (srcident->sadb_ident_id)
3358 	        {
3359 		  pwd = getpwuid (srcident->sadb_ident_id);
3360 		  if (!pwd)
3361 		    {
3362 		      log_error ("pf_key_v2_acquire: could not acquire "
3363 				 "username from provided ID %llu",
3364 				 srcident->sadb_ident_id);
3365 		      goto fail;
3366 		    }
3367 
3368 		  if (slen != 0)
3369 		    if (strcmp (pwd->pw_name, (char *)(srcident + 1)) != 0)
3370 		      {
3371 			log_print ("pf_key_v2_acquire: provided user name and "
3372 				   "ID do not match (%s != %s)",
3373 				   (char *)(srcident + 1), pwd->pw_name);
3374 			/* String has precedence, per RFC 2367. */
3375 		      }
3376 		}
3377 	    }
3378 
3379 	  buflen = (slen ? slen : strlen (pwd->pw_name)) + strlen (prefstring)
3380 	    + sizeof "ID:/";
3381 	  srcid = malloc (buflen);
3382 	  if (!srcid)
3383 	    {
3384 	      log_error ("pf_key_v2_acquire: malloc (%d) failed", buflen);
3385 	      goto fail;
3386 	    }
3387 
3388 	  snprintf (srcid, buflen, "ID:%s/", prefstring);
3389 	  if (slen != 0)
3390 	    strlcat (srcid, (char *)(srcident + 1), buflen);
3391 	  else
3392 	    strlcat (srcid, pwd->pw_name, buflen);
3393 	  pwd = 0;
3394 
3395 	  /* Set the section if it doesn't already exist. */
3396 	  af = conf_begin ();
3397 	  if (!conf_get_str (srcid, "ID-type"))
3398 	    {
3399 	      if (conf_set (af, srcid, "ID-type", prefstring, 1, 0)
3400 		  || conf_set (af, srcid, "Refcount", "1", 1, 0)
3401 		  || conf_set (af, srcid, "Name",
3402 			       srcid + sizeof "ID:/" - 1 + strlen (prefstring),
3403 			       1, 0))
3404 		{
3405 		  conf_end (af, 0);
3406 		  goto fail;
3407 		}
3408 	    }
3409 	  else
3410 	    pf_key_v2_conf_refinc (af, srcid);
3411 	  conf_end (af, 1);
3412 	  break;
3413 
3414 	default:
3415 	  LOG_DBG ((LOG_SYSDEP, 20,
3416 		    "pf_key_v2_acquire: invalid source ID type %d",
3417 		    srcident->sadb_ident_type));
3418 	  goto fail;
3419 	}
3420 
3421       LOG_DBG ((LOG_SYSDEP, 50,
3422 		"pf_key_v2_acquire: constructed source ID \"%s\"", srcid));
3423       prefstring = 0;
3424     }
3425 
3426   /* Insert destination ID. */
3427   if (dstident)
3428     {
3429       slen = (dstident->sadb_ident_len * sizeof (u_int64_t))
3430 	- sizeof (struct sadb_ident);
3431 
3432       /* Check for valid type. */
3433       switch (dstident->sadb_ident_type)
3434         {
3435 #if defined (SADB_X_IDENTTYPE_CONNECTION)
3436 	case SADB_X_IDENTTYPE_CONNECTION:
3437 	  /* XXX */
3438 	  break;
3439 #endif
3440 
3441 	case SADB_IDENTTYPE_PREFIX:
3442 	  /* Determine what the address family is. */
3443 	  dstid = memchr (dstident + 1, ':', slen);
3444 	  if (dstid)
3445 	    afamily = AF_INET6;
3446 	  else
3447 	    afamily = AF_INET;
3448 
3449 	  dstid = memchr (dstident + 1, '/', slen);
3450 	  if (!dstid)
3451 	    {
3452 	      log_print ("pf_key_v2_acquire: badly formatted PREFIX identity");
3453 	      goto fail;
3454 	    }
3455 
3456 	  masklen = atoi (dstid + 1);
3457 
3458 	  /* XXX We only support host addresses. */
3459 	  if ((afamily == AF_INET6 && masklen != 128)
3460 	      || (afamily == AF_INET && masklen != 32))
3461 	    {
3462 	      log_print ("pf_key_v2_acquire: non-host address specified in "
3463 			 "destination identity (mask length %d), ignoring "
3464 			 "request",
3465 			 masklen);
3466 	      goto fail;
3467 	    }
3468 
3469 	  /* NUL-terminate the PREFIX string at the separator, then dup. */
3470 	  *dstid = '\0';
3471 	  slen = strlen ((char *)(dstident + 1)) + sizeof "ID:Address/";
3472 	  dstid = malloc (slen);
3473 	  if (!dstid)
3474 	    {
3475 	      log_error ("pf_key_v2_acquire: malloc (%d) failed", slen);
3476 	      goto fail;
3477 	    }
3478 
3479 	  snprintf (dstid, slen, "ID:Address/%s", (char *)(dstident + 1));
3480 
3481 	  /* Set the section if it doesn't already exist. */
3482 	  af = conf_begin ();
3483 	  if (!conf_get_str (dstid, "ID-type"))
3484 	    {
3485 	      if (conf_set (af, dstid, "ID-type",
3486 			    afamily == AF_INET ? "IPV4_ADDR" : "IPV6_ADDR",
3487 			    1, 0)
3488 		  || conf_set (af, dstid, "Refcount", "1", 1, 0)
3489 		  || conf_set (af, dstid, "Address", (char *)(dstident + 1),
3490 			       1, 0))
3491 		{
3492 		  conf_end (af, 0);
3493 		  goto fail;
3494 		}
3495 	    }
3496 	  else
3497 	    pf_key_v2_conf_refinc (af, dstid);
3498 	  conf_end (af, 1);
3499 	  break;
3500 
3501 	case SADB_IDENTTYPE_FQDN:
3502 	  prefstring = "FQDN";
3503 	  /* Fall through */
3504 
3505 	case SADB_IDENTTYPE_USERFQDN:
3506 	  if (!prefstring)
3507 	    {
3508 	      prefstring = "USER_FQDN";
3509 
3510 	      /*
3511 	       * Check whether there is a string following the header;
3512 	       * if no, that there is a user ID (and acquire the login
3513 	       * name). If there is both a string and a user ID, check
3514 	       * that they match.
3515 	       */
3516 	      if (slen == 0 && dstident->sadb_ident_id == 0)
3517 	        {
3518 		  log_print ("pf_key_v2_acquire: no user FQDN or ID provided");
3519 		  goto fail;
3520 		}
3521 
3522 	      if (dstident->sadb_ident_id)
3523 	        {
3524 		  pwd = getpwuid (dstident->sadb_ident_id);
3525 		  if (!pwd)
3526 		    {
3527 		      log_error ("pf_key_v2_acquire: could not acquire "
3528 				 "username from provided ID %llu",
3529 				 dstident->sadb_ident_id);
3530 		      goto fail;
3531 		    }
3532 
3533 		  if (slen != 0)
3534 		    if (strcmp (pwd->pw_name, (char *)(dstident + 1)) != 0)
3535 		      {
3536 			log_print ("pf_key_v2_acquire: provided user name and "
3537 				   "ID do not match (%s != %s)",
3538 				   (char *)(dstident + 1), pwd->pw_name);
3539 			/* String has precedence, per RF 2367. */
3540 		      }
3541 		}
3542 	    }
3543 
3544 	  buflen = (slen ? slen : strlen (pwd->pw_name)) + strlen (prefstring)
3545 	    + sizeof "ID:/";
3546 	  dstid = malloc (buflen);
3547 	  if (!dstid)
3548 	    {
3549 	      log_error ("pf_key_v2_acquire: malloc (%d) failed", buflen);
3550 	      goto fail;
3551 	    }
3552 
3553 	  snprintf (dstid, buflen, "ID:%s/", prefstring);
3554 	  if (slen != 0)
3555 	    strlcat (dstid, (char *)(dstident + 1), buflen);
3556 	  else
3557 	    strlcat (dstid, pwd->pw_name, buflen);
3558 	  pwd = 0;
3559 
3560 	  /* Set the section if it doesn't already exist. */
3561 	  af = conf_begin ();
3562 	  if (!conf_get_str (dstid, "ID-type"))
3563 	    {
3564 	      if (conf_set (af, dstid, "ID-type", prefstring, 1, 0)
3565 		  || conf_set (af, dstid, "Refcount", "1", 1, 0)
3566 		  || conf_set (af, dstid, "Name",
3567 			       dstid + sizeof "ID:/" - 1 + strlen (prefstring),
3568 			       1, 0))
3569 		{
3570 		  conf_end (af, 0);
3571 		  goto fail;
3572 		}
3573 	    }
3574 	  else
3575 	    pf_key_v2_conf_refinc (af, dstid);
3576 	  conf_end (af, 1);
3577 	  break;
3578 
3579 	default:
3580 	  LOG_DBG ((LOG_SYSDEP, 20,
3581 		    "pf_key_v2_acquire: invalid destination ID type %d",
3582 		    dstident->sadb_ident_type));
3583 	  goto fail;
3584 	}
3585 
3586       LOG_DBG ((LOG_SYSDEP, 50,
3587 		"pf_key_v2_acquire: constructed destination ID \"%s\"",
3588 		dstid));
3589     }
3590 
3591   /* Now we've placed the necessary IDs in the configuration space. */
3592 
3593   /* Get a new connection sequence number. */
3594   for (;; connection_seq++)
3595     {
3596       snprintf (conn, connlen, "Connection-%u", connection_seq);
3597       snprintf (configname, sizeof configname, "Config-Phase2-%u",
3598 		connection_seq);
3599 
3600       /* Does it exist ? */
3601       if (!conf_get_str (conn, "Phase")
3602 	  && !conf_get_str (configname, "Suites"))
3603 	break;
3604     }
3605 
3606   /*
3607    * Set the IPsec connection entry. In particular, the following fields:
3608    * - Phase
3609    * - ISAKMP-peer
3610    * - Local-ID/Remote-ID (if provided)
3611    * - Acquire-ID (sequence number of kernel message, e.g., PF_KEYv2)
3612    * - Configuration
3613    *
3614    * Also set the following section:
3615    *    [Peer-dstaddr(/srcaddr)(-srcid)(/dstid)]
3616    * with these fields:
3617    * - Phase
3618    * - ID (if provided)
3619    * - Remote-ID (if provided)
3620    * - Local-address (if provided)
3621    * - Address
3622    * - Configuration (if an entry "ISAKMP-configuration-dstaddr(/srcaddr)"
3623    *                  exists -- otherwise use the defaults)
3624    */
3625 
3626   slen = strlen (dstbuf) + strlen (srcbuf) + (srcid ? strlen (srcid) : 0)
3627     + (dstid ? strlen (dstid) : 0) + sizeof "Peer-/-/";
3628   peer = malloc (slen);
3629   if (!peer)
3630     goto fail;
3631 
3632   /*
3633    * The various cases:
3634    * - Peer-dstaddr
3635    * - Peer-dstaddr/srcaddr
3636    * - Peer-dstaddr/srcaddr-srcid
3637    * - Peer-dstaddr/srcaddr-srcid/dstid
3638    * - Peer-dstaddr/srcaddr-/dstid
3639    * - Peer-dstaddr-srcid/dstid
3640    * - Peer-dstaddr-/dstid
3641    * - Peer-dstaddr-srcid
3642    */
3643   snprintf (peer, slen, "Peer-%s%s%s%s%s%s%s", dstbuf, srcaddr ? "/" : "",
3644 	    srcaddr ? srcbuf : "", srcid ? "-" : "", srcid ? srcid : "",
3645 	    dstid ? (srcid ? "/" : "-/") : "", dstid ? dstid : "");
3646 
3647   /*
3648    * Set the IPsec connection section. Refcount is set to 2, because
3649    * it will be linked both to the incoming and the outgoing SA.
3650    */
3651   af = conf_begin ();
3652   if (conf_set (af, conn, "Phase", "2", 0, 0)
3653       || conf_set (af, conn, "Flags", "__ondemand", 0 , 0)
3654       || conf_set (af, conn, "Refcount", "2", 0 , 0)
3655       || conf_set (af, conn, "ISAKMP-peer", peer, 0, 0))
3656     {
3657       conf_end (af, 0);
3658       goto fail;
3659     }
3660 
3661   /* Set the sequence number. */
3662   snprintf (lname, sizeof lname, "%u", msg->sadb_msg_seq);
3663   if (conf_set (af, conn, "Acquire-ID", lname, 0, 0))
3664     {
3665       conf_end (af, 0);
3666       goto fail;
3667     }
3668 
3669   /* Set Phase 2 IDs -- this is the Local-ID section. */
3670   snprintf (lname, sizeof lname, "Phase2-ID:%s/%s/%u/%u", ssflow, ssmask,
3671 	    tproto, sport);
3672   if (conf_set (af, conn, "Local-ID", lname, 0, 0))
3673     {
3674       conf_end (af, 0);
3675       goto fail;
3676     }
3677 
3678   if (!conf_get_str (lname, "ID-type"))
3679     {
3680       if (conf_set (af, lname, "Refcount", "1", 0, 0))
3681 	{
3682 	  conf_end (af, 0);
3683 	  goto fail;
3684 	}
3685 
3686       if (shostflag)
3687         {
3688 	  if (conf_set (af, lname, "ID-type", sidtype, 0, 0)
3689 	      || conf_set (af, lname, "Address", ssflow, 0, 0))
3690 	    {
3691 	      conf_end (af, 0);
3692 	      goto fail;
3693 	    }
3694 	}
3695       else
3696         {
3697 	  if (conf_set (af, lname, "ID-type", sidtype, 0, 0)
3698 	      || conf_set (af, lname, "Network", ssflow, 0, 0)
3699 	      || conf_set (af, lname, "Netmask", ssmask, 0, 0))
3700 	    {
3701 	      conf_end (af, 0);
3702 	      goto fail;
3703 	    }
3704 	}
3705       if (tproto)
3706         {
3707 	  snprintf (tmbuf, sizeof sport * 3 + 1, "%u", tproto);
3708 	  if (conf_set (af, lname, "Protocol", tmbuf, 0, 0))
3709 	    {
3710 	      conf_end (af, 0);
3711 	      goto fail;
3712 	    }
3713 
3714 	  if (sport)
3715 	    {
3716 	      snprintf (tmbuf, sizeof sport * 3 + 1, "%u", ntohs (sport));
3717 	      if (conf_set (af, lname, "Port", tmbuf, 0, 0))
3718 	        {
3719 		  conf_end (af, 0);
3720 		  goto fail;
3721 		}
3722 	    }
3723 	}
3724     }
3725   else
3726     pf_key_v2_conf_refinc (af, lname);
3727 
3728   /* Set Remote-ID section. */
3729   snprintf (dname, sizeof dname, "Phase2-ID:%s/%s/%u/%u", sdflow, sdmask,
3730 	    tproto, dport);
3731   if (conf_set (af, conn, "Remote-ID", dname, 0, 0))
3732     {
3733       conf_end (af, 0);
3734       goto fail;
3735     }
3736 
3737   if (!conf_get_str (dname, "ID-type"))
3738     {
3739       if (conf_set (af, dname, "Refcount", "1", 0, 0))
3740 	{
3741 	  conf_end (af, 0);
3742 	  goto fail;
3743 	}
3744 
3745       if (dhostflag)
3746         {
3747 	  if (conf_set (af, dname, "ID-type", didtype, 0, 0)
3748 	      || conf_set (af, dname, "Address", sdflow, 0, 0))
3749 	    {
3750 	      conf_end (af, 0);
3751 	      goto fail;
3752 	    }
3753 	}
3754       else
3755         {
3756 	  if (conf_set (af, dname, "ID-type", didtype, 0, 0)
3757 	      || conf_set (af, dname, "Network", sdflow, 0, 0)
3758 	      || conf_set (af, dname, "Netmask", sdmask, 0, 0))
3759 	    {
3760 	      conf_end (af, 0);
3761 	      goto fail;
3762 	    }
3763 	}
3764 
3765       if (tproto)
3766         {
3767 	  snprintf (tmbuf, sizeof dport * 3 + 1, "%u", tproto);
3768 	  if (conf_set (af, dname, "Protocol", tmbuf, 0, 0))
3769 	    {
3770 	      conf_end (af, 0);
3771 	      goto fail;
3772 	    }
3773 
3774 	  if (dport)
3775 	    {
3776 	      snprintf (tmbuf, sizeof dport * 3 + 1, "%u", ntohs (dport));
3777 	      if (conf_set (af, dname, "Port", tmbuf, 0, 0))
3778 	        {
3779 		  conf_end (af, 0);
3780 		  goto fail;
3781 		}
3782 	    }
3783 	}
3784     }
3785   else
3786     pf_key_v2_conf_refinc (af, dname);
3787 
3788   /*
3789    * XXX
3790    * We should be using information from the proposal to set this up.
3791    * At least, we should make this selectable.
3792    */
3793 
3794   /* Phase 2 configuration. */
3795   if (conf_set (af, conn, "Configuration", configname, 0, 0))
3796     {
3797       conf_end (af, 0);
3798       goto fail;
3799     }
3800 
3801   if (conf_set (af, configname, "Exchange_type", "Quick_mode", 0, 0)
3802       || conf_set (af, configname, "DOI", "IPSEC", 0, 0))
3803     {
3804       conf_end (af, 0);
3805       goto fail;
3806     }
3807 
3808   if (conf_get_str ("General", "Default-phase-2-suites"))
3809     {
3810       if (conf_set (af, configname, "Suites",
3811 		    conf_get_str ("General", "Default-phase-2-suites"), 0, 0))
3812         {
3813 	  conf_end (af, 0);
3814 	  goto fail;
3815 	}
3816     }
3817   else
3818     {
3819       if (conf_set (af, configname, "Suites",
3820 		    "QM-ESP-3DES-SHA-PFS-SUITE", 0, 0))
3821         {
3822 	  conf_end (af, 0);
3823 	  goto fail;
3824 	}
3825     }
3826 
3827   /* Set the ISAKMP-peer section. */
3828   if (!conf_get_str (peer, "Phase"))
3829     {
3830       if (conf_set (af, peer, "Phase", "1", 0, 0)
3831 	  || conf_set (af, peer, "Refcount", "1", 0, 0)
3832 	  || conf_set (af, peer, "Address", dstbuf, 0, 0))
3833         {
3834 	  conf_end (af, 0);
3835 	  goto fail;
3836         }
3837 
3838       if (srcaddr && conf_set (af, peer, "Local-address", srcbuf, 0, 0))
3839 	{
3840 	  conf_end (af, 0);
3841 	  goto fail;
3842 	}
3843 
3844       snprintf (confname, sizeof confname, "ISAKMP-Configuration-%s", peer);
3845       if (conf_set (af, peer, "Configuration", confname, 0, 0))
3846         {
3847 	  conf_end (af, 0);
3848 	  goto fail;
3849 	}
3850 
3851 #if defined (SADB_X_CREDTYPE_NONE)
3852       /* Store any credentials passed to us. */
3853       if (cred)
3854 	{
3855 	  struct cert_handler *handler = 0;
3856 	  void *cert;
3857 	  char num[12], *certprint;
3858 
3859 	  /* Convert to bytes in-place. */
3860 	  cred->sadb_x_cred_len *= PF_KEY_V2_CHUNK;
3861 
3862 	  if (cred->sadb_x_cred_len <= sizeof *cred)
3863 	    {
3864 	      log_print ("pf_key_v2_acquire: zero-length credentials, "
3865 			 "aborting SA acquisition");
3866 	      conf_end (af, 0);
3867 	      goto fail;
3868 	    }
3869 
3870 	  switch (cred->sadb_x_cred_type)
3871 	    {
3872 	    case SADB_X_CREDTYPE_X509:
3873 	      snprintf (num, sizeof num, "%d", ISAKMP_CERTENC_X509_SIG);
3874 	      handler = cert_get (ISAKMP_CERTENC_X509_SIG);
3875 	      break;
3876 	    case SADB_X_CREDTYPE_KEYNOTE:
3877 	      snprintf (num, sizeof num, "%d", ISAKMP_CERTENC_KEYNOTE);
3878 	      handler = cert_get (ISAKMP_CERTENC_KEYNOTE);
3879 	      break;
3880 	    default:
3881 	      log_print ("pf_key_v2_acquire: unknown credential type %d",
3882 			 cred->sadb_x_cred_type);
3883 	      conf_end (af, 0);
3884 	      goto fail;
3885 	    }
3886 
3887 	  if (!handler)
3888 	    {
3889 	      log_print ("pf_key_v2_acquire: cert_get (%s) failed", num);
3890 	      conf_end (af, 0);
3891 	      goto fail;
3892 	    }
3893 
3894 	  /* Set the credential type as a number. */
3895 	  if (conf_set (af, peer, "Credential_type", num, 0, 0))
3896 	    {
3897 	      conf_end (af, 0);
3898 	      goto fail;
3899 	    }
3900 
3901 	  /* Get the certificate. */
3902 	  cert = handler->cert_get ((u_int8_t *)(cred + 1),
3903 				    cred->sadb_x_cred_len - sizeof *cred);
3904 
3905 	  /* Now convert to printable format. */
3906 	  certprint = handler->cert_printable (cert);
3907 	  handler->cert_free (cert);
3908 	  if (!certprint
3909 	      || conf_set (af, peer, "Credentials", certprint, 0, 0))
3910 	    {
3911 	      if (certprint)
3912 		free (certprint);
3913 	      conf_end (af, 0);
3914 	      goto fail;
3915 	    }
3916 	  free (certprint);
3917 	}
3918 #endif /* SADB_X_CREDTYPE_NONE */
3919 
3920       /* Phase 1 configuration. */
3921       if (!conf_get_str (confname, "exchange_type"))
3922         {
3923 #if defined (SADB_X_EXT_LOCAL_AUTH)
3924 	  /* We may have been provided with authentication material. */
3925 	  if (sauth)
3926 	    {
3927 	      char *authm;
3928 
3929 	      /* Convert to bytes in-place. */
3930 	      sauth->sadb_x_cred_len *= PF_KEY_V2_CHUNK;
3931 
3932 	      switch (sauth->sadb_x_cred_type)
3933 		{
3934 		case SADB_X_AUTHTYPE_PASSPHRASE:
3935 		  if (conf_set (af, confname, "Transforms", "3DES-SHA", 0, 0))
3936 		    {
3937 		      conf_end (af, 0);
3938 		      goto fail;
3939 		    }
3940 
3941 		  if (sauth->sadb_x_cred_len <= sizeof *sauth)
3942 		    {
3943 		      log_print ("pf_key_v2_acquire: zero-length passphrase, "
3944 				 "aborting SA acquisition");
3945 		      conf_end (af, 0);
3946 		      goto fail;
3947 		    }
3948 
3949 		  authm = malloc (sauth->sadb_x_cred_len - sizeof *sauth + 1);
3950 		  if (!authm)
3951 		    {
3952 		      log_error ("pf_key_v2_acquire: malloc (%lu) failed",
3953 				 sauth->sadb_x_cred_len -
3954 				 (unsigned long)sizeof *sauth + 1);
3955 		      conf_end (af, 0);
3956 		      goto fail;
3957 		    }
3958 		  memcpy (authm, sauth + 1,
3959 			  sauth->sadb_x_cred_len - sizeof *sauth + 1);
3960 
3961 		  /* Set the passphrase in the peer. */
3962 		  if (conf_set (af, peer, "Authentication", authm, 0, 0))
3963 		    {
3964 		      free (authm);
3965 		      conf_end (af, 0);
3966 		      goto fail;
3967 		    }
3968 		  free (authm);
3969 		  break;
3970 
3971 		case SADB_X_AUTHTYPE_RSA:
3972 		  if (conf_set (af, confname, "Transforms", "3DES-SHA-RSA_SIG",
3973 				0, 0))
3974 		    {
3975 		      conf_end (af, 0);
3976 		      goto fail;
3977 		    }
3978 
3979 		  if (sauth->sadb_x_cred_len <= sizeof *sauth)
3980 		    {
3981 		      log_print ("pf_key_v2_acquire: zero-length RSA key, "
3982 				 "aborting SA acquisition");
3983 		      conf_end (af, 0);
3984 		      goto fail;
3985 		    }
3986 
3987 		  authm = key_printable (ISAKMP_KEY_RSA,
3988 					 ISAKMP_KEYTYPE_PRIVATE,
3989 					 (u_int8_t *) sauth + 1,
3990 					 sauth->sadb_x_cred_len
3991 					 - sizeof *sauth);
3992 		  if (!authm)
3993 		    {
3994 		      log_print ("pf_key_v2_acquire: failed to convert "
3995 				 "private key to printable format (size %lu)",
3996 				 sauth->sadb_x_cred_len -
3997 				 (unsigned long)sizeof *sauth);
3998 		      conf_end (af, 0);
3999 		      goto fail;
4000 		    }
4001 
4002 		  /*
4003 		   * Set the key in the peer. We don't use "Authentication"
4004 		   * to avoid potential conflicts with file-based
4005 		   * configurations that use public key authentication
4006 		   * but still specify an "Authentication" tag (typically
4007 		   * as a remnant of passphrase-based testing).
4008 		   */
4009 		  if (conf_set (af, peer, "PKAuthentication", authm, 0, 0))
4010 		    {
4011 		      free (authm);
4012 		      conf_end (af, 0);
4013 		      goto fail;
4014 		    }
4015 		  free (authm);
4016 		  break;
4017 
4018 		default:
4019 		  log_print ("pf_key_v2_acquire: unknown authentication "
4020 			     "material type %d received from kernel",
4021 			     sauth->sadb_x_cred_type);
4022 		  conf_end (af, 0);
4023 		  goto fail;
4024 		}
4025 	    }
4026 	  else /* Fall through */
4027 #endif /* SADB_X_EXT_LOCAL_AUTH */
4028 	  {
4029 	    xform = conf_get_str ("Default-phase-1-configuration",
4030 				  "Transforms");
4031 	    if (conf_set (af, confname, "Transforms",
4032 			  xform ? xform : "3DES-SHA-RSA_SIG", 0, 0))
4033 	      {
4034 		conf_end (af, 0);
4035 		goto fail;
4036 	      }
4037 	  }
4038 
4039 	  if (conf_set (af, confname, "Exchange_Type", "ID_PROT", 0, 0)
4040 	      || conf_set (af, confname, "DOI", "IPSEC", 0, 0)
4041 	      || conf_set (af, confname, "Refcount", "1", 0, 0))
4042 	    {
4043 	      conf_end (af, 0);
4044 	      goto fail;
4045 	    }
4046 	}
4047       else
4048 	pf_key_v2_conf_refinc (af, confname);
4049 
4050       /* The ID we should use in Phase 1. */
4051       if (srcid && conf_set (af, peer, "ID", srcid, 0, 0))
4052 	  {
4053 	    conf_end (af, 0);
4054 	    goto fail;
4055 	  }
4056 
4057       /* The ID the other side should use in Phase 1. */
4058       if (dstid && conf_set (af, peer, "Remote-ID", dstid, 0, 0))
4059 	{
4060 	  conf_end (af, 0);
4061 	  goto fail;
4062 	}
4063     }
4064   else
4065     pf_key_v2_conf_refinc (af, peer);
4066 
4067   /* All done. */
4068   conf_end (af, 1);
4069 
4070   /* Let's rock 'n roll. */
4071   pf_key_v2_connection_check (conn);
4072   conn = 0;
4073 
4074   /* Fall-through to cleanup. */
4075  fail:
4076   if (ret)
4077     pf_key_v2_msg_free (ret);
4078   if (askpolicy)
4079     pf_key_v2_msg_free (askpolicy);
4080   if (srcid)
4081     free (srcid);
4082   if (dstid)
4083     free (dstid);
4084   if (peer)
4085     free (peer);
4086   if (conn)
4087     free (conn);
4088   return;
4089 #else
4090   /* acquire not supported */
4091   return;
4092 #endif /* SADB_X_ASKPOLICY */
4093 }
4094 
4095 static void
4096 pf_key_v2_notify (struct pf_key_v2_msg *msg)
4097 {
4098   switch (((struct sadb_msg *)TAILQ_FIRST (msg)->seg)->sadb_msg_type)
4099     {
4100     case SADB_EXPIRE:
4101       pf_key_v2_expire (msg);
4102       break;
4103 
4104     case SADB_ACQUIRE:
4105       pf_key_v2_acquire (msg);
4106       break;
4107 
4108     default:
4109       log_print ("pf_key_v2_notify: unexpected message type (%d)",
4110 		 ((struct sadb_msg *)TAILQ_FIRST (msg)->seg)->sadb_msg_type);
4111     }
4112   pf_key_v2_msg_free (msg);
4113 }
4114 
4115 void
4116 pf_key_v2_handler (int fd)
4117 {
4118   struct pf_key_v2_msg *msg;
4119 #if !defined (LINUX_IPSEC)
4120   int n;
4121 
4122   /*
4123    * As synchronous read/writes to the socket can have taken place between
4124    * the select(2) call of the main loop and this handler, we need to recheck
4125    * the readability.
4126    */
4127   if (ioctl (pf_key_v2_socket, FIONREAD, &n) == -1)
4128     {
4129       log_error ("pf_key_v2_handler: ioctl (%d, FIONREAD, &n) failed",
4130 		 pf_key_v2_socket);
4131       return;
4132     }
4133   if (!n)
4134     return;
4135 #endif /* LINUX_IPSEC */
4136 
4137   msg = pf_key_v2_read (0);
4138   if (msg)
4139     pf_key_v2_notify (msg);
4140 }
4141 
4142 /*
4143  * Group 2 IPsec SAs given by the PROTO1 and PROTO2 protocols of the SA IKE
4144  * security association in a chain.
4145  * XXX Assumes OpenBSD GRPSPIS extension.  Should probably be moved to sysdep.c
4146  */
4147 int
4148 pf_key_v2_group_spis (struct sa *sa, struct proto *proto1,
4149 		      struct proto *proto2, int incoming)
4150 {
4151 #if defined (SADB_X_GRPSPIS)
4152   struct sadb_msg msg;
4153   struct sadb_sa sa1, sa2;
4154   struct sadb_address *addr = 0;
4155   struct sadb_protocol protocol;
4156   struct pf_key_v2_msg *grpspis = 0, *ret = 0;
4157   struct sockaddr *saddr;
4158   int err;
4159   size_t len;
4160 #ifdef KAME
4161   struct sadb_x_sa2 kamesa2;
4162 #endif
4163 
4164   msg.sadb_msg_type = SADB_X_GRPSPIS;
4165   switch (proto1->proto)
4166     {
4167     case IPSEC_PROTO_IPSEC_ESP:
4168       msg.sadb_msg_satype = SADB_SATYPE_ESP;
4169       break;
4170     case IPSEC_PROTO_IPSEC_AH:
4171       msg.sadb_msg_satype = SADB_SATYPE_AH;
4172       break;
4173 #if defined (SADB_X_SATYPE_IPCOMP)
4174     case IPSEC_PROTO_IPCOMP:
4175       msg.sadb_msg_satype = SADB_X_SATYPE_IPCOMP;
4176       break;
4177 #endif
4178     default:
4179       log_print ("pf_key_v2_group_spis: invalid proto %d", proto1->proto);
4180       goto cleanup;
4181     }
4182   msg.sadb_msg_seq = 0;
4183   grpspis = pf_key_v2_msg_new (&msg, 0);
4184   if (!grpspis)
4185     goto cleanup;
4186 
4187   /* Setup the SA extensions.  */
4188   sa1.sadb_sa_exttype = SADB_EXT_SA;
4189   sa1.sadb_sa_len = sizeof sa1 / PF_KEY_V2_CHUNK;
4190   memcpy (&sa1.sadb_sa_spi, proto1->spi[incoming], sizeof sa1.sadb_sa_spi);
4191   sa1.sadb_sa_replay = 0;
4192   sa1.sadb_sa_state = 0;
4193   sa1.sadb_sa_auth = 0;
4194   sa1.sadb_sa_encrypt = 0;
4195   sa1.sadb_sa_flags = 0;
4196   if (pf_key_v2_msg_add (grpspis, (struct sadb_ext *)&sa1, 0) == -1)
4197     goto cleanup;
4198 
4199 #ifndef KAME
4200   sa2.sadb_sa_exttype = SADB_X_EXT_SA2;
4201   sa2.sadb_sa_len = sizeof sa2 / PF_KEY_V2_CHUNK;
4202   memcpy (&sa2.sadb_sa_spi, proto2->spi[incoming], sizeof sa2.sadb_sa_spi);
4203   sa2.sadb_sa_replay = 0;
4204   sa2.sadb_sa_state = 0;
4205   sa2.sadb_sa_auth = 0;
4206   sa2.sadb_sa_encrypt = 0;
4207   sa2.sadb_sa_flags = 0;
4208   if (pf_key_v2_msg_add (grpspis, (struct sadb_ext *)&sa2, 0) == -1)
4209     goto cleanup;
4210 #else
4211   memset (&kamesa2, 0, sizeof kamesa2);
4212   kamesa2.sadb_x_sa2_exttype = SADB_X_EXT_SA2;
4213   kamesa2.sadb_x_sa2_len = sizeof kamesa2 / PF_KEY_V2_CHUNK;
4214   kamesa2.sadb_x_sa2_mode = 0;
4215   if (pf_key_v2_msg_add (grpspis, (struct sadb_ext *)&kamesa2, 0) == -1)
4216     goto cleanup;
4217 #endif
4218 
4219   /*
4220    * Setup the ADDRESS extensions.
4221    */
4222   if (incoming)
4223     sa->transport->vtbl->get_src (sa->transport, &saddr);
4224   else
4225     sa->transport->vtbl->get_dst (sa->transport, &saddr);
4226   len = sizeof *addr + PF_KEY_V2_ROUND (sysdep_sa_len (saddr));
4227   addr = calloc (1, len);
4228   if (!addr)
4229     goto cleanup;
4230   addr->sadb_address_exttype = SADB_EXT_ADDRESS_DST;
4231   addr->sadb_address_len = len / PF_KEY_V2_CHUNK;
4232 #ifndef __OpenBSD__
4233   addr->sadb_address_proto = 0;
4234   addr->sadb_address_prefixlen = 0;
4235 #endif
4236   addr->sadb_address_reserved = 0;
4237   memcpy (addr + 1, saddr, sysdep_sa_len (saddr));
4238   ((struct sockaddr_in *)(addr + 1))->sin_port = 0;
4239   if (pf_key_v2_msg_add (grpspis, (struct sadb_ext *)addr,
4240 			 PF_KEY_V2_NODE_MALLOCED) == -1)
4241     goto cleanup;
4242   addr = 0;
4243 
4244   addr = calloc (1, len);
4245   if (!addr)
4246     goto cleanup;
4247   addr->sadb_address_exttype = SADB_X_EXT_DST2;
4248   addr->sadb_address_len = len / PF_KEY_V2_CHUNK;
4249 #ifndef __OpenBSD__
4250   addr->sadb_address_proto = 0;
4251   addr->sadb_address_prefixlen = 0;
4252 #endif
4253   addr->sadb_address_reserved = 0;
4254   memcpy (addr + 1, saddr, sysdep_sa_len (saddr));
4255   ((struct sockaddr_in *)(addr + 1))->sin_port = 0;
4256   if (pf_key_v2_msg_add (grpspis, (struct sadb_ext *)addr,
4257 			 PF_KEY_V2_NODE_MALLOCED) == -1)
4258     goto cleanup;
4259   addr = 0;
4260 
4261   /* Setup the PROTOCOL extension.  */
4262   protocol.sadb_protocol_exttype = SADB_X_EXT_PROTOCOL;
4263   protocol.sadb_protocol_len = sizeof protocol / PF_KEY_V2_CHUNK;
4264   switch (proto2->proto)
4265     {
4266     case IPSEC_PROTO_IPSEC_ESP:
4267       protocol.sadb_protocol_proto = SADB_SATYPE_ESP;
4268       break;
4269     case IPSEC_PROTO_IPSEC_AH:
4270       protocol.sadb_protocol_proto = SADB_SATYPE_AH;
4271       break;
4272 #if defined (SADB_X_SATYPE_IPCOMP)
4273     case IPSEC_PROTO_IPCOMP:
4274       protocol.sadb_protocol_proto = SADB_X_SATYPE_IPCOMP;
4275       break;
4276 #endif
4277     default:
4278       log_print ("pf_key_v2_group_spis: invalid proto %d", proto2->proto);
4279       goto cleanup;
4280     }
4281   protocol.sadb_protocol_reserved2 = 0;
4282   if (pf_key_v2_msg_add (grpspis, (struct sadb_ext *)&protocol, 0) == -1)
4283     goto cleanup;
4284 
4285   ret = pf_key_v2_call (grpspis);
4286   pf_key_v2_msg_free (grpspis);
4287   grpspis = 0;
4288   if (!ret)
4289     goto cleanup;
4290   err = ((struct sadb_msg *)TAILQ_FIRST (ret)->seg)->sadb_msg_errno;
4291   if (err)
4292     {
4293       log_print ("pf_key_v2_group_spis: GRPSPIS: %s", strerror (err));
4294       goto cleanup;
4295     }
4296   pf_key_v2_msg_free (ret);
4297 
4298   LOG_DBG ((LOG_SYSDEP, 50, "pf_key_v2_group_spis: done"));
4299 
4300   return 0;
4301 
4302  cleanup:
4303   if (addr)
4304      free (addr);
4305   if (grpspis)
4306     pf_key_v2_msg_free (grpspis);
4307   if (ret)
4308     pf_key_v2_msg_free (ret);
4309   return -1;
4310 
4311 #else /* SADB_X_GRPSPIS */
4312   log_print ("pf_key_v2_group_spis: not supported in pure PF_KEYv2");
4313   return -1;
4314 #endif
4315 }
4316