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