xref: /netbsd-src/crypto/dist/ipsec-tools/src/racoon/pfkey.c (revision 6a1508dad3515842aa76bf5ec8fc2daab5f5af02)
1 /*	$NetBSD: pfkey.c,v 1.45 2009/01/23 08:32:58 tteras Exp $	*/
2 
3 /* $Id: pfkey.c,v 1.45 2009/01/23 08:32:58 tteras Exp $ */
4 
5 /*
6  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
7  * 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  * 3. Neither the name of the project nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33 
34 #include "config.h"
35 
36 #include <stdlib.h>
37 #include <string.h>
38 #include <stdio.h>
39 #include <netdb.h>
40 #include <errno.h>
41 #ifdef HAVE_UNISTD_H
42 #include <unistd.h>
43 #endif
44 #include <netdb.h>
45 #include <netinet/in.h>
46 #include <arpa/inet.h>
47 
48 #ifdef ENABLE_NATT
49 # ifdef __linux__
50 #  include <linux/udp.h>
51 # endif
52 # if defined(__NetBSD__) || defined(__FreeBSD__) ||	\
53   (defined(__APPLE__) && defined(__MACH__))
54 #  include <netinet/udp.h>
55 # endif
56 #endif
57 
58 #include <sys/types.h>
59 #include <sys/param.h>
60 #include <sys/socket.h>
61 #include <sys/queue.h>
62 #include <sys/sysctl.h>
63 
64 #include <net/route.h>
65 #include <net/pfkeyv2.h>
66 
67 #include <netinet/in.h>
68 #include PATH_IPSEC_H
69 #include <fcntl.h>
70 
71 #include "libpfkey.h"
72 
73 #include "var.h"
74 #include "misc.h"
75 #include "vmbuf.h"
76 #include "plog.h"
77 #include "sockmisc.h"
78 #include "session.h"
79 #include "debug.h"
80 
81 #include "schedule.h"
82 #include "localconf.h"
83 #include "remoteconf.h"
84 #include "handler.h"
85 #include "policy.h"
86 #include "proposal.h"
87 #include "isakmp_var.h"
88 #include "isakmp.h"
89 #include "isakmp_inf.h"
90 #include "ipsec_doi.h"
91 #include "oakley.h"
92 #include "pfkey.h"
93 #include "algorithm.h"
94 #include "sainfo.h"
95 #include "admin.h"
96 #include "evt.h"
97 #include "privsep.h"
98 #include "strnames.h"
99 #include "backupsa.h"
100 #include "gcmalloc.h"
101 #include "nattraversal.h"
102 #include "crypto_openssl.h"
103 #include "grabmyaddr.h"
104 
105 #if defined(SADB_X_EALG_RIJNDAELCBC) && !defined(SADB_X_EALG_AESCBC)
106 #define SADB_X_EALG_AESCBC  SADB_X_EALG_RIJNDAELCBC
107 #endif
108 
109 /* prototype */
110 static u_int ipsecdoi2pfkey_aalg __P((u_int));
111 static u_int ipsecdoi2pfkey_ealg __P((u_int));
112 static u_int ipsecdoi2pfkey_calg __P((u_int));
113 static u_int ipsecdoi2pfkey_alg __P((u_int, u_int));
114 static u_int keylen_aalg __P((u_int));
115 static u_int keylen_ealg __P((u_int, int));
116 
117 static int pk_recvgetspi __P((caddr_t *));
118 static int pk_recvupdate __P((caddr_t *));
119 static int pk_recvadd __P((caddr_t *));
120 static int pk_recvdelete __P((caddr_t *));
121 static int pk_recvacquire __P((caddr_t *));
122 static int pk_recvexpire __P((caddr_t *));
123 static int pk_recvflush __P((caddr_t *));
124 static int getsadbpolicy __P((caddr_t *, int *, int, struct ph2handle *));
125 static int pk_recvspdupdate __P((caddr_t *));
126 static int pk_recvspdadd __P((caddr_t *));
127 static int pk_recvspddelete __P((caddr_t *));
128 static int pk_recvspdexpire __P((caddr_t *));
129 static int pk_recvspdget __P((caddr_t *));
130 static int pk_recvspddump __P((caddr_t *));
131 static int pk_recvspdflush __P((caddr_t *));
132 #if defined(SADB_X_MIGRATE) && defined(SADB_X_EXT_KMADDRESS)
133 static int pk_recvmigrate __P((caddr_t *));
134 #endif
135 static struct sadb_msg *pk_recv __P((int, int *));
136 
137 static int (*pkrecvf[]) __P((caddr_t *)) = {
138 NULL,
139 pk_recvgetspi,
140 pk_recvupdate,
141 pk_recvadd,
142 pk_recvdelete,
143 NULL,	/* SADB_GET */
144 pk_recvacquire,
145 NULL,	/* SABD_REGISTER */
146 pk_recvexpire,
147 pk_recvflush,
148 NULL,	/* SADB_DUMP */
149 NULL,	/* SADB_X_PROMISC */
150 NULL,	/* SADB_X_PCHANGE */
151 pk_recvspdupdate,
152 pk_recvspdadd,
153 pk_recvspddelete,
154 pk_recvspdget,
155 NULL,	/* SADB_X_SPDACQUIRE */
156 pk_recvspddump,
157 pk_recvspdflush,
158 NULL,	/* SADB_X_SPDSETIDX */
159 pk_recvspdexpire,
160 NULL,	/* SADB_X_SPDDELETE2 */
161 NULL,	/* SADB_X_NAT_T_NEW_MAPPING */
162 #if defined(SADB_X_MIGRATE) && defined(SADB_X_EXT_KMADDRESS)
163 pk_recvmigrate,
164 #else
165 NULL,	/* SADB_X_MIGRATE */
166 #endif
167 #if (SADB_MAX > 24)
168 #error "SADB extra message?"
169 #endif
170 };
171 
172 static int addnewsp __P((caddr_t *, struct sockaddr *, struct sockaddr *));
173 
174 /* cope with old kame headers - ugly */
175 #ifndef SADB_X_AALG_MD5
176 #define SADB_X_AALG_MD5		SADB_AALG_MD5
177 #endif
178 #ifndef SADB_X_AALG_SHA
179 #define SADB_X_AALG_SHA		SADB_AALG_SHA
180 #endif
181 #ifndef SADB_X_AALG_NULL
182 #define SADB_X_AALG_NULL	SADB_AALG_NULL
183 #endif
184 
185 #ifndef SADB_X_EALG_BLOWFISHCBC
186 #define SADB_X_EALG_BLOWFISHCBC	SADB_EALG_BLOWFISHCBC
187 #endif
188 #ifndef SADB_X_EALG_CAST128CBC
189 #define SADB_X_EALG_CAST128CBC	SADB_EALG_CAST128CBC
190 #endif
191 #ifndef SADB_X_EALG_RC5CBC
192 #ifdef SADB_EALG_RC5CBC
193 #define SADB_X_EALG_RC5CBC	SADB_EALG_RC5CBC
194 #endif
195 #endif
196 
197 /*
198  * PF_KEY packet handler
199  *	0: success
200  *	-1: fail
201  */
202 static int
203 pfkey_handler(ctx, fd)
204 	void *ctx;
205 	int fd;
206 {
207 	struct sadb_msg *msg;
208 	int len;
209 	caddr_t mhp[SADB_EXT_MAX + 1];
210 	int error = -1;
211 
212 	/* receive pfkey message. */
213 	len = 0;
214 	msg = (struct sadb_msg *) pk_recv(fd, &len);
215 	if (msg == NULL) {
216 		if (len < 0) {
217 			plog(LLV_ERROR, LOCATION, NULL,
218 				"failed to recv from pfkey (%s)\n",
219 				strerror(errno));
220 			goto end;
221 		} else {
222 			/* short message - msg not ready */
223 			return 0;
224 		}
225 	}
226 
227 	plog(LLV_DEBUG, LOCATION, NULL, "get pfkey %s message\n",
228 		s_pfkey_type(msg->sadb_msg_type));
229 	plogdump(LLV_DEBUG2, msg, msg->sadb_msg_len << 3);
230 
231 	/* validity check */
232 	if (msg->sadb_msg_errno) {
233 		int pri;
234 
235 		/* when SPD is empty, treat the state as no error. */
236 		if (msg->sadb_msg_type == SADB_X_SPDDUMP &&
237 		    msg->sadb_msg_errno == ENOENT)
238 			pri = LLV_DEBUG;
239 		else
240 			pri = LLV_ERROR;
241 
242 		plog(pri, LOCATION, NULL,
243 			"pfkey %s failed: %s\n",
244 			s_pfkey_type(msg->sadb_msg_type),
245 			strerror(msg->sadb_msg_errno));
246 
247 		goto end;
248 	}
249 
250 	/* check pfkey message. */
251 	if (pfkey_align(msg, mhp)) {
252 		plog(LLV_ERROR, LOCATION, NULL,
253 			"libipsec failed pfkey align (%s)\n",
254 			ipsec_strerror());
255 		goto end;
256 	}
257 	if (pfkey_check(mhp)) {
258 		plog(LLV_ERROR, LOCATION, NULL,
259 			"libipsec failed pfkey check (%s)\n",
260 			ipsec_strerror());
261 		goto end;
262 	}
263 	msg = (struct sadb_msg *)mhp[0];
264 
265 	/* safety check */
266 	if (msg->sadb_msg_type >= ARRAYLEN(pkrecvf)) {
267 		plog(LLV_ERROR, LOCATION, NULL,
268 			"unknown PF_KEY message type=%u\n",
269 			msg->sadb_msg_type);
270 		goto end;
271 	}
272 
273 	if (pkrecvf[msg->sadb_msg_type] == NULL) {
274 		plog(LLV_INFO, LOCATION, NULL,
275 			"unsupported PF_KEY message %s\n",
276 			s_pfkey_type(msg->sadb_msg_type));
277 		goto end;
278 	}
279 
280 	if ((pkrecvf[msg->sadb_msg_type])(mhp) < 0)
281 		goto end;
282 
283 	error = 1;
284 end:
285 	if (msg)
286 		racoon_free(msg);
287 	return(error);
288 }
289 
290 /*
291  * dump SADB
292  */
293 vchar_t *
294 pfkey_dump_sadb(satype)
295 	int satype;
296 {
297 	int s;
298 	vchar_t *buf = NULL;
299 	pid_t pid = getpid();
300 	struct sadb_msg *msg = NULL;
301 	size_t bl, ml;
302 	int len;
303 	int bufsiz;
304 
305 	if ((s = privsep_socket(PF_KEY, SOCK_RAW, PF_KEY_V2)) < 0) {
306 		plog(LLV_ERROR, LOCATION, NULL,
307 			"libipsec failed pfkey open: %s\n",
308 			ipsec_strerror());
309 		return NULL;
310 	}
311 
312 	if ((bufsiz = pfkey_set_buffer_size(s, lcconf->pfkey_buffer_size)) < 0) {
313 		plog(LLV_ERROR, LOCATION, NULL,
314 		     "libipsec failed pfkey set buffer size to %d: %s\n",
315 		     lcconf->pfkey_buffer_size, ipsec_strerror());
316 		return NULL;
317 	} else if (bufsiz < lcconf->pfkey_buffer_size) {
318 		plog(LLV_WARNING, LOCATION, NULL,
319 		     "pfkey socket receive buffer set to %dKB, instead of %d\n",
320 		     bufsiz, lcconf->pfkey_buffer_size);
321 	}
322 
323 	plog(LLV_DEBUG, LOCATION, NULL, "call pfkey_send_dump\n");
324 	if (pfkey_send_dump(s, satype) < 0) {
325 		plog(LLV_ERROR, LOCATION, NULL,
326 			"libipsec failed dump: %s\n", ipsec_strerror());
327 		goto fail;
328 	}
329 
330 	while (1) {
331 		if (msg)
332 			racoon_free(msg);
333 		msg = pk_recv(s, &len);
334 		if (msg == NULL) {
335 			if (len < 0)
336 				goto done;
337 			else
338 				continue;
339 		}
340 
341 		if (msg->sadb_msg_type != SADB_DUMP || msg->sadb_msg_pid != pid)
342 		{
343 		    plog(LLV_DEBUG, LOCATION, NULL,
344 			 "discarding non-sadb dump msg %p, our pid=%i\n", msg, pid);
345 		    plog(LLV_DEBUG, LOCATION, NULL,
346 			 "type %i, pid %i\n", msg->sadb_msg_type, msg->sadb_msg_pid);
347 		    continue;
348 		}
349 
350 
351 		ml = msg->sadb_msg_len << 3;
352 		bl = buf ? buf->l : 0;
353 		buf = vrealloc(buf, bl + ml);
354 		if (buf == NULL) {
355 			plog(LLV_ERROR, LOCATION, NULL,
356 				"failed to reallocate buffer to dump.\n");
357 			goto fail;
358 		}
359 		memcpy(buf->v + bl, msg, ml);
360 
361 		if (msg->sadb_msg_seq == 0)
362 			break;
363 	}
364 	goto done;
365 
366 fail:
367 	if (buf)
368 		vfree(buf);
369 	buf = NULL;
370 done:
371 	if (msg)
372 		racoon_free(msg);
373 	close(s);
374 	return buf;
375 }
376 
377 #ifdef ENABLE_ADMINPORT
378 /*
379  * flush SADB
380  */
381 void
382 pfkey_flush_sadb(proto)
383 	u_int proto;
384 {
385 	int satype;
386 
387 	/* convert to SADB_SATYPE */
388 	if ((satype = admin2pfkey_proto(proto)) < 0)
389 		return;
390 
391 	plog(LLV_DEBUG, LOCATION, NULL, "call pfkey_send_flush\n");
392 	if (pfkey_send_flush(lcconf->sock_pfkey, satype) < 0) {
393 		plog(LLV_ERROR, LOCATION, NULL,
394 			"libipsec failed send flush (%s)\n", ipsec_strerror());
395 		return;
396 	}
397 
398 	return;
399 }
400 #endif
401 
402 /*
403  * These are the SATYPEs that we manage.  We register to get
404  * PF_KEY messages related to these SATYPEs, and we also use
405  * this list to determine which SATYPEs to delete SAs for when
406  * we receive an INITIAL-CONTACT.
407  */
408 const struct pfkey_satype pfkey_satypes[] = {
409 	{ SADB_SATYPE_AH,	"AH" },
410 	{ SADB_SATYPE_ESP,	"ESP" },
411 	{ SADB_X_SATYPE_IPCOMP,	"IPCOMP" },
412 };
413 const int pfkey_nsatypes =
414     sizeof(pfkey_satypes) / sizeof(pfkey_satypes[0]);
415 
416 /*
417  * PF_KEY initialization
418  */
419 int
420 pfkey_init()
421 {
422 	int i, reg_fail;
423 	int bufsiz;
424 
425 	if ((lcconf->sock_pfkey = pfkey_open()) < 0) {
426 		plog(LLV_ERROR, LOCATION, NULL,
427 			"libipsec failed pfkey open (%s)\n", ipsec_strerror());
428 		return -1;
429 	}
430 	if ((bufsiz = pfkey_set_buffer_size(lcconf->sock_pfkey,
431 					    lcconf->pfkey_buffer_size)) < 0) {
432 		plog(LLV_ERROR, LOCATION, NULL,
433 		     "libipsec failed to set pfkey buffer size to %d (%s)\n",
434 		     lcconf->pfkey_buffer_size, ipsec_strerror());
435 		return -1;
436 	} else if (bufsiz < lcconf->pfkey_buffer_size) {
437 		plog(LLV_WARNING, LOCATION, NULL,
438 		     "pfkey socket receive buffer set to %dKB, instead of %d\n",
439 		     bufsiz, lcconf->pfkey_buffer_size);
440 	}
441 
442 	if (fcntl(lcconf->sock_pfkey, F_SETFL, O_NONBLOCK) == -1)
443 		plog(LLV_WARNING, LOCATION, NULL,
444 		    "failed to set the pfkey socket to NONBLOCK\n");
445 
446 	for (i = 0, reg_fail = 0; i < pfkey_nsatypes; i++) {
447 		plog(LLV_DEBUG, LOCATION, NULL,
448 		    "call pfkey_send_register for %s\n",
449 		    pfkey_satypes[i].ps_name);
450 		if (pfkey_send_register(lcconf->sock_pfkey,
451 					pfkey_satypes[i].ps_satype) < 0 ||
452 		    pfkey_recv_register(lcconf->sock_pfkey) < 0) {
453 			plog(LLV_WARNING, LOCATION, NULL,
454 			    "failed to register %s (%s)\n",
455 			    pfkey_satypes[i].ps_name,
456 			    ipsec_strerror());
457 			reg_fail++;
458 		}
459 	}
460 
461 	if (reg_fail == pfkey_nsatypes) {
462 		plog(LLV_ERROR, LOCATION, NULL,
463 			"failed to regist any protocol.\n");
464 		pfkey_close(lcconf->sock_pfkey);
465 		return -1;
466 	}
467 
468 	initsp();
469 
470 	if (pfkey_send_spddump(lcconf->sock_pfkey) < 0) {
471 		plog(LLV_ERROR, LOCATION, NULL,
472 			"libipsec sending spddump failed: %s\n",
473 			ipsec_strerror());
474 		pfkey_close(lcconf->sock_pfkey);
475 		return -1;
476 	}
477 #if 0
478 	if (pfkey_promisc_toggle(1) < 0) {
479 		pfkey_close(lcconf->sock_pfkey);
480 		return -1;
481 	}
482 #endif
483 	monitor_fd(lcconf->sock_pfkey, pfkey_handler, NULL);
484 	return 0;
485 }
486 
487 int
488 pfkey_reload()
489 {
490 	flushsp();
491 
492 	if (pfkey_send_spddump(lcconf->sock_pfkey) < 0) {
493 		plog(LLV_ERROR, LOCATION, NULL,
494 			"libipsec sending spddump failed: %s\n",
495 			ipsec_strerror());
496 		return -1;
497 	}
498 
499 	while (pfkey_handler(NULL, lcconf->sock_pfkey) > 0)
500 		continue;
501 
502 	return 0;
503 }
504 
505 /* %%% for conversion */
506 /* IPSECDOI_ATTR_AUTH -> SADB_AALG */
507 static u_int
508 ipsecdoi2pfkey_aalg(hashtype)
509 	u_int hashtype;
510 {
511 	switch (hashtype) {
512 	case IPSECDOI_ATTR_AUTH_HMAC_MD5:
513 		return SADB_AALG_MD5HMAC;
514 	case IPSECDOI_ATTR_AUTH_HMAC_SHA1:
515 		return SADB_AALG_SHA1HMAC;
516 	case IPSECDOI_ATTR_AUTH_HMAC_SHA2_256:
517 #if (defined SADB_X_AALG_SHA2_256) && !defined(SADB_X_AALG_SHA2_256HMAC)
518 		return SADB_X_AALG_SHA2_256;
519 #else
520 		return SADB_X_AALG_SHA2_256HMAC;
521 #endif
522 	case IPSECDOI_ATTR_AUTH_HMAC_SHA2_384:
523 #if (defined SADB_X_AALG_SHA2_384) && !defined(SADB_X_AALG_SHA2_384HMAC)
524 		return SADB_X_AALG_SHA2_384;
525 #else
526 		return SADB_X_AALG_SHA2_384HMAC;
527 #endif
528 	case IPSECDOI_ATTR_AUTH_HMAC_SHA2_512:
529 #if (defined SADB_X_AALG_SHA2_512) && !defined(SADB_X_AALG_SHA2_512HMAC)
530 		return SADB_X_AALG_SHA2_512;
531 #else
532 		return SADB_X_AALG_SHA2_512HMAC;
533 #endif
534 	case IPSECDOI_ATTR_AUTH_KPDK:		/* need special care */
535 		return SADB_AALG_NONE;
536 
537 	/* not supported */
538 	case IPSECDOI_ATTR_AUTH_DES_MAC:
539 		plog(LLV_ERROR, LOCATION, NULL,
540 			"Not supported hash type: %u\n", hashtype);
541 		return ~0;
542 
543 	case 0: /* reserved */
544 	default:
545 		return SADB_AALG_NONE;
546 
547 		plog(LLV_ERROR, LOCATION, NULL,
548 			"Invalid hash type: %u\n", hashtype);
549 		return ~0;
550 	}
551 	/*NOTREACHED*/
552 }
553 
554 /* IPSECDOI_ESP -> SADB_EALG */
555 static u_int
556 ipsecdoi2pfkey_ealg(t_id)
557 	u_int t_id;
558 {
559 	switch (t_id) {
560 	case IPSECDOI_ESP_DES_IV64:		/* sa_flags |= SADB_X_EXT_OLD */
561 		return SADB_EALG_DESCBC;
562 	case IPSECDOI_ESP_DES:
563 		return SADB_EALG_DESCBC;
564 	case IPSECDOI_ESP_3DES:
565 		return SADB_EALG_3DESCBC;
566 #ifdef SADB_X_EALG_RC5CBC
567 	case IPSECDOI_ESP_RC5:
568 		return SADB_X_EALG_RC5CBC;
569 #endif
570 	case IPSECDOI_ESP_CAST:
571 		return SADB_X_EALG_CAST128CBC;
572 	case IPSECDOI_ESP_BLOWFISH:
573 		return SADB_X_EALG_BLOWFISHCBC;
574 	case IPSECDOI_ESP_DES_IV32:	/* flags |= (SADB_X_EXT_OLD|
575 							SADB_X_EXT_IV4B)*/
576 		return SADB_EALG_DESCBC;
577 	case IPSECDOI_ESP_NULL:
578 		return SADB_EALG_NULL;
579 #ifdef SADB_X_EALG_AESCBC
580 	case IPSECDOI_ESP_AES:
581 		return SADB_X_EALG_AESCBC;
582 #endif
583 #ifdef SADB_X_EALG_TWOFISHCBC
584 	case IPSECDOI_ESP_TWOFISH:
585 		return SADB_X_EALG_TWOFISHCBC;
586 #endif
587 #ifdef SADB_X_EALG_CAMELLIACBC
588 	case IPSECDOI_ESP_CAMELLIA:
589 		return SADB_X_EALG_CAMELLIACBC;
590 #endif
591 
592 	/* not supported */
593 	case IPSECDOI_ESP_3IDEA:
594 	case IPSECDOI_ESP_IDEA:
595 	case IPSECDOI_ESP_RC4:
596 		plog(LLV_ERROR, LOCATION, NULL,
597 			"Not supported transform: %u\n", t_id);
598 		return ~0;
599 
600 	case 0: /* reserved */
601 	default:
602 		plog(LLV_ERROR, LOCATION, NULL,
603 			"Invalid transform id: %u\n", t_id);
604 		return ~0;
605 	}
606 	/*NOTREACHED*/
607 }
608 
609 /* IPCOMP -> SADB_CALG */
610 static u_int
611 ipsecdoi2pfkey_calg(t_id)
612 	u_int t_id;
613 {
614 	switch (t_id) {
615 	case IPSECDOI_IPCOMP_OUI:
616 		return SADB_X_CALG_OUI;
617 	case IPSECDOI_IPCOMP_DEFLATE:
618 		return SADB_X_CALG_DEFLATE;
619 	case IPSECDOI_IPCOMP_LZS:
620 		return SADB_X_CALG_LZS;
621 
622 	case 0: /* reserved */
623 	default:
624 		plog(LLV_ERROR, LOCATION, NULL,
625 			"Invalid transform id: %u\n", t_id);
626 		return ~0;
627 	}
628 	/*NOTREACHED*/
629 }
630 
631 /* IPSECDOI_PROTO -> SADB_SATYPE */
632 u_int
633 ipsecdoi2pfkey_proto(proto)
634 	u_int proto;
635 {
636 	switch (proto) {
637 	case IPSECDOI_PROTO_IPSEC_AH:
638 		return SADB_SATYPE_AH;
639 	case IPSECDOI_PROTO_IPSEC_ESP:
640 		return SADB_SATYPE_ESP;
641 	case IPSECDOI_PROTO_IPCOMP:
642 		return SADB_X_SATYPE_IPCOMP;
643 
644 	default:
645 		plog(LLV_ERROR, LOCATION, NULL,
646 			"Invalid ipsec_doi proto: %u\n", proto);
647 		return ~0;
648 	}
649 	/*NOTREACHED*/
650 }
651 
652 static u_int
653 ipsecdoi2pfkey_alg(algclass, type)
654 	u_int algclass, type;
655 {
656 	switch (algclass) {
657 	case IPSECDOI_ATTR_AUTH:
658 		return ipsecdoi2pfkey_aalg(type);
659 	case IPSECDOI_PROTO_IPSEC_ESP:
660 		return ipsecdoi2pfkey_ealg(type);
661 	case IPSECDOI_PROTO_IPCOMP:
662 		return ipsecdoi2pfkey_calg(type);
663 	default:
664 		plog(LLV_ERROR, LOCATION, NULL,
665 			"Invalid ipsec_doi algclass: %u\n", algclass);
666 		return ~0;
667 	}
668 	/*NOTREACHED*/
669 }
670 
671 /* SADB_SATYPE -> IPSECDOI_PROTO */
672 u_int
673 pfkey2ipsecdoi_proto(satype)
674 	u_int satype;
675 {
676 	switch (satype) {
677 	case SADB_SATYPE_AH:
678 		return IPSECDOI_PROTO_IPSEC_AH;
679 	case SADB_SATYPE_ESP:
680 		return IPSECDOI_PROTO_IPSEC_ESP;
681 	case SADB_X_SATYPE_IPCOMP:
682 		return IPSECDOI_PROTO_IPCOMP;
683 
684 	default:
685 		plog(LLV_ERROR, LOCATION, NULL,
686 			"Invalid pfkey proto: %u\n", satype);
687 		return ~0;
688 	}
689 	/*NOTREACHED*/
690 }
691 
692 /* IPSECDOI_ATTR_ENC_MODE -> IPSEC_MODE */
693 u_int
694 ipsecdoi2pfkey_mode(mode)
695 	u_int mode;
696 {
697 	switch (mode) {
698 	case IPSECDOI_ATTR_ENC_MODE_TUNNEL:
699 #ifdef ENABLE_NATT
700 	case IPSECDOI_ATTR_ENC_MODE_UDPTUNNEL_RFC:
701 	case IPSECDOI_ATTR_ENC_MODE_UDPTUNNEL_DRAFT:
702 #endif
703 		return IPSEC_MODE_TUNNEL;
704 	case IPSECDOI_ATTR_ENC_MODE_TRNS:
705 #ifdef ENABLE_NATT
706 	case IPSECDOI_ATTR_ENC_MODE_UDPTRNS_RFC:
707 	case IPSECDOI_ATTR_ENC_MODE_UDPTRNS_DRAFT:
708 #endif
709 		return IPSEC_MODE_TRANSPORT;
710 	default:
711 		plog(LLV_ERROR, LOCATION, NULL, "Invalid mode type: %u\n", mode);
712 		return ~0;
713 	}
714 	/*NOTREACHED*/
715 }
716 
717 /* IPSECDOI_ATTR_ENC_MODE -> IPSEC_MODE */
718 u_int
719 pfkey2ipsecdoi_mode(mode)
720 	u_int mode;
721 {
722 	switch (mode) {
723 	case IPSEC_MODE_TUNNEL:
724 		return IPSECDOI_ATTR_ENC_MODE_TUNNEL;
725 	case IPSEC_MODE_TRANSPORT:
726 		return IPSECDOI_ATTR_ENC_MODE_TRNS;
727 	case IPSEC_MODE_ANY:
728 		return IPSECDOI_ATTR_ENC_MODE_ANY;
729 	default:
730 		plog(LLV_ERROR, LOCATION, NULL, "Invalid mode type: %u\n", mode);
731 		return ~0;
732 	}
733 	/*NOTREACHED*/
734 }
735 
736 /* default key length for encryption algorithm */
737 static u_int
738 keylen_aalg(hashtype)
739 	u_int hashtype;
740 {
741 	int res;
742 
743 	if (hashtype == 0)
744 		return SADB_AALG_NONE;
745 
746 	res = alg_ipsec_hmacdef_hashlen(hashtype);
747 	if (res == -1) {
748 		plog(LLV_ERROR, LOCATION, NULL,
749 			"invalid hmac algorithm %u.\n", hashtype);
750 		return ~0;
751 	}
752 	return res;
753 }
754 
755 /* default key length for encryption algorithm */
756 static u_int
757 keylen_ealg(enctype, encklen)
758 	u_int enctype;
759 	int encklen;
760 {
761 	int res;
762 
763 	res = alg_ipsec_encdef_keylen(enctype, encklen);
764 	if (res == -1) {
765 		plog(LLV_ERROR, LOCATION, NULL,
766 			"invalid encryption algorithm %u.\n", enctype);
767 		return ~0;
768 	}
769 	return res;
770 }
771 
772 int
773 pfkey_convertfromipsecdoi(proto_id, t_id, hashtype,
774 		e_type, e_keylen, a_type, a_keylen, flags)
775 	u_int proto_id;
776 	u_int t_id;
777 	u_int hashtype;
778 	u_int *e_type;
779 	u_int *e_keylen;
780 	u_int *a_type;
781 	u_int *a_keylen;
782 	u_int *flags;
783 {
784 	*flags = 0;
785 	switch (proto_id) {
786 	case IPSECDOI_PROTO_IPSEC_ESP:
787 		if ((*e_type = ipsecdoi2pfkey_ealg(t_id)) == ~0)
788 			goto bad;
789 		if ((*e_keylen = keylen_ealg(t_id, *e_keylen)) == ~0)
790 			goto bad;
791 		*e_keylen >>= 3;
792 
793 		if ((*a_type = ipsecdoi2pfkey_aalg(hashtype)) == ~0)
794 			goto bad;
795 		if ((*a_keylen = keylen_aalg(hashtype)) == ~0)
796 			goto bad;
797 		*a_keylen >>= 3;
798 
799 		if (*e_type == SADB_EALG_NONE) {
800 			plog(LLV_ERROR, LOCATION, NULL, "no ESP algorithm.\n");
801 			goto bad;
802 		}
803 		break;
804 
805 	case IPSECDOI_PROTO_IPSEC_AH:
806 		if ((*a_type = ipsecdoi2pfkey_aalg(hashtype)) == ~0)
807 			goto bad;
808 		if ((*a_keylen = keylen_aalg(hashtype)) == ~0)
809 			goto bad;
810 		*a_keylen >>= 3;
811 
812 		if (t_id == IPSECDOI_ATTR_AUTH_HMAC_MD5
813 		 && hashtype == IPSECDOI_ATTR_AUTH_KPDK) {
814 			/* AH_MD5 + Auth(KPDK) = RFC1826 keyed-MD5 */
815 			*a_type = SADB_X_AALG_MD5;
816 			*flags |= SADB_X_EXT_OLD;
817 		}
818 		*e_type = SADB_EALG_NONE;
819 		*e_keylen = 0;
820 		if (*a_type == SADB_AALG_NONE) {
821 			plog(LLV_ERROR, LOCATION, NULL, "no AH algorithm.\n");
822 			goto bad;
823 		}
824 		break;
825 
826 	case IPSECDOI_PROTO_IPCOMP:
827 		if ((*e_type = ipsecdoi2pfkey_calg(t_id)) == ~0)
828 			goto bad;
829 		*e_keylen = 0;
830 
831 		*flags = SADB_X_EXT_RAWCPI;
832 
833 		*a_type = SADB_AALG_NONE;
834 		*a_keylen = 0;
835 		if (*e_type == SADB_X_CALG_NONE) {
836 			plog(LLV_ERROR, LOCATION, NULL, "no IPCOMP algorithm.\n");
837 			goto bad;
838 		}
839 		break;
840 
841 	default:
842 		plog(LLV_ERROR, LOCATION, NULL, "unknown IPsec protocol.\n");
843 		goto bad;
844 	}
845 
846 	return 0;
847 
848     bad:
849 	errno = EINVAL;
850 	return -1;
851 }
852 
853 /*%%%*/
854 /* send getspi message per ipsec protocol per remote address */
855 /*
856  * the local address and remote address in ph1handle are dealed
857  * with destination address and source address respectively.
858  * Because SPI is decided by responder.
859  */
860 int
861 pk_sendgetspi(iph2)
862 	struct ph2handle *iph2;
863 {
864 	struct sockaddr *src = NULL, *dst = NULL;
865 	u_int satype, mode;
866 	struct saprop *pp;
867 	struct saproto *pr;
868 	u_int32_t minspi, maxspi;
869 
870 	if (iph2->side == INITIATOR)
871 		pp = iph2->proposal;
872 	else
873 		pp = iph2->approval;
874 
875 	if (iph2->sa_src && iph2->sa_dst) {
876 		/* MIPv6: Use SA addresses, not IKE ones */
877 		src = dupsaddr(iph2->sa_src);
878 		dst = dupsaddr(iph2->sa_dst);
879 	} else {
880 		/* Common case: SA addresses and IKE ones are the same */
881 		src = dupsaddr(iph2->src);
882 		dst = dupsaddr(iph2->dst);
883 	}
884 
885 	if (src == NULL || dst == NULL) {
886 		racoon_free(src);
887 		racoon_free(dst);
888 		return -1;
889 	}
890 
891 	for (pr = pp->head; pr != NULL; pr = pr->next) {
892 
893 		/* validity check */
894 		satype = ipsecdoi2pfkey_proto(pr->proto_id);
895 		if (satype == ~0) {
896 			plog(LLV_ERROR, LOCATION, NULL,
897 				"invalid proto_id %d\n", pr->proto_id);
898 			racoon_free(src);
899 			racoon_free(dst);
900 			return -1;
901 		}
902 		/* this works around a bug in Linux kernel where it allocates 4 byte
903 		   spi's for IPCOMP */
904 		else if (satype == SADB_X_SATYPE_IPCOMP) {
905 			minspi = 0x100;
906 			maxspi = 0xffff;
907 		}
908 		else {
909 			minspi = 0;
910 			maxspi = 0;
911 		}
912 		mode = ipsecdoi2pfkey_mode(pr->encmode);
913 		if (mode == ~0) {
914 			plog(LLV_ERROR, LOCATION, NULL,
915 				"invalid encmode %d\n", pr->encmode);
916 			racoon_free(src);
917 			racoon_free(dst);
918 			return -1;
919 		}
920 
921 #ifdef ENABLE_NATT
922 		if (! pr->udp_encap) {
923 			/* Remove port information, that SA doesn't use it */
924 			set_port(iph2->src, 0);
925 			set_port(iph2->dst, 0);
926 		}
927 #endif
928 		plog(LLV_DEBUG, LOCATION, NULL, "call pfkey_send_getspi\n");
929 		if (pfkey_send_getspi(
930 				lcconf->sock_pfkey,
931 				satype,
932 				mode,
933 				dst,			/* src of SA */
934 				src,			/* dst of SA */
935 				minspi, maxspi,
936 				pr->reqid_in, iph2->seq) < 0) {
937 			plog(LLV_ERROR, LOCATION, NULL,
938 				"ipseclib failed send getspi (%s)\n",
939 				ipsec_strerror());
940 			racoon_free(src);
941 			racoon_free(dst);
942 			return -1;
943 		}
944 		plog(LLV_DEBUG, LOCATION, NULL,
945 			"pfkey GETSPI sent: %s\n",
946 			sadbsecas2str(dst, src, satype, 0, mode));
947 	}
948 
949 	racoon_free(src);
950 	racoon_free(dst);
951 	return 0;
952 }
953 
954 /*
955  * receive GETSPI from kernel.
956  */
957 static int
958 pk_recvgetspi(mhp)
959 	caddr_t *mhp;
960 {
961 	struct sadb_msg *msg;
962 	struct sadb_sa *sa;
963 	struct ph2handle *iph2;
964 	struct sockaddr *src, *dst;
965 	int proto_id;
966 	int allspiok, notfound;
967 	struct saprop *pp;
968 	struct saproto *pr;
969 
970 	/* validity check */
971 	if (mhp[SADB_EXT_SA] == NULL
972 	 || mhp[SADB_EXT_ADDRESS_DST] == NULL
973 	 || mhp[SADB_EXT_ADDRESS_SRC] == NULL) {
974 		plog(LLV_ERROR, LOCATION, NULL,
975 			"inappropriate sadb getspi message passed.\n");
976 		return -1;
977 	}
978 	msg = (struct sadb_msg *)mhp[0];
979 	sa = (struct sadb_sa *)mhp[SADB_EXT_SA];
980 	dst = PFKEY_ADDR_SADDR(mhp[SADB_EXT_ADDRESS_SRC]); /* note SA dir */
981 	src = PFKEY_ADDR_SADDR(mhp[SADB_EXT_ADDRESS_DST]);
982 
983 	/* the message has to be processed or not ? */
984 	if (msg->sadb_msg_pid != getpid()) {
985 		plog(LLV_DEBUG, LOCATION, NULL,
986 			"%s message is not interesting "
987 			"because pid %d is not mine.\n",
988 			s_pfkey_type(msg->sadb_msg_type),
989 			msg->sadb_msg_pid);
990 		return -1;
991 	}
992 
993 	iph2 = getph2byseq(msg->sadb_msg_seq);
994 	if (iph2 == NULL) {
995 		plog(LLV_DEBUG, LOCATION, NULL,
996 			"seq %d of %s message not interesting.\n",
997 			msg->sadb_msg_seq,
998 			s_pfkey_type(msg->sadb_msg_type));
999 		return -1;
1000 	}
1001 
1002 	if (iph2->status != PHASE2ST_GETSPISENT) {
1003 		plog(LLV_ERROR, LOCATION, NULL,
1004 			"status mismatch (db:%d msg:%d)\n",
1005 			iph2->status, PHASE2ST_GETSPISENT);
1006 		return -1;
1007 	}
1008 
1009 	/* set SPI, and check to get all spi whether or not */
1010 	allspiok = 1;
1011 	notfound = 1;
1012 	proto_id = pfkey2ipsecdoi_proto(msg->sadb_msg_satype);
1013 	pp = iph2->side == INITIATOR ? iph2->proposal : iph2->approval;
1014 
1015 	for (pr = pp->head; pr != NULL; pr = pr->next) {
1016 		if (pr->proto_id == proto_id && pr->spi == 0) {
1017 			pr->spi = sa->sadb_sa_spi;
1018 			notfound = 0;
1019 			plog(LLV_DEBUG, LOCATION, NULL,
1020 				"pfkey GETSPI succeeded: %s\n",
1021 				sadbsecas2str(dst, src,
1022 				    msg->sadb_msg_satype,
1023 				    sa->sadb_sa_spi,
1024 				    ipsecdoi2pfkey_mode(pr->encmode)));
1025 		}
1026 		if (pr->spi == 0)
1027 			allspiok = 0;	/* not get all spi */
1028 	}
1029 
1030 	if (notfound) {
1031 		plog(LLV_ERROR, LOCATION, NULL,
1032 			"get spi for unknown address %s\n",
1033 			saddrwop2str(dst));
1034 		return -1;
1035 	}
1036 
1037 	if (allspiok) {
1038 		/* update status */
1039 		iph2->status = PHASE2ST_GETSPIDONE;
1040 		if (isakmp_post_getspi(iph2) < 0) {
1041 			plog(LLV_ERROR, LOCATION, NULL,
1042 				"failed to start post getspi.\n");
1043 			remph2(iph2);
1044 			delph2(iph2);
1045 			iph2 = NULL;
1046 			return -1;
1047 		}
1048 	}
1049 
1050 	return 0;
1051 }
1052 
1053 /*
1054  * set inbound SA
1055  */
1056 int
1057 pk_sendupdate(iph2)
1058 	struct ph2handle *iph2;
1059 {
1060 	struct saproto *pr;
1061 	struct pfkey_send_sa_args sa_args;
1062 
1063 	/* sanity check */
1064 	if (iph2->approval == NULL) {
1065 		plog(LLV_ERROR, LOCATION, NULL,
1066 			"no approvaled SAs found.\n");
1067 		return -1;
1068 	}
1069 
1070 	/* fill in some needed for pfkey_send_update2 */
1071 	memset (&sa_args, 0, sizeof (sa_args));
1072 	sa_args.so = lcconf->sock_pfkey;
1073 	if (iph2->lifetime_secs)
1074 		sa_args.l_addtime = iph2->lifetime_secs;
1075 	else
1076 		sa_args.l_addtime = iph2->approval->lifetime;
1077 	sa_args.seq = iph2->seq;
1078 	sa_args.wsize = 4;
1079 
1080 	if (iph2->sa_src && iph2->sa_dst) {
1081 		/* MIPv6: Use SA addresses, not IKE ones */
1082 		sa_args.dst = dupsaddr(iph2->sa_src);
1083 		sa_args.src = dupsaddr(iph2->sa_dst);
1084 	} else {
1085 		/* Common case: SA addresses and IKE ones are the same */
1086 		sa_args.dst = dupsaddr(iph2->src);
1087 		sa_args.src = dupsaddr(iph2->dst);
1088 	}
1089 
1090 	if (sa_args.src == NULL || sa_args.dst == NULL) {
1091 		racoon_free(sa_args.src);
1092 		racoon_free(sa_args.dst);
1093 		return -1;
1094 	}
1095 
1096 	for (pr = iph2->approval->head; pr != NULL; pr = pr->next) {
1097 		/* validity check */
1098 		sa_args.satype = ipsecdoi2pfkey_proto(pr->proto_id);
1099 		if (sa_args.satype == ~0) {
1100 			plog(LLV_ERROR, LOCATION, NULL,
1101 				"invalid proto_id %d\n", pr->proto_id);
1102 			racoon_free(sa_args.src);
1103 			racoon_free(sa_args.dst);
1104 			return -1;
1105 		}
1106 		else if (sa_args.satype == SADB_X_SATYPE_IPCOMP) {
1107 			/* IPCOMP has no replay window */
1108 			sa_args.wsize = 0;
1109 		}
1110 #ifdef ENABLE_SAMODE_UNSPECIFIED
1111 		sa_args.mode = IPSEC_MODE_ANY;
1112 #else
1113 		sa_args.mode = ipsecdoi2pfkey_mode(pr->encmode);
1114 		if (sa_args.mode == ~0) {
1115 			plog(LLV_ERROR, LOCATION, NULL,
1116 				"invalid encmode %d\n", pr->encmode);
1117 			racoon_free(sa_args.src);
1118 			racoon_free(sa_args.dst);
1119 			return -1;
1120 		}
1121 #endif
1122 		/* set algorithm type and key length */
1123 		sa_args.e_keylen = pr->head->encklen;
1124 		if (pfkey_convertfromipsecdoi(
1125 				pr->proto_id,
1126 				pr->head->trns_id,
1127 				pr->head->authtype,
1128 				&sa_args.e_type, &sa_args.e_keylen,
1129 				&sa_args.a_type, &sa_args.a_keylen,
1130 				&sa_args.flags) < 0){
1131 			racoon_free(sa_args.src);
1132 			racoon_free(sa_args.dst);
1133 			return -1;
1134 		}
1135 
1136 #if 0
1137 		sa_args.l_bytes = iph2->approval->lifebyte * 1024,
1138 #else
1139 		sa_args.l_bytes = 0;
1140 #endif
1141 
1142 #ifdef HAVE_SECCTX
1143 		if (*iph2->approval->sctx.ctx_str) {
1144 			sa_args.ctxdoi = iph2->approval->sctx.ctx_doi;
1145 			sa_args.ctxalg = iph2->approval->sctx.ctx_alg;
1146 			sa_args.ctxstrlen = iph2->approval->sctx.ctx_strlen;
1147 			sa_args.ctxstr = iph2->approval->sctx.ctx_str;
1148 		}
1149 #endif /* HAVE_SECCTX */
1150 
1151 #ifdef ENABLE_NATT
1152 		if (pr->udp_encap) {
1153 			sa_args.l_natt_type = iph2->ph1->natt_options->encaps_type;
1154 			sa_args.l_natt_sport = extract_port (iph2->ph1->remote);
1155 			sa_args.l_natt_dport = extract_port (iph2->ph1->local);
1156 			sa_args.l_natt_oa = iph2->natoa_src;
1157 #ifdef SADB_X_EXT_NAT_T_FRAG
1158 			sa_args.l_natt_frag = iph2->ph1->rmconf->esp_frag;
1159 #endif
1160 		} else {
1161 			/* Remove port information, that SA doesn't use it */
1162 			set_port(sa_args.src, 0);
1163 			set_port(sa_args.dst, 0);
1164 		}
1165 
1166 #endif
1167 		/* more info to fill in */
1168 		sa_args.spi = pr->spi;
1169 		sa_args.reqid = pr->reqid_in;
1170 		sa_args.keymat = pr->keymat->v;
1171 
1172 		plog(LLV_DEBUG, LOCATION, NULL, "call pfkey_send_update2\n");
1173 		if (pfkey_send_update2(&sa_args) < 0) {
1174 			plog(LLV_ERROR, LOCATION, NULL,
1175 				"libipsec failed send update (%s)\n",
1176 				ipsec_strerror());
1177 			racoon_free(sa_args.src);
1178 			racoon_free(sa_args.dst);
1179 			return -1;
1180 		}
1181 
1182 		if (!lcconf->pathinfo[LC_PATHTYPE_BACKUPSA])
1183 			continue;
1184 
1185 		/*
1186 		 * It maybe good idea to call backupsa_to_file() after
1187 		 * racoon will receive the sadb_update messages.
1188 		 * But it is impossible because there is not key in the
1189 		 * information from the kernel.
1190 		 */
1191 
1192 		/* change some things before backing up */
1193 		sa_args.wsize = 4;
1194 		sa_args.l_bytes = iph2->approval->lifebyte * 1024;
1195 
1196 		if (backupsa_to_file(&sa_args) < 0) {
1197 			plog(LLV_ERROR, LOCATION, NULL,
1198 				"backuped SA failed: %s\n",
1199 				sadbsecas2str(sa_args.src, sa_args.dst,
1200 				sa_args.satype, sa_args.spi, sa_args.mode));
1201 		}
1202 		plog(LLV_DEBUG, LOCATION, NULL,
1203 			"backuped SA: %s\n",
1204 			sadbsecas2str(sa_args.src, sa_args.dst,
1205 			sa_args.satype, sa_args.spi, sa_args.mode));
1206 	}
1207 
1208 	racoon_free(sa_args.src);
1209 	racoon_free(sa_args.dst);
1210 	return 0;
1211 }
1212 
1213 static int
1214 pk_recvupdate(mhp)
1215 	caddr_t *mhp;
1216 {
1217 	struct sadb_msg *msg;
1218 	struct sadb_sa *sa;
1219 	struct sockaddr *src, *dst;
1220 	struct ph2handle *iph2;
1221 	u_int proto_id, encmode, sa_mode;
1222 	int incomplete = 0;
1223 	struct saproto *pr;
1224 
1225 	/* ignore this message because of local test mode. */
1226 	if (f_local)
1227 		return 0;
1228 
1229 	/* sanity check */
1230 	if (mhp[0] == NULL
1231 	 || mhp[SADB_EXT_SA] == NULL
1232 	 || mhp[SADB_EXT_ADDRESS_SRC] == NULL
1233 	 || mhp[SADB_EXT_ADDRESS_DST] == NULL) {
1234 		plog(LLV_ERROR, LOCATION, NULL,
1235 			"inappropriate sadb update message passed.\n");
1236 		return -1;
1237 	}
1238 	msg = (struct sadb_msg *)mhp[0];
1239 	src = PFKEY_ADDR_SADDR(mhp[SADB_EXT_ADDRESS_SRC]);
1240 	dst = PFKEY_ADDR_SADDR(mhp[SADB_EXT_ADDRESS_DST]);
1241 	sa = (struct sadb_sa *)mhp[SADB_EXT_SA];
1242 
1243 	sa_mode = mhp[SADB_X_EXT_SA2] == NULL
1244 		? IPSEC_MODE_ANY
1245 		: ((struct sadb_x_sa2 *)mhp[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
1246 
1247 	/* the message has to be processed or not ? */
1248 	if (msg->sadb_msg_pid != getpid()) {
1249 		plog(LLV_DEBUG, LOCATION, NULL,
1250 			"%s message is not interesting "
1251 			"because pid %d is not mine.\n",
1252 			s_pfkey_type(msg->sadb_msg_type),
1253 			msg->sadb_msg_pid);
1254 		return -1;
1255 	}
1256 
1257 	iph2 = getph2byseq(msg->sadb_msg_seq);
1258 	if (iph2 == NULL) {
1259 		plog(LLV_DEBUG, LOCATION, NULL,
1260 			"seq %d of %s message not interesting.\n",
1261 			msg->sadb_msg_seq,
1262 			s_pfkey_type(msg->sadb_msg_type));
1263 		return -1;
1264 	}
1265 
1266 	if (iph2->status != PHASE2ST_ADDSA) {
1267 		plog(LLV_ERROR, LOCATION, NULL,
1268 			"status mismatch (db:%d msg:%d)\n",
1269 			iph2->status, PHASE2ST_ADDSA);
1270 		return -1;
1271 	}
1272 
1273 	/* check to complete all keys ? */
1274 	for (pr = iph2->approval->head; pr != NULL; pr = pr->next) {
1275 		proto_id = pfkey2ipsecdoi_proto(msg->sadb_msg_satype);
1276 		if (proto_id == ~0) {
1277 			plog(LLV_ERROR, LOCATION, NULL,
1278 				"invalid proto_id %d\n", msg->sadb_msg_satype);
1279 			return -1;
1280 		}
1281 		encmode = pfkey2ipsecdoi_mode(sa_mode);
1282 		if (encmode == ~0) {
1283 			plog(LLV_ERROR, LOCATION, NULL,
1284 				"invalid encmode %d\n", sa_mode);
1285 			return -1;
1286 		}
1287 
1288 		if (pr->proto_id == proto_id
1289 		 && pr->spi == sa->sadb_sa_spi) {
1290 			pr->ok = 1;
1291 			plog(LLV_DEBUG, LOCATION, NULL,
1292 				"pfkey UPDATE succeeded: %s\n",
1293 				sadbsecas2str(dst, src,
1294 				    msg->sadb_msg_satype,
1295 				    sa->sadb_sa_spi,
1296 				    sa_mode));
1297 
1298 			plog(LLV_INFO, LOCATION, NULL,
1299 				"IPsec-SA established: %s\n",
1300 				sadbsecas2str(dst, src,
1301 					msg->sadb_msg_satype, sa->sadb_sa_spi,
1302 					sa_mode));
1303 		}
1304 
1305 		if (pr->ok == 0)
1306 			incomplete = 1;
1307 	}
1308 
1309 	if (incomplete)
1310 		return 0;
1311 
1312 	/* turn off the timer for calling pfkey_timeover() */
1313 	sched_cancel(&iph2->sce);
1314 
1315 	/* update status */
1316 	iph2->status = PHASE2ST_ESTABLISHED;
1317 	evt_phase2(iph2, EVT_PHASE2_UP, NULL);
1318 
1319 #ifdef ENABLE_STATS
1320 	gettimeofday(&iph2->end, NULL);
1321 	syslog(LOG_NOTICE, "%s(%s): %8.6f",
1322 		"phase2", "quick", timedelta(&iph2->start, &iph2->end));
1323 #endif
1324 
1325 	/* turn off schedule */
1326 	sched_cancel(&iph2->scr);
1327 
1328 	/* Force the update of ph2's ports, as there is at least one
1329 	 * situation where they'll mismatch with ph1's values
1330 	 */
1331 
1332 #ifdef ENABLE_NATT
1333 	set_port(iph2->src, extract_port(iph2->ph1->local));
1334 	set_port(iph2->dst, extract_port(iph2->ph1->remote));
1335 #endif
1336 
1337 	/*
1338 	 * since we are going to reuse the phase2 handler, we need to
1339 	 * remain it and refresh all the references between ph1 and ph2 to use.
1340 	 */
1341 	sched_schedule(&iph2->sce, iph2->approval->lifetime,
1342 		       isakmp_ph2expire_stub);
1343 
1344 	plog(LLV_DEBUG, LOCATION, NULL, "===\n");
1345 	return 0;
1346 }
1347 
1348 /*
1349  * set outbound SA
1350  */
1351 int
1352 pk_sendadd(iph2)
1353 	struct ph2handle *iph2;
1354 {
1355 	struct saproto *pr;
1356 	struct pfkey_send_sa_args sa_args;
1357 
1358 	/* sanity check */
1359 	if (iph2->approval == NULL) {
1360 		plog(LLV_ERROR, LOCATION, NULL,
1361 			"no approvaled SAs found.\n");
1362 		return -1;
1363 	}
1364 
1365 	/* fill in some needed for pfkey_send_update2 */
1366 	memset (&sa_args, 0, sizeof (sa_args));
1367 	sa_args.so = lcconf->sock_pfkey;
1368 	if (iph2->lifetime_secs)
1369 		sa_args.l_addtime = iph2->lifetime_secs;
1370 	else
1371 		sa_args.l_addtime = iph2->approval->lifetime;
1372 	sa_args.seq = iph2->seq;
1373 	sa_args.wsize = 4;
1374 
1375 	if (iph2->sa_src && iph2->sa_dst) {
1376 		/* MIPv6: Use SA addresses, not IKE ones */
1377 		sa_args.src = dupsaddr(iph2->sa_src);
1378 		sa_args.dst = dupsaddr(iph2->sa_dst);
1379 	} else {
1380 		/* Common case: SA addresses and IKE ones are the same */
1381 		sa_args.src = dupsaddr(iph2->src);
1382 		sa_args.dst = dupsaddr(iph2->dst);
1383 	}
1384 
1385 	if (sa_args.src == NULL || sa_args.dst == NULL) {
1386 		racoon_free(sa_args.src);
1387 		racoon_free(sa_args.dst);
1388 		return -1;
1389  	}
1390 
1391 	for (pr = iph2->approval->head; pr != NULL; pr = pr->next) {
1392 		/* validity check */
1393 		sa_args.satype = ipsecdoi2pfkey_proto(pr->proto_id);
1394 		if (sa_args.satype == ~0) {
1395 			plog(LLV_ERROR, LOCATION, NULL,
1396 				"invalid proto_id %d\n", pr->proto_id);
1397 			racoon_free(sa_args.src);
1398 			racoon_free(sa_args.dst);
1399 			return -1;
1400 		}
1401 		else if (sa_args.satype == SADB_X_SATYPE_IPCOMP) {
1402 			/* no replay window for IPCOMP */
1403 			sa_args.wsize = 0;
1404 		}
1405 #ifdef ENABLE_SAMODE_UNSPECIFIED
1406 		sa_args.mode = IPSEC_MODE_ANY;
1407 #else
1408 		sa_args.mode = ipsecdoi2pfkey_mode(pr->encmode);
1409 		if (sa_args.mode == ~0) {
1410 			plog(LLV_ERROR, LOCATION, NULL,
1411 				"invalid encmode %d\n", pr->encmode);
1412 			racoon_free(sa_args.src);
1413 			racoon_free(sa_args.dst);
1414 			return -1;
1415 		}
1416 #endif
1417 
1418 		/* set algorithm type and key length */
1419 		sa_args.e_keylen = pr->head->encklen;
1420 		if (pfkey_convertfromipsecdoi(
1421 				pr->proto_id,
1422 				pr->head->trns_id,
1423 				pr->head->authtype,
1424 				&sa_args.e_type, &sa_args.e_keylen,
1425 				&sa_args.a_type, &sa_args.a_keylen,
1426 				&sa_args.flags) < 0){
1427 			racoon_free(sa_args.src);
1428 			racoon_free(sa_args.dst);
1429 			return -1;
1430 		}
1431 
1432 #if 0
1433 		sa_args.l_bytes = iph2->approval->lifebyte * 1024,
1434 #else
1435 		sa_args.l_bytes = 0;
1436 #endif
1437 
1438 #ifdef HAVE_SECCTX
1439 		if (*iph2->approval->sctx.ctx_str) {
1440 			sa_args.ctxdoi = iph2->approval->sctx.ctx_doi;
1441 			sa_args.ctxalg = iph2->approval->sctx.ctx_alg;
1442 			sa_args.ctxstrlen = iph2->approval->sctx.ctx_strlen;
1443 			sa_args.ctxstr = iph2->approval->sctx.ctx_str;
1444 		}
1445 #endif /* HAVE_SECCTX */
1446 
1447 #ifdef ENABLE_NATT
1448 		plog(LLV_DEBUG, LOCATION, NULL, "call pfkey_send_add2 "
1449 		    "(NAT flavor)\n");
1450 
1451 		if (pr->udp_encap) {
1452 			sa_args.l_natt_type = UDP_ENCAP_ESPINUDP;
1453 			sa_args.l_natt_sport = extract_port(iph2->ph1->local);
1454 			sa_args.l_natt_dport = extract_port(iph2->ph1->remote);
1455 			sa_args.l_natt_oa = iph2->natoa_dst;
1456 #ifdef SADB_X_EXT_NAT_T_FRAG
1457 			sa_args.l_natt_frag = iph2->ph1->rmconf->esp_frag;
1458 #endif
1459 		} else {
1460 			/* Remove port information, that SA doesn't use it */
1461 			set_port(sa_args.src, 0);
1462 			set_port(sa_args.dst, 0);
1463 		}
1464 
1465 #else
1466 		/* Remove port information, it is not used without NAT-T */
1467 		set_port(sa_args.src, 0);
1468 		set_port(sa_args.dst, 0);
1469 #endif
1470 
1471 		/* more info to fill in */
1472 		sa_args.spi = pr->spi_p;
1473 		sa_args.reqid = pr->reqid_out;
1474 		sa_args.keymat = pr->keymat_p->v;
1475 
1476 		plog(LLV_DEBUG, LOCATION, NULL, "call pfkey_send_add2\n");
1477 		if (pfkey_send_add2(&sa_args) < 0) {
1478 			plog(LLV_ERROR, LOCATION, NULL,
1479 				"libipsec failed send add (%s)\n",
1480 				ipsec_strerror());
1481 			racoon_free(sa_args.src);
1482 			racoon_free(sa_args.dst);
1483 			return -1;
1484 		}
1485 
1486 		if (!lcconf->pathinfo[LC_PATHTYPE_BACKUPSA])
1487 			continue;
1488 
1489 		/*
1490 		 * It maybe good idea to call backupsa_to_file() after
1491 		 * racoon will receive the sadb_update messages.
1492 		 * But it is impossible because there is not key in the
1493 		 * information from the kernel.
1494 		 */
1495 		if (backupsa_to_file(&sa_args) < 0) {
1496 			plog(LLV_ERROR, LOCATION, NULL,
1497 				"backuped SA failed: %s\n",
1498 				sadbsecas2str(sa_args.src, sa_args.dst,
1499 				sa_args.satype, sa_args.spi, sa_args.mode));
1500 		}
1501 		plog(LLV_DEBUG, LOCATION, NULL,
1502 			"backuped SA: %s\n",
1503 			sadbsecas2str(sa_args.src, sa_args.dst,
1504 			sa_args.satype, sa_args.spi, sa_args.mode));
1505 	}
1506 	racoon_free(sa_args.src);
1507 	racoon_free(sa_args.dst);
1508 	return 0;
1509 }
1510 
1511 static int
1512 pk_recvadd(mhp)
1513 	caddr_t *mhp;
1514 {
1515 	struct sadb_msg *msg;
1516 	struct sadb_sa *sa;
1517 	struct sockaddr *src, *dst;
1518 	struct ph2handle *iph2;
1519 	u_int sa_mode;
1520 
1521 	/* ignore this message because of local test mode. */
1522 	if (f_local)
1523 		return 0;
1524 
1525 	/* sanity check */
1526 	if (mhp[0] == NULL
1527 	 || mhp[SADB_EXT_SA] == NULL
1528 	 || mhp[SADB_EXT_ADDRESS_SRC] == NULL
1529 	 || mhp[SADB_EXT_ADDRESS_DST] == NULL) {
1530 		plog(LLV_ERROR, LOCATION, NULL,
1531 			"inappropriate sadb add message passed.\n");
1532 		return -1;
1533 	}
1534 	msg = (struct sadb_msg *)mhp[0];
1535 	src = PFKEY_ADDR_SADDR(mhp[SADB_EXT_ADDRESS_SRC]);
1536 	dst = PFKEY_ADDR_SADDR(mhp[SADB_EXT_ADDRESS_DST]);
1537 	sa = (struct sadb_sa *)mhp[SADB_EXT_SA];
1538 
1539 	sa_mode = mhp[SADB_X_EXT_SA2] == NULL
1540 		? IPSEC_MODE_ANY
1541 		: ((struct sadb_x_sa2 *)mhp[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
1542 
1543 	/* the message has to be processed or not ? */
1544 	if (msg->sadb_msg_pid != getpid()) {
1545 		plog(LLV_DEBUG, LOCATION, NULL,
1546 			"%s message is not interesting "
1547 			"because pid %d is not mine.\n",
1548 			s_pfkey_type(msg->sadb_msg_type),
1549 			msg->sadb_msg_pid);
1550 		return -1;
1551 	}
1552 
1553 	iph2 = getph2byseq(msg->sadb_msg_seq);
1554 	if (iph2 == NULL) {
1555 		plog(LLV_DEBUG, LOCATION, NULL,
1556 			"seq %d of %s message not interesting.\n",
1557 			msg->sadb_msg_seq,
1558 			s_pfkey_type(msg->sadb_msg_type));
1559 		return -1;
1560 	}
1561 
1562 	/*
1563 	 * NOTE don't update any status of phase2 handle
1564 	 * because they must be updated by SADB_UPDATE message
1565 	 */
1566 
1567 	plog(LLV_INFO, LOCATION, NULL,
1568 		"IPsec-SA established: %s\n",
1569 		sadbsecas2str(src, dst,
1570 			msg->sadb_msg_satype, sa->sadb_sa_spi, sa_mode));
1571 
1572 	plog(LLV_DEBUG, LOCATION, NULL, "===\n");
1573 	return 0;
1574 }
1575 
1576 static int
1577 pk_recvexpire(mhp)
1578 	caddr_t *mhp;
1579 {
1580 	struct sadb_msg *msg;
1581 	struct sadb_sa *sa;
1582 	struct sockaddr *src, *dst;
1583 	struct ph2handle *iph2;
1584 	u_int proto_id, sa_mode;
1585 
1586 	/* sanity check */
1587 	if (mhp[0] == NULL
1588 	 || mhp[SADB_EXT_SA] == NULL
1589 	 || mhp[SADB_EXT_ADDRESS_SRC] == NULL
1590 	 || mhp[SADB_EXT_ADDRESS_DST] == NULL
1591 	 || (mhp[SADB_EXT_LIFETIME_HARD] != NULL
1592 	  && mhp[SADB_EXT_LIFETIME_SOFT] != NULL)) {
1593 		plog(LLV_ERROR, LOCATION, NULL,
1594 			"inappropriate sadb expire message passed.\n");
1595 		return -1;
1596 	}
1597 	msg = (struct sadb_msg *)mhp[0];
1598 	sa = (struct sadb_sa *)mhp[SADB_EXT_SA];
1599 	src = PFKEY_ADDR_SADDR(mhp[SADB_EXT_ADDRESS_SRC]);
1600 	dst = PFKEY_ADDR_SADDR(mhp[SADB_EXT_ADDRESS_DST]);
1601 
1602 	sa_mode = mhp[SADB_X_EXT_SA2] == NULL
1603 		? IPSEC_MODE_ANY
1604 		: ((struct sadb_x_sa2 *)mhp[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
1605 
1606 	proto_id = pfkey2ipsecdoi_proto(msg->sadb_msg_satype);
1607 	if (proto_id == ~0) {
1608 		plog(LLV_ERROR, LOCATION, NULL,
1609 			"invalid proto_id %d\n", msg->sadb_msg_satype);
1610 		return -1;
1611 	}
1612 
1613 	plog(LLV_INFO, LOCATION, NULL,
1614 		"IPsec-SA expired: %s\n",
1615 		sadbsecas2str(src, dst,
1616 			msg->sadb_msg_satype, sa->sadb_sa_spi, sa_mode));
1617 
1618 	iph2 = getph2bysaidx(src, dst, proto_id, sa->sadb_sa_spi);
1619 	if (iph2 == NULL) {
1620 		/*
1621 		 * Ignore it because two expire messages are come up.
1622 		 * phase2 handler has been deleted already when 2nd message
1623 		 * is received.
1624 		 */
1625 		plog(LLV_DEBUG, LOCATION, NULL,
1626 			"no such a SA found: %s\n",
1627 			sadbsecas2str(src, dst,
1628 			    msg->sadb_msg_satype, sa->sadb_sa_spi,
1629 			    sa_mode));
1630 		return 0;
1631 	}
1632 
1633 	/* resent expiry message? */
1634 	if (iph2->status > PHASE2ST_ESTABLISHED)
1635 		return 0;
1636 
1637 	/* still negotiating? */
1638 	if (iph2->status < PHASE2ST_ESTABLISHED) {
1639 		/* not a hard timeout? */
1640 		if (mhp[SADB_EXT_LIFETIME_HARD] == NULL)
1641 			return 0;
1642 
1643 		/*
1644 		 * We were negotiating for that SA (w/o much success
1645 		 * from current status) and kernel has decided our time
1646 		 * is over trying (xfrm_larval_drop controls that and
1647 		 * is enabled by default on Linux >= 2.6.28 kernels).
1648 		 */
1649 		plog(LLV_WARNING, LOCATION, NULL,
1650 		     "PF_KEY EXPIRE message received from kernel for SA"
1651 		     " being negotiated. Stopping negotiation.\n");
1652 	}
1653 
1654 	/* turn off the timer for calling isakmp_ph2expire() */
1655 	sched_cancel(&iph2->sce);
1656 
1657 	if (iph2->status == PHASE2ST_ESTABLISHED &&
1658 	    iph2->side == INITIATOR) {
1659 		/*
1660 		 * Active phase 2 expired and we were initiator.
1661 		 * Begin new phase 2 exchange, so we can keep on sending
1662 		 * traffic.
1663 		 */
1664 
1665 		/* update status for re-use */
1666 		initph2(iph2);
1667 		iph2->status = PHASE2ST_STATUS2;
1668 
1669 		/* start quick exchange */
1670 		if (isakmp_post_acquire(iph2) < 0) {
1671 			plog(LLV_ERROR, LOCATION, iph2->dst,
1672 				"failed to begin ipsec sa "
1673 				"re-negotication.\n");
1674 			remph2(iph2);
1675 			delph2(iph2);
1676 			return -1;
1677 		}
1678 
1679 		return 0;
1680 	}
1681 
1682 	/*
1683 	 * We are responder or the phase 2 was not established.
1684 	 * Just remove the ph2handle to reflect SADB.
1685 	 */
1686 	iph2->status = PHASE2ST_EXPIRED;
1687 	remph2(iph2);
1688 	delph2(iph2);
1689 
1690 	return 0;
1691 }
1692 
1693 static int
1694 pk_recvacquire(mhp)
1695 	caddr_t *mhp;
1696 {
1697 	struct sadb_msg *msg;
1698 	struct sadb_x_policy *xpl;
1699 	struct secpolicy *sp_out = NULL, *sp_in = NULL;
1700 	struct ph2handle *iph2;
1701 	struct sockaddr *src, *dst;     /* IKE addresses (for exchanges) */
1702 	struct sockaddr *sp_src, *sp_dst;   /* SP addresses (selectors). */
1703 	struct sockaddr *sa_src = NULL, *sa_dst = NULL ; /* SA addresses */
1704 #ifdef HAVE_SECCTX
1705 	struct sadb_x_sec_ctx *m_sec_ctx;
1706 #endif /* HAVE_SECCTX */
1707 	struct policyindex spidx;
1708 
1709 	/* ignore this message because of local test mode. */
1710 	if (f_local)
1711 		return 0;
1712 
1713 	/* sanity check */
1714 	if (mhp[0] == NULL
1715 	 || mhp[SADB_EXT_ADDRESS_SRC] == NULL
1716 	 || mhp[SADB_EXT_ADDRESS_DST] == NULL
1717 	 || mhp[SADB_X_EXT_POLICY] == NULL) {
1718 		plog(LLV_ERROR, LOCATION, NULL,
1719 			"inappropriate sadb acquire message passed.\n");
1720 		return -1;
1721 	}
1722 	msg = (struct sadb_msg *)mhp[0];
1723 	xpl = (struct sadb_x_policy *)mhp[SADB_X_EXT_POLICY];
1724 	sp_src = PFKEY_ADDR_SADDR(mhp[SADB_EXT_ADDRESS_SRC]);
1725 	sp_dst = PFKEY_ADDR_SADDR(mhp[SADB_EXT_ADDRESS_DST]);
1726 
1727 #ifdef HAVE_SECCTX
1728 	m_sec_ctx = (struct sadb_x_sec_ctx *)mhp[SADB_X_EXT_SEC_CTX];
1729 
1730 	if (m_sec_ctx != NULL) {
1731 		plog(LLV_INFO, LOCATION, NULL, "security context doi: %u\n",
1732 		     m_sec_ctx->sadb_x_ctx_doi);
1733 		plog(LLV_INFO, LOCATION, NULL,
1734 		     "security context algorithm: %u\n",
1735 		     m_sec_ctx->sadb_x_ctx_alg);
1736 		plog(LLV_INFO, LOCATION, NULL, "security context length: %u\n",
1737 		     m_sec_ctx->sadb_x_ctx_len);
1738 		plog(LLV_INFO, LOCATION, NULL, "security context: %s\n",
1739 		     ((char *)m_sec_ctx + sizeof(struct sadb_x_sec_ctx)));
1740 	}
1741 #endif /* HAVE_SECCTX */
1742 
1743 	/* ignore if type is not IPSEC_POLICY_IPSEC */
1744 	if (xpl->sadb_x_policy_type != IPSEC_POLICY_IPSEC) {
1745 		plog(LLV_DEBUG, LOCATION, NULL,
1746 			"ignore ACQUIRE message. type is not IPsec.\n");
1747 		return 0;
1748 	}
1749 
1750 	/* ignore it if src or dst are multicast addresses. */
1751 	if ((sp_dst->sa_family == AF_INET
1752 	  && IN_MULTICAST(ntohl(((struct sockaddr_in *)sp_dst)->sin_addr.s_addr)))
1753 #ifdef INET6
1754 	 || (sp_dst->sa_family == AF_INET6
1755 	  && IN6_IS_ADDR_MULTICAST(&((struct sockaddr_in6 *)sp_dst)->sin6_addr))
1756 #endif
1757 	) {
1758 		plog(LLV_DEBUG, LOCATION, NULL,
1759 			"ignore due to multicast destination address: %s.\n",
1760 			saddrwop2str(sp_dst));
1761 		return 0;
1762 	}
1763 
1764 	if ((sp_src->sa_family == AF_INET
1765 	  && IN_MULTICAST(ntohl(((struct sockaddr_in *)sp_src)->sin_addr.s_addr)))
1766 #ifdef INET6
1767 	 || (sp_src->sa_family == AF_INET6
1768 	  && IN6_IS_ADDR_MULTICAST(&((struct sockaddr_in6 *)sp_src)->sin6_addr))
1769 #endif
1770 	) {
1771 		plog(LLV_DEBUG, LOCATION, NULL,
1772 			"ignore due to multicast source address: %s.\n",
1773 			saddrwop2str(sp_src));
1774 		return 0;
1775 	}
1776 
1777 	/* search for proper policyindex */
1778 	sp_out = getspbyspid(xpl->sadb_x_policy_id);
1779 	if (sp_out == NULL) {
1780 		plog(LLV_ERROR, LOCATION, NULL, "no policy found: id:%d.\n",
1781 			xpl->sadb_x_policy_id);
1782 		return -1;
1783 	}
1784 	plog(LLV_DEBUG, LOCATION, NULL,
1785 		"suitable outbound SP found: %s.\n", spidx2str(&sp_out->spidx));
1786 
1787 	/* Before going further, let first get the source and destination
1788 	 * address that would be used for IKE negotiation. The logic is:
1789 	 * - if SP from SPD image contains local and remote hints, we
1790 	 *   use them (provided by MIGRATE).
1791 	 * - otherwise, we use the ones from the ipsecrequest, which means:
1792 	 *   - the addresses from the request for transport mode
1793 	 *   - the endpoints addresses for tunnel mode
1794 	 *
1795 	 * Note that:
1796 	 * 1) racoon does not support negotiation of bundles which
1797 	 *    simplifies the lookup for the addresses in the ipsecrequest
1798 	 *    list, as we expect only one.
1799 	 * 2) We do source and destination parts all together and do not
1800 	 *    accept semi-defined information. This is just a decision,
1801 	 *    there might be needs.
1802 	 *
1803 	 * --arno
1804 	 */
1805 	if (sp_out->req && sp_out->req->saidx.mode == IPSEC_MODE_TUNNEL) {
1806 		/* For Tunnel mode, SA addresses are the endpoints */
1807 		src = (struct sockaddr *) &sp_out->req->saidx.src;
1808 		dst = (struct sockaddr *) &sp_out->req->saidx.dst;
1809 	} else {
1810 		/* Otherwise use requested addresses */
1811 		src = sp_src;
1812 		dst = sp_dst;
1813 	}
1814 	if (sp_out->local && sp_out->remote) {
1815 		/* hints available, let's use them */
1816 		sa_src = src;
1817 		sa_dst = dst;
1818 		src = (struct sockaddr *) sp_out->local;
1819 		dst = (struct sockaddr *) sp_out->remote;
1820 	}
1821 
1822 	/*
1823 	 * If there is a phase 2 handler against the policy identifier in
1824 	 * the acquire message, and if
1825 	 *    1. its state is less than PHASE2ST_ESTABLISHED, then racoon
1826 	 *       should ignore such a acquire message because the phase 2
1827 	 *       is just negotiating.
1828 	 *    2. its state is equal to PHASE2ST_ESTABLISHED, then racoon
1829 	 *       has to prcesss such a acquire message because racoon may
1830 	 *       lost the expire message.
1831 	 */
1832 	iph2 = getph2byid(src, dst, xpl->sadb_x_policy_id);
1833 	if (iph2 != NULL) {
1834 		if (iph2->status < PHASE2ST_ESTABLISHED) {
1835 			plog(LLV_DEBUG, LOCATION, NULL,
1836 				"ignore the acquire because ph2 found\n");
1837 			return -1;
1838 		}
1839 		if (iph2->status == PHASE2ST_EXPIRED)
1840 			iph2 = NULL;
1841 		/*FALLTHROUGH*/
1842 	}
1843 
1844 	/* Check we are listening on source address. If not, ignore. */
1845 	if (myaddr_getsport(src) == -1) {
1846 		plog(LLV_DEBUG, LOCATION, NULL,
1847 		     "Not listening on source address %s. Ignoring ACQUIRE.\n",
1848 		     saddrwop2str(src));
1849 		return 0;
1850 	}
1851 
1852 	/* get inbound policy */
1853     {
1854 
1855 	memset(&spidx, 0, sizeof(spidx));
1856 	spidx.dir = IPSEC_DIR_INBOUND;
1857 	memcpy(&spidx.src, &sp_out->spidx.dst, sizeof(spidx.src));
1858 	memcpy(&spidx.dst, &sp_out->spidx.src, sizeof(spidx.dst));
1859 	spidx.prefs = sp_out->spidx.prefd;
1860 	spidx.prefd = sp_out->spidx.prefs;
1861 	spidx.ul_proto = sp_out->spidx.ul_proto;
1862 
1863 #ifdef HAVE_SECCTX
1864 	if (m_sec_ctx) {
1865 		spidx.sec_ctx.ctx_doi = m_sec_ctx->sadb_x_ctx_doi;
1866 		spidx.sec_ctx.ctx_alg = m_sec_ctx->sadb_x_ctx_alg;
1867 		spidx.sec_ctx.ctx_strlen = m_sec_ctx->sadb_x_ctx_len;
1868 		memcpy(spidx.sec_ctx.ctx_str,
1869 		      ((char *)m_sec_ctx + sizeof(struct sadb_x_sec_ctx)),
1870 		      spidx.sec_ctx.ctx_strlen);
1871 	}
1872 #endif /* HAVE_SECCTX */
1873 
1874 	sp_in = getsp(&spidx);
1875 	if (sp_in) {
1876 		plog(LLV_DEBUG, LOCATION, NULL,
1877 			"suitable inbound SP found: %s.\n",
1878 			spidx2str(&sp_in->spidx));
1879 	} else {
1880 		plog(LLV_NOTIFY, LOCATION, NULL,
1881 			"no in-bound policy found: %s\n",
1882 			spidx2str(&spidx));
1883 	}
1884     }
1885 
1886 	/* allocate a phase 2 */
1887 	iph2 = newph2();
1888 	if (iph2 == NULL) {
1889 		plog(LLV_ERROR, LOCATION, NULL,
1890 			"failed to allocate phase2 entry.\n");
1891 		return -1;
1892 	}
1893 	iph2->side = INITIATOR;
1894 	iph2->spid = xpl->sadb_x_policy_id;
1895 	iph2->satype = msg->sadb_msg_satype;
1896 	iph2->seq = msg->sadb_msg_seq;
1897 	iph2->status = PHASE2ST_STATUS2;
1898 
1899 	/* set address used by IKE for the negotiation (might differ from
1900 	 * SA address, i.e. might not be tunnel endpoints or addresses
1901 	 * of transport mode SA) */
1902 	iph2->dst = dupsaddr(dst);
1903 	if (iph2->dst == NULL) {
1904 		delph2(iph2);
1905 		return -1;
1906 	}
1907 	iph2->src = dupsaddr(src);
1908 	if (iph2->src == NULL) {
1909 		delph2(iph2);
1910 		return -1;
1911 	}
1912 
1913 	/* If sa_src and sa_dst have been set, this mean we have to
1914 	 * set iph2->sa_src and iph2->sa_dst to provide the addresses
1915 	 * of the SA because iph2->src and iph2->dst are only the ones
1916 	 * used for the IKE exchanges. Those that need these addresses
1917 	 * are for instance pk_sendupdate() or pk_sendgetspi() */
1918 	if (sa_src) {
1919 		iph2->sa_src = dupsaddr(sa_src);
1920 		iph2->sa_dst = dupsaddr(sa_dst);
1921 	}
1922 
1923 	if (isakmp_get_sainfo(iph2, sp_out, sp_in) < 0) {
1924 		delph2(iph2);
1925 		return -1;
1926 	}
1927 
1928 #ifdef HAVE_SECCTX
1929 	if (m_sec_ctx) {
1930 		set_secctx_in_proposal(iph2, spidx);
1931 	}
1932 #endif /* HAVE_SECCTX */
1933 
1934 	insph2(iph2);
1935 
1936 	/* start isakmp initiation by using ident exchange */
1937 	/* XXX should be looped if there are multiple phase 2 handler. */
1938 	if (isakmp_post_acquire(iph2) < 0) {
1939 		plog(LLV_ERROR, LOCATION, NULL,
1940 			"failed to begin ipsec sa negotication.\n");
1941 		remph2(iph2);
1942 		delph2(iph2);
1943 		return -1;
1944 	}
1945 
1946 	return 0;
1947 }
1948 
1949 static int
1950 pk_recvdelete(mhp)
1951 	caddr_t *mhp;
1952 {
1953 	struct sadb_msg *msg;
1954 	struct sadb_sa *sa;
1955 	struct sockaddr *src, *dst;
1956 	struct ph2handle *iph2 = NULL;
1957 	u_int proto_id;
1958 
1959 	/* ignore this message because of local test mode. */
1960 	if (f_local)
1961 		return 0;
1962 
1963 	/* sanity check */
1964 	if (mhp[0] == NULL
1965 	 || mhp[SADB_EXT_SA] == NULL
1966 	 || mhp[SADB_EXT_ADDRESS_SRC] == NULL
1967 	 || mhp[SADB_EXT_ADDRESS_DST] == NULL) {
1968 		plog(LLV_ERROR, LOCATION, NULL,
1969 			"inappropriate sadb delete message passed.\n");
1970 		return -1;
1971 	}
1972 	msg = (struct sadb_msg *)mhp[0];
1973 	sa = (struct sadb_sa *)mhp[SADB_EXT_SA];
1974 	src = PFKEY_ADDR_SADDR(mhp[SADB_EXT_ADDRESS_SRC]);
1975 	dst = PFKEY_ADDR_SADDR(mhp[SADB_EXT_ADDRESS_DST]);
1976 
1977 	/* the message has to be processed or not ? */
1978 	if (msg->sadb_msg_pid == getpid()) {
1979 		plog(LLV_DEBUG, LOCATION, NULL,
1980 			"%s message is not interesting "
1981 			"because the message was originated by me.\n",
1982 			s_pfkey_type(msg->sadb_msg_type));
1983 		return -1;
1984 	}
1985 
1986 	proto_id = pfkey2ipsecdoi_proto(msg->sadb_msg_satype);
1987 	if (proto_id == ~0) {
1988 		plog(LLV_ERROR, LOCATION, NULL,
1989 			"invalid proto_id %d\n", msg->sadb_msg_satype);
1990 		return -1;
1991 	}
1992 
1993 	iph2 = getph2bysaidx(src, dst, proto_id, sa->sadb_sa_spi);
1994 	if (iph2 == NULL) {
1995 		/* ignore */
1996 		plog(LLV_ERROR, LOCATION, NULL,
1997 			"no iph2 found: %s\n",
1998 			sadbsecas2str(src, dst, msg->sadb_msg_satype,
1999 				sa->sadb_sa_spi, IPSEC_MODE_ANY));
2000 		return 0;
2001 	}
2002 
2003 	plog(LLV_ERROR, LOCATION, NULL,
2004 		"pfkey DELETE received: %s\n",
2005 		sadbsecas2str(src, dst,
2006 			msg->sadb_msg_satype, sa->sadb_sa_spi, IPSEC_MODE_ANY));
2007 
2008 	/* send delete information */
2009 	if (iph2->status == PHASE2ST_ESTABLISHED)
2010 		isakmp_info_send_d2(iph2);
2011 
2012 	remph2(iph2);
2013 	delph2(iph2);
2014 
2015 	return 0;
2016 }
2017 
2018 static int
2019 pk_recvflush(mhp)
2020 	caddr_t *mhp;
2021 {
2022 	/* ignore this message because of local test mode. */
2023 	if (f_local)
2024 		return 0;
2025 
2026 	/* sanity check */
2027 	if (mhp[0] == NULL) {
2028 		plog(LLV_ERROR, LOCATION, NULL,
2029 			"inappropriate sadb flush message passed.\n");
2030 		return -1;
2031 	}
2032 
2033 	flushph2();
2034 
2035 	return 0;
2036 }
2037 
2038 static int
2039 getsadbpolicy(policy0, policylen0, type, iph2)
2040 	caddr_t *policy0;
2041 	int *policylen0, type;
2042 	struct ph2handle *iph2;
2043 {
2044 	struct policyindex *spidx = (struct policyindex *)iph2->spidx_gen;
2045 	struct sockaddr *src = NULL, *dst = NULL;
2046 	struct sadb_x_policy *xpl;
2047 	struct sadb_x_ipsecrequest *xisr;
2048 	struct saproto *pr;
2049 	struct saproto **pr_rlist;
2050 	int rlist_len = 0;
2051 	caddr_t policy, p;
2052 	int policylen;
2053 	int xisrlen;
2054 	u_int satype, mode;
2055 	int len = 0;
2056 #ifdef HAVE_SECCTX
2057 	int ctxlen = 0;
2058 #endif /* HAVE_SECCTX */
2059 
2060 
2061 	/* get policy buffer size */
2062 	policylen = sizeof(struct sadb_x_policy);
2063 	if (type != SADB_X_SPDDELETE) {
2064 		if (iph2->sa_src && iph2->sa_dst) {
2065 			src = iph2->sa_src; /* MIPv6: Use SA addresses, */
2066 			dst = iph2->sa_dst; /* not IKE ones             */
2067 		} else {
2068 			src = iph2->src; /* Common case: SA addresses */
2069 			dst = iph2->dst; /* and IKE ones are the same */
2070 		}
2071 
2072 		for (pr = iph2->approval->head; pr; pr = pr->next) {
2073 			xisrlen = sizeof(*xisr);
2074 			if (pr->encmode == IPSECDOI_ATTR_ENC_MODE_TUNNEL) {
2075 				xisrlen += (sysdep_sa_len(src) +
2076 					    sysdep_sa_len(dst));
2077 			}
2078 
2079 			policylen += PFKEY_ALIGN8(xisrlen);
2080 		}
2081 	}
2082 
2083 #ifdef HAVE_SECCTX
2084 	if (*spidx->sec_ctx.ctx_str) {
2085 		ctxlen = sizeof(struct sadb_x_sec_ctx)
2086 				+ PFKEY_ALIGN8(spidx->sec_ctx.ctx_strlen);
2087 		policylen += ctxlen;
2088 	}
2089 #endif /* HAVE_SECCTX */
2090 
2091 	/* make policy structure */
2092 	policy = racoon_malloc(policylen);
2093 	memset((void*)policy, 0xcd, policylen);
2094 	if (!policy) {
2095 		plog(LLV_ERROR, LOCATION, NULL,
2096 			"buffer allocation failed.\n");
2097 		return -1;
2098 	}
2099 
2100 	xpl = (struct sadb_x_policy *)policy;
2101 	xpl->sadb_x_policy_len = PFKEY_UNIT64(policylen);
2102 	xpl->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
2103 	xpl->sadb_x_policy_type = IPSEC_POLICY_IPSEC;
2104 	xpl->sadb_x_policy_dir = spidx->dir;
2105 	xpl->sadb_x_policy_id = 0;
2106 #ifdef HAVE_PFKEY_POLICY_PRIORITY
2107 	xpl->sadb_x_policy_priority = PRIORITY_DEFAULT;
2108 #endif
2109 	len++;
2110 
2111 #ifdef HAVE_SECCTX
2112 	if (*spidx->sec_ctx.ctx_str) {
2113 		struct sadb_x_sec_ctx *p;
2114 
2115 		p = (struct sadb_x_sec_ctx *)(xpl + len);
2116 		memset(p, 0, ctxlen);
2117 		p->sadb_x_sec_len = PFKEY_UNIT64(ctxlen);
2118 		p->sadb_x_sec_exttype = SADB_X_EXT_SEC_CTX;
2119 		p->sadb_x_ctx_len = spidx->sec_ctx.ctx_strlen;
2120 		p->sadb_x_ctx_doi = spidx->sec_ctx.ctx_doi;
2121 		p->sadb_x_ctx_alg = spidx->sec_ctx.ctx_alg;
2122 
2123 		memcpy(p + 1,spidx->sec_ctx.ctx_str,spidx->sec_ctx.ctx_strlen);
2124 		len += ctxlen;
2125 	}
2126 #endif /* HAVE_SECCTX */
2127 
2128 	/* no need to append policy information any more if type is SPDDELETE */
2129 	if (type == SADB_X_SPDDELETE)
2130 		goto end;
2131 
2132 	xisr = (struct sadb_x_ipsecrequest *)(xpl + len);
2133 
2134 	/* The order of things is reversed for use in add policy messages */
2135 	for (pr = iph2->approval->head; pr; pr = pr->next) rlist_len++;
2136 	pr_rlist = racoon_malloc((rlist_len+1)*sizeof(struct saproto*));
2137 	if (!pr_rlist) {
2138 		plog(LLV_ERROR, LOCATION, NULL,
2139 			"buffer allocation failed.\n");
2140 		return -1;
2141 	}
2142 	pr_rlist[rlist_len--] = NULL;
2143 	for (pr = iph2->approval->head; pr; pr = pr->next) pr_rlist[rlist_len--] = pr;
2144 	rlist_len = 0;
2145 
2146 	for (pr = pr_rlist[rlist_len++]; pr; pr = pr_rlist[rlist_len++]) {
2147 
2148 		satype = doi2ipproto(pr->proto_id);
2149 		if (satype == ~0) {
2150 			plog(LLV_ERROR, LOCATION, NULL,
2151 				"invalid proto_id %d\n", pr->proto_id);
2152 			goto err;
2153 		}
2154 		mode = ipsecdoi2pfkey_mode(pr->encmode);
2155 		if (mode == ~0) {
2156 			plog(LLV_ERROR, LOCATION, NULL,
2157 				"invalid encmode %d\n", pr->encmode);
2158 			goto err;
2159 		}
2160 
2161 		/*
2162 		 * the policy level cannot be unique because the policy
2163 		 * is defined later than SA, so req_id cannot be bound to SA.
2164 		 */
2165 		xisr->sadb_x_ipsecrequest_proto = satype;
2166 		xisr->sadb_x_ipsecrequest_mode = mode;
2167 		if(iph2->proposal->head->reqid_in > 0){
2168 			xisr->sadb_x_ipsecrequest_level = IPSEC_LEVEL_UNIQUE;
2169 			xisr->sadb_x_ipsecrequest_reqid = iph2->proposal->head->reqid_in;
2170 		}else{
2171 			xisr->sadb_x_ipsecrequest_level = IPSEC_LEVEL_REQUIRE;
2172 			xisr->sadb_x_ipsecrequest_reqid = 0;
2173 		}
2174 		p = (caddr_t)(xisr + 1);
2175 
2176 		xisrlen = sizeof(*xisr);
2177 
2178 		if (pr->encmode == IPSECDOI_ATTR_ENC_MODE_TUNNEL) {
2179 			int src_len, dst_len;
2180 
2181 			src_len = sysdep_sa_len(src);
2182 			dst_len = sysdep_sa_len(dst);
2183 			xisrlen += src_len + dst_len;
2184 
2185 			memcpy(p, src, src_len);
2186 			p += src_len;
2187 
2188 			memcpy(p, dst, dst_len);
2189 			p += dst_len;
2190 		}
2191 
2192 		xisr->sadb_x_ipsecrequest_len = PFKEY_ALIGN8(xisrlen);
2193 		xisr = (struct sadb_x_ipsecrequest *)p;
2194 
2195 	}
2196 	racoon_free(pr_rlist);
2197 
2198 end:
2199 	*policy0 = policy;
2200 	*policylen0 = policylen;
2201 
2202 	return 0;
2203 
2204 err:
2205 	if (policy)
2206 		racoon_free(policy);
2207 	if (pr_rlist) racoon_free(pr_rlist);
2208 
2209 	return -1;
2210 }
2211 
2212 int
2213 pk_sendspdupdate2(iph2)
2214 	struct ph2handle *iph2;
2215 {
2216 	struct policyindex *spidx = (struct policyindex *)iph2->spidx_gen;
2217 	caddr_t policy = NULL;
2218 	int policylen = 0;
2219 	u_int64_t ltime, vtime;
2220 
2221 	ltime = iph2->approval->lifetime;
2222 	vtime = 0;
2223 
2224 	if (getsadbpolicy(&policy, &policylen, SADB_X_SPDUPDATE, iph2)) {
2225 		plog(LLV_ERROR, LOCATION, NULL,
2226 			"getting sadb policy failed.\n");
2227 		return -1;
2228 	}
2229 
2230 	if (pfkey_send_spdupdate2(
2231 			lcconf->sock_pfkey,
2232 			(struct sockaddr *)&spidx->src,
2233 			spidx->prefs,
2234 			(struct sockaddr *)&spidx->dst,
2235 			spidx->prefd,
2236 			spidx->ul_proto,
2237 			ltime, vtime,
2238 			policy, policylen, 0) < 0) {
2239 		plog(LLV_ERROR, LOCATION, NULL,
2240 			"libipsec failed send spdupdate2 (%s)\n",
2241 			ipsec_strerror());
2242 		goto end;
2243 	}
2244 	plog(LLV_DEBUG, LOCATION, NULL, "call pfkey_send_spdupdate2\n");
2245 
2246 end:
2247 	if (policy)
2248 		racoon_free(policy);
2249 
2250 	return 0;
2251 }
2252 
2253 static int
2254 pk_recvspdupdate(mhp)
2255 	caddr_t *mhp;
2256 {
2257 	struct sadb_address *saddr, *daddr;
2258 	struct sadb_x_policy *xpl;
2259 	struct sadb_lifetime *lt;
2260 	struct policyindex spidx;
2261 	struct secpolicy *sp;
2262 	struct sockaddr *local=NULL, *remote=NULL;
2263 	u_int64_t created;
2264 	int ret;
2265 
2266 	/* sanity check */
2267 	if (mhp[0] == NULL
2268 	 || mhp[SADB_EXT_ADDRESS_SRC] == NULL
2269 	 || mhp[SADB_EXT_ADDRESS_DST] == NULL
2270 	 || mhp[SADB_X_EXT_POLICY] == NULL) {
2271 		plog(LLV_ERROR, LOCATION, NULL,
2272 			"inappropriate sadb spdupdate message passed.\n");
2273 		return -1;
2274 	}
2275 	saddr = (struct sadb_address *)mhp[SADB_EXT_ADDRESS_SRC];
2276 	daddr = (struct sadb_address *)mhp[SADB_EXT_ADDRESS_DST];
2277 	xpl = (struct sadb_x_policy *)mhp[SADB_X_EXT_POLICY];
2278 	lt = (struct sadb_lifetime*)mhp[SADB_EXT_LIFETIME_HARD];
2279 	if(lt != NULL)
2280 		created = lt->sadb_lifetime_addtime;
2281 	else
2282 		created = 0;
2283 
2284 #ifdef HAVE_PFKEY_POLICY_PRIORITY
2285 	KEY_SETSECSPIDX(xpl->sadb_x_policy_dir,
2286 			saddr + 1,
2287 			daddr + 1,
2288 			saddr->sadb_address_prefixlen,
2289 			daddr->sadb_address_prefixlen,
2290 			saddr->sadb_address_proto,
2291 			xpl->sadb_x_policy_priority,
2292 			created,
2293 			&spidx);
2294 #else
2295 	KEY_SETSECSPIDX(xpl->sadb_x_policy_dir,
2296 			saddr + 1,
2297 			daddr + 1,
2298 			saddr->sadb_address_prefixlen,
2299 			daddr->sadb_address_prefixlen,
2300 			saddr->sadb_address_proto,
2301 			created,
2302 			&spidx);
2303 #endif
2304 
2305 #ifdef HAVE_SECCTX
2306 	if (mhp[SADB_X_EXT_SEC_CTX] != NULL) {
2307 		struct sadb_x_sec_ctx *ctx;
2308 
2309 		ctx = (struct sadb_x_sec_ctx *)mhp[SADB_X_EXT_SEC_CTX];
2310 		spidx.sec_ctx.ctx_alg = ctx->sadb_x_ctx_alg;
2311 		spidx.sec_ctx.ctx_doi = ctx->sadb_x_ctx_doi;
2312 		spidx.sec_ctx.ctx_strlen = ctx->sadb_x_ctx_len;
2313 		memcpy(spidx.sec_ctx.ctx_str, ctx + 1, ctx->sadb_x_ctx_len);
2314 	}
2315 #endif /* HAVE_SECCTX */
2316 
2317 	sp = getsp(&spidx);
2318 	if (sp == NULL) {
2319 		plog(LLV_ERROR, LOCATION, NULL,
2320 			"such policy does not already exist: \"%s\"\n",
2321 			spidx2str(&spidx));
2322 	} else {
2323 		/* preserve hints before deleting the SP */
2324 		local = sp->local;
2325 		remote = sp->remote;
2326 		sp->local = NULL;
2327 		sp->remote = NULL;
2328 
2329 		remsp(sp);
2330 		delsp(sp);
2331 	}
2332 
2333 	/* Add new SP (with old hints) */
2334 	ret = addnewsp(mhp, local, remote);
2335 
2336 	if (local != NULL)
2337 		racoon_free(local);
2338 	if (remote != NULL)
2339 		racoon_free(remote);
2340 
2341 	if (ret < 0)
2342 		return -1;
2343 
2344 	return 0;
2345 }
2346 
2347 /*
2348  * this function has to be used by responder side.
2349  */
2350 int
2351 pk_sendspdadd2(iph2)
2352 	struct ph2handle *iph2;
2353 {
2354 	struct policyindex *spidx = (struct policyindex *)iph2->spidx_gen;
2355 	caddr_t policy = NULL;
2356 	int policylen = 0;
2357 	u_int64_t ltime, vtime;
2358 
2359 	ltime = iph2->approval->lifetime;
2360 	vtime = 0;
2361 
2362 	if (getsadbpolicy(&policy, &policylen, SADB_X_SPDADD, iph2)) {
2363 		plog(LLV_ERROR, LOCATION, NULL,
2364 			"getting sadb policy failed.\n");
2365 		return -1;
2366 	}
2367 
2368 	if (pfkey_send_spdadd2(
2369 			lcconf->sock_pfkey,
2370 			(struct sockaddr *)&spidx->src,
2371 			spidx->prefs,
2372 			(struct sockaddr *)&spidx->dst,
2373 			spidx->prefd,
2374 			spidx->ul_proto,
2375 			ltime, vtime,
2376 			policy, policylen, 0) < 0) {
2377 		plog(LLV_ERROR, LOCATION, NULL,
2378 			"libipsec failed send spdadd2 (%s)\n",
2379 			ipsec_strerror());
2380 		goto end;
2381 	}
2382 	plog(LLV_DEBUG, LOCATION, NULL, "call pfkey_send_spdadd2\n");
2383 
2384 end:
2385 	if (policy)
2386 		racoon_free(policy);
2387 
2388 	return 0;
2389 }
2390 
2391 static int
2392 pk_recvspdadd(mhp)
2393 	caddr_t *mhp;
2394 {
2395 	struct sadb_address *saddr, *daddr;
2396 	struct sadb_x_policy *xpl;
2397 	struct sadb_lifetime *lt;
2398 	struct policyindex spidx;
2399 	struct secpolicy *sp;
2400 	struct sockaddr *local = NULL, *remote = NULL;
2401 	u_int64_t created;
2402 	int ret;
2403 
2404 	/* sanity check */
2405 	if (mhp[0] == NULL
2406 	 || mhp[SADB_EXT_ADDRESS_SRC] == NULL
2407 	 || mhp[SADB_EXT_ADDRESS_DST] == NULL
2408 	 || mhp[SADB_X_EXT_POLICY] == NULL) {
2409 		plog(LLV_ERROR, LOCATION, NULL,
2410 			"inappropriate sadb spdadd message passed.\n");
2411 		return -1;
2412 	}
2413 	saddr = (struct sadb_address *)mhp[SADB_EXT_ADDRESS_SRC];
2414 	daddr = (struct sadb_address *)mhp[SADB_EXT_ADDRESS_DST];
2415 	xpl = (struct sadb_x_policy *)mhp[SADB_X_EXT_POLICY];
2416 	lt = (struct sadb_lifetime*)mhp[SADB_EXT_LIFETIME_HARD];
2417 	if(lt != NULL)
2418 		created = lt->sadb_lifetime_addtime;
2419 	else
2420 		created = 0;
2421 
2422 #ifdef HAVE_PFKEY_POLICY_PRIORITY
2423 	KEY_SETSECSPIDX(xpl->sadb_x_policy_dir,
2424 			saddr + 1,
2425 			daddr + 1,
2426 			saddr->sadb_address_prefixlen,
2427 			daddr->sadb_address_prefixlen,
2428 			saddr->sadb_address_proto,
2429 			xpl->sadb_x_policy_priority,
2430 			created,
2431 			&spidx);
2432 #else
2433 	KEY_SETSECSPIDX(xpl->sadb_x_policy_dir,
2434 			saddr + 1,
2435 			daddr + 1,
2436 			saddr->sadb_address_prefixlen,
2437 			daddr->sadb_address_prefixlen,
2438 			saddr->sadb_address_proto,
2439 			created,
2440 			&spidx);
2441 #endif
2442 
2443 #ifdef HAVE_SECCTX
2444 	if (mhp[SADB_X_EXT_SEC_CTX] != NULL) {
2445 		struct sadb_x_sec_ctx *ctx;
2446 
2447 		ctx = (struct sadb_x_sec_ctx *)mhp[SADB_X_EXT_SEC_CTX];
2448 		spidx.sec_ctx.ctx_alg = ctx->sadb_x_ctx_alg;
2449 		spidx.sec_ctx.ctx_doi = ctx->sadb_x_ctx_doi;
2450 		spidx.sec_ctx.ctx_strlen = ctx->sadb_x_ctx_len;
2451 		memcpy(spidx.sec_ctx.ctx_str, ctx + 1, ctx->sadb_x_ctx_len);
2452 	}
2453 #endif /* HAVE_SECCTX */
2454 
2455 	sp = getsp(&spidx);
2456 	if (sp != NULL) {
2457 		plog(LLV_ERROR, LOCATION, NULL,
2458 			"such policy already exists. "
2459 			"anyway replace it: %s\n",
2460 			spidx2str(&spidx));
2461 
2462 		/* preserve hints before deleting the SP */
2463 		local = sp->local;
2464 		remote = sp->remote;
2465 		sp->local = NULL;
2466 		sp->remote = NULL;
2467 
2468 		remsp(sp);
2469 		delsp(sp);
2470 	}
2471 
2472 	/* Add new SP (with old hints) */
2473 	ret = addnewsp(mhp, local, remote);
2474 
2475 	if (local != NULL)
2476 		racoon_free(local);
2477 	if (remote != NULL)
2478 		racoon_free(remote);
2479 
2480 	if (ret < 0)
2481 		return -1;
2482 
2483 	return 0;
2484 }
2485 
2486 /*
2487  * this function has to be used by responder side.
2488  */
2489 int
2490 pk_sendspddelete(iph2)
2491 	struct ph2handle *iph2;
2492 {
2493 	struct policyindex *spidx = (struct policyindex *)iph2->spidx_gen;
2494 	caddr_t policy = NULL;
2495 	int policylen;
2496 
2497 	if (getsadbpolicy(&policy, &policylen, SADB_X_SPDDELETE, iph2)) {
2498 		plog(LLV_ERROR, LOCATION, NULL,
2499 			"getting sadb policy failed.\n");
2500 		return -1;
2501 	}
2502 
2503 	if (pfkey_send_spddelete(
2504 			lcconf->sock_pfkey,
2505 			(struct sockaddr *)&spidx->src,
2506 			spidx->prefs,
2507 			(struct sockaddr *)&spidx->dst,
2508 			spidx->prefd,
2509 			spidx->ul_proto,
2510 			policy, policylen, 0) < 0) {
2511 		plog(LLV_ERROR, LOCATION, NULL,
2512 			"libipsec failed send spddelete (%s)\n",
2513 			ipsec_strerror());
2514 		goto end;
2515 	}
2516 	plog(LLV_DEBUG, LOCATION, NULL, "call pfkey_send_spddelete\n");
2517 
2518 end:
2519 	if (policy)
2520 		racoon_free(policy);
2521 
2522 	return 0;
2523 }
2524 
2525 static int
2526 pk_recvspddelete(mhp)
2527 	caddr_t *mhp;
2528 {
2529 	struct sadb_address *saddr, *daddr;
2530 	struct sadb_x_policy *xpl;
2531 	struct sadb_lifetime *lt;
2532 	struct policyindex spidx;
2533 	struct secpolicy *sp;
2534 	u_int64_t created;
2535 
2536 	/* sanity check */
2537 	if (mhp[0] == NULL
2538 	 || mhp[SADB_EXT_ADDRESS_SRC] == NULL
2539 	 || mhp[SADB_EXT_ADDRESS_DST] == NULL
2540 	 || mhp[SADB_X_EXT_POLICY] == NULL) {
2541 		plog(LLV_ERROR, LOCATION, NULL,
2542 			"inappropriate sadb spddelete message passed.\n");
2543 		return -1;
2544 	}
2545 	saddr = (struct sadb_address *)mhp[SADB_EXT_ADDRESS_SRC];
2546 	daddr = (struct sadb_address *)mhp[SADB_EXT_ADDRESS_DST];
2547 	xpl = (struct sadb_x_policy *)mhp[SADB_X_EXT_POLICY];
2548 	lt = (struct sadb_lifetime*)mhp[SADB_EXT_LIFETIME_HARD];
2549 	if(lt != NULL)
2550 		created = lt->sadb_lifetime_addtime;
2551 	else
2552 		created = 0;
2553 
2554 #ifdef HAVE_PFKEY_POLICY_PRIORITY
2555 	KEY_SETSECSPIDX(xpl->sadb_x_policy_dir,
2556 			saddr + 1,
2557 			daddr + 1,
2558 			saddr->sadb_address_prefixlen,
2559 			daddr->sadb_address_prefixlen,
2560 			saddr->sadb_address_proto,
2561 			xpl->sadb_x_policy_priority,
2562 			created,
2563 			&spidx);
2564 #else
2565 	KEY_SETSECSPIDX(xpl->sadb_x_policy_dir,
2566 			saddr + 1,
2567 			daddr + 1,
2568 			saddr->sadb_address_prefixlen,
2569 			daddr->sadb_address_prefixlen,
2570 			saddr->sadb_address_proto,
2571 			created,
2572 			&spidx);
2573 #endif
2574 
2575 #ifdef HAVE_SECCTX
2576 	if (mhp[SADB_X_EXT_SEC_CTX] != NULL) {
2577 		struct sadb_x_sec_ctx *ctx;
2578 
2579 		ctx = (struct sadb_x_sec_ctx *)mhp[SADB_X_EXT_SEC_CTX];
2580 		spidx.sec_ctx.ctx_alg = ctx->sadb_x_ctx_alg;
2581 		spidx.sec_ctx.ctx_doi = ctx->sadb_x_ctx_doi;
2582 		spidx.sec_ctx.ctx_strlen = ctx->sadb_x_ctx_len;
2583 		memcpy(spidx.sec_ctx.ctx_str, ctx + 1, ctx->sadb_x_ctx_len);
2584 	}
2585 #endif /* HAVE_SECCTX */
2586 
2587 	sp = getsp(&spidx);
2588 	if (sp == NULL) {
2589 		plog(LLV_ERROR, LOCATION, NULL,
2590 			"no policy found: %s\n",
2591 			spidx2str(&spidx));
2592 		return -1;
2593 	}
2594 
2595 	remsp(sp);
2596 	delsp(sp);
2597 
2598 	return 0;
2599 }
2600 
2601 static int
2602 pk_recvspdexpire(mhp)
2603 	caddr_t *mhp;
2604 {
2605 	struct sadb_address *saddr, *daddr;
2606 	struct sadb_x_policy *xpl;
2607 	struct sadb_lifetime *lt;
2608 	struct policyindex spidx;
2609 	struct secpolicy *sp;
2610 	u_int64_t created;
2611 
2612 	/* sanity check */
2613 	if (mhp[0] == NULL
2614 	 || mhp[SADB_EXT_ADDRESS_SRC] == NULL
2615 	 || mhp[SADB_EXT_ADDRESS_DST] == NULL
2616 	 || mhp[SADB_X_EXT_POLICY] == NULL) {
2617 		plog(LLV_ERROR, LOCATION, NULL,
2618 			"inappropriate sadb spdexpire message passed.\n");
2619 		return -1;
2620 	}
2621 	saddr = (struct sadb_address *)mhp[SADB_EXT_ADDRESS_SRC];
2622 	daddr = (struct sadb_address *)mhp[SADB_EXT_ADDRESS_DST];
2623 	xpl = (struct sadb_x_policy *)mhp[SADB_X_EXT_POLICY];
2624 	lt = (struct sadb_lifetime*)mhp[SADB_EXT_LIFETIME_HARD];
2625 	if(lt != NULL)
2626 		created = lt->sadb_lifetime_addtime;
2627 	else
2628 		created = 0;
2629 
2630 #ifdef HAVE_PFKEY_POLICY_PRIORITY
2631 	KEY_SETSECSPIDX(xpl->sadb_x_policy_dir,
2632 			saddr + 1,
2633 			daddr + 1,
2634 			saddr->sadb_address_prefixlen,
2635 			daddr->sadb_address_prefixlen,
2636 			saddr->sadb_address_proto,
2637 			xpl->sadb_x_policy_priority,
2638 			created,
2639 			&spidx);
2640 #else
2641 	KEY_SETSECSPIDX(xpl->sadb_x_policy_dir,
2642 			saddr + 1,
2643 			daddr + 1,
2644 			saddr->sadb_address_prefixlen,
2645 			daddr->sadb_address_prefixlen,
2646 			saddr->sadb_address_proto,
2647 			created,
2648 			&spidx);
2649 #endif
2650 
2651 #ifdef HAVE_SECCTX
2652 	if (mhp[SADB_X_EXT_SEC_CTX] != NULL) {
2653 		struct sadb_x_sec_ctx *ctx;
2654 
2655 		ctx = (struct sadb_x_sec_ctx *)mhp[SADB_X_EXT_SEC_CTX];
2656 		spidx.sec_ctx.ctx_alg = ctx->sadb_x_ctx_alg;
2657 		spidx.sec_ctx.ctx_doi = ctx->sadb_x_ctx_doi;
2658 		spidx.sec_ctx.ctx_strlen = ctx->sadb_x_ctx_len;
2659 		memcpy(spidx.sec_ctx.ctx_str, ctx + 1, ctx->sadb_x_ctx_len);
2660 	}
2661 #endif /* HAVE_SECCTX */
2662 
2663 	sp = getsp(&spidx);
2664 	if (sp == NULL) {
2665 		plog(LLV_ERROR, LOCATION, NULL,
2666 			"no policy found: %s\n",
2667 			spidx2str(&spidx));
2668 		return -1;
2669 	}
2670 
2671 	remsp(sp);
2672 	delsp(sp);
2673 
2674 	return 0;
2675 }
2676 
2677 static int
2678 pk_recvspdget(mhp)
2679 	caddr_t *mhp;
2680 {
2681 	/* sanity check */
2682 	if (mhp[0] == NULL) {
2683 		plog(LLV_ERROR, LOCATION, NULL,
2684 			"inappropriate sadb spdget message passed.\n");
2685 		return -1;
2686 	}
2687 
2688 	return 0;
2689 }
2690 
2691 static int
2692 pk_recvspddump(mhp)
2693 	caddr_t *mhp;
2694 {
2695 	struct sadb_msg *msg;
2696 	struct sadb_address *saddr, *daddr;
2697 	struct sadb_x_policy *xpl;
2698 	struct sadb_lifetime *lt;
2699 	struct policyindex spidx;
2700 	struct secpolicy *sp;
2701 	struct sockaddr *local=NULL, *remote=NULL;
2702 	u_int64_t created;
2703 	int ret;
2704 
2705 	/* sanity check */
2706 	if (mhp[0] == NULL) {
2707 		plog(LLV_ERROR, LOCATION, NULL,
2708 			"inappropriate sadb spddump message passed.\n");
2709 		return -1;
2710 	}
2711 	msg = (struct sadb_msg *)mhp[0];
2712 
2713 	saddr = (struct sadb_address *)mhp[SADB_EXT_ADDRESS_SRC];
2714 	daddr = (struct sadb_address *)mhp[SADB_EXT_ADDRESS_DST];
2715 	xpl = (struct sadb_x_policy *)mhp[SADB_X_EXT_POLICY];
2716 	lt = (struct sadb_lifetime*)mhp[SADB_EXT_LIFETIME_HARD];
2717 	if(lt != NULL)
2718 		created = lt->sadb_lifetime_addtime;
2719 	else
2720 		created = 0;
2721 
2722 	if (saddr == NULL || daddr == NULL || xpl == NULL) {
2723 		plog(LLV_ERROR, LOCATION, NULL,
2724 			"inappropriate sadb spddump message passed.\n");
2725 		return -1;
2726 	}
2727 
2728 #ifdef HAVE_PFKEY_POLICY_PRIORITY
2729 	KEY_SETSECSPIDX(xpl->sadb_x_policy_dir,
2730 			saddr + 1,
2731 			daddr + 1,
2732 			saddr->sadb_address_prefixlen,
2733 			daddr->sadb_address_prefixlen,
2734 			saddr->sadb_address_proto,
2735 			xpl->sadb_x_policy_priority,
2736 			created,
2737 			&spidx);
2738 #else
2739 	KEY_SETSECSPIDX(xpl->sadb_x_policy_dir,
2740 			saddr + 1,
2741 			daddr + 1,
2742 			saddr->sadb_address_prefixlen,
2743 			daddr->sadb_address_prefixlen,
2744 			saddr->sadb_address_proto,
2745 			created,
2746 			&spidx);
2747 #endif
2748 
2749 #ifdef HAVE_SECCTX
2750 	if (mhp[SADB_X_EXT_SEC_CTX] != NULL) {
2751 		struct sadb_x_sec_ctx *ctx;
2752 
2753 		ctx = (struct sadb_x_sec_ctx *)mhp[SADB_X_EXT_SEC_CTX];
2754 		spidx.sec_ctx.ctx_alg = ctx->sadb_x_ctx_alg;
2755 		spidx.sec_ctx.ctx_doi = ctx->sadb_x_ctx_doi;
2756 		spidx.sec_ctx.ctx_strlen = ctx->sadb_x_ctx_len;
2757 		memcpy(spidx.sec_ctx.ctx_str, ctx + 1, ctx->sadb_x_ctx_len);
2758 	}
2759 #endif /* HAVE_SECCTX */
2760 
2761 	sp = getsp(&spidx);
2762 	if (sp != NULL) {
2763 		plog(LLV_ERROR, LOCATION, NULL,
2764 			"such policy already exists. "
2765 			"anyway replace it: %s\n",
2766 			spidx2str(&spidx));
2767 
2768 		/* preserve hints before deleting the SP */
2769 		local = sp->local;
2770 		remote = sp->remote;
2771 		sp->local = NULL;
2772 		sp->remote = NULL;
2773 
2774 		remsp(sp);
2775 		delsp(sp);
2776 	}
2777 
2778 	/* Add new SP (with old hints) */
2779 	ret = addnewsp(mhp, local, remote);
2780 
2781 	if (local != NULL)
2782 		racoon_free(local);
2783 	if (remote != NULL)
2784 		racoon_free(remote);
2785 
2786 	if (ret < 0)
2787 		return -1;
2788 
2789 	return 0;
2790 }
2791 
2792 static int
2793 pk_recvspdflush(mhp)
2794 	caddr_t *mhp;
2795 {
2796 	/* sanity check */
2797 	if (mhp[0] == NULL) {
2798 		plog(LLV_ERROR, LOCATION, NULL,
2799 			"inappropriate sadb spdflush message passed.\n");
2800 		return -1;
2801 	}
2802 
2803 	flushsp();
2804 
2805 	return 0;
2806 }
2807 
2808 #if defined(SADB_X_MIGRATE) && defined(SADB_X_EXT_KMADDRESS)
2809 
2810 /* MIGRATE support (pk_recvmigrate() is the handler of MIGRATE message).
2811  *
2812  * pk_recvmigrate()
2813  *   1) some preprocessing and checks
2814  *   2) parsing of sadb_x_kmaddress extension
2815  *   3) SP lookup using selectors and content of policy extension from MIGRATE
2816  *   4) resolution of current local and remote IKE addresses
2817  *   5) Use of addresses to get Phase 1 handler if any
2818  *   6) Update of IKE addresses in Phase 1 (iph1->local and iph1->remote)
2819  *   7) Update of IKE addresses in Phase 2 (iph2->src and iph2->dst)
2820  *   8) Update of IKE addresses in SP (sp->local and sp->remote)
2821  *   9) Loop on sadb_x_ipsecrequests pairs from MIGRATE
2822  *      - update of associated ipsecrequests entries in sp->req (should be
2823  *        only one as racoon does not support bundles), i.e. update of
2824  *        tunnel endpoints when required.
2825  *      - If tunnel mode endpoints have been updated, lookup of associated
2826  *        Phase 2 handle to also update sa_src and sa_dst entries
2827  *
2828  * XXX Note that we do not support yet the update of SA addresses for transport
2829  *     mode, but only the update of SA addresses for tunnel mode (endpoints).
2830  *     Reasons are:
2831  *      - there is no initial need for MIPv6
2832  *      - racoon does not support bundles
2833  *      - this would imply more work to deal with sainfo update (if feasible).
2834  */
2835 
2836 /* Generic argument structure for migration callbacks */
2837 struct migrate_args {
2838 	struct sockaddr *local;
2839 	struct sockaddr *remote;
2840 };
2841 
2842 /*
2843  * Update local and remote addresses of given Phase 1. Schedule removal
2844  * if negotiation was going on and restart a one from updated address.
2845  *
2846  * -1 is returned on error. 0 if everything went right.
2847  */
2848 static int
2849 migrate_ph1_ike_addresses(iph1, arg)
2850         struct ph1handle *iph1;
2851         void *arg;
2852 {
2853 	struct migrate_args *ma = (struct migrate_args *) arg;
2854 	struct remoteconf *rmconf;
2855 	u_int16_t port;
2856 
2857 	/* Already up-to-date? */
2858 	if (cmpsaddrwop(iph1->local, ma->local) == 0 &&
2859 	    cmpsaddrwop(iph1->remote, ma->remote) == 0)
2860 		return 0;
2861 
2862 	if (iph1->status < PHASE1ST_ESTABLISHED) {
2863 		/* Bad luck! We received a MIGRATE *while* negotiating
2864 		 * Phase 1 (i.e. it was not established yet). If we act as
2865 		 * initiator we need to restart the negotiation. As
2866 		 * responder, our best bet is to update our addresses
2867 		 * and wait for the initiator to do something */
2868 		plog(LLV_WARNING, LOCATION, NULL, "MIGRATE received *during* "
2869 		     "Phase 1 negotiation (%s).\n",
2870 		     saddr2str_fromto("%s => %s", ma->local, ma->remote));
2871 
2872 		/* If we are not acting as initiator, let's just leave and
2873 		 * let the remote peer handle the restart */
2874 		rmconf = getrmconf(ma->remote);
2875 		if (rmconf == NULL || !rmconf->passive) {
2876 			iph1->status = PHASE1ST_EXPIRED;
2877 			sched_schedule(&iph1->sce, 1, isakmp_ph1delete_stub);
2878 
2879 			/* This is unlikely, but let's just check if a Phase 1
2880 			 * for the new addresses already exist */
2881 			if (getph1byaddr(ma->local, ma->remote, 0)) {
2882 				plog(LLV_WARNING, LOCATION, NULL, "No need "
2883 				     "to start a new Phase 1 negotiation. One "
2884 				     "already exists.\n");
2885 				return 0;
2886 			}
2887 
2888 			plog(LLV_WARNING, LOCATION, NULL, "As initiator, "
2889 			     "restarting it.\n");
2890 			 /* Note that the insertion of the new Phase 1 will not
2891 			  * interfere with the fact we are called from enumph1,
2892 			  * because it is inserted as first element. --arno */
2893 			isakmp_ph1begin_i(rmconf, ma->local, ma->remote);
2894 
2895 			return 0;
2896 		}
2897 	}
2898 
2899 	if (iph1->local != NULL) {
2900 		plog(LLV_DEBUG, LOCATION, NULL, "Migrating Phase 1 local "
2901 		     "address from %s\n",
2902 		     saddr2str_fromto("%s to %s", iph1->local, ma->local));
2903 		port = extract_port(iph1->local);
2904 		racoon_free(iph1->local);
2905 	} else
2906 		port = 0;
2907 
2908 	iph1->local = dupsaddr(ma->local);
2909 	if (iph1->local == NULL) {
2910 		plog(LLV_ERROR, LOCATION, NULL, "unable to allocate "
2911 		     "Phase 1 local address.\n");
2912 		return -1;
2913 	}
2914 	set_port(iph1->local, port);
2915 
2916 	if (iph1->remote != NULL) {
2917 		plog(LLV_DEBUG, LOCATION, NULL, "Migrating Phase 1 remote "
2918 		     "address from %s\n",
2919 		     saddr2str_fromto("%s to %s", iph1->remote, ma->remote));
2920 		port = extract_port(iph1->remote);
2921 		racoon_free(iph1->remote);
2922 	} else
2923 		port = 0;
2924 
2925 	iph1->remote = dupsaddr(ma->remote);
2926 	if (iph1->remote == NULL) {
2927 		plog(LLV_ERROR, LOCATION, NULL, "unable to allocate "
2928 		     "Phase 1 remote address.\n");
2929 		return -1;
2930 	}
2931 	set_port(iph1->remote, port);
2932 
2933 	return 0;
2934 }
2935 
2936 /* Update src and dst of all current Phase 2 handles.
2937  * with provided local and remote addresses.
2938  * Our intent is NOT to modify IPsec SA endpoints but IKE
2939  * addresses so we need to take care to separate those if
2940  * they are different. -1 is returned on error. 0 if everything
2941  * went right.
2942  *
2943  * Note: we do not maintain port information as it is not
2944  *       expected to be meaningful --arno
2945  */
2946 static int
2947 migrate_ph2_ike_addresses(iph2, arg)
2948 	struct ph2handle *iph2;
2949 	void *arg;
2950 {
2951 	struct migrate_args *ma = (struct migrate_args *) arg;
2952 	struct ph1handle *iph1;
2953 
2954 	/* If Phase 2 has an associated Phase 1, migrate addresses */
2955 	if (iph2->ph1)
2956 		migrate_ph1_ike_addresses(iph2->ph1, arg);
2957 
2958 	/* Already up-to-date? */
2959 	if (CMPSADDR(iph2->src, ma->local) == 0 &&
2960 	    CMPSADDR(iph2->dst, ma->remote) == 0)
2961 		return 0;
2962 
2963 	/* save src/dst as sa_src/sa_dst before rewriting */
2964 	if (iph2->sa_src == NULL && iph2->sa_dst == NULL) {
2965 		iph2->sa_src = iph2->src;
2966 		iph2->sa_dst = iph2->dst;
2967 		iph2->src = NULL;
2968 		iph2->dst = NULL;
2969 	}
2970 
2971 	if (iph2->src != NULL)
2972 		racoon_free(iph2->src);
2973 	iph2->src = dupsaddr(ma->local);
2974 	if (iph2->src == NULL) {
2975 		plog(LLV_ERROR, LOCATION, NULL,
2976 		     "unable to allocate Phase 2 src address.\n");
2977 		return -1;
2978 	}
2979 
2980 	if (iph2->dst != NULL)
2981 		racoon_free(iph2->dst);
2982 	iph2->dst = dupsaddr(ma->remote);
2983 	if (iph2->dst == NULL) {
2984 		plog(LLV_ERROR, LOCATION, NULL,
2985 		     "unable to allocate Phase 2 dst address.\n");
2986 		return -1;
2987 	}
2988 
2989 	return 0;
2990 }
2991 
2992 /* Consider existing Phase 2 handles with given spid and update their source
2993  * and destination addresses for SA. As racoon does not support bundles, if
2994  * we modify multiple occurrences, this probably imply rekeying has happened.
2995  *
2996  * Both addresses passed to the function are expected not to be NULL and of
2997  * same family. -1 is returned on error. 0 if everything went right.
2998  *
2999  * Specific care is needed to support Phase 2 for which negotiation has
3000  * already started but are which not yet established.
3001  */
3002 static int
3003 migrate_ph2_sa_addresses(iph2, args)
3004 	struct ph2handle *iph2;
3005 	void *args;
3006 {
3007 	struct migrate_args *ma = (struct migrate_args *) args;
3008 
3009 	if (iph2->sa_src != NULL) {
3010 		racoon_free(iph2->sa_src);
3011 		iph2->sa_src = NULL;
3012 	}
3013 
3014 	if (iph2->sa_dst != NULL) {
3015 		racoon_free(iph2->sa_dst);
3016 		iph2->sa_dst = NULL;
3017 	}
3018 
3019 	iph2->sa_src = dupsaddr(ma->local);
3020 	if (iph2->sa_src == NULL) {
3021 		plog(LLV_ERROR, LOCATION, NULL,
3022 		     "unable to allocate Phase 2 sa_src address.\n");
3023 		return -1;
3024 	}
3025 
3026 	iph2->sa_dst = dupsaddr(ma->remote);
3027 	if (iph2->sa_dst == NULL) {
3028 		plog(LLV_ERROR, LOCATION, NULL,
3029 		     "unable to allocate Phase 2 sa_dst address.\n");
3030 		return -1;
3031 	}
3032 
3033 	if (iph2->status < PHASE2ST_ESTABLISHED) {
3034 		struct remoteconf *rmconf;
3035 		/* We were negotiating for that SA when we received the MIGRATE.
3036 		 * We cannot simply update the addresses and let the exchange
3037 		 * go on. We have to restart the whole negotiation if we are
3038 		 * the initiator. Otherwise (acting as responder), we just need
3039 		 * to delete our ph2handle and wait for the initiator to start
3040 		 * a new negotiation. */
3041 
3042 		if (iph2->ph1 && iph2->ph1->rmconf)
3043 			rmconf = iph2->ph1->rmconf;
3044 		else
3045 			rmconf = getrmconf(iph2->dst);
3046 
3047 		if (rmconf && !rmconf->passive) {
3048 			plog(LLV_WARNING, LOCATION, iph2->dst, "MIGRATE received "
3049 			     "*during* IPsec SA negotiation. As initiator, "
3050 			     "restarting it.\n");
3051 
3052 			/* Turn off expiration timer ...*/
3053 			sched_cancel(&iph2->sce);
3054 			iph2->status = PHASE2ST_EXPIRED;
3055 
3056 			/* ... clean Phase 2 handle ... */
3057 			initph2(iph2);
3058 			iph2->status = PHASE2ST_STATUS2;
3059 
3060 			/* and start a new negotiation */
3061 			if (isakmp_post_acquire(iph2) < 0) {
3062 				plog(LLV_ERROR, LOCATION, iph2->dst, "failed "
3063 				     "to begin IPsec SA renegotiation after "
3064 				     "MIGRATE reception.\n");
3065 				remph2(iph2);
3066 				delph2(iph2);
3067 				return -1;
3068 			}
3069 		} else {
3070 			plog(LLV_WARNING, LOCATION, iph2->dst, "MIGRATE received "
3071 			     "*during* IPsec SA negotiation. As responder, let's"
3072 			     "wait for the initiator to act.\n");
3073 
3074 			/* Simply schedule deletion */
3075 			isakmp_ph2expire(iph2);
3076 		}
3077 	}
3078 
3079 	return 0;
3080 }
3081 
3082 /* Update SP hints (local and remote addresses) for future IKE
3083  * negotiations of SA associated with that SP. -1 is returned
3084  * on error. 0 if everything went right.
3085  *
3086  * Note: we do not maintain port information as it is not
3087  *       expected to be meaningful --arno
3088  */
3089 static int
3090 migrate_sp_ike_addresses(sp, local, remote)
3091         struct secpolicy *sp;
3092         struct sockaddr *local, *remote;
3093 {
3094 	if (sp == NULL || local == NULL || remote == NULL)
3095 		return -1;
3096 
3097 	if (sp->local != NULL)
3098 		racoon_free(sp->local);
3099 
3100 	sp->local = dupsaddr(local);
3101 	if (sp->local == NULL) {
3102 		plog(LLV_ERROR, LOCATION, NULL, "unable to allocate "
3103 		     "local hint for SP.\n");
3104 		return -1;
3105 	}
3106 
3107 	if (sp->remote != NULL)
3108 		racoon_free(sp->remote);
3109 
3110 	sp->remote = dupsaddr(remote);
3111 	if (sp->remote == NULL) {
3112 		plog(LLV_ERROR, LOCATION, NULL, "unable to allocate "
3113 		     "remote hint for SP.\n");
3114 		return -1;
3115 	}
3116 
3117 	return 0;
3118 }
3119 
3120 /* Given current ipsecrequest (isr_cur) to be migrated in considered
3121    tree, the function first checks that it matches the expected one
3122    (xisr_old) provided in MIGRATE message and then updates the addresses
3123    if it is tunnel mode (with content of xisr_new). Various other checks
3124    are performed. For transport mode, structures are not modified, only
3125    the checks are done. -1 is returned on error. */
3126 static int
3127 migrate_ph2_one_isr(spid, isr_cur, xisr_old, xisr_new)
3128         u_int32_t spid;
3129         struct ipsecrequest *isr_cur;
3130 	struct sadb_x_ipsecrequest *xisr_old, *xisr_new;
3131 {
3132 	struct secasindex *saidx = &isr_cur->saidx;
3133 	struct sockaddr *osaddr, *odaddr, *nsaddr, *ndaddr;
3134 	struct ph2selector ph2sel;
3135 	struct migrate_args ma;
3136 
3137 	/* First, check that mode and proto do match */
3138 	if (xisr_old->sadb_x_ipsecrequest_proto != saidx->proto ||
3139 	    xisr_old->sadb_x_ipsecrequest_mode != saidx->mode ||
3140 	    xisr_new->sadb_x_ipsecrequest_proto != saidx->proto ||
3141 	    xisr_new->sadb_x_ipsecrequest_mode != saidx->mode)
3142 		return -1;
3143 
3144 	/* Then, verify reqid if necessary */
3145 	if (isr_cur->saidx.reqid &&
3146 	    (xisr_old->sadb_x_ipsecrequest_reqid != IPSEC_LEVEL_UNIQUE ||
3147 	     xisr_new->sadb_x_ipsecrequest_reqid != IPSEC_LEVEL_UNIQUE ||
3148 	     isr_cur->saidx.reqid != xisr_old->sadb_x_ipsecrequest_reqid ||
3149 	     isr_cur->saidx.reqid != xisr_new->sadb_x_ipsecrequest_reqid))
3150 		return -1;
3151 
3152 	/* If not tunnel mode, our work is over */
3153 	if (saidx->mode != IPSEC_MODE_TUNNEL) {
3154 		plog(LLV_DEBUG, LOCATION, NULL, "SADB_X_MIGRATE: "
3155 		     "non tunnel mode isr, skipping SA address migration.\n");
3156 		return 0;
3157 	}
3158 
3159 	/* Tunnel mode: let's check addresses do match and then update them. */
3160 	osaddr = (struct sockaddr *)(xisr_old + 1);
3161 	odaddr = (struct sockaddr *)(((u_int8_t *)osaddr) + sysdep_sa_len(osaddr));
3162 	nsaddr = (struct sockaddr *)(xisr_new + 1);
3163 	ndaddr = (struct sockaddr *)(((u_int8_t *)nsaddr) + sysdep_sa_len(nsaddr));
3164 
3165 	/* Check family does match */
3166 	if (osaddr->sa_family != odaddr->sa_family ||
3167 	    nsaddr->sa_family != ndaddr->sa_family)
3168 		return -1;
3169 
3170 	/* Check family does match */
3171 	if (saidx->src.ss_family != osaddr->sa_family)
3172 		return -1;
3173 
3174 	/* We log IPv4 to IPv6 and IPv6 to IPv4 switches */
3175 	if (nsaddr->sa_family != osaddr->sa_family)
3176 		plog(LLV_INFO, LOCATION, NULL, "SADB_X_MIGRATE: "
3177 		     "changing address families (%d to %d) for endpoints.\n",
3178 		     osaddr->sa_family, nsaddr->sa_family);
3179 
3180 	if (CMPSADDR(osaddr, (struct sockaddr *)&saidx->src) ||
3181 	    CMPSADDR(odaddr, (struct sockaddr *)&saidx->dst)) {
3182 		plog(LLV_DEBUG, LOCATION, NULL, "SADB_X_MIGRATE: "
3183 		     "mismatch of addresses in saidx and xisr.\n");
3184 		return -1;
3185 	}
3186 
3187 	/* Excellent. Let's grab associated Phase 2 handle (if any)
3188 	 * and update its sa_src and sa_dst entries.  Note that we
3189 	 * make the assumption that racoon does not support bundles
3190 	 * and make the lookup using spid: we blindly update
3191 	 * sa_src and sa_dst for _all_ found Phase 2 handles */
3192 	memset(&ph2sel, 0, sizeof(ph2sel));
3193 	ph2sel.spid = spid;
3194 
3195 	memset(&ma, 0, sizeof(ma));
3196 	ma.local = nsaddr;
3197 	ma.remote = ndaddr;
3198 
3199 	if (enumph2(&ph2sel, migrate_ph2_sa_addresses, &ma) < 0)
3200 		return -1;
3201 
3202 	/* Now we can do the update of endpoints in secasindex */
3203 	memcpy(&saidx->src, nsaddr, sysdep_sa_len(nsaddr));
3204 	memcpy(&saidx->dst, ndaddr, sysdep_sa_len(ndaddr));
3205 
3206 	return 0;
3207 }
3208 
3209 /* Process the raw (unparsed yet) list of sadb_x_ipsecrequests of MIGRATE
3210  * message. For each sadb_x_ipsecrequest pair (old followed by new),
3211  * the corresponding ipsecrequest entry in the SP is updated. Associated
3212  * existing Phase 2 handle is also updated (if any) */
3213 static int
3214 migrate_sp_isr_list(sp, xisr_list, xisr_list_len)
3215         struct secpolicy *sp;
3216 	struct sadb_x_ipsecrequest *xisr_list;
3217 	int xisr_list_len;
3218 {
3219 	struct sadb_x_ipsecrequest *xisr_new, *xisr_old = xisr_list;
3220 	int xisr_old_len, xisr_new_len;
3221 	struct ipsecrequest *isr_cur;
3222 
3223 	isr_cur = sp->req; /* ipsecrequest list from from sp */
3224 
3225 	while (xisr_list_len > 0 && isr_cur != NULL) {
3226 		/* Get old xisr (length field is in bytes) */
3227 		xisr_old_len = xisr_old->sadb_x_ipsecrequest_len;
3228 		if (xisr_old_len < sizeof(*xisr_old) ||
3229 		    xisr_old_len + sizeof(*xisr_new) > xisr_list_len) {
3230 			plog(LLV_ERROR, LOCATION, NULL, "SADB_X_MIGRATE: "
3231 			     "invalid ipsecrequest length. Exiting.\n");
3232 			return -1;
3233 		}
3234 
3235 		/* Get new xisr with updated info */
3236 		xisr_new = (struct sadb_x_ipsecrequest *)(((u_int8_t *)xisr_old) + xisr_old_len);
3237 		xisr_new_len = xisr_new->sadb_x_ipsecrequest_len;
3238 		if (xisr_new_len < sizeof(*xisr_new) ||
3239 		    xisr_new_len + xisr_old_len > xisr_list_len) {
3240 			plog(LLV_ERROR, LOCATION, NULL, "SADB_X_MIGRATE: "
3241 			     "invalid ipsecrequest length. Exiting.\n");
3242 			return -1;
3243 		}
3244 
3245 		/* Start by migrating current ipsecrequest from SP */
3246 		if (migrate_ph2_one_isr(sp->id, isr_cur, xisr_old, xisr_new) == -1) {
3247 			plog(LLV_ERROR, LOCATION, NULL, "SADB_X_MIGRATE: "
3248 			     "Unable to match and migrate isr. Exiting.\n");
3249 			return -1;
3250 		}
3251 
3252 		/* Update pointers for next round */
3253 		xisr_list_len -= xisr_old_len + xisr_new_len;
3254 		xisr_old = (struct sadb_x_ipsecrequest *)(((u_int8_t *)xisr_new) +
3255 							  xisr_new_len);
3256 
3257 		isr_cur = isr_cur->next; /* Get next ipsecrequest from SP */
3258 	}
3259 
3260 	/* Check we had the same amount of pairs in the MIGRATE
3261 	   as the number of ipsecrequests in the SP */
3262 	if ((xisr_list_len != 0) || isr_cur != NULL) {
3263 		plog(LLV_ERROR, LOCATION, NULL, "SADB_X_MIGRATE: "
3264 		     "number of ipsecrequest does not match the one in SP.\n");
3265 		return -1;
3266 	}
3267 
3268 	return 0;
3269 }
3270 
3271 /* Parse sadb_x_kmaddress extension and make local and remote
3272  * parameters point to the new addresses (zero copy). -1 is
3273  * returned on error, meaning that addresses are not usable */
3274 static int
3275 parse_kmaddress(kmaddr, local, remote)
3276         struct sadb_x_kmaddress *kmaddr;
3277 	struct sockaddr **local, **remote;
3278 {
3279 	int addrslen, local_len=0;
3280 	struct ph1handle *iph1;
3281 
3282 	if (kmaddr == NULL)
3283 		return -1;
3284 
3285 	/* Grab addresses in sadb_x_kmaddress extension */
3286 	addrslen = PFKEY_EXTLEN(kmaddr) - sizeof(*kmaddr);
3287 	if (addrslen < sizeof(struct sockaddr))
3288 		return -1;
3289 
3290 	*local = (struct sockaddr *)(kmaddr + 1);
3291 
3292 	switch ((*local)->sa_family) {
3293 	case AF_INET:
3294 		local_len = sizeof(struct sockaddr_in);
3295 		break;
3296 #ifdef INET6
3297 	case AF_INET6:
3298 		local_len = sizeof(struct sockaddr_in6);
3299 		break;
3300 #endif
3301 	default:
3302 		return -1;
3303 	}
3304 
3305 	if (addrslen != PFKEY_ALIGN8(2*local_len))
3306 		return -1;
3307 
3308 	*remote = (struct sockaddr *)(((u_int8_t *)(*local)) + local_len);
3309 
3310 	if ((*local)->sa_family != (*remote)->sa_family)
3311 		return -1;
3312 
3313 	return 0;
3314 }
3315 
3316 /* Handler of PF_KEY MIGRATE message. Helpers are above */
3317 static int
3318 pk_recvmigrate(mhp)
3319 	caddr_t *mhp;
3320 {
3321 	struct sadb_address *saddr, *daddr;
3322 	struct sockaddr *old_saddr, *new_saddr;
3323 	struct sockaddr *old_daddr, *new_daddr;
3324 	struct sockaddr *old_local, *old_remote;
3325 	struct sockaddr *local, *remote;
3326 	struct sadb_x_kmaddress *kmaddr;
3327 	struct sadb_x_policy *xpl;
3328 	struct sadb_x_ipsecrequest *xisr_list;
3329 	struct sadb_lifetime *lt;
3330 	struct policyindex spidx;
3331 	struct secpolicy *sp;
3332 	struct ipsecrequest *isr_cur;
3333 	struct secasindex *oldsaidx;
3334 	struct ph2handle *iph2;
3335 	struct ph1handle *iph1;
3336 	struct ph2selector ph2sel;
3337 	struct ph1selector ph1sel;
3338 	u_int32_t spid;
3339 	u_int64_t created;
3340 	int xisr_list_len;
3341 	int ulproto;
3342 	struct migrate_args ma;
3343 
3344 	/* Some sanity checks */
3345 
3346 	if (mhp[0] == NULL
3347 	 || mhp[SADB_EXT_ADDRESS_SRC] == NULL
3348 	 || mhp[SADB_EXT_ADDRESS_DST] == NULL
3349 	 || mhp[SADB_X_EXT_KMADDRESS] == NULL
3350 	 || mhp[SADB_X_EXT_POLICY] == NULL) {
3351 		plog(LLV_ERROR, LOCATION, NULL,
3352 			"SADB_X_MIGRATE: invalid MIGRATE message received.\n");
3353 		return -1;
3354 	}
3355 	kmaddr = (struct sadb_x_kmaddress *)mhp[SADB_X_EXT_KMADDRESS];
3356 	saddr = (struct sadb_address *)mhp[SADB_EXT_ADDRESS_SRC];
3357 	daddr = (struct sadb_address *)mhp[SADB_EXT_ADDRESS_DST];
3358 	xpl = (struct sadb_x_policy *)mhp[SADB_X_EXT_POLICY];
3359 	lt = (struct sadb_lifetime*)mhp[SADB_EXT_LIFETIME_HARD];
3360 	if (lt != NULL)
3361 		created = lt->sadb_lifetime_addtime;
3362 	else
3363 		created = 0;
3364 
3365 	if (xpl->sadb_x_policy_type != IPSEC_POLICY_IPSEC) {
3366 		plog(LLV_WARNING, LOCATION, NULL,"SADB_X_MIGRATE: "
3367 		     "found non IPsec policy in MIGRATE message. Exiting.\n");
3368 		return -1;
3369 	}
3370 
3371 	if (PFKEY_EXTLEN(xpl) < sizeof(*xpl)) {
3372 		plog(LLV_ERROR, LOCATION, NULL, "SADB_X_MIGRATE: "
3373 		     "invalid size for sadb_x_policy. Exiting.\n");
3374 		return -1;
3375 	}
3376 
3377 	/* Some logging to help debbugging */
3378 	if (xpl->sadb_x_policy_dir == IPSEC_DIR_OUTBOUND)
3379 		plog(LLV_DEBUG, LOCATION, NULL,
3380 		     "SADB_X_MIGRATE: Outbound SA being migrated.\n");
3381 	else
3382 		plog(LLV_DEBUG, LOCATION, NULL,
3383 		     "SADB_X_MIGRATE: Inbound SA being migrated.\n");
3384 
3385 	/* validity check */
3386 	xisr_list = (struct sadb_x_ipsecrequest *)(xpl + 1);
3387 	xisr_list_len = PFKEY_EXTLEN(xpl) - sizeof(*xpl);
3388 	if (xisr_list_len < sizeof(*xisr_list)) {
3389 		plog(LLV_ERROR, LOCATION, NULL, "SADB_X_MIGRATE: "
3390 		     "invalid sadb_x_policy message length. Exiting.\n");
3391 		return -1;
3392 	}
3393 
3394 	if (parse_kmaddress(kmaddr, &local, &remote) == -1) {
3395 		plog(LLV_ERROR, LOCATION, NULL, "SADB_X_MIGRATE: "
3396 		     "invalid sadb_x_kmaddress extension. Exiting.\n");
3397 		return -1;
3398 	}
3399 
3400 	/* 0 means ANY */
3401 	if (saddr->sadb_address_proto == 0)
3402 		ulproto = IPSEC_ULPROTO_ANY;
3403 	else
3404 		ulproto = saddr->sadb_address_proto;
3405 
3406 #ifdef HAVE_PFKEY_POLICY_PRIORITY
3407 	KEY_SETSECSPIDX(xpl->sadb_x_policy_dir,
3408 			saddr + 1,
3409 			daddr + 1,
3410 			saddr->sadb_address_prefixlen,
3411 			daddr->sadb_address_prefixlen,
3412 			ulproto,
3413 			xpl->sadb_x_policy_priority,
3414 			created,
3415 			&spidx);
3416 #else
3417 	KEY_SETSECSPIDX(xpl->sadb_x_policy_dir,
3418 			saddr + 1,
3419 			daddr + 1,
3420 			saddr->sadb_address_prefixlen,
3421 			daddr->sadb_address_prefixlen,
3422 			ulproto,
3423 			created,
3424 			&spidx);
3425 #endif
3426 
3427 	/* Everything seems ok, let's get the SP.
3428 	 *
3429 	 * XXX We could also do the lookup using the spid from xpl.
3430 	 *     I don't know which one is better.  --arno */
3431 	sp = getsp(&spidx);
3432 	if (sp == NULL) {
3433 		plog(LLV_ERROR, LOCATION, NULL,
3434 			"SADB_X_MIGRATE: Passed policy does not exist: %s\n",
3435 			spidx2str(&spidx));
3436 		return -1;
3437 	}
3438 
3439 	/* Get the best source and destination addresses used for IKE
3440 	 * negotiation, to find and migrate existing Phase 1 */
3441 	if (sp->local && sp->remote) {
3442 		/* hints available, let's use them */
3443 		old_local  = (struct sockaddr *)sp->local;
3444 		old_remote = (struct sockaddr *)sp->remote;
3445 	} else if (sp->req && sp->req->saidx.mode == IPSEC_MODE_TUNNEL) {
3446 		/* Tunnel mode and no hint, use endpoints */
3447 		old_local  = (struct sockaddr *)&sp->req->saidx.src;
3448 		old_remote = (struct sockaddr *)&sp->req->saidx.dst;
3449 	} else {
3450 		/* default, use selectors as fallback */
3451 		old_local  = (struct sockaddr *)&sp->spidx.src;
3452 		old_remote = (struct sockaddr *)&sp->spidx.dst;
3453 	}
3454 
3455 	/* We migrate all Phase 1 that match our old local and remote
3456 	 * addresses (no matter their state).
3457 	 *
3458 	 * XXX In fact, we should probably havea special treatment for
3459 	 * Phase 1 that are being established when we receive a MIGRATE.
3460 	 * This can happen if a movement occurs during the initial IKE
3461 	 * negotiation. In that case, I wonder if should restart the
3462 	 * negotiation from the new address or just update things like
3463 	 * we do it now.
3464 	 *
3465 	 * XXX while looking at getph1byaddr(), the comment at the
3466 	 * beginning of the function expects comparison to happen
3467 	 * without ports considerations but it uses CMPSADDR() which
3468 	 * relies either on cmpsaddrstrict() or cmpsaddrwop() based
3469 	 * on NAT-T support being activated. That make me wonder if I
3470 	 * should force ports to 0 (ANY) in local and remote values
3471 	 * used below.
3472 	 *
3473 	 * -- arno */
3474 
3475 	/* Apply callback data ...*/
3476 	memset(&ma, 0, sizeof(ma));
3477 	ma.local = local;
3478 	ma.remote = remote;
3479 
3480 	/* Fill phase1 match criteria ... */
3481 	memset(&ph1sel, 0, sizeof(ph1sel));
3482 	ph1sel.local = old_local;
3483 	ph1sel.remote = old_remote;
3484 
3485 
3486 	/* Have matching Phase 1 found and addresses updated. As this is a
3487 	 * time consuming task on a busy responder, and MIGRATE messages
3488 	 * are always sent for *both* inbound and outbound (and possibly
3489 	 * forward), we only do that for outbound SP. */
3490 	if (xpl->sadb_x_policy_dir == IPSEC_DIR_OUTBOUND &&
3491 	    enumph1(&ph1sel, migrate_ph1_ike_addresses, &ma) < 0) {
3492 		plog(LLV_ERROR, LOCATION, NULL, "SADB_X_MIGRATE: Unable "
3493 		     "to migrate Phase 1 addresses.\n");
3494 		return -1;
3495 	}
3496 
3497 	/* We can now update IKE addresses in Phase 2 handle. */
3498 	memset(&ph2sel, 0, sizeof(ph2sel));
3499 	ph2sel.spid = sp->id;
3500 	if (enumph2(&ph2sel, migrate_ph2_ike_addresses, &ma) < 0) {
3501 		plog(LLV_ERROR, LOCATION, NULL, "SADB_X_MIGRATE: Unable "
3502 		     "to migrate Phase 2 IKE addresses.\n");
3503 		return -1;
3504 	}
3505 
3506 	/* and _then_ in SP. */
3507 	if (migrate_sp_ike_addresses(sp, local, remote) < 0) {
3508 		plog(LLV_ERROR, LOCATION, NULL,
3509 		     "SADB_X_MIGRATE: Unable to migrate SP IKE addresses.\n");
3510 		return -1;
3511 	}
3512 
3513 	/* Loop on sadb_x_ipsecrequest list to possibly update sp->req
3514 	 * entries and associated live Phase 2 handles (their sa_src
3515 	 * and sa_dst) */
3516 	if (migrate_sp_isr_list(sp, xisr_list, xisr_list_len) < 0) {
3517 		plog(LLV_ERROR, LOCATION, NULL,
3518 		     "SADB_X_MIGRATE: Unable to migrate isr list.\n");
3519 		return -1;
3520 	}
3521 
3522 	return 0;
3523 }
3524 #endif
3525 
3526 /*
3527  * send error against acquire message to kenrel.
3528  */
3529 int
3530 pk_sendeacquire(iph2)
3531 	struct ph2handle *iph2;
3532 {
3533 	struct sadb_msg *newmsg;
3534 	int len;
3535 
3536 	len = sizeof(struct sadb_msg);
3537 	newmsg = racoon_calloc(1, len);
3538 	if (newmsg == NULL) {
3539 		plog(LLV_ERROR, LOCATION, NULL,
3540 			"failed to get buffer to send acquire.\n");
3541 		return -1;
3542 	}
3543 
3544 	memset(newmsg, 0, len);
3545 	newmsg->sadb_msg_version = PF_KEY_V2;
3546 	newmsg->sadb_msg_type = SADB_ACQUIRE;
3547 	newmsg->sadb_msg_errno = ENOENT;	/* XXX */
3548 	newmsg->sadb_msg_satype = iph2->satype;
3549 	newmsg->sadb_msg_len = PFKEY_UNIT64(len);
3550 	newmsg->sadb_msg_reserved = 0;
3551 	newmsg->sadb_msg_seq = iph2->seq;
3552 	newmsg->sadb_msg_pid = (u_int32_t)getpid();
3553 
3554 	/* send message */
3555 	len = pfkey_send(lcconf->sock_pfkey, newmsg, len);
3556 
3557 	racoon_free(newmsg);
3558 
3559 	return 0;
3560 }
3561 
3562 /*
3563  * check if the algorithm is supported or not.
3564  * OUT	 0: ok
3565  *	-1: ng
3566  */
3567 int
3568 pk_checkalg(class, calg, keylen)
3569 	int class, calg, keylen;
3570 {
3571 	int sup, error;
3572 	u_int alg;
3573 	struct sadb_alg alg0;
3574 
3575 	switch (algclass2doi(class)) {
3576 	case IPSECDOI_PROTO_IPSEC_ESP:
3577 		sup = SADB_EXT_SUPPORTED_ENCRYPT;
3578 		break;
3579 	case IPSECDOI_ATTR_AUTH:
3580 		sup = SADB_EXT_SUPPORTED_AUTH;
3581 		break;
3582 	case IPSECDOI_PROTO_IPCOMP:
3583 		plog(LLV_DEBUG, LOCATION, NULL,
3584 			"compression algorithm can not be checked "
3585 			"because sadb message doesn't support it.\n");
3586 		return 0;
3587 	default:
3588 		plog(LLV_ERROR, LOCATION, NULL,
3589 			"invalid algorithm class.\n");
3590 		return -1;
3591 	}
3592 	alg = ipsecdoi2pfkey_alg(algclass2doi(class), algtype2doi(class, calg));
3593 	if (alg == ~0)
3594 		return -1;
3595 
3596 	if (keylen == 0) {
3597 		if (ipsec_get_keylen(sup, alg, &alg0)) {
3598 			plog(LLV_ERROR, LOCATION, NULL,
3599 				"%s.\n", ipsec_strerror());
3600 			return -1;
3601 		}
3602 		keylen = alg0.sadb_alg_minbits;
3603 	}
3604 
3605 	error = ipsec_check_keylen(sup, alg, keylen);
3606 	if (error)
3607 		plog(LLV_ERROR, LOCATION, NULL,
3608 			"%s.\n", ipsec_strerror());
3609 
3610 	return error;
3611 }
3612 
3613 /*
3614  * differences with pfkey_recv() in libipsec/pfkey.c:
3615  * - never performs busy wait loop.
3616  * - returns NULL and set *lenp to negative on fatal failures
3617  * - returns NULL and set *lenp to non-negative on non-fatal failures
3618  * - returns non-NULL on success
3619  */
3620 static struct sadb_msg *
3621 pk_recv(so, lenp)
3622 	int so;
3623 	int *lenp;
3624 {
3625 	struct sadb_msg buf, *newmsg;
3626 	int reallen;
3627 	int retry = 0;
3628 
3629 	*lenp = -1;
3630 	do
3631 	{
3632 	    plog(LLV_DEBUG, LOCATION, NULL, "pk_recv: retry[%d] recv() \n", retry );
3633 	    *lenp = recv(so, (caddr_t)&buf, sizeof(buf), MSG_PEEK | MSG_DONTWAIT);
3634 	    retry++;
3635 	}
3636 	while (*lenp < 0 && errno == EAGAIN && retry < 3);
3637 
3638 	if (*lenp < 0)
3639 		return NULL;	/*fatal*/
3640 
3641 	else if (*lenp < sizeof(buf))
3642 		return NULL;
3643 
3644 	reallen = PFKEY_UNUNIT64(buf.sadb_msg_len);
3645 	if (reallen < sizeof(buf)) {
3646 		*lenp = -1;
3647 		errno = EIO;
3648 		return NULL;    /*fatal*/
3649 	}
3650 	if ((newmsg = racoon_calloc(1, reallen)) == NULL)
3651 		return NULL;
3652 
3653 	*lenp = recv(so, (caddr_t)newmsg, reallen, MSG_PEEK);
3654 	if (*lenp < 0) {
3655 		racoon_free(newmsg);
3656 		return NULL;	/*fatal*/
3657 	} else if (*lenp != reallen) {
3658 		racoon_free(newmsg);
3659 		return NULL;
3660 	}
3661 
3662 	*lenp = recv(so, (caddr_t)newmsg, reallen, 0);
3663 	if (*lenp < 0) {
3664 		racoon_free(newmsg);
3665 		return NULL;	/*fatal*/
3666 	} else if (*lenp != reallen) {
3667 		racoon_free(newmsg);
3668 		return NULL;
3669 	}
3670 
3671 	return newmsg;
3672 }
3673 
3674 /* see handler.h */
3675 u_int32_t
3676 pk_getseq()
3677 {
3678 	return eay_random();
3679 }
3680 
3681 static int
3682 addnewsp(mhp, local, remote)
3683 	caddr_t *mhp;
3684 	struct sockaddr *local, *remote;
3685 {
3686 	struct secpolicy *new = NULL;
3687 	struct sadb_address *saddr, *daddr;
3688 	struct sadb_x_policy *xpl;
3689 	struct sadb_lifetime *lt;
3690 	u_int64_t created;
3691 
3692 	/* sanity check */
3693 	if (mhp[SADB_EXT_ADDRESS_SRC] == NULL
3694 	 || mhp[SADB_EXT_ADDRESS_DST] == NULL
3695 	 || mhp[SADB_X_EXT_POLICY] == NULL) {
3696 		plog(LLV_ERROR, LOCATION, NULL,
3697 			"inappropriate sadb spd management message passed.\n");
3698 		goto bad;
3699 	}
3700 
3701 	saddr = (struct sadb_address *)mhp[SADB_EXT_ADDRESS_SRC];
3702 	daddr = (struct sadb_address *)mhp[SADB_EXT_ADDRESS_DST];
3703 	xpl = (struct sadb_x_policy *)mhp[SADB_X_EXT_POLICY];
3704 	lt = (struct sadb_lifetime*)mhp[SADB_EXT_LIFETIME_HARD];
3705 	if(lt != NULL)
3706 		created = lt->sadb_lifetime_addtime;
3707 	else
3708 		created = 0;
3709 	lt = (struct sadb_lifetime*)mhp[SADB_EXT_LIFETIME_HARD];
3710 	if(lt != NULL)
3711 		created = lt->sadb_lifetime_addtime;
3712 	else
3713 		created = 0;
3714 
3715 #ifdef __linux__
3716 	/* bsd skips over per-socket policies because there will be no
3717 	 * src and dst extensions in spddump messages. On Linux the only
3718 	 * way to achieve the same is check for policy id.
3719 	 */
3720 	if (xpl->sadb_x_policy_id % 8 >= 3) return 0;
3721 #endif
3722 
3723 	new = newsp();
3724 	if (new == NULL) {
3725 		plog(LLV_ERROR, LOCATION, NULL,
3726 			"failed to allocate buffer\n");
3727 		goto bad;
3728 	}
3729 
3730 	new->spidx.dir = xpl->sadb_x_policy_dir;
3731 	new->id = xpl->sadb_x_policy_id;
3732 	new->policy = xpl->sadb_x_policy_type;
3733 	new->req = NULL;
3734 
3735 	/* check policy */
3736 	switch (xpl->sadb_x_policy_type) {
3737 	case IPSEC_POLICY_DISCARD:
3738 	case IPSEC_POLICY_NONE:
3739 	case IPSEC_POLICY_ENTRUST:
3740 	case IPSEC_POLICY_BYPASS:
3741 		break;
3742 
3743 	case IPSEC_POLICY_IPSEC:
3744 	    {
3745 		int tlen;
3746 		struct sadb_x_ipsecrequest *xisr;
3747 		struct ipsecrequest **p_isr = &new->req;
3748 
3749 		/* validity check */
3750 		if (PFKEY_EXTLEN(xpl) < sizeof(*xpl)) {
3751 			plog(LLV_ERROR, LOCATION, NULL,
3752 				"invalid msg length.\n");
3753 			goto bad;
3754 		}
3755 
3756 		tlen = PFKEY_EXTLEN(xpl) - sizeof(*xpl);
3757 		xisr = (struct sadb_x_ipsecrequest *)(xpl + 1);
3758 
3759 		while (tlen > 0) {
3760 
3761 			/* length check */
3762 			if (xisr->sadb_x_ipsecrequest_len < sizeof(*xisr)) {
3763 				plog(LLV_ERROR, LOCATION, NULL,
3764 					"invalid msg length.\n");
3765 				goto bad;
3766 			}
3767 
3768 			/* allocate request buffer */
3769 			*p_isr = newipsecreq();
3770 			if (*p_isr == NULL) {
3771 				plog(LLV_ERROR, LOCATION, NULL,
3772 					"failed to get new ipsecreq.\n");
3773 				goto bad;
3774 			}
3775 
3776 			/* set values */
3777 			(*p_isr)->next = NULL;
3778 
3779 			switch (xisr->sadb_x_ipsecrequest_proto) {
3780 			case IPPROTO_ESP:
3781 			case IPPROTO_AH:
3782 			case IPPROTO_IPCOMP:
3783 				break;
3784 			default:
3785 				plog(LLV_ERROR, LOCATION, NULL,
3786 					"invalid proto type: %u\n",
3787 					xisr->sadb_x_ipsecrequest_proto);
3788 				goto bad;
3789 			}
3790 			(*p_isr)->saidx.proto = xisr->sadb_x_ipsecrequest_proto;
3791 
3792 			switch (xisr->sadb_x_ipsecrequest_mode) {
3793 			case IPSEC_MODE_TRANSPORT:
3794 			case IPSEC_MODE_TUNNEL:
3795 				break;
3796 			case IPSEC_MODE_ANY:
3797 			default:
3798 				plog(LLV_ERROR, LOCATION, NULL,
3799 					"invalid mode: %u\n",
3800 					xisr->sadb_x_ipsecrequest_mode);
3801 				goto bad;
3802 			}
3803 			(*p_isr)->saidx.mode = xisr->sadb_x_ipsecrequest_mode;
3804 
3805 			switch (xisr->sadb_x_ipsecrequest_level) {
3806 			case IPSEC_LEVEL_DEFAULT:
3807 			case IPSEC_LEVEL_USE:
3808 			case IPSEC_LEVEL_REQUIRE:
3809 				break;
3810 			case IPSEC_LEVEL_UNIQUE:
3811 				(*p_isr)->saidx.reqid =
3812 					xisr->sadb_x_ipsecrequest_reqid;
3813 				break;
3814 
3815 			default:
3816 				plog(LLV_ERROR, LOCATION, NULL,
3817 					"invalid level: %u\n",
3818 					xisr->sadb_x_ipsecrequest_level);
3819 				goto bad;
3820 			}
3821 			(*p_isr)->level = xisr->sadb_x_ipsecrequest_level;
3822 
3823 			/* set IP addresses if there */
3824 			if (xisr->sadb_x_ipsecrequest_len > sizeof(*xisr)) {
3825 				struct sockaddr *paddr;
3826 
3827 				paddr = (struct sockaddr *)(xisr + 1);
3828 				bcopy(paddr, &(*p_isr)->saidx.src,
3829 					sysdep_sa_len(paddr));
3830 
3831 				paddr = (struct sockaddr *)((caddr_t)paddr
3832 							+ sysdep_sa_len(paddr));
3833 				bcopy(paddr, &(*p_isr)->saidx.dst,
3834 					sysdep_sa_len(paddr));
3835 			}
3836 
3837 			(*p_isr)->sp = new;
3838 
3839 			/* initialization for the next. */
3840 			p_isr = &(*p_isr)->next;
3841 			tlen -= xisr->sadb_x_ipsecrequest_len;
3842 
3843 			/* validity check */
3844 			if (tlen < 0) {
3845 				plog(LLV_ERROR, LOCATION, NULL,
3846 					"becoming tlen < 0\n");
3847 			}
3848 
3849 			xisr = (struct sadb_x_ipsecrequest *)((caddr_t)xisr
3850 			                 + xisr->sadb_x_ipsecrequest_len);
3851 		}
3852 	    }
3853 		break;
3854 	default:
3855 		plog(LLV_ERROR, LOCATION, NULL,
3856 			"invalid policy type.\n");
3857 		goto bad;
3858 	}
3859 
3860 #ifdef HAVE_PFKEY_POLICY_PRIORITY
3861 	KEY_SETSECSPIDX(xpl->sadb_x_policy_dir,
3862 			saddr + 1,
3863 			daddr + 1,
3864 			saddr->sadb_address_prefixlen,
3865 			daddr->sadb_address_prefixlen,
3866 			saddr->sadb_address_proto,
3867 			xpl->sadb_x_policy_priority,
3868 			created,
3869 			&new->spidx);
3870 #else
3871 	KEY_SETSECSPIDX(xpl->sadb_x_policy_dir,
3872 			saddr + 1,
3873 			daddr + 1,
3874 			saddr->sadb_address_prefixlen,
3875 			daddr->sadb_address_prefixlen,
3876 			saddr->sadb_address_proto,
3877 			created,
3878 			&new->spidx);
3879 #endif
3880 
3881 #ifdef HAVE_SECCTX
3882 	if (mhp[SADB_X_EXT_SEC_CTX] != NULL) {
3883 		struct sadb_x_sec_ctx *ctx;
3884 
3885 		ctx = (struct sadb_x_sec_ctx *)mhp[SADB_X_EXT_SEC_CTX];
3886 		new->spidx.sec_ctx.ctx_alg = ctx->sadb_x_ctx_alg;
3887 		new->spidx.sec_ctx.ctx_doi = ctx->sadb_x_ctx_doi;
3888 		new->spidx.sec_ctx.ctx_strlen = ctx->sadb_x_ctx_len;
3889 		memcpy(new->spidx.sec_ctx.ctx_str,ctx + 1,ctx->sadb_x_ctx_len);
3890 	}
3891 #endif /* HAVE_SECCTX */
3892 
3893 	/* Set local and remote hints for that SP, if available */
3894 	if (local && remote) {
3895 		new->local = dupsaddr(local);
3896 		new->remote = dupsaddr(remote);
3897 	}
3898 
3899 	inssp(new);
3900 
3901 	return 0;
3902 bad:
3903 	if (new != NULL) {
3904 		if (new->req != NULL)
3905 			racoon_free(new->req);
3906 		racoon_free(new);
3907 	}
3908 	return -1;
3909 }
3910 
3911 /* proto/mode/src->dst spi */
3912 const char *
3913 sadbsecas2str(src, dst, proto, spi, mode)
3914 	struct sockaddr *src, *dst;
3915 	int proto;
3916 	u_int32_t spi;
3917 	int mode;
3918 {
3919 	static char buf[256];
3920 	u_int doi_proto, doi_mode = 0;
3921 	char *p;
3922 	int blen, i;
3923 
3924 	doi_proto = pfkey2ipsecdoi_proto(proto);
3925 	if (doi_proto == ~0)
3926 		return NULL;
3927 	if (mode) {
3928 		doi_mode = pfkey2ipsecdoi_mode(mode);
3929 		if (doi_mode == ~0)
3930 			return NULL;
3931 	}
3932 
3933 	blen = sizeof(buf) - 1;
3934 	p = buf;
3935 
3936 	i = snprintf(p, blen, "%s%s%s ",
3937 		s_ipsecdoi_proto(doi_proto),
3938 		mode ? "/" : "",
3939 		mode ? s_ipsecdoi_encmode(doi_mode) : "");
3940 	if (i < 0 || i >= blen)
3941 		return NULL;
3942 	p += i;
3943 	blen -= i;
3944 
3945 	i = snprintf(p, blen, "%s->", saddr2str(src));
3946 	if (i < 0 || i >= blen)
3947 		return NULL;
3948 	p += i;
3949 	blen -= i;
3950 
3951 	i = snprintf(p, blen, "%s ", saddr2str(dst));
3952 	if (i < 0 || i >= blen)
3953 		return NULL;
3954 	p += i;
3955 	blen -= i;
3956 
3957 	if (spi) {
3958 		snprintf(p, blen, "spi=%lu(0x%lx)", (unsigned long)ntohl(spi),
3959 		    (unsigned long)ntohl(spi));
3960 	}
3961 
3962 	return buf;
3963 }
3964