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