xref: /netbsd-src/crypto/dist/ipsec-tools/src/racoon/isakmp.c (revision ce666bb8ce77792a3948ca697c2fdad578a542a7)
1 /*	$NetBSD: isakmp.c,v 1.11 2005/11/21 14:20:29 manu Exp $	*/
2 
3 /* Id: isakmp.c,v 1.34.2.20 2005/09/26 16:12:20 manubsd 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 <sys/types.h>
37 #include <sys/param.h>
38 #include <sys/socket.h>
39 #include <sys/queue.h>
40 
41 #include <netinet/in.h>
42 #include <arpa/inet.h>
43 
44 #ifndef HAVE_NETINET6_IPSEC
45 #include <netinet/ipsec.h>
46 #else
47 #include <netinet6/ipsec.h>
48 #endif
49 
50 #include <stdlib.h>
51 #include <stdio.h>
52 #include <string.h>
53 #include <errno.h>
54 #if TIME_WITH_SYS_TIME
55 # include <sys/time.h>
56 # include <time.h>
57 #else
58 # if HAVE_SYS_TIME_H
59 #  include <sys/time.h>
60 # else
61 #  include <time.h>
62 # endif
63 #endif
64 #include <netdb.h>
65 #ifdef HAVE_UNISTD_H
66 #include <unistd.h>
67 #endif
68 #include <ctype.h>
69 #include <fcntl.h>
70 
71 #include "var.h"
72 #include "misc.h"
73 #include "vmbuf.h"
74 #include "plog.h"
75 #include "sockmisc.h"
76 #include "schedule.h"
77 #include "debug.h"
78 
79 #include "remoteconf.h"
80 #include "localconf.h"
81 #include "grabmyaddr.h"
82 #include "admin.h"
83 #include "privsep.h"
84 #include "isakmp_var.h"
85 #include "isakmp.h"
86 #include "oakley.h"
87 #include "evt.h"
88 #include "handler.h"
89 #include "proposal.h"
90 #include "ipsec_doi.h"
91 #include "pfkey.h"
92 #include "crypto_openssl.h"
93 #include "policy.h"
94 #include "isakmp_ident.h"
95 #include "isakmp_agg.h"
96 #include "isakmp_base.h"
97 #include "isakmp_quick.h"
98 #include "isakmp_inf.h"
99 #include "isakmp_newg.h"
100 #ifdef ENABLE_HYBRID
101 #include "isakmp_xauth.h"
102 #include "isakmp_cfg.h"
103 #endif
104 #ifdef ENABLE_FRAG
105 #include "isakmp_frag.h"
106 #endif
107 #include "strnames.h"
108 
109 #ifdef ENABLE_NATT
110 # include "nattraversal.h"
111 # ifdef __linux__
112 #  include <linux/udp.h>
113 #include <fcntl.h>
114 
115 #  ifndef SOL_UDP
116 #   define SOL_UDP 17
117 #  endif
118 # endif /* __linux__ */
119 # if defined(__NetBSD__) || defined(__FreeBSD__)
120 #  include <netinet/in.h>
121 #  include <netinet/udp.h>
122 #  define SOL_UDP IPPROTO_UDP
123 # endif /* __NetBSD__ / __FreeBSD__ */
124 #endif
125 
126 static int nostate1 __P((struct ph1handle *, vchar_t *));
127 static int nostate2 __P((struct ph2handle *, vchar_t *));
128 
129 extern caddr_t val2str(const char *, size_t);
130 
131 static int (*ph1exchange[][2][PHASE1ST_MAX])
132 	__P((struct ph1handle *, vchar_t *)) = {
133  /* error */
134  { {}, {}, },
135  /* Identity Protection exchange */
136  {
137   { nostate1, ident_i1send, nostate1, ident_i2recv, ident_i2send,
138     ident_i3recv, ident_i3send, ident_i4recv, ident_i4send, nostate1, },
139   { nostate1, ident_r1recv, ident_r1send, ident_r2recv, ident_r2send,
140     ident_r3recv, ident_r3send, nostate1, nostate1, nostate1, },
141  },
142  /* Aggressive exchange */
143  {
144   { nostate1, agg_i1send, nostate1, agg_i2recv, agg_i2send,
145     nostate1, nostate1, nostate1, nostate1, nostate1, },
146   { nostate1, agg_r1recv, agg_r1send, agg_r2recv, agg_r2send,
147     nostate1, nostate1, nostate1, nostate1, nostate1, },
148  },
149  /* Base exchange */
150  {
151   { nostate1, base_i1send, nostate1, base_i2recv, base_i2send,
152     base_i3recv, base_i3send, nostate1, nostate1, nostate1, },
153   { nostate1, base_r1recv, base_r1send, base_r2recv, base_r2send,
154     nostate1, nostate1, nostate1, nostate1, nostate1, },
155  },
156 };
157 
158 static int (*ph2exchange[][2][PHASE2ST_MAX])
159 	__P((struct ph2handle *, vchar_t *)) = {
160  /* error */
161  { {}, {}, },
162  /* Quick mode for IKE*/
163  {
164   { nostate2, nostate2, quick_i1prep, nostate2, quick_i1send,
165     quick_i2recv, quick_i2send, quick_i3recv, nostate2, nostate2, },
166   { nostate2, quick_r1recv, quick_r1prep, nostate2, quick_r2send,
167     quick_r3recv, quick_r3prep, quick_r3send, nostate2, nostate2, }
168  },
169 };
170 
171 static u_char r_ck0[] = { 0,0,0,0,0,0,0,0 }; /* used to verify the r_ck. */
172 
173 static int isakmp_main __P((vchar_t *, struct sockaddr *, struct sockaddr *));
174 static int ph1_main __P((struct ph1handle *, vchar_t *));
175 static int quick_main __P((struct ph2handle *, vchar_t *));
176 static int isakmp_ph1begin_r __P((vchar_t *,
177 	struct sockaddr *, struct sockaddr *, u_int8_t));
178 static int isakmp_ph2begin_i __P((struct ph1handle *, struct ph2handle *));
179 static int isakmp_ph2begin_r __P((struct ph1handle *, vchar_t *));
180 static int etypesw1 __P((int));
181 static int etypesw2 __P((int));
182 #ifdef ENABLE_FRAG
183 static int frag_handler(struct ph1handle *,
184     vchar_t *, struct sockaddr *, struct sockaddr *);
185 #endif
186 
187 /*
188  * isakmp packet handler
189  */
190 int
191 isakmp_handler(so_isakmp)
192 	int so_isakmp;
193 {
194 	struct isakmp isakmp;
195 	union {
196 		char		buf[sizeof (isakmp) + 4];
197 		u_int32_t	non_esp[2];
198 	} x;
199 	struct sockaddr_storage remote;
200 	struct sockaddr_storage local;
201 	unsigned int remote_len = sizeof(remote);
202 	unsigned int local_len = sizeof(local);
203 	int len = 0, extralen = 0;
204 	u_short port;
205 	vchar_t *buf = NULL, *tmpbuf = NULL;
206 	int error = -1;
207 
208 	/* read message by MSG_PEEK */
209 	while ((len = recvfromto(so_isakmp, x.buf, sizeof(x),
210 		    MSG_PEEK, (struct sockaddr *)&remote, &remote_len,
211 		    (struct sockaddr *)&local, &local_len)) < 0) {
212 		if (errno == EINTR)
213 			continue;
214 		plog(LLV_ERROR, LOCATION, NULL,
215 			"failed to receive isakmp packet: %s\n",
216 			strerror (errno));
217 		goto end;
218 	}
219 
220 	/* keep-alive packet - ignore */
221 	if (len == 1 && (x.buf[0]&0xff) == 0xff) {
222 		/* Pull the keep-alive packet */
223 		if ((len = recvfrom(so_isakmp, (char *)x.buf, 1,
224 		    0, (struct sockaddr *)&remote, &remote_len)) != 1) {
225 			plog(LLV_ERROR, LOCATION, NULL,
226 			    "failed to receive keep alive packet: %s\n",
227 			    strerror (errno));
228 		}
229 		goto end;
230 	}
231 
232 #ifdef ENABLE_NATT
233 	/* we don't know about portchange yet,
234 	   look for non-esp marker instead */
235 	if (x.non_esp[0] == 0 && x.non_esp[1] != 0)
236 		extralen = NON_ESP_MARKER_LEN;
237 #endif
238 
239 	/* now we know if there is an extra non-esp
240 	   marker at the beginning or not */
241 	memcpy ((char *)&isakmp, x.buf + extralen, sizeof (isakmp));
242 
243 	/* check isakmp header length, as well as sanity of header length */
244 	if (len < sizeof(isakmp) || ntohl(isakmp.len) < sizeof(isakmp)) {
245 		plog(LLV_ERROR, LOCATION, (struct sockaddr *)&remote,
246 			"packet shorter than isakmp header size (%u, %u, %zu)\n",
247 			len, ntohl(isakmp.len), sizeof(isakmp));
248 		/* dummy receive */
249 		if ((len = recvfrom(so_isakmp, (char *)&isakmp, sizeof(isakmp),
250 			    0, (struct sockaddr *)&remote, &remote_len)) < 0) {
251 			plog(LLV_ERROR, LOCATION, NULL,
252 				"failed to receive isakmp packet: %s\n",
253 				strerror (errno));
254 		}
255 		goto end;
256 	}
257 
258 	/* reject it if the size is tooooo big. */
259 	if (ntohl(isakmp.len) > 0xffff) {
260 		plog(LLV_ERROR, LOCATION, NULL,
261 			"the length in the isakmp header is too big.\n");
262 		if ((len = recvfrom(so_isakmp, (char *)&isakmp, sizeof(isakmp),
263 			    0, (struct sockaddr *)&remote, &remote_len)) < 0) {
264 			plog(LLV_ERROR, LOCATION, NULL,
265 				"failed to receive isakmp packet: %s\n",
266 				strerror (errno));
267 		}
268 		goto end;
269 	}
270 
271 	/* read real message */
272 	if ((tmpbuf = vmalloc(ntohl(isakmp.len) + extralen)) == NULL) {
273 		plog(LLV_ERROR, LOCATION, NULL,
274 			"failed to allocate reading buffer (%u Bytes)\n",
275 			ntohl(isakmp.len) + extralen);
276 		/* dummy receive */
277 		if ((len = recvfrom(so_isakmp, (char *)&isakmp, sizeof(isakmp),
278 			    0, (struct sockaddr *)&remote, &remote_len)) < 0) {
279 			plog(LLV_ERROR, LOCATION, NULL,
280 				"failed to receive isakmp packet: %s\n",
281 				strerror (errno));
282 		}
283 		goto end;
284 	}
285 
286 	while ((len = recvfromto(so_isakmp, (char *)tmpbuf->v, tmpbuf->l,
287 	                    0, (struct sockaddr *)&remote, &remote_len,
288 	                    (struct sockaddr *)&local, &local_len)) < 0) {
289 		if (errno == EINTR)
290 			continue;
291 		plog(LLV_ERROR, LOCATION, NULL,
292 			"failed to receive isakmp packet: %s\n",
293 			strerror (errno));
294 		goto end;
295 	}
296 
297 	if ((buf = vmalloc(len - extralen)) == NULL) {
298 		plog(LLV_ERROR, LOCATION, NULL,
299 			"failed to allocate reading buffer (%u Bytes)\n",
300 			(len - extralen));
301 		goto end;
302 	}
303 
304 	memcpy (buf->v, tmpbuf->v + extralen, buf->l);
305 
306 	vfree (tmpbuf);
307 
308 	len -= extralen;
309 
310 	if (len != buf->l) {
311 		plog(LLV_ERROR, LOCATION, (struct sockaddr *)&remote,
312 			"received invalid length (%d != %zu), why ?\n",
313 			len, buf->l);
314 		goto end;
315 	}
316 
317 	plog(LLV_DEBUG, LOCATION, NULL, "===\n");
318 	plog(LLV_DEBUG, LOCATION, NULL,
319 		"%d bytes message received %s\n",
320 		len, saddr2str_fromto("from %s to %s",
321 			(struct sockaddr *)&remote,
322 			(struct sockaddr *)&local));
323 	plogdump(LLV_DEBUG, buf->v, buf->l);
324 
325 	/* avoid packets with malicious port/address */
326 	switch (remote.ss_family) {
327 	case AF_INET:
328 		port = ((struct sockaddr_in *)&remote)->sin_port;
329 		break;
330 #ifdef INET6
331 	case AF_INET6:
332 		port = ((struct sockaddr_in6 *)&remote)->sin6_port;
333 		break;
334 #endif
335 	default:
336 		plog(LLV_ERROR, LOCATION, NULL,
337 			"invalid family: %d\n", remote.ss_family);
338 		goto end;
339 	}
340 	if (port == 0) {
341 		plog(LLV_ERROR, LOCATION, (struct sockaddr *)&remote,
342 			"src port == 0 (valid as UDP but not with IKE)\n");
343 		goto end;
344 	}
345 
346 	/* XXX: check sender whether to be allowed or not to accept */
347 
348 	/* XXX: I don't know how to check isakmp half connection attack. */
349 
350 	/* simply reply if the packet was processed. */
351 	if (check_recvdpkt((struct sockaddr *)&remote,
352 			(struct sockaddr *)&local, buf)) {
353 		plog(LLV_NOTIFY, LOCATION, NULL,
354 			"the packet is retransmitted by %s.\n",
355 			saddr2str((struct sockaddr *)&remote));
356 		error = 0;
357 		goto end;
358 	}
359 
360 	/* isakmp main routine */
361 	if (isakmp_main(buf, (struct sockaddr *)&remote,
362 			(struct sockaddr *)&local) != 0) goto end;
363 
364 	error = 0;
365 
366 end:
367 	if (buf != NULL)
368 		vfree(buf);
369 
370 	return(error);
371 }
372 
373 /*
374  * main processing to handle isakmp payload
375  */
376 static int
377 isakmp_main(msg, remote, local)
378 	vchar_t *msg;
379 	struct sockaddr *remote, *local;
380 {
381 	struct isakmp *isakmp = (struct isakmp *)msg->v;
382 	isakmp_index *index = (isakmp_index *)isakmp;
383 	u_int32_t msgid = isakmp->msgid;
384 	struct ph1handle *iph1;
385 
386 #ifdef HAVE_PRINT_ISAKMP_C
387 	isakmp_printpacket(msg, remote, local, 0);
388 #endif
389 
390 	/* the initiator's cookie must not be zero */
391 	if (memcmp(&isakmp->i_ck, r_ck0, sizeof(cookie_t)) == 0) {
392 		plog(LLV_ERROR, LOCATION, remote,
393 			"malformed cookie received.\n");
394 		return -1;
395 	}
396 
397 	/* Check the Major and Minor Version fields. */
398 	/*
399 	 * XXX Is is right to check version here ?
400 	 * I think it may no be here because the version depends
401 	 * on exchange status.
402 	 */
403 	if (isakmp->v < ISAKMP_VERSION_NUMBER) {
404 		if (ISAKMP_GETMAJORV(isakmp->v) < ISAKMP_MAJOR_VERSION) {
405 			plog(LLV_ERROR, LOCATION, remote,
406 				"invalid major version %d.\n",
407 				ISAKMP_GETMAJORV(isakmp->v));
408 			return -1;
409 		}
410 #if ISAKMP_MINOR_VERSION > 0
411 		if (ISAKMP_GETMINORV(isakmp->v) < ISAKMP_MINOR_VERSION) {
412 			plog(LLV_ERROR, LOCATION, remote,
413 				"invalid minor version %d.\n",
414 				ISAKMP_GETMINORV(isakmp->v));
415 			return -1;
416 		}
417 #endif
418 	}
419 
420 	/* check the Flags field. */
421 	/* XXX How is the exclusive check, E and A ? */
422 	if (isakmp->flags & ~(ISAKMP_FLAG_E | ISAKMP_FLAG_C | ISAKMP_FLAG_A)) {
423 		plog(LLV_ERROR, LOCATION, remote,
424 			"invalid flag 0x%02x.\n", isakmp->flags);
425 		return -1;
426 	}
427 
428 	/* ignore commit bit. */
429 	if (ISSET(isakmp->flags, ISAKMP_FLAG_C)) {
430 		if (isakmp->msgid == 0) {
431 			isakmp_info_send_nx(isakmp, remote, local,
432 				ISAKMP_NTYPE_INVALID_FLAGS, NULL);
433 			plog(LLV_ERROR, LOCATION, remote,
434 				"Commit bit on phase1 forbidden.\n");
435 			return -1;
436 		}
437 	}
438 
439 	iph1 = getph1byindex(index);
440 	if (iph1 != NULL) {
441 		/* validity check */
442 		if (memcmp(&isakmp->r_ck, r_ck0, sizeof(cookie_t)) == 0 &&
443 		    iph1->side == INITIATOR) {
444 			plog(LLV_DEBUG, LOCATION, remote,
445 				"malformed cookie received or "
446 				"the initiator's cookies collide.\n");
447 			return -1;
448 		}
449 
450 #ifdef ENABLE_NATT
451 		/* Floating ports for NAT-T */
452 		if (NATT_AVAILABLE(iph1) &&
453 		    ! (iph1->natt_flags & NAT_PORTS_CHANGED) &&
454 		    ((cmpsaddrstrict(iph1->remote, remote) != 0) ||
455 		    (cmpsaddrstrict(iph1->local, local) != 0)))
456 		{
457 			/* prevent memory leak */
458 			racoon_free(iph1->remote);
459 			racoon_free(iph1->local);
460 
461 			/* copy-in new addresses */
462 			iph1->remote = dupsaddr(remote);
463 			iph1->local = dupsaddr(local);
464 
465 			/* set the flag to prevent further port floating
466 			   (FIXME: should we allow it? E.g. when the NAT gw
467 			    is rebooted?) */
468 			iph1->natt_flags |= NAT_PORTS_CHANGED | NAT_ADD_NON_ESP_MARKER;
469 
470 			/* print some neat info */
471 			plog (LLV_INFO, LOCATION, NULL,
472 			      "NAT-T: ports changed to: %s\n",
473 			      saddr2str_fromto ("%s<->%s", iph1->remote, iph1->local));
474 
475 			natt_keepalive_add_ph1 (iph1);
476 		}
477 #endif
478 
479 		/* must be same addresses in one stream of a phase at least. */
480 		if (cmpsaddrstrict(iph1->remote, remote) != 0) {
481 			char *saddr_db, *saddr_act;
482 
483 			saddr_db = strdup(saddr2str(iph1->remote));
484 			saddr_act = strdup(saddr2str(remote));
485 
486 			plog(LLV_WARNING, LOCATION, remote,
487 				"remote address mismatched. db=%s, act=%s\n",
488 				saddr_db, saddr_act);
489 
490 			racoon_free(saddr_db);
491 			racoon_free(saddr_act);
492 		}
493 
494 		/*
495 		 * don't check of exchange type here because other type will be
496 		 * with same index, for example, informational exchange.
497 		 */
498 
499 		/* XXX more acceptable check */
500 	}
501 
502 	switch (isakmp->etype) {
503 	case ISAKMP_ETYPE_IDENT:
504 	case ISAKMP_ETYPE_AGG:
505 	case ISAKMP_ETYPE_BASE:
506 		/* phase 1 validity check */
507 		if (isakmp->msgid != 0) {
508 			plog(LLV_ERROR, LOCATION, remote,
509 				"message id should be zero in phase1.\n");
510 			return -1;
511 		}
512 
513 		/* search for isakmp status record of phase 1 */
514 		if (iph1 == NULL) {
515 			/*
516 			 * the packet must be the 1st message from a initiator
517 			 * or the 2nd message from the responder.
518 			 */
519 
520 			/* search for phase1 handle by index without r_ck */
521 			iph1 = getph1byindex0(index);
522 			if (iph1 == NULL) {
523 				/*it must be the 1st message from a initiator.*/
524 				if (memcmp(&isakmp->r_ck, r_ck0,
525 					sizeof(cookie_t)) != 0) {
526 
527 					plog(LLV_DEBUG, LOCATION, remote,
528 						"malformed cookie received "
529 						"or the spi expired.\n");
530 					return -1;
531 				}
532 
533 				/* it must be responder's 1st exchange. */
534 				if (isakmp_ph1begin_r(msg, remote, local,
535 					isakmp->etype) < 0)
536 					return -1;
537 				break;
538 
539 				/*NOTREACHED*/
540 			}
541 
542 			/* it must be the 2nd message from the responder. */
543 			if (iph1->side != INITIATOR) {
544 				plog(LLV_DEBUG, LOCATION, remote,
545 					"malformed cookie received. "
546 					"it has to be as the initiator.  %s\n",
547 					isakmp_pindex(&iph1->index, 0));
548 				return -1;
549 			}
550 		}
551 
552 		/*
553 		 * Don't delete phase 1 handler when the exchange type
554 		 * in handler is not equal to packet's one because of no
555 		 * authencication completed.
556 		 */
557 		if (iph1->etype != isakmp->etype) {
558 			plog(LLV_ERROR, LOCATION, iph1->remote,
559 				"exchange type is mismatched: "
560 				"db=%s packet=%s, ignore it.\n",
561 				s_isakmp_etype(iph1->etype),
562 				s_isakmp_etype(isakmp->etype));
563 			return -1;
564 		}
565 
566 #ifdef ENABLE_FRAG
567 		if (isakmp->np == ISAKMP_NPTYPE_FRAG)
568 			return frag_handler(iph1, msg, remote, local);
569 #endif
570 
571 		/* call main process of phase 1 */
572 		if (ph1_main(iph1, msg) < 0) {
573 			plog(LLV_ERROR, LOCATION, iph1->remote,
574 				"phase1 negotiation failed.\n");
575 			remph1(iph1);
576 			delph1(iph1);
577 			return -1;
578 		}
579 		break;
580 
581 	case ISAKMP_ETYPE_AUTH:
582 		plog(LLV_INFO, LOCATION, remote,
583 			"unsupported exchange %d received.\n",
584 			isakmp->etype);
585 		break;
586 
587 	case ISAKMP_ETYPE_INFO:
588 	case ISAKMP_ETYPE_ACKINFO:
589 		/*
590 		 * iph1 must be present for Information message.
591 		 * if iph1 is null then trying to get the phase1 status
592 		 * as the packet from responder againt initiator's 1st
593 		 * exchange in phase 1.
594 		 * NOTE: We think such informational exchange should be ignored.
595 		 */
596 		if (iph1 == NULL) {
597 			iph1 = getph1byindex0(index);
598 			if (iph1 == NULL) {
599 				plog(LLV_ERROR, LOCATION, remote,
600 					"unknown Informational "
601 					"exchange received.\n");
602 				return -1;
603 			}
604 			if (cmpsaddrstrict(iph1->remote, remote) != 0) {
605 				plog(LLV_WARNING, LOCATION, remote,
606 					"remote address mismatched. "
607 					"db=%s\n",
608 					saddr2str(iph1->remote));
609 			}
610 		}
611 
612 #ifdef ENABLE_FRAG
613 		if (isakmp->np == ISAKMP_NPTYPE_FRAG)
614 			return frag_handler(iph1, msg, remote, local);
615 #endif
616 
617 		if (isakmp_info_recv(iph1, msg) < 0)
618 			return -1;
619 		break;
620 
621 	case ISAKMP_ETYPE_QUICK:
622 	{
623 		struct ph2handle *iph2;
624 
625 		if (iph1 == NULL) {
626 			isakmp_info_send_nx(isakmp, remote, local,
627 				ISAKMP_NTYPE_INVALID_COOKIE, NULL);
628 			plog(LLV_ERROR, LOCATION, remote,
629 				"can't start the quick mode, "
630 				"there is no ISAKMP-SA, %s\n",
631 				isakmp_pindex((isakmp_index *)&isakmp->i_ck,
632 					isakmp->msgid));
633 			return -1;
634 		}
635 
636 #ifdef ENABLE_FRAG
637 		if (isakmp->np == ISAKMP_NPTYPE_FRAG)
638 			return frag_handler(iph1, msg, remote, local);
639 #endif
640 
641 		/* check status of phase 1 whether negotiated or not. */
642 		if (iph1->status != PHASE1ST_ESTABLISHED) {
643 			plog(LLV_ERROR, LOCATION, remote,
644 				"can't start the quick mode, "
645 				"there is no valid ISAKMP-SA, %s\n",
646 				isakmp_pindex(&iph1->index, iph1->msgid));
647 			return -1;
648 		}
649 
650 		/* search isakmp phase 2 stauts record. */
651 		iph2 = getph2bymsgid(iph1, msgid);
652 		if (iph2 == NULL) {
653 			/* it must be new negotiation as responder */
654 			if (isakmp_ph2begin_r(iph1, msg) < 0)
655 				return -1;
656 			return 0;
657 			/*NOTREACHED*/
658 		}
659 
660 		/* commit bit. */
661 		/* XXX
662 		 * we keep to set commit bit during negotiation.
663 		 * When SA is configured, bit will be reset.
664 		 * XXX
665 		 * don't initiate commit bit.  should be fixed in the future.
666 		 */
667 		if (ISSET(isakmp->flags, ISAKMP_FLAG_C))
668 			iph2->flags |= ISAKMP_FLAG_C;
669 
670 		/* call main process of quick mode */
671 		if (quick_main(iph2, msg) < 0) {
672 			plog(LLV_ERROR, LOCATION, iph1->remote,
673 				"phase2 negotiation failed.\n");
674 			unbindph12(iph2);
675 			remph2(iph2);
676 			delph2(iph2);
677 			return -1;
678 		}
679 	}
680 		break;
681 
682 	case ISAKMP_ETYPE_NEWGRP:
683 		if (iph1 == NULL) {
684 			plog(LLV_ERROR, LOCATION, remote,
685 				"Unknown new group mode exchange, "
686 				"there is no ISAKMP-SA.\n");
687 			return -1;
688 		}
689 
690 #ifdef ENABLE_FRAG
691 		if (isakmp->np == ISAKMP_NPTYPE_FRAG)
692 			return frag_handler(iph1, msg, remote, local);
693 #endif
694 
695 		isakmp_newgroup_r(iph1, msg);
696 		break;
697 
698 #ifdef ENABLE_HYBRID
699 	case ISAKMP_ETYPE_CFG:
700 		if (iph1 == NULL) {
701 			plog(LLV_ERROR, LOCATION, NULL,
702 			     "mode config %d from %s, "
703 			     "but we have no ISAKMP-SA.\n",
704 			     isakmp->etype, saddr2str(remote));
705 			return -1;
706 		}
707 
708 #ifdef ENABLE_FRAG
709 		if (isakmp->np == ISAKMP_NPTYPE_FRAG)
710 			return frag_handler(iph1, msg, remote, local);
711 #endif
712 
713 		isakmp_cfg_r(iph1, msg);
714 		break;
715 #endif
716 
717 	case ISAKMP_ETYPE_NONE:
718 	default:
719 		plog(LLV_ERROR, LOCATION, NULL,
720 			"Invalid exchange type %d from %s.\n",
721 			isakmp->etype, saddr2str(remote));
722 		return -1;
723 	}
724 
725 	return 0;
726 }
727 
728 /*
729  * main function of phase 1.
730  */
731 static int
732 ph1_main(iph1, msg)
733 	struct ph1handle *iph1;
734 	vchar_t *msg;
735 {
736 	int error;
737 #ifdef ENABLE_STATS
738 	struct timeval start, end;
739 #endif
740 
741 	/* ignore a packet */
742 	if (iph1->status == PHASE1ST_ESTABLISHED)
743 		return 0;
744 
745 #ifdef ENABLE_STATS
746 	gettimeofday(&start, NULL);
747 #endif
748 	/* receive */
749 	if (ph1exchange[etypesw1(iph1->etype)]
750 		       [iph1->side]
751 		       [iph1->status] == NULL) {
752 		plog(LLV_ERROR, LOCATION, iph1->remote,
753 			"why isn't the function defined.\n");
754 		return -1;
755 	}
756 	error = (ph1exchange[etypesw1(iph1->etype)]
757 			    [iph1->side]
758 			    [iph1->status])(iph1, msg);
759 	if (error != 0) {
760 #if 0
761 		/* XXX
762 		 * When an invalid packet is received on phase1, it should
763 		 * be selected to process this packet.  That is to respond
764 		 * with a notify and delete phase 1 handler, OR not to respond
765 		 * and keep phase 1 handler.
766 		 */
767 		plog(LLV_ERROR, LOCATION, iph1->remote,
768 			"failed to pre-process packet.\n");
769 		return -1;
770 #else
771 		/* ignore the error and keep phase 1 handler */
772 		return 0;
773 #endif
774 	}
775 
776 	/* free resend buffer */
777 	if (iph1->sendbuf == NULL) {
778 		plog(LLV_ERROR, LOCATION, NULL,
779 			"no buffer found as sendbuf\n");
780 		return -1;
781 	}
782 	VPTRINIT(iph1->sendbuf);
783 
784 	/* turn off schedule */
785 	if (iph1->scr)
786 		SCHED_KILL(iph1->scr);
787 
788 	/* send */
789 	plog(LLV_DEBUG, LOCATION, NULL, "===\n");
790 	if ((ph1exchange[etypesw1(iph1->etype)]
791 			[iph1->side]
792 			[iph1->status])(iph1, msg) != 0) {
793 		plog(LLV_ERROR, LOCATION, iph1->remote,
794 			"failed to process packet.\n");
795 		return -1;
796 	}
797 
798 #ifdef ENABLE_STATS
799 	gettimeofday(&end, NULL);
800 	syslog(LOG_NOTICE, "%s(%s): %8.6f",
801 		"phase1", s_isakmp_state(iph1->etype, iph1->side, iph1->status),
802 		timedelta(&start, &end));
803 #endif
804 	if (iph1->status == PHASE1ST_ESTABLISHED) {
805 
806 #ifdef ENABLE_STATS
807 		gettimeofday(&iph1->end, NULL);
808 		syslog(LOG_NOTICE, "%s(%s): %8.6f",
809 			"phase1", s_isakmp_etype(iph1->etype),
810 			timedelta(&iph1->start, &iph1->end));
811 #endif
812 
813 		/* save created date. */
814 		(void)time(&iph1->created);
815 
816 		/* add to the schedule to expire, and seve back pointer. */
817 		iph1->sce = sched_new(iph1->approval->lifetime,
818 		    isakmp_ph1expire_stub, iph1);
819 #ifdef ENABLE_HYBRID
820 		if (iph1->mode_cfg->flags & ISAKMP_CFG_VENDORID_XAUTH) {
821 			switch(iph1->approval->authmethod) {
822 			case OAKLEY_ATTR_AUTH_METHOD_HYBRID_RSA_I:
823 			case OAKLEY_ATTR_AUTH_METHOD_HYBRID_DSS_I:
824 				xauth_sendreq(iph1);
825 				/* XXX Don't process INITIAL_CONTACT */
826 				iph1->rmconf->ini_contact = 0;
827 				break;
828 			default:
829 				break;
830 			}
831 		}
832 #endif
833 #ifdef ENABLE_DPD
834 		/* Schedule the r_u_there.... */
835 		if(iph1->dpd_support && iph1->rmconf->dpd_interval)
836 			isakmp_sched_r_u(iph1, 0);
837 #endif
838 
839 		/* INITIAL-CONTACT processing */
840 		/* don't anything if local test mode. */
841 		if (!f_local
842 		 && iph1->rmconf->ini_contact && !getcontacted(iph1->remote)) {
843 			/* send INITIAL-CONTACT */
844 			isakmp_info_send_n1(iph1,
845 					ISAKMP_NTYPE_INITIAL_CONTACT, NULL);
846 			/* insert a node into contacted list. */
847 			if (inscontacted(iph1->remote) == -1) {
848 				plog(LLV_ERROR, LOCATION, iph1->remote,
849 					"failed to add contacted list.\n");
850 				/* ignore */
851 			}
852 		}
853 
854 		log_ph1established(iph1);
855 		plog(LLV_DEBUG, LOCATION, NULL, "===\n");
856 
857 		/*
858 		 * SA up shell script hook: do it now,except if
859 		 * ISAKMP mode config was requested. In the later
860 		 * case it is done when we receive the configuration.
861 		 */
862 		if ((iph1->status == PHASE1ST_ESTABLISHED) &&
863 		    !iph1->rmconf->mode_cfg)
864 			script_hook(iph1, SCRIPT_PHASE1_UP);
865 	}
866 
867 	return 0;
868 }
869 
870 /*
871  * main function of quick mode.
872  */
873 static int
874 quick_main(iph2, msg)
875 	struct ph2handle *iph2;
876 	vchar_t *msg;
877 {
878 	struct isakmp *isakmp = (struct isakmp *)msg->v;
879 	int error;
880 #ifdef ENABLE_STATS
881 	struct timeval start, end;
882 #endif
883 
884 	/* ignore a packet */
885 	if (iph2->status == PHASE2ST_ESTABLISHED
886 	 || iph2->status == PHASE2ST_GETSPISENT)
887 		return 0;
888 
889 #ifdef ENABLE_STATS
890 	gettimeofday(&start, NULL);
891 #endif
892 
893 	/* receive */
894 	if (ph2exchange[etypesw2(isakmp->etype)]
895 		       [iph2->side]
896 		       [iph2->status] == NULL) {
897 		plog(LLV_ERROR, LOCATION, iph2->ph1->remote,
898 			"why isn't the function defined.\n");
899 		return -1;
900 	}
901 	error = (ph2exchange[etypesw2(isakmp->etype)]
902 			    [iph2->side]
903 			    [iph2->status])(iph2, msg);
904 	if (error != 0) {
905 		plog(LLV_ERROR, LOCATION, iph2->ph1->remote,
906 			"failed to pre-process packet.\n");
907 		if (error == ISAKMP_INTERNAL_ERROR)
908 			return 0;
909 		isakmp_info_send_n1(iph2->ph1, error, NULL);
910 		return -1;
911 	}
912 
913 	/* when using commit bit, status will be reached here. */
914 	if (iph2->status == PHASE2ST_ADDSA)
915 		return 0;
916 
917 	/* free resend buffer */
918 	if (iph2->sendbuf == NULL) {
919 		plog(LLV_ERROR, LOCATION, NULL,
920 			"no buffer found as sendbuf\n");
921 		return -1;
922 	}
923 	VPTRINIT(iph2->sendbuf);
924 
925 	/* turn off schedule */
926 	if (iph2->scr)
927 		SCHED_KILL(iph2->scr);
928 
929 	/* send */
930 	plog(LLV_DEBUG, LOCATION, NULL, "===\n");
931 	if ((ph2exchange[etypesw2(isakmp->etype)]
932 			[iph2->side]
933 			[iph2->status])(iph2, msg) != 0) {
934 		plog(LLV_ERROR, LOCATION, iph2->ph1->remote,
935 			"failed to process packet.\n");
936 		return -1;
937 	}
938 
939 #ifdef ENABLE_STATS
940 	gettimeofday(&end, NULL);
941 	syslog(LOG_NOTICE, "%s(%s): %8.6f",
942 		"phase2",
943 		s_isakmp_state(ISAKMP_ETYPE_QUICK, iph2->side, iph2->status),
944 		timedelta(&start, &end));
945 #endif
946 
947 	return 0;
948 }
949 
950 /* new negotiation of phase 1 for initiator */
951 int
952 isakmp_ph1begin_i(rmconf, remote, local)
953 	struct remoteconf *rmconf;
954 	struct sockaddr *remote, *local;
955 {
956 	struct ph1handle *iph1;
957 #ifdef ENABLE_STATS
958 	struct timeval start, end;
959 #endif
960 
961 	/* get new entry to isakmp status table. */
962 	iph1 = newph1();
963 	if (iph1 == NULL)
964 		return -1;
965 
966 	iph1->status = PHASE1ST_START;
967 	iph1->rmconf = rmconf;
968 	iph1->side = INITIATOR;
969 	iph1->version = ISAKMP_VERSION_NUMBER;
970 	iph1->msgid = 0;
971 	iph1->flags = 0;
972 	iph1->ph2cnt = 0;
973 #ifdef HAVE_GSSAPI
974 	iph1->gssapi_state = NULL;
975 #endif
976 #ifdef ENABLE_HYBRID
977 	if ((iph1->mode_cfg = isakmp_cfg_mkstate()) == NULL)
978 		return -1;
979 #endif
980 #ifdef ENABLE_FRAG
981 	iph1->frag = 0;
982 	iph1->frag_chain = NULL;
983 #endif
984 	iph1->approval = NULL;
985 
986 	/* XXX copy remote address */
987 	if (copy_ph1addresses(iph1, rmconf, remote, local) < 0)
988 		return -1;
989 
990 	(void)insph1(iph1);
991 
992 	/* start phase 1 exchange */
993 	iph1->etype = rmconf->etypes->type;
994 
995 	plog(LLV_DEBUG, LOCATION, NULL, "===\n");
996     {
997 	char *a;
998 
999 	a = strdup(saddr2str(iph1->local));
1000 	plog(LLV_INFO, LOCATION, NULL,
1001 		"initiate new phase 1 negotiation: %s<=>%s\n",
1002 		a, saddr2str(iph1->remote));
1003 	racoon_free(a);
1004     }
1005 	plog(LLV_INFO, LOCATION, NULL,
1006 		"begin %s mode.\n",
1007 		s_isakmp_etype(iph1->etype));
1008 
1009 #ifdef ENABLE_STATS
1010 	gettimeofday(&iph1->start, NULL);
1011 	gettimeofday(&start, NULL);
1012 #endif
1013 	/* start exchange */
1014 	if ((ph1exchange[etypesw1(iph1->etype)]
1015 			[iph1->side]
1016 			[iph1->status])(iph1, NULL) != 0) {
1017 		/* failed to start phase 1 negotiation */
1018 		remph1(iph1);
1019 		delph1(iph1);
1020 
1021 		return -1;
1022 	}
1023 
1024 #ifdef ENABLE_STATS
1025 	gettimeofday(&end, NULL);
1026 	syslog(LOG_NOTICE, "%s(%s): %8.6f",
1027 		"phase1",
1028 		s_isakmp_state(iph1->etype, iph1->side, iph1->status),
1029 		timedelta(&start, &end));
1030 #endif
1031 
1032 	return 0;
1033 }
1034 
1035 /* new negotiation of phase 1 for responder */
1036 static int
1037 isakmp_ph1begin_r(msg, remote, local, etype)
1038 	vchar_t *msg;
1039 	struct sockaddr *remote, *local;
1040 	u_int8_t etype;
1041 {
1042 	struct isakmp *isakmp = (struct isakmp *)msg->v;
1043 	struct remoteconf *rmconf;
1044 	struct ph1handle *iph1;
1045 	struct etypes *etypeok;
1046 #ifdef ENABLE_STATS
1047 	struct timeval start, end;
1048 #endif
1049 
1050 	/* look for my configuration */
1051 	rmconf = getrmconf(remote);
1052 	if (rmconf == NULL) {
1053 		plog(LLV_ERROR, LOCATION, remote,
1054 			"couldn't find "
1055 			"configuration.\n");
1056 		return -1;
1057 	}
1058 
1059 	/* check to be acceptable exchange type */
1060 	etypeok = check_etypeok(rmconf, etype);
1061 	if (etypeok == NULL) {
1062 		plog(LLV_ERROR, LOCATION, remote,
1063 			"not acceptable %s mode\n", s_isakmp_etype(etype));
1064 		return -1;
1065 	}
1066 
1067 	/* get new entry to isakmp status table. */
1068 	iph1 = newph1();
1069 	if (iph1 == NULL)
1070 		return -1;
1071 
1072 	memcpy(&iph1->index.i_ck, &isakmp->i_ck, sizeof(iph1->index.i_ck));
1073 	iph1->status = PHASE1ST_START;
1074 	iph1->rmconf = rmconf;
1075 	iph1->flags = 0;
1076 	iph1->side = RESPONDER;
1077 	iph1->etype = etypeok->type;
1078 	iph1->version = isakmp->v;
1079 	iph1->msgid = 0;
1080 #ifdef HAVE_GSSAPI
1081 	iph1->gssapi_state = NULL;
1082 #endif
1083 #ifdef ENABLE_HYBRID
1084 	if ((iph1->mode_cfg = isakmp_cfg_mkstate()) == NULL)
1085 		return -1;
1086 #endif
1087 #ifdef ENABLE_FRAG
1088 	iph1->frag = 0;
1089 	iph1->frag_chain = NULL;
1090 #endif
1091 	iph1->approval = NULL;
1092 
1093 #ifdef ENABLE_NATT
1094 	/* RFC3947 says that we MUST accept new phases1 on NAT-T floated port.
1095 	 * We have to setup this flag now to correctly generate the first reply.
1096 	 * Don't know if a better check could be done for that ?
1097 	 */
1098 	if(extract_port(local) == lcconf->port_isakmp_natt)
1099 		iph1->natt_flags |= (NAT_PORTS_CHANGED);
1100 #endif
1101 
1102 	/* copy remote address */
1103 	if (copy_ph1addresses(iph1, rmconf, remote, local) < 0)
1104 		return -1;
1105 
1106 	(void)insph1(iph1);
1107 
1108 	plog(LLV_DEBUG, LOCATION, NULL, "===\n");
1109     {
1110 	char *a;
1111 
1112 	a = strdup(saddr2str(iph1->local));
1113 	plog(LLV_INFO, LOCATION, NULL,
1114 		"respond new phase 1 negotiation: %s<=>%s\n",
1115 		a, saddr2str(iph1->remote));
1116 	racoon_free(a);
1117     }
1118 	plog(LLV_INFO, LOCATION, NULL,
1119 		"begin %s mode.\n", s_isakmp_etype(etype));
1120 
1121 #ifdef ENABLE_STATS
1122 	gettimeofday(&iph1->start, NULL);
1123 	gettimeofday(&start, NULL);
1124 #endif
1125 	/* start exchange */
1126 	if ((ph1exchange[etypesw1(iph1->etype)]
1127 	                [iph1->side]
1128 	                [iph1->status])(iph1, msg) < 0
1129 	 || (ph1exchange[etypesw1(iph1->etype)]
1130 			[iph1->side]
1131 			[iph1->status])(iph1, msg) < 0) {
1132 		plog(LLV_ERROR, LOCATION, remote,
1133 			"failed to process packet.\n");
1134 		remph1(iph1);
1135 		delph1(iph1);
1136 		return -1;
1137 	}
1138 #ifdef ENABLE_STATS
1139 	gettimeofday(&end, NULL);
1140 	syslog(LOG_NOTICE, "%s(%s): %8.6f",
1141 		"phase1",
1142 		s_isakmp_state(iph1->etype, iph1->side, iph1->status),
1143 		timedelta(&start, &end));
1144 #endif
1145 
1146 	return 0;
1147 }
1148 
1149 /* new negotiation of phase 2 for initiator */
1150 static int
1151 isakmp_ph2begin_i(iph1, iph2)
1152 	struct ph1handle *iph1;
1153 	struct ph2handle *iph2;
1154 {
1155 #ifdef ENABLE_HYBRID
1156 	if (xauth_check(iph1) != 0) {
1157 		plog(LLV_ERROR, LOCATION, NULL,
1158 		    "Attempt to start phase 2 whereas Xauth failed\n");
1159 		return -1;
1160 	}
1161 #endif
1162 
1163 	/* found ISAKMP-SA. */
1164 	plog(LLV_DEBUG, LOCATION, NULL, "===\n");
1165 	plog(LLV_DEBUG, LOCATION, NULL, "begin QUICK mode.\n");
1166     {
1167 	char *a;
1168 	a = strdup(saddr2str(iph2->src));
1169 	plog(LLV_INFO, LOCATION, NULL,
1170 		"initiate new phase 2 negotiation: %s<=>%s\n",
1171 		a, saddr2str(iph2->dst));
1172 	racoon_free(a);
1173     }
1174 
1175 #ifdef ENABLE_STATS
1176 	gettimeofday(&iph2->start, NULL);
1177 #endif
1178 	/* found isakmp-sa */
1179 	bindph12(iph1, iph2);
1180 	iph2->status = PHASE2ST_STATUS2;
1181 
1182 	if ((ph2exchange[etypesw2(ISAKMP_ETYPE_QUICK)]
1183 			 [iph2->side]
1184 			 [iph2->status])(iph2, NULL) < 0) {
1185 		unbindph12(iph2);
1186 		/* release ipsecsa handler due to internal error. */
1187 		remph2(iph2);
1188 		return -1;
1189 	}
1190 	return 0;
1191 }
1192 
1193 /* new negotiation of phase 2 for responder */
1194 static int
1195 isakmp_ph2begin_r(iph1, msg)
1196 	struct ph1handle *iph1;
1197 	vchar_t *msg;
1198 {
1199 	struct isakmp *isakmp = (struct isakmp *)msg->v;
1200 	struct ph2handle *iph2 = 0;
1201 	int error;
1202 #ifdef ENABLE_STATS
1203 	struct timeval start, end;
1204 #endif
1205 #ifdef ENABLE_HYBRID
1206 	if (xauth_check(iph1) != 0) {
1207 		plog(LLV_ERROR, LOCATION, NULL,
1208 		    "Attempt to start phase 2 whereas Xauth failed\n");
1209 		return -1;
1210 	}
1211 #endif
1212 
1213 	iph2 = newph2();
1214 	if (iph2 == NULL) {
1215 		plog(LLV_ERROR, LOCATION, NULL,
1216 			"failed to allocate phase2 entry.\n");
1217 		return -1;
1218 	}
1219 
1220 	iph2->ph1 = iph1;
1221 	iph2->side = RESPONDER;
1222 	iph2->status = PHASE2ST_START;
1223 	iph2->flags = isakmp->flags;
1224 	iph2->msgid = isakmp->msgid;
1225 	iph2->seq = pk_getseq();
1226 	iph2->ivm = oakley_newiv2(iph1, iph2->msgid);
1227 	if (iph2->ivm == NULL) {
1228 		delph2(iph2);
1229 		return -1;
1230 	}
1231 	iph2->dst = dupsaddr(iph1->remote);	/* XXX should be considered */
1232 	if (iph2->dst == NULL) {
1233 		delph2(iph2);
1234 		return -1;
1235 	}
1236 	switch (iph2->dst->sa_family) {
1237 	case AF_INET:
1238 #ifndef ENABLE_NATT
1239 		((struct sockaddr_in *)iph2->dst)->sin_port = 0;
1240 #endif
1241 		break;
1242 #ifdef INET6
1243 	case AF_INET6:
1244 #ifndef ENABLE_NATT
1245 		((struct sockaddr_in6 *)iph2->dst)->sin6_port = 0;
1246 #endif
1247 		break;
1248 #endif
1249 	default:
1250 		plog(LLV_ERROR, LOCATION, NULL,
1251 			"invalid family: %d\n", iph2->dst->sa_family);
1252 		delph2(iph2);
1253 		return -1;
1254 	}
1255 
1256 	iph2->src = dupsaddr(iph1->local);	/* XXX should be considered */
1257 	if (iph2->src == NULL) {
1258 		delph2(iph2);
1259 		return -1;
1260 	}
1261 	switch (iph2->src->sa_family) {
1262 	case AF_INET:
1263 #ifndef ENABLE_NATT
1264 		((struct sockaddr_in *)iph2->src)->sin_port = 0;
1265 #endif
1266 		break;
1267 #ifdef INET6
1268 	case AF_INET6:
1269 #ifndef ENABLE_NATT
1270 		((struct sockaddr_in6 *)iph2->src)->sin6_port = 0;
1271 #endif
1272 		break;
1273 #endif
1274 	default:
1275 		plog(LLV_ERROR, LOCATION, NULL,
1276 			"invalid family: %d\n", iph2->src->sa_family);
1277 		delph2(iph2);
1278 		return -1;
1279 	}
1280 
1281 	/* add new entry to isakmp status table */
1282 	insph2(iph2);
1283 	bindph12(iph1, iph2);
1284 
1285 	plog(LLV_DEBUG, LOCATION, NULL, "===\n");
1286     {
1287 	char *a;
1288 
1289 	a = strdup(saddr2str(iph2->src));
1290 	plog(LLV_INFO, LOCATION, NULL,
1291 		"respond new phase 2 negotiation: %s<=>%s\n",
1292 		a, saddr2str(iph2->dst));
1293 	racoon_free(a);
1294     }
1295 
1296 #ifdef ENABLE_STATS
1297 	gettimeofday(&start, NULL);
1298 #endif
1299 
1300 	error = (ph2exchange[etypesw2(ISAKMP_ETYPE_QUICK)]
1301 	                   [iph2->side]
1302 	                   [iph2->status])(iph2, msg);
1303 	if (error != 0) {
1304 		plog(LLV_ERROR, LOCATION, iph1->remote,
1305 			"failed to pre-process packet.\n");
1306 		if (error != ISAKMP_INTERNAL_ERROR)
1307 			isakmp_info_send_n1(iph2->ph1, error, NULL);
1308 		/*
1309 		 * release handler because it's wrong that ph2handle is kept
1310 		 * after failed to check message for responder's.
1311 		 */
1312 		unbindph12(iph2);
1313 		remph2(iph2);
1314 		delph2(iph2);
1315 		return -1;
1316 	}
1317 
1318 	/* send */
1319 	plog(LLV_DEBUG, LOCATION, NULL, "===\n");
1320 	if ((ph2exchange[etypesw2(isakmp->etype)]
1321 			[iph2->side]
1322 			[iph2->status])(iph2, msg) < 0) {
1323 		plog(LLV_ERROR, LOCATION, iph2->ph1->remote,
1324 			"failed to process packet.\n");
1325 		/* don't release handler */
1326 		return -1;
1327 	}
1328 #ifdef ENABLE_STATS
1329 	gettimeofday(&end, NULL);
1330 	syslog(LOG_NOTICE, "%s(%s): %8.6f",
1331 		"phase2",
1332 		s_isakmp_state(ISAKMP_ETYPE_QUICK, iph2->side, iph2->status),
1333 		timedelta(&start, &end));
1334 #endif
1335 
1336 	return 0;
1337 }
1338 
1339 /*
1340  * parse ISAKMP payloads, without ISAKMP base header.
1341  */
1342 vchar_t *
1343 isakmp_parsewoh(np0, gen, len)
1344 	int np0;
1345 	struct isakmp_gen *gen;
1346 	int len;
1347 {
1348 	u_char np = np0 & 0xff;
1349 	int tlen, plen;
1350 	vchar_t *result;
1351 	struct isakmp_parse_t *p, *ep;
1352 
1353 	plog(LLV_DEBUG, LOCATION, NULL, "begin.\n");
1354 
1355 	/*
1356 	 * 5 is a magic number, but any value larger than 2 should be fine
1357 	 * as we do vrealloc() in the following loop.
1358 	 */
1359 	result = vmalloc(sizeof(struct isakmp_parse_t) * 5);
1360 	if (result == NULL) {
1361 		plog(LLV_ERROR, LOCATION, NULL,
1362 			"failed to get buffer.\n");
1363 		return NULL;
1364 	}
1365 	p = (struct isakmp_parse_t *)result->v;
1366 	ep = (struct isakmp_parse_t *)(result->v + result->l - sizeof(*ep));
1367 
1368 	tlen = len;
1369 
1370 	/* parse through general headers */
1371 	while (0 < tlen && np != ISAKMP_NPTYPE_NONE) {
1372 		if (tlen <= sizeof(struct isakmp_gen)) {
1373 			/* don't send information, see isakmp_ident_r1() */
1374 			plog(LLV_ERROR, LOCATION, NULL,
1375 				"invalid length of payload\n");
1376 			vfree(result);
1377 			return NULL;
1378 		}
1379 
1380 		plog(LLV_DEBUG, LOCATION, NULL,
1381 			"seen nptype=%u(%s)\n", np, s_isakmp_nptype(np));
1382 
1383 		p->type = np;
1384 		p->len = ntohs(gen->len);
1385 		if (p->len < sizeof(struct isakmp_gen) || p->len > tlen) {
1386 			plog(LLV_DEBUG, LOCATION, NULL,
1387 				"invalid length of payload\n");
1388 			vfree(result);
1389 			return NULL;
1390 		}
1391 		p->ptr = gen;
1392 		p++;
1393 		if (ep <= p) {
1394 			int off;
1395 
1396 			off = p - (struct isakmp_parse_t *)result->v;
1397 			result = vrealloc(result, result->l * 2);
1398 			if (result == NULL) {
1399 				plog(LLV_DEBUG, LOCATION, NULL,
1400 					"failed to realloc buffer.\n");
1401 				vfree(result);
1402 				return NULL;
1403 			}
1404 			ep = (struct isakmp_parse_t *)
1405 				(result->v + result->l - sizeof(*ep));
1406 			p = (struct isakmp_parse_t *)result->v;
1407 			p += off;
1408 		}
1409 
1410 		np = gen->np;
1411 		plen = ntohs(gen->len);
1412 		gen = (struct isakmp_gen *)((caddr_t)gen + plen);
1413 		tlen -= plen;
1414 	}
1415 	p->type = ISAKMP_NPTYPE_NONE;
1416 	p->len = 0;
1417 	p->ptr = NULL;
1418 
1419 	plog(LLV_DEBUG, LOCATION, NULL, "succeed.\n");
1420 
1421 	return result;
1422 }
1423 
1424 /*
1425  * parse ISAKMP payloads, including ISAKMP base header.
1426  */
1427 vchar_t *
1428 isakmp_parse(buf)
1429 	vchar_t *buf;
1430 {
1431 	struct isakmp *isakmp = (struct isakmp *)buf->v;
1432 	struct isakmp_gen *gen;
1433 	int tlen;
1434 	vchar_t *result;
1435 	u_char np;
1436 
1437 	np = isakmp->np;
1438 	gen = (struct isakmp_gen *)(buf->v + sizeof(*isakmp));
1439 	tlen = buf->l - sizeof(struct isakmp);
1440 	result = isakmp_parsewoh(np, gen, tlen);
1441 
1442 	return result;
1443 }
1444 
1445 /* %%% */
1446 int
1447 isakmp_init()
1448 {
1449 	/* initialize a isakmp status table */
1450 	initph1tree();
1451 	initph2tree();
1452 	initctdtree();
1453 	init_recvdpkt();
1454 
1455 	if (isakmp_open() < 0)
1456 		goto err;
1457 
1458 	return(0);
1459 
1460 err:
1461 	isakmp_close();
1462 	return(-1);
1463 }
1464 
1465 /*
1466  * make strings containing i_cookie + r_cookie + msgid
1467  */
1468 const char *
1469 isakmp_pindex(index, msgid)
1470 	const isakmp_index *index;
1471 	const u_int32_t msgid;
1472 {
1473 	static char buf[64];
1474 	const u_char *p;
1475 	int i, j;
1476 
1477 	memset(buf, 0, sizeof(buf));
1478 
1479 	/* copy index */
1480 	p = (const u_char *)index;
1481 	for (j = 0, i = 0; i < sizeof(isakmp_index); i++) {
1482 		snprintf((char *)&buf[j], sizeof(buf) - j, "%02x", p[i]);
1483 		j += 2;
1484 		switch (i) {
1485 		case 7:
1486 			buf[j++] = ':';
1487 		}
1488 	}
1489 
1490 	if (msgid == 0)
1491 		return buf;
1492 
1493 	/* copy msgid */
1494 	snprintf((char *)&buf[j], sizeof(buf) - j, ":%08x", ntohs(msgid));
1495 
1496 	return buf;
1497 }
1498 
1499 /* open ISAKMP sockets. */
1500 int
1501 isakmp_open()
1502 {
1503 	const int yes = 1;
1504 	int ifnum = 0, encap_ifnum = 0;
1505 #ifdef INET6
1506 	int pktinfo;
1507 #endif
1508 	struct myaddrs *p;
1509 
1510 	for (p = lcconf->myaddrs; p; p = p->next) {
1511 		if (!p->addr)
1512 			continue;
1513 
1514 		/* warn if wildcard address - should we forbid this? */
1515 		switch (p->addr->sa_family) {
1516 		case AF_INET:
1517 			if (((struct sockaddr_in *)p->addr)->sin_addr.s_addr == 0)
1518 				plog(LLV_WARNING, LOCATION, NULL,
1519 					"listening to wildcard address,"
1520 					"broadcast IKE packet may kill you\n");
1521 			break;
1522 #ifdef INET6
1523 		case AF_INET6:
1524 			if (IN6_IS_ADDR_UNSPECIFIED(&((struct sockaddr_in6 *)p->addr)->sin6_addr))
1525 				plog(LLV_WARNING, LOCATION, NULL,
1526 					"listening to wildcard address, "
1527 					"broadcast IKE packet may kill you\n");
1528 			break;
1529 #endif
1530 		default:
1531 			plog(LLV_ERROR, LOCATION, NULL,
1532 				"unsupported address family %d\n",
1533 				lcconf->default_af);
1534 			goto err_and_next;
1535 		}
1536 
1537 #ifdef INET6
1538 		if (p->addr->sa_family == AF_INET6 &&
1539 		    IN6_IS_ADDR_MULTICAST(&((struct sockaddr_in6 *)
1540 					    p->addr)->sin6_addr))
1541 		{
1542 			plog(LLV_DEBUG, LOCATION, NULL,
1543 				"Ignoring multicast address %s\n",
1544 				saddr2str(p->addr));
1545 				racoon_free(p->addr);
1546 				p->addr = NULL;
1547 			continue;
1548 		}
1549 #endif
1550 
1551 		if ((p->sock = socket(p->addr->sa_family, SOCK_DGRAM, 0)) < 0) {
1552 			plog(LLV_ERROR, LOCATION, NULL,
1553 				"socket (%s)\n", strerror(errno));
1554 			goto err_and_next;
1555 		}
1556 
1557 		/* receive my interface address on inbound packets. */
1558 		switch (p->addr->sa_family) {
1559 		case AF_INET:
1560 			if (setsockopt(p->sock, IPPROTO_IP,
1561 #ifdef __linux__
1562 				       IP_PKTINFO,
1563 #else
1564 				       IP_RECVDSTADDR,
1565 #endif
1566 					(const void *)&yes, sizeof(yes)) < 0) {
1567 				plog(LLV_ERROR, LOCATION, NULL,
1568 					"setsockopt (%s)\n", strerror(errno));
1569 				goto err_and_next;
1570 			}
1571 			break;
1572 #ifdef INET6
1573 		case AF_INET6:
1574 #ifdef INET6_ADVAPI
1575 #ifdef IPV6_RECVPKTINFO
1576 			pktinfo = IPV6_RECVPKTINFO;
1577 #else  /* old adv. API */
1578 			pktinfo = IPV6_PKTINFO;
1579 #endif /* IPV6_RECVPKTINFO */
1580 #else
1581 			pktinfo = IPV6_RECVDSTADDR;
1582 #endif
1583 			if (setsockopt(p->sock, IPPROTO_IPV6, pktinfo,
1584 					(const void *)&yes, sizeof(yes)) < 0)
1585 			{
1586 				plog(LLV_ERROR, LOCATION, NULL,
1587 					"setsockopt(%d): %s\n",
1588 					pktinfo, strerror(errno));
1589 		if (fcntl(p->sock, F_SETFL, O_NONBLOCK) == -1)
1590 			plog(LLV_WARNING, LOCATION, NULL,
1591 				"failed to put socket in non-blocking mode\n");
1592 
1593 				goto err_and_next;
1594 			}
1595 			break;
1596 #endif
1597 		}
1598 
1599 #ifdef IPV6_USE_MIN_MTU
1600 		if (p->addr->sa_family == AF_INET6 &&
1601 		    setsockopt(p->sock, IPPROTO_IPV6, IPV6_USE_MIN_MTU,
1602 		    (void *)&yes, sizeof(yes)) < 0) {
1603 			plog(LLV_ERROR, LOCATION, NULL,
1604 			    "setsockopt (%s)\n", strerror(errno));
1605 			return -1;
1606 		}
1607 #endif
1608 
1609 		if (setsockopt_bypass(p->sock, p->addr->sa_family) < 0)
1610 			goto err_and_next;
1611 
1612 		if (bind(p->sock, p->addr, sysdep_sa_len(p->addr)) < 0) {
1613 			plog(LLV_ERROR, LOCATION, p->addr,
1614 				"failed to bind to address %s (%s).\n",
1615 				saddr2str(p->addr), strerror(errno));
1616 			close(p->sock);
1617 			goto err_and_next;
1618 		}
1619 
1620 		ifnum++;
1621 
1622 		plog(LLV_INFO, LOCATION, NULL,
1623 			"%s used as isakmp port (fd=%d)\n",
1624 			saddr2str(p->addr), p->sock);
1625 
1626 #ifdef ENABLE_NATT
1627 		if (p->addr->sa_family == AF_INET) {
1628 			int option = -1;
1629 
1630 
1631 			if(p->udp_encap)
1632 				option = UDP_ENCAP_ESPINUDP;
1633 #if defined(ENABLE_NATT_00) || defined(ENABLE_NATT_01)
1634 			else
1635 				option = UDP_ENCAP_ESPINUDP_NON_IKE;
1636 #endif
1637 			if(option != -1){
1638 				if (setsockopt (p->sock, SOL_UDP, UDP_ENCAP,
1639 								&option, sizeof (option)) < 0) {
1640 					plog(LLV_WARNING, LOCATION, NULL,
1641 						 "setsockopt(%s): %s\n",
1642 						 option == UDP_ENCAP_ESPINUDP ? "UDP_ENCAP_ESPINUDP" : "UDP_ENCAP_ESPINUDP_NON_IKE",
1643 						 strerror(errno));
1644 					goto skip_encap;
1645 				}
1646 				else {
1647 					plog(LLV_INFO, LOCATION, NULL,
1648 						 "%s used for NAT-T\n",
1649 						 saddr2str(p->addr));
1650 					encap_ifnum++;
1651 				}
1652 			}
1653 		}
1654 skip_encap:
1655 #endif
1656 		continue;
1657 
1658 	err_and_next:
1659 		racoon_free(p->addr);
1660 		p->addr = NULL;
1661 		if (! lcconf->autograbaddr && lcconf->strict_address)
1662 			return -1;
1663 		continue;
1664 	}
1665 
1666 	if (!ifnum) {
1667 		plog(LLV_ERROR, LOCATION, NULL,
1668 			"no address could be bound.\n");
1669 		return -1;
1670 	}
1671 
1672 #ifdef ENABLE_NATT
1673 	if (natt_enabled_in_rmconf() && !encap_ifnum) {
1674 		plog(LLV_WARNING, LOCATION, NULL,
1675 			"NAT-T is enabled in at least one remote{} section,\n");
1676 		plog(LLV_WARNING, LOCATION, NULL,
1677 			"but no 'isakmp_natt' address was specified!\n");
1678 	}
1679 #endif
1680 
1681 	return 0;
1682 }
1683 
1684 void
1685 isakmp_close()
1686 {
1687 	struct myaddrs *p, *next;
1688 
1689 	for (p = lcconf->myaddrs; p; p = next) {
1690 		next = p->next;
1691 
1692 		if (!p->addr) {
1693 			racoon_free(p);
1694 			continue;
1695 		}
1696 		close(p->sock);
1697 		racoon_free(p->addr);
1698 		racoon_free(p);
1699 	}
1700 
1701 	lcconf->myaddrs = NULL;
1702 }
1703 
1704 int
1705 isakmp_send(iph1, sbuf)
1706 	struct ph1handle *iph1;
1707 	vchar_t *sbuf;
1708 {
1709 	int len = 0;
1710 	int s;
1711 	vchar_t *vbuf = NULL;
1712 
1713 #ifdef ENABLE_NATT
1714 	size_t extralen = NON_ESP_MARKER_USE(iph1) ? NON_ESP_MARKER_LEN : 0;
1715 
1716 #ifdef ENABLE_FRAG
1717 	/*
1718 	 * Do not add the non ESP marker for a packet that will
1719 	 * be fragmented. The non ESP marker should appear in
1720 	 * all fragment's packets, but not in the fragmented packet
1721 	 */
1722 	if (iph1->frag && sbuf->l > ISAKMP_FRAG_MAXLEN)
1723 		extralen = 0;
1724 #endif
1725 	if (extralen)
1726 		plog (LLV_DEBUG, LOCATION, NULL, "Adding NON-ESP marker\n");
1727 
1728 	/* If NAT-T port floating is in use, 4 zero bytes (non-ESP marker)
1729 	   must added just before the packet itself. For this we must
1730 	   allocate a new buffer and release it at the end. */
1731 	if (extralen) {
1732 		vbuf = vmalloc (sbuf->l + extralen);
1733 		*(u_int32_t *)vbuf->v = 0;
1734 		memcpy (vbuf->v + extralen, sbuf->v, sbuf->l);
1735 		sbuf = vbuf;
1736 	}
1737 #endif
1738 
1739 	/* select the socket to be sent */
1740 	s = getsockmyaddr(iph1->local);
1741 	if (s == -1){
1742 		if ( vbuf != NULL )
1743 			vfree(vbuf);
1744 		return -1;
1745 	}
1746 
1747 	plog (LLV_DEBUG, LOCATION, NULL, "%zu bytes %s\n", sbuf->l,
1748 	      saddr2str_fromto("from %s to %s", iph1->local, iph1->remote));
1749 
1750 #ifdef ENABLE_FRAG
1751 	if (iph1->frag && sbuf->l > ISAKMP_FRAG_MAXLEN) {
1752 		if (isakmp_sendfrags(iph1, sbuf) == -1) {
1753 			plog(LLV_ERROR, LOCATION, NULL,
1754 			    "isakmp_sendfrags failed\n");
1755 			if ( vbuf != NULL )
1756 				vfree(vbuf);
1757 			return -1;
1758 		}
1759 	} else
1760 #endif
1761 	{
1762 		len = sendfromto(s, sbuf->v, sbuf->l,
1763 		    iph1->local, iph1->remote, lcconf->count_persend);
1764 		if (len == -1) {
1765 			plog(LLV_ERROR, LOCATION, NULL, "sendfromto failed\n");
1766 			if ( vbuf != NULL )
1767 				vfree(vbuf);
1768 			return -1;
1769 		}
1770 	}
1771 
1772 	if ( vbuf != NULL )
1773 		vfree(vbuf);
1774 
1775 	return 0;
1776 }
1777 
1778 /* called from scheduler */
1779 void
1780 isakmp_ph1resend_stub(p)
1781 	void *p;
1782 {
1783 	(void)isakmp_ph1resend((struct ph1handle *)p);
1784 }
1785 
1786 int
1787 isakmp_ph1resend(iph1)
1788 	struct ph1handle *iph1;
1789 {
1790 	if (iph1->retry_counter < 0) {
1791 		plog(LLV_ERROR, LOCATION, NULL,
1792 			"phase1 negotiation failed due to time up. %s\n",
1793 			isakmp_pindex(&iph1->index, iph1->msgid));
1794 		EVT_PUSH(iph1->local, iph1->remote,
1795 		    EVTT_PEER_NO_RESPONSE, NULL);
1796 
1797 		remph1(iph1);
1798 		delph1(iph1);
1799 		return -1;
1800 	}
1801 
1802 	if (isakmp_send(iph1, iph1->sendbuf) < 0)
1803 		return -1;
1804 
1805 	plog(LLV_DEBUG, LOCATION, NULL,
1806 		"resend phase1 packet %s\n",
1807 		isakmp_pindex(&iph1->index, iph1->msgid));
1808 
1809 	iph1->retry_counter--;
1810 
1811 	iph1->scr = sched_new(iph1->rmconf->retry_interval,
1812 		isakmp_ph1resend_stub, iph1);
1813 
1814 	return 0;
1815 }
1816 
1817 /* called from scheduler */
1818 void
1819 isakmp_ph2resend_stub(p)
1820 	void *p;
1821 {
1822 
1823 	(void)isakmp_ph2resend((struct ph2handle *)p);
1824 }
1825 
1826 int
1827 isakmp_ph2resend(iph2)
1828 	struct ph2handle *iph2;
1829 {
1830 	if (iph2->retry_counter < 0) {
1831 		plog(LLV_ERROR, LOCATION, NULL,
1832 			"phase2 negotiation failed due to time up. %s\n",
1833 				isakmp_pindex(&iph2->ph1->index, iph2->msgid));
1834 		EVT_PUSH(iph2->src, iph2->dst, EVTT_PEER_NO_RESPONSE, NULL);
1835 		unbindph12(iph2);
1836 		remph2(iph2);
1837 		delph2(iph2);
1838 		return -1;
1839 	}
1840 
1841 	if (isakmp_send(iph2->ph1, iph2->sendbuf) < 0)
1842 		return -1;
1843 
1844 	plog(LLV_DEBUG, LOCATION, NULL,
1845 		"resend phase2 packet %s\n",
1846 		isakmp_pindex(&iph2->ph1->index, iph2->msgid));
1847 
1848 	iph2->retry_counter--;
1849 
1850 	iph2->scr = sched_new(iph2->ph1->rmconf->retry_interval,
1851 		isakmp_ph2resend_stub, iph2);
1852 
1853 	return 0;
1854 }
1855 
1856 /* called from scheduler */
1857 void
1858 isakmp_ph1expire_stub(p)
1859 	void *p;
1860 {
1861 
1862 	isakmp_ph1expire((struct ph1handle *)p);
1863 }
1864 
1865 void
1866 isakmp_ph1expire(iph1)
1867 	struct ph1handle *iph1;
1868 {
1869 	char *src, *dst;
1870 
1871 	SCHED_KILL(iph1->sce);
1872 
1873 	if(iph1->status != PHASE1ST_EXPIRED){
1874 		src = strdup(saddr2str(iph1->local));
1875 		dst = strdup(saddr2str(iph1->remote));
1876 		plog(LLV_INFO, LOCATION, NULL,
1877 			 "ISAKMP-SA expired %s-%s spi:%s\n",
1878 			 src, dst,
1879 			 isakmp_pindex(&iph1->index, 0));
1880 		racoon_free(src);
1881 		racoon_free(dst);
1882 		iph1->status = PHASE1ST_EXPIRED;
1883 	}
1884 
1885 	/*
1886 	 * the phase1 deletion is postponed until there is no phase2.
1887 	 */
1888 	if (LIST_FIRST(&iph1->ph2tree) != NULL) {
1889 		iph1->sce = sched_new(1, isakmp_ph1expire_stub, iph1);
1890 		return;
1891 	}
1892 
1893 	iph1->sce = sched_new(1, isakmp_ph1delete_stub, iph1);
1894 }
1895 
1896 /* called from scheduler */
1897 void
1898 isakmp_ph1delete_stub(p)
1899 	void *p;
1900 {
1901 
1902 	isakmp_ph1delete((struct ph1handle *)p);
1903 }
1904 
1905 void
1906 isakmp_ph1delete(iph1)
1907 	struct ph1handle *iph1;
1908 {
1909 	char *src, *dst;
1910 
1911 	SCHED_KILL(iph1->sce);
1912 
1913 	if (LIST_FIRST(&iph1->ph2tree) != NULL) {
1914 		iph1->sce = sched_new(1, isakmp_ph1delete_stub, iph1);
1915 		return;
1916 	}
1917 
1918 	/* don't re-negosiation when the phase 1 SA expires. */
1919 
1920 	src = strdup(saddr2str(iph1->local));
1921 	dst = strdup(saddr2str(iph1->remote));
1922 	plog(LLV_INFO, LOCATION, NULL,
1923 		"ISAKMP-SA deleted %s-%s spi:%s\n",
1924 		src, dst, isakmp_pindex(&iph1->index, 0));
1925 	EVT_PUSH(iph1->local, iph1->remote, EVTT_PHASE1_DOWN, NULL);
1926 	racoon_free(src);
1927 	racoon_free(dst);
1928 
1929 	remph1(iph1);
1930 	delph1(iph1);
1931 
1932 	return;
1933 }
1934 
1935 /* called from scheduler.
1936  * this function will call only isakmp_ph2delete().
1937  * phase 2 handler remain forever if kernel doesn't cry a expire of phase 2 SA
1938  * by something cause.  That's why this function is called after phase 2 SA
1939  * expires in the userland.
1940  */
1941 void
1942 isakmp_ph2expire_stub(p)
1943 	void *p;
1944 {
1945 
1946 	isakmp_ph2expire((struct ph2handle *)p);
1947 }
1948 
1949 void
1950 isakmp_ph2expire(iph2)
1951 	struct ph2handle *iph2;
1952 {
1953 	char *src, *dst;
1954 
1955 	SCHED_KILL(iph2->sce);
1956 
1957 	src = strdup(saddrwop2str(iph2->src));
1958 	dst = strdup(saddrwop2str(iph2->dst));
1959 	plog(LLV_INFO, LOCATION, NULL,
1960 		"phase2 sa expired %s-%s\n", src, dst);
1961 	racoon_free(src);
1962 	racoon_free(dst);
1963 
1964 	iph2->status = PHASE2ST_EXPIRED;
1965 
1966 	iph2->sce = sched_new(1, isakmp_ph2delete_stub, iph2);
1967 
1968 	return;
1969 }
1970 
1971 /* called from scheduler */
1972 void
1973 isakmp_ph2delete_stub(p)
1974 	void *p;
1975 {
1976 
1977 	isakmp_ph2delete((struct ph2handle *)p);
1978 }
1979 
1980 void
1981 isakmp_ph2delete(iph2)
1982 	struct ph2handle *iph2;
1983 {
1984 	char *src, *dst;
1985 
1986 	SCHED_KILL(iph2->sce);
1987 
1988 	src = strdup(saddrwop2str(iph2->src));
1989 	dst = strdup(saddrwop2str(iph2->dst));
1990 	plog(LLV_INFO, LOCATION, NULL,
1991 		"phase2 sa deleted %s-%s\n", src, dst);
1992 	racoon_free(src);
1993 	racoon_free(dst);
1994 
1995 	unbindph12(iph2);
1996 	remph2(iph2);
1997 	delph2(iph2);
1998 
1999 	return;
2000 }
2001 
2002 /* %%%
2003  * Interface between PF_KEYv2 and ISAKMP
2004  */
2005 /*
2006  * receive ACQUIRE from kernel, and begin either phase1 or phase2.
2007  * if phase1 has been finished, begin phase2.
2008  */
2009 int
2010 isakmp_post_acquire(iph2)
2011 	struct ph2handle *iph2;
2012 {
2013 	struct remoteconf *rmconf;
2014 	struct ph1handle *iph1 = NULL;
2015 
2016 	/* search appropreate configuration with masking port. */
2017 	rmconf = getrmconf(iph2->dst);
2018 	if (rmconf == NULL) {
2019 		plog(LLV_ERROR, LOCATION, NULL,
2020 			"no configuration found for %s.\n",
2021 			saddrwop2str(iph2->dst));
2022 		return -1;
2023 	}
2024 
2025 	/* if passive mode, ignore the acquire message */
2026 	if (rmconf->passive) {
2027 		plog(LLV_DEBUG, LOCATION, NULL,
2028 			"because of passive mode, "
2029 			"ignore the acquire message for %s.\n",
2030 			saddrwop2str(iph2->dst));
2031 		return 0;
2032 	}
2033 
2034 	/*
2035 	 * Search isakmp status table by address and port
2036 	 * If NAT-T is in use, consider null ports as a
2037 	 * wildcard and use IKE ports instead.
2038 	 */
2039 #ifdef ENABLE_NATT
2040 	if (!extract_port(iph2->src) && !extract_port(iph2->dst)) {
2041 		if ((iph1 = getph1byaddrwop(iph2->src, iph2->dst)) != NULL) {
2042 			set_port(iph2->src, extract_port(iph1->local));
2043 			set_port(iph2->dst, extract_port(iph1->remote));
2044 		}
2045 	} else {
2046 		iph1 = getph1byaddr(iph2->src, iph2->dst);
2047 	}
2048 #else
2049 	iph1 = getph1byaddr(iph2->src, iph2->dst);
2050 #endif
2051 
2052 	/* no ISAKMP-SA found. */
2053 	if (iph1 == NULL) {
2054 		struct sched *sc;
2055 
2056 		iph2->retry_checkph1 = lcconf->retry_checkph1;
2057 		sc = sched_new(1, isakmp_chkph1there_stub, iph2);
2058 		plog(LLV_INFO, LOCATION, NULL,
2059 			"IPsec-SA request for %s queued "
2060 			"due to no phase1 found.\n",
2061 			saddrwop2str(iph2->dst));
2062 
2063 		/* start phase 1 negotiation as a initiator. */
2064 		if (isakmp_ph1begin_i(rmconf, iph2->dst, iph2->src) < 0) {
2065 			SCHED_KILL(sc);
2066 			return -1;
2067 		}
2068 
2069 		return 0;
2070 		/*NOTREACHED*/
2071 	}
2072 
2073 	/* found ISAKMP-SA, but on negotiation. */
2074 	if (iph1->status != PHASE1ST_ESTABLISHED) {
2075 		iph2->retry_checkph1 = lcconf->retry_checkph1;
2076 		sched_new(1, isakmp_chkph1there_stub, iph2);
2077 		plog(LLV_INFO, LOCATION, iph2->dst,
2078 			"request for establishing IPsec-SA was queued "
2079 			"due to no phase1 found.\n");
2080 		return 0;
2081 		/*NOTREACHED*/
2082 	}
2083 
2084 	/* found established ISAKMP-SA */
2085 	/* i.e. iph1->status == PHASE1ST_ESTABLISHED */
2086 
2087 	/* found ISAKMP-SA. */
2088 	plog(LLV_DEBUG, LOCATION, NULL, "begin QUICK mode.\n");
2089 
2090 	/* begin quick mode */
2091 	if (isakmp_ph2begin_i(iph1, iph2))
2092 		return -1;
2093 
2094 	return 0;
2095 }
2096 
2097 /*
2098  * receive GETSPI from kernel.
2099  */
2100 int
2101 isakmp_post_getspi(iph2)
2102 	struct ph2handle *iph2;
2103 {
2104 #ifdef ENABLE_STATS
2105 	struct timeval start, end;
2106 #endif
2107 
2108 	/* don't process it because there is no suitable phase1-sa. */
2109 	if (iph2->ph1->status == PHASE1ST_EXPIRED) {
2110 		plog(LLV_ERROR, LOCATION, iph2->ph1->remote,
2111 			"the negotiation is stopped, "
2112 			"because there is no suitable ISAKMP-SA.\n");
2113 		return -1;
2114 	}
2115 
2116 #ifdef ENABLE_STATS
2117 	gettimeofday(&start, NULL);
2118 #endif
2119 	if ((ph2exchange[etypesw2(ISAKMP_ETYPE_QUICK)]
2120 	                [iph2->side]
2121 	                [iph2->status])(iph2, NULL) != 0)
2122 		return -1;
2123 #ifdef ENABLE_STATS
2124 	gettimeofday(&end, NULL);
2125 	syslog(LOG_NOTICE, "%s(%s): %8.6f",
2126 		"phase2",
2127 		s_isakmp_state(ISAKMP_ETYPE_QUICK, iph2->side, iph2->status),
2128 		timedelta(&start, &end));
2129 #endif
2130 
2131 	return 0;
2132 }
2133 
2134 /* called by scheduler */
2135 void
2136 isakmp_chkph1there_stub(p)
2137 	void *p;
2138 {
2139 	isakmp_chkph1there((struct ph2handle *)p);
2140 }
2141 
2142 void
2143 isakmp_chkph1there(iph2)
2144 	struct ph2handle *iph2;
2145 {
2146 	struct ph1handle *iph1;
2147 
2148 	iph2->retry_checkph1--;
2149 	if (iph2->retry_checkph1 < 0) {
2150 		plog(LLV_ERROR, LOCATION, iph2->dst,
2151 			"phase2 negotiation failed "
2152 			"due to time up waiting for phase1. %s\n",
2153 			sadbsecas2str(iph2->dst, iph2->src,
2154 				iph2->satype, 0, 0));
2155 		plog(LLV_INFO, LOCATION, NULL,
2156 			"delete phase 2 handler.\n");
2157 
2158 		/* send acquire to kernel as error */
2159 		pk_sendeacquire(iph2);
2160 
2161 		unbindph12(iph2);
2162 		remph2(iph2);
2163 		delph2(iph2);
2164 
2165 		return;
2166 	}
2167 
2168 	/*
2169 	 * Search isakmp status table by address and port
2170 	 * If NAT-T is in use, consider null ports as a
2171 	 * wildcard and use IKE ports instead.
2172 	 */
2173 #ifdef ENABLE_NATT
2174 	if (!extract_port(iph2->src) && !extract_port(iph2->dst)) {
2175 		if ((iph1 = getph1byaddrwop(iph2->src, iph2->dst)) != NULL) {
2176 			set_port(iph2->src, extract_port(iph1->local));
2177 			set_port(iph2->dst, extract_port(iph1->remote));
2178 		}
2179 	} else {
2180 		iph1 = getph1byaddr(iph2->src, iph2->dst);
2181 	}
2182 #else
2183 	iph1 = getph1byaddr(iph2->src, iph2->dst);
2184 #endif
2185 
2186 	/* XXX Even if ph1 as responder is there, should we not start
2187 	 * phase 2 negotiation ? */
2188 	if (iph1 != NULL
2189 	 && iph1->status == PHASE1ST_ESTABLISHED) {
2190 		/* found isakmp-sa */
2191 		/* begin quick mode */
2192 		(void)isakmp_ph2begin_i(iph1, iph2);
2193 		return;
2194 	}
2195 
2196 	/* no isakmp-sa found */
2197 	sched_new(1, isakmp_chkph1there_stub, iph2);
2198 
2199 	return;
2200 }
2201 
2202 /* copy variable data into ALLOCATED buffer. */
2203 caddr_t
2204 isakmp_set_attr_v(buf, type, val, len)
2205 	caddr_t buf;
2206 	int type;
2207 	caddr_t val;
2208 	int len;
2209 {
2210 	struct isakmp_data *data;
2211 
2212 	data = (struct isakmp_data *)buf;
2213 	data->type = htons((u_int16_t)type | ISAKMP_GEN_TLV);
2214 	data->lorv = htons((u_int16_t)len);
2215 	memcpy(data + 1, val, len);
2216 
2217 	return buf + sizeof(*data) + len;
2218 }
2219 
2220 /* copy fixed length data into ALLOCATED buffer. */
2221 caddr_t
2222 isakmp_set_attr_l(buf, type, val)
2223 	caddr_t buf;
2224 	int type;
2225 	u_int32_t val;
2226 {
2227 	struct isakmp_data *data;
2228 
2229 	data = (struct isakmp_data *)buf;
2230 	data->type = htons((u_int16_t)type | ISAKMP_GEN_TV);
2231 	data->lorv = htons((u_int16_t)val);
2232 
2233 	return buf + sizeof(*data);
2234 }
2235 
2236 /* add a variable data attribute to the buffer by reallocating it. */
2237 vchar_t *
2238 isakmp_add_attr_v(buf0, type, val, len)
2239 	vchar_t *buf0;
2240 	int type;
2241 	caddr_t val;
2242 	int len;
2243 {
2244 	vchar_t *buf = NULL;
2245 	struct isakmp_data *data;
2246 	int tlen;
2247 	int oldlen = 0;
2248 
2249 	tlen = sizeof(*data) + len;
2250 
2251 	if (buf0) {
2252 		oldlen = buf0->l;
2253 		buf = vrealloc(buf0, oldlen + tlen);
2254 	} else
2255 		buf = vmalloc(tlen);
2256 	if (!buf) {
2257 		plog(LLV_ERROR, LOCATION, NULL,
2258 			"failed to get a attribute buffer.\n");
2259 		return NULL;
2260 	}
2261 
2262 	data = (struct isakmp_data *)(buf->v + oldlen);
2263 	data->type = htons((u_int16_t)type | ISAKMP_GEN_TLV);
2264 	data->lorv = htons((u_int16_t)len);
2265 	memcpy(data + 1, val, len);
2266 
2267 	return buf;
2268 }
2269 
2270 /* add a fixed data attribute to the buffer by reallocating it. */
2271 vchar_t *
2272 isakmp_add_attr_l(buf0, type, val)
2273 	vchar_t *buf0;
2274 	int type;
2275 	u_int32_t val;
2276 {
2277 	vchar_t *buf = NULL;
2278 	struct isakmp_data *data;
2279 	int tlen;
2280 	int oldlen = 0;
2281 
2282 	tlen = sizeof(*data);
2283 
2284 	if (buf0) {
2285 		oldlen = buf0->l;
2286 		buf = vrealloc(buf0, oldlen + tlen);
2287 	} else
2288 		buf = vmalloc(tlen);
2289 	if (!buf) {
2290 		plog(LLV_ERROR, LOCATION, NULL,
2291 			"failed to get a attribute buffer.\n");
2292 		return NULL;
2293 	}
2294 
2295 	data = (struct isakmp_data *)(buf->v + oldlen);
2296 	data->type = htons((u_int16_t)type | ISAKMP_GEN_TV);
2297 	data->lorv = htons((u_int16_t)val);
2298 
2299 	return buf;
2300 }
2301 
2302 /*
2303  * calculate cookie and set.
2304  */
2305 int
2306 isakmp_newcookie(place, remote, local)
2307 	caddr_t place;
2308 	struct sockaddr *remote;
2309 	struct sockaddr *local;
2310 {
2311 	vchar_t *buf = NULL, *buf2 = NULL;
2312 	char *p;
2313 	int blen;
2314 	int alen;
2315 	caddr_t sa1, sa2;
2316 	time_t t;
2317 	int error = -1;
2318 	u_short port;
2319 
2320 
2321 	if (remote->sa_family != local->sa_family) {
2322 		plog(LLV_ERROR, LOCATION, NULL,
2323 			"address family mismatch, remote:%d local:%d\n",
2324 			remote->sa_family, local->sa_family);
2325 		goto end;
2326 	}
2327 	switch (remote->sa_family) {
2328 	case AF_INET:
2329 		alen = sizeof(struct in_addr);
2330 		sa1 = (caddr_t)&((struct sockaddr_in *)remote)->sin_addr;
2331 		sa2 = (caddr_t)&((struct sockaddr_in *)local)->sin_addr;
2332 		break;
2333 #ifdef INET6
2334 	case AF_INET6:
2335 		alen = sizeof(struct in_addr);
2336 		sa1 = (caddr_t)&((struct sockaddr_in6 *)remote)->sin6_addr;
2337 		sa2 = (caddr_t)&((struct sockaddr_in6 *)local)->sin6_addr;
2338 		break;
2339 #endif
2340 	default:
2341 		plog(LLV_ERROR, LOCATION, NULL,
2342 			"invalid family: %d\n", remote->sa_family);
2343 		goto end;
2344 	}
2345 	blen = (alen + sizeof(u_short)) * 2
2346 		+ sizeof(time_t) + lcconf->secret_size;
2347 	buf = vmalloc(blen);
2348 	if (buf == NULL) {
2349 		plog(LLV_ERROR, LOCATION, NULL,
2350 			"failed to get a cookie.\n");
2351 		goto end;
2352 	}
2353 	p = buf->v;
2354 
2355 	/* copy my address */
2356 	memcpy(p, sa1, alen);
2357 	p += alen;
2358 	port = ((struct sockaddr_in *)remote)->sin_port;
2359 	memcpy(p, &port, sizeof(u_short));
2360 	p += sizeof(u_short);
2361 
2362 	/* copy target address */
2363 	memcpy(p, sa2, alen);
2364 	p += alen;
2365 	port = ((struct sockaddr_in *)local)->sin_port;
2366 	memcpy(p, &port, sizeof(u_short));
2367 	p += sizeof(u_short);
2368 
2369 	/* copy time */
2370 	t = time(0);
2371 	memcpy(p, (caddr_t)&t, sizeof(t));
2372 	p += sizeof(t);
2373 
2374 	/* copy random value */
2375 	buf2 = eay_set_random(lcconf->secret_size);
2376 	if (buf2 == NULL)
2377 		goto end;
2378 	memcpy(p, buf2->v, lcconf->secret_size);
2379 	p += lcconf->secret_size;
2380 	vfree(buf2);
2381 
2382 	buf2 = eay_sha1_one(buf);
2383 	memcpy(place, buf2->v, sizeof(cookie_t));
2384 
2385 	sa1 = val2str(place, sizeof (cookie_t));
2386 	plog(LLV_DEBUG, LOCATION, NULL, "new cookie:\n%s\n", sa1);
2387 	racoon_free(sa1);
2388 
2389 	error = 0;
2390 end:
2391 	if (buf != NULL)
2392 		vfree(buf);
2393 	if (buf2 != NULL)
2394 		vfree(buf2);
2395 	return error;
2396 }
2397 
2398 /*
2399  * save partner's(payload) data into phhandle.
2400  */
2401 int
2402 isakmp_p2ph(buf, gen)
2403 	vchar_t **buf;
2404 	struct isakmp_gen *gen;
2405 {
2406 	/* XXX to be checked in each functions for logging. */
2407 	if (*buf) {
2408 		plog(LLV_WARNING, LOCATION, NULL,
2409 			"ignore this payload, same payload type exist.\n");
2410 		return -1;
2411 	}
2412 
2413 	*buf = vmalloc(ntohs(gen->len) - sizeof(*gen));
2414 	if (*buf == NULL) {
2415 		plog(LLV_ERROR, LOCATION, NULL,
2416 			"failed to get buffer.\n");
2417 		return -1;
2418 	}
2419 	memcpy((*buf)->v, gen + 1, (*buf)->l);
2420 
2421 	return 0;
2422 }
2423 
2424 u_int32_t
2425 isakmp_newmsgid2(iph1)
2426 	struct ph1handle *iph1;
2427 {
2428 	u_int32_t msgid2;
2429 
2430 	do {
2431 		msgid2 = eay_random();
2432 	} while (getph2bymsgid(iph1, msgid2));
2433 
2434 	return msgid2;
2435 }
2436 
2437 /*
2438  * set values into allocated buffer of isakmp header for phase 1
2439  */
2440 static caddr_t
2441 set_isakmp_header(vbuf, iph1, nptype, etype, flags, msgid)
2442 	vchar_t *vbuf;
2443 	struct ph1handle *iph1;
2444 	int nptype;
2445 	u_int8_t etype;
2446 	u_int8_t flags;
2447 	u_int32_t msgid;
2448 {
2449 	struct isakmp *isakmp;
2450 
2451 	if (vbuf->l < sizeof(*isakmp))
2452 		return NULL;
2453 
2454 	isakmp = (struct isakmp *)vbuf->v;
2455 
2456 	memcpy(&isakmp->i_ck, &iph1->index.i_ck, sizeof(cookie_t));
2457 	memcpy(&isakmp->r_ck, &iph1->index.r_ck, sizeof(cookie_t));
2458 	isakmp->np = nptype;
2459 	isakmp->v = iph1->version;
2460 	isakmp->etype = etype;
2461 	isakmp->flags = flags;
2462 	isakmp->msgid = msgid;
2463 	isakmp->len = htonl(vbuf->l);
2464 
2465 	return vbuf->v + sizeof(*isakmp);
2466 }
2467 
2468 /*
2469  * set values into allocated buffer of isakmp header for phase 1
2470  */
2471 caddr_t
2472 set_isakmp_header1(vbuf, iph1, nptype)
2473 	vchar_t *vbuf;
2474 	struct ph1handle *iph1;
2475 	int nptype;
2476 {
2477 	return set_isakmp_header (vbuf, iph1, nptype, iph1->etype, iph1->flags, iph1->msgid);
2478 }
2479 
2480 /*
2481  * set values into allocated buffer of isakmp header for phase 2
2482  */
2483 caddr_t
2484 set_isakmp_header2(vbuf, iph2, nptype)
2485 	vchar_t *vbuf;
2486 	struct ph2handle *iph2;
2487 	int nptype;
2488 {
2489 	return set_isakmp_header (vbuf, iph2->ph1, nptype, ISAKMP_ETYPE_QUICK, iph2->flags, iph2->msgid);
2490 }
2491 
2492 /*
2493  * set values into allocated buffer of isakmp payload.
2494  */
2495 caddr_t
2496 set_isakmp_payload(buf, src, nptype)
2497 	caddr_t buf;
2498 	vchar_t *src;
2499 	int nptype;
2500 {
2501 	struct isakmp_gen *gen;
2502 	caddr_t p = buf;
2503 
2504 	plog(LLV_DEBUG, LOCATION, NULL, "add payload of len %zu, next type %d\n",
2505 	    src->l, nptype);
2506 
2507 	gen = (struct isakmp_gen *)p;
2508 	gen->np = nptype;
2509 	gen->len = htons(sizeof(*gen) + src->l);
2510 	p += sizeof(*gen);
2511 	memcpy(p, src->v, src->l);
2512 	p += src->l;
2513 
2514 	return p;
2515 }
2516 
2517 static int
2518 etypesw1(etype)
2519 	int etype;
2520 {
2521 	switch (etype) {
2522 	case ISAKMP_ETYPE_IDENT:
2523 		return 1;
2524 	case ISAKMP_ETYPE_AGG:
2525 		return 2;
2526 	case ISAKMP_ETYPE_BASE:
2527 		return 3;
2528 	default:
2529 		return 0;
2530 	}
2531 	/*NOTREACHED*/
2532 }
2533 
2534 static int
2535 etypesw2(etype)
2536 	int etype;
2537 {
2538 	switch (etype) {
2539 	case ISAKMP_ETYPE_QUICK:
2540 		return 1;
2541 	default:
2542 		return 0;
2543 	}
2544 	/*NOTREACHED*/
2545 }
2546 
2547 #ifdef HAVE_PRINT_ISAKMP_C
2548 /* for print-isakmp.c */
2549 char *snapend;
2550 extern void isakmp_print __P((const u_char *, u_int, const u_char *));
2551 
2552 char *getname __P((const u_char *));
2553 #ifdef INET6
2554 char *getname6 __P((const u_char *));
2555 #endif
2556 int safeputchar __P((int));
2557 
2558 /*
2559  * Return a name for the IP address pointed to by ap.  This address
2560  * is assumed to be in network byte order.
2561  */
2562 char *
2563 getname(ap)
2564 	const u_char *ap;
2565 {
2566 	struct sockaddr_in addr;
2567 	static char ntop_buf[NI_MAXHOST];
2568 
2569 	memset(&addr, 0, sizeof(addr));
2570 #ifndef __linux__
2571 	addr.sin_len = sizeof(struct sockaddr_in);
2572 #endif
2573 	addr.sin_family = AF_INET;
2574 	memcpy(&addr.sin_addr, ap, sizeof(addr.sin_addr));
2575 	if (getnameinfo((struct sockaddr *)&addr, sizeof(addr),
2576 			ntop_buf, sizeof(ntop_buf), NULL, 0,
2577 			NI_NUMERICHOST | niflags))
2578 		strlcpy(ntop_buf, "?", sizeof(ntop_buf));
2579 
2580 	return ntop_buf;
2581 }
2582 
2583 #ifdef INET6
2584 /*
2585  * Return a name for the IP6 address pointed to by ap.  This address
2586  * is assumed to be in network byte order.
2587  */
2588 char *
2589 getname6(ap)
2590 	const u_char *ap;
2591 {
2592 	struct sockaddr_in6 addr;
2593 	static char ntop_buf[NI_MAXHOST];
2594 
2595 	memset(&addr, 0, sizeof(addr));
2596 	addr.sin6_len = sizeof(struct sockaddr_in6);
2597 	addr.sin6_family = AF_INET6;
2598 	memcpy(&addr.sin6_addr, ap, sizeof(addr.sin6_addr));
2599 	if (getnameinfo((struct sockaddr *)&addr, addr.sin6_len,
2600 			ntop_buf, sizeof(ntop_buf), NULL, 0,
2601 			NI_NUMERICHOST | niflags))
2602 		strlcpy(ntop_buf, "?", sizeof(ntop_buf));
2603 
2604 	return ntop_buf;
2605 }
2606 #endif /* INET6 */
2607 
2608 int
2609 safeputchar(c)
2610 	int c;
2611 {
2612 	unsigned char ch;
2613 
2614 	ch = (unsigned char)(c & 0xff);
2615 	if (c < 0x80 && isprint(c))
2616 		return printf("%c", c & 0xff);
2617 	else
2618 		return printf("\\%03o", c & 0xff);
2619 }
2620 
2621 void
2622 isakmp_printpacket(msg, from, my, decoded)
2623 	vchar_t *msg;
2624 	struct sockaddr *from;
2625 	struct sockaddr *my;
2626 	int decoded;
2627 {
2628 #ifdef YIPS_DEBUG
2629 	struct timeval tv;
2630 	int s;
2631 	char hostbuf[NI_MAXHOST];
2632 	char portbuf[NI_MAXSERV];
2633 	struct isakmp *isakmp;
2634 	vchar_t *buf;
2635 #endif
2636 
2637 	if (loglevel < LLV_DEBUG)
2638 		return;
2639 
2640 #ifdef YIPS_DEBUG
2641 	plog(LLV_DEBUG, LOCATION, NULL, "begin.\n");
2642 
2643 	gettimeofday(&tv, NULL);
2644 	s = tv.tv_sec % 3600;
2645 	printf("%02d:%02d.%06u ", s / 60, s % 60, (u_int32_t)tv.tv_usec);
2646 
2647 	if (from) {
2648 		if (getnameinfo(from, sysdep_sa_len(from), hostbuf, sizeof(hostbuf),
2649 				portbuf, sizeof(portbuf),
2650 				NI_NUMERICHOST | NI_NUMERICSERV | niflags)) {
2651 			strlcpy(hostbuf, "?", sizeof(hostbuf));
2652 			strlcpy(portbuf, "?", sizeof(portbuf));
2653 		}
2654 		printf("%s:%s", hostbuf, portbuf);
2655 	} else
2656 		printf("?");
2657 	printf(" -> ");
2658 	if (my) {
2659 		if (getnameinfo(my, sysdep_sa_len(my), hostbuf, sizeof(hostbuf),
2660 				portbuf, sizeof(portbuf),
2661 				NI_NUMERICHOST | NI_NUMERICSERV | niflags)) {
2662 			strlcpy(hostbuf, "?", sizeof(hostbuf));
2663 			strlcpy(portbuf, "?", sizeof(portbuf));
2664 		}
2665 		printf("%s:%s", hostbuf, portbuf);
2666 	} else
2667 		printf("?");
2668 	printf(": ");
2669 
2670 	buf = vdup(msg);
2671 	if (!buf) {
2672 		printf("(malloc fail)\n");
2673 		return;
2674 	}
2675 	if (decoded) {
2676 		isakmp = (struct isakmp *)buf->v;
2677 		if (isakmp->flags & ISAKMP_FLAG_E) {
2678 #if 0
2679 			int pad;
2680 			pad = *(u_char *)(buf->v + buf->l - 1);
2681 			if (buf->l < pad && 2 < vflag)
2682 				printf("(wrong padding)");
2683 #endif
2684 			isakmp->flags &= ~ISAKMP_FLAG_E;
2685 		}
2686 	}
2687 
2688 	snapend = buf->v + buf->l;
2689 	isakmp_print(buf->v, buf->l, NULL);
2690 	vfree(buf);
2691 	printf("\n");
2692 	fflush(stdout);
2693 
2694 	return;
2695 #endif
2696 }
2697 #endif /*HAVE_PRINT_ISAKMP_C*/
2698 
2699 int
2700 copy_ph1addresses(iph1, rmconf, remote, local)
2701 	struct ph1handle *iph1;
2702 	struct remoteconf *rmconf;
2703 	struct sockaddr *remote, *local;
2704 {
2705 	u_short *port = NULL;
2706 
2707 	/* address portion must be grabbed from real remote address "remote" */
2708 	iph1->remote = dupsaddr(remote);
2709 	if (iph1->remote == NULL) {
2710 		delph1(iph1);
2711 		return -1;
2712 	}
2713 
2714 	/*
2715 	 * if remote has no port # (in case of initiator - from ACQUIRE msg)
2716 	 * - if remote.conf specifies port #, use that
2717 	 * - if remote.conf does not, use 500
2718 	 * if remote has port # (in case of responder - from recvfrom(2))
2719 	 * respect content of "remote".
2720 	 */
2721 	switch (iph1->remote->sa_family) {
2722 	case AF_INET:
2723 		port = &((struct sockaddr_in *)iph1->remote)->sin_port;
2724 		if (*port)
2725 			break;
2726 		*port = ((struct sockaddr_in *)rmconf->remote)->sin_port;
2727 		if (*port)
2728 			break;
2729 		*port = htons(PORT_ISAKMP);
2730 		break;
2731 #ifdef INET6
2732 	case AF_INET6:
2733 		port = &((struct sockaddr_in6 *)iph1->remote)->sin6_port;
2734 		if (*port)
2735 			break;
2736 		*port = ((struct sockaddr_in6 *)rmconf->remote)->sin6_port;
2737 		if (*port)
2738 			break;
2739 		*port = htons(PORT_ISAKMP);
2740 		break;
2741 #endif
2742 	default:
2743 		plog(LLV_ERROR, LOCATION, NULL,
2744 			"invalid family: %d\n", iph1->remote->sa_family);
2745 		return -1;
2746 	}
2747 
2748 	if (local == NULL)
2749 		iph1->local = getlocaladdr(iph1->remote);
2750 	else
2751 		iph1->local = dupsaddr(local);
2752 	if (iph1->local == NULL) {
2753 		delph1(iph1);
2754 		return -1;
2755 	}
2756 	port = NULL;
2757 	switch (iph1->local->sa_family) {
2758 	case AF_INET:
2759 		port = &((struct sockaddr_in *)iph1->local)->sin_port;
2760 		if (*port)
2761 			break;
2762 		*port = ((struct sockaddr_in *)local)->sin_port;
2763 		if (*port)
2764 			break;
2765 		*port = getmyaddrsport(iph1->local);
2766 		break;
2767 #ifdef INET6
2768 	case AF_INET6:
2769 		port = &((struct sockaddr_in6 *)iph1->local)->sin6_port;
2770 		if (*port)
2771 			break;
2772 		*port = ((struct sockaddr_in6 *)local)->sin6_port;
2773 		if (*port)
2774 			break;
2775 		*port = getmyaddrsport(iph1->local);
2776 		break;
2777 #endif
2778 	default:
2779 		plog(LLV_ERROR, LOCATION, NULL,
2780 			"invalid family: %d\n", iph1->local->sa_family);
2781 		delph1(iph1);
2782 		return -1;
2783 	}
2784 #ifdef ENABLE_NATT
2785 	if ( port != NULL && *port == htons(lcconf->port_isakmp_natt) ) {
2786 	    plog (LLV_DEBUG, LOCATION, NULL, "Marking ports as changed\n");
2787 	    iph1->natt_flags |= NAT_ADD_NON_ESP_MARKER;
2788 	}
2789 #endif
2790 
2791 	return 0;
2792 }
2793 
2794 static int
2795 nostate1(iph1, msg)
2796 	struct ph1handle *iph1;
2797 	vchar_t *msg;
2798 {
2799 	plog(LLV_ERROR, LOCATION, iph1->remote, "wrong state %u.\n",
2800 			iph1->status);
2801 	return -1;
2802 }
2803 
2804 static int
2805 nostate2(iph2, msg)
2806 	struct ph2handle *iph2;
2807 	vchar_t *msg;
2808 {
2809 	plog(LLV_ERROR, LOCATION, iph2->ph1->remote, "wrong state %u.\n",
2810 		iph2->status);
2811 	return -1;
2812 }
2813 
2814 void
2815 log_ph1established(iph1)
2816 	const struct ph1handle *iph1;
2817 {
2818 	char *src, *dst;
2819 
2820 	src = strdup(saddr2str(iph1->local));
2821 	dst = strdup(saddr2str(iph1->remote));
2822 	plog(LLV_INFO, LOCATION, NULL,
2823 		"ISAKMP-SA established %s-%s spi:%s\n",
2824 		src, dst,
2825 		isakmp_pindex(&iph1->index, 0));
2826 	EVT_PUSH(iph1->local, iph1->remote, EVTT_PHASE1_UP, NULL);
2827 	racoon_free(src);
2828 	racoon_free(dst);
2829 
2830 	return;
2831 }
2832 
2833 struct payload_list *
2834 isakmp_plist_append (struct payload_list *plist, vchar_t *payload, int payload_type)
2835 {
2836 	if (! plist) {
2837 		plist = racoon_malloc (sizeof (struct payload_list));
2838 		plist->prev = NULL;
2839 	}
2840 	else {
2841 		plist->next = racoon_malloc (sizeof (struct payload_list));
2842 		plist->next->prev = plist;
2843 		plist = plist->next;
2844 	}
2845 
2846 	plist->next = NULL;
2847 	plist->payload = payload;
2848 	plist->payload_type = payload_type;
2849 
2850 	return plist;
2851 }
2852 
2853 vchar_t *
2854 isakmp_plist_set_all (struct payload_list **plist, struct ph1handle *iph1)
2855 {
2856 	struct payload_list *ptr, *first;
2857 	size_t tlen = sizeof (struct isakmp), n = 0;
2858 	vchar_t *buf;
2859 	char *p;
2860 
2861 	if (plist == NULL) {
2862 		plog(LLV_ERROR, LOCATION, NULL,
2863 		    "in isakmp_plist_set_all: plist == NULL\n");
2864 		return NULL;
2865 	}
2866 
2867 	/* Seek to the first item.  */
2868 	ptr = *plist;
2869 	while (ptr->prev)
2870 		ptr = ptr->prev;
2871 	first = ptr;
2872 
2873 	/* Compute the whole length.  */
2874 	while (ptr) {
2875 		tlen += ptr->payload->l + sizeof (struct isakmp_gen);
2876 		ptr = ptr->next;
2877 	}
2878 
2879 	buf = vmalloc(tlen);
2880 	if (buf == NULL) {
2881 		plog(LLV_ERROR, LOCATION, NULL,
2882 			"failed to get buffer to send.\n");
2883 		goto end;
2884 	}
2885 
2886 	ptr = first;
2887 
2888 	p = set_isakmp_header1(buf, iph1, ptr->payload_type);
2889 	if (p == NULL)
2890 		goto end;
2891 
2892 	while (ptr)
2893 	{
2894 		p = set_isakmp_payload (p, ptr->payload, ptr->next ? ptr->next->payload_type : ISAKMP_NPTYPE_NONE);
2895 		first = ptr;
2896 		ptr = ptr->next;
2897 		racoon_free (first);
2898 		/* ptr->prev = NULL; first = NULL; ... omitted.  */
2899 		n++;
2900 	}
2901 
2902 	*plist = NULL;
2903 
2904 	return buf;
2905 end:
2906 	return NULL;
2907 }
2908 
2909 #ifdef ENABLE_FRAG
2910 int
2911 frag_handler(iph1, msg, remote, local)
2912 	struct ph1handle *iph1;
2913 	vchar_t *msg;
2914 	struct sockaddr *remote;
2915 	struct sockaddr *local;
2916 {
2917 	vchar_t *newmsg;
2918 
2919 	if (isakmp_frag_extract(iph1, msg) == 1) {
2920 		if ((newmsg = isakmp_frag_reassembly(iph1)) == NULL) {
2921 			plog(LLV_ERROR, LOCATION, remote,
2922 			    "Packet reassembly failed\n");
2923 			return -1;
2924 		}
2925 		return isakmp_main(newmsg, remote, local);
2926 	}
2927 
2928 	return 0;
2929 }
2930 #endif
2931 
2932 void
2933 script_hook(iph1, script)
2934 	struct ph1handle *iph1;
2935 	int script;
2936 {
2937 #define IP_MAX 40
2938 #define PORT_MAX 6
2939 	char addrstr[IP_MAX];
2940 	char portstr[PORT_MAX];
2941 	char **envp = NULL;
2942 	int envc = 1;
2943 	struct sockaddr_in *sin;
2944 	char **c;
2945 
2946 	if (iph1->rmconf->script[script] == -1)
2947 		return;
2948 
2949 #ifdef ENABLE_HYBRID
2950 	(void)isakmp_cfg_setenv(iph1, &envp, &envc);
2951 #endif
2952 
2953 	/* local address */
2954 	sin = (struct sockaddr_in *)iph1->local;
2955 	inet_ntop(sin->sin_family, &sin->sin_addr, addrstr, IP_MAX);
2956 	snprintf(portstr, PORT_MAX, "%d", ntohs(sin->sin_port));
2957 
2958 	if (script_env_append(&envp, &envc, "LOCAL_ADDR", addrstr) != 0) {
2959 		plog(LLV_ERROR, LOCATION, NULL, "Cannot set LOCAL_ADDR\n");
2960 		goto out;
2961 	}
2962 
2963 	if (script_env_append(&envp, &envc, "LOCAL_PORT", portstr) != 0) {
2964 		plog(LLV_ERROR, LOCATION, NULL, "Cannot set LOCAL_PORT\n");
2965 		goto out;
2966 	}
2967 
2968 	/* Peer address */
2969 	sin = (struct sockaddr_in *)iph1->remote;
2970 	inet_ntop(sin->sin_family, &sin->sin_addr, addrstr, IP_MAX);
2971 	snprintf(portstr, PORT_MAX, "%d", ntohs(sin->sin_port));
2972 
2973 	if (script_env_append(&envp, &envc, "REMOTE_ADDR", addrstr) != 0) {
2974 		plog(LLV_ERROR, LOCATION, NULL, "Cannot set REMOTE_ADDR\n");
2975 		goto out;
2976 	}
2977 
2978 	if (script_env_append(&envp, &envc, "REMOTE_PORT", portstr) != 0) {
2979 		plog(LLV_ERROR, LOCATION, NULL, "Cannot set REMOTEL_PORT\n");
2980 		goto out;
2981 	}
2982 
2983 	if (privsep_script_exec(iph1->rmconf->script[script],
2984 	    script, envp) != 0)
2985 		plog(LLV_ERROR, LOCATION, NULL,
2986 		    "Script %s execution failed\n", script_names[script]);
2987 
2988 out:
2989 	for (c = envp; *c; c++)
2990 		racoon_free(*c);
2991 
2992 	racoon_free(envp);
2993 
2994 	return;
2995 }
2996 
2997 int
2998 script_env_append(envp, envc, name, value)
2999 	char ***envp;
3000 	int *envc;
3001 	char *name;
3002 	char *value;
3003 {
3004 	char *envitem;
3005 	char **newenvp;
3006 	int newenvc;
3007 
3008 	envitem = racoon_malloc(strlen(name) + 1 + strlen(value) + 1);
3009 	if (envitem == NULL) {
3010 		plog(LLV_ERROR, LOCATION, NULL,
3011 		    "Cannot allocate memory: %s\n", strerror(errno));
3012 		return -1;
3013 	}
3014 	sprintf(envitem, "%s=%s", name, value);
3015 
3016 	newenvc = (*envc) + 1;
3017 	newenvp = racoon_realloc(*envp, newenvc * sizeof(char *));
3018 	if (newenvp == NULL) {
3019 		plog(LLV_ERROR, LOCATION, NULL,
3020 		    "Cannot allocate memory: %s\n", strerror(errno));
3021 		return -1;
3022 	}
3023 
3024 	newenvp[newenvc - 2] = envitem;
3025 	newenvp[newenvc - 1] = NULL;
3026 
3027 	*envp = newenvp;
3028 	*envc = newenvc;
3029 	return 0;
3030 }
3031 
3032 int
3033 script_exec(script, name, envp)
3034 	int script;
3035 	int name;
3036 	char *const envp[];
3037 {
3038 	char *argv[] = { NULL, NULL, NULL };
3039 	vchar_t **sp;
3040 
3041 	if (script_paths == NULL) {
3042 		plog(LLV_ERROR, LOCATION, NULL,
3043 		    "privsep_script_exec: script_paths was not initialized\n");
3044 		return -1;
3045 	}
3046 
3047 	sp = (vchar_t **)(script_paths->v);
3048 
3049 	argv[0] = sp[script]->v;
3050 	argv[1] = script_names[name];
3051 	argv[2] = NULL;
3052 
3053 	switch (fork()) {
3054 	case 0:
3055 		execve(argv[0], argv, envp);
3056 		plog(LLV_ERROR, LOCATION, NULL,
3057 		    "execve(\"%s\") failed: %s\n",
3058 		    argv[0], strerror(errno));
3059 		_exit(1);
3060 		break;
3061 	case -1:
3062 		plog(LLV_ERROR, LOCATION, NULL,
3063 		    "Cannot fork: %s\n", strerror(errno));
3064 		return -1;
3065 		break;
3066 	default:
3067 		break;
3068 	}
3069 
3070 	return 0;
3071 }
3072 
3073 void
3074 purge_remote(iph1)
3075 	struct ph1handle *iph1;
3076 {
3077 	vchar_t *buf = NULL;
3078 	struct sadb_msg *msg, *next, *end;
3079 	struct sadb_sa *sa;
3080 	struct sockaddr *src, *dst;
3081 	caddr_t mhp[SADB_EXT_MAX + 1];
3082 	u_int proto_id;
3083 	struct ph2handle *iph2;
3084 	struct ph1handle *new_iph1;
3085 
3086 	plog(LLV_INFO, LOCATION, NULL,
3087 		 "purging ISAKMP-SA spi=%s.\n",
3088 		 isakmp_pindex(&(iph1->index), iph1->msgid));
3089 
3090 	/* Mark as expired. */
3091 	iph1->status = PHASE1ST_EXPIRED;
3092 
3093 	/* Check if we have another, still valid, phase1 SA. */
3094 	new_iph1 = getph1byaddr(iph1->local, iph1->remote);
3095 
3096 	/*
3097 	 * Delete all orphaned or binded to the deleting ph1handle phase2 SAs.
3098 	 * Keep all others phase2 SAs.
3099 	 */
3100 	buf = pfkey_dump_sadb(SADB_SATYPE_UNSPEC);
3101 	if (buf == NULL) {
3102 		plog(LLV_DEBUG, LOCATION, NULL,
3103 			"pfkey_dump_sadb returned nothing.\n");
3104 		return;
3105 	}
3106 
3107 	msg = (struct sadb_msg *)buf->v;
3108 	end = (struct sadb_msg *)(buf->v + buf->l);
3109 
3110 	while (msg < end) {
3111 		if ((msg->sadb_msg_len << 3) < sizeof(*msg))
3112 			break;
3113 		next = (struct sadb_msg *)((caddr_t)msg + (msg->sadb_msg_len << 3));
3114 		if (msg->sadb_msg_type != SADB_DUMP) {
3115 			msg = next;
3116 			continue;
3117 		}
3118 
3119 		if (pfkey_align(msg, mhp) || pfkey_check(mhp)) {
3120 			plog(LLV_ERROR, LOCATION, NULL,
3121 				"pfkey_check (%s)\n", ipsec_strerror());
3122 			msg = next;
3123 			continue;
3124 		}
3125 
3126 		sa = (struct sadb_sa *)(mhp[SADB_EXT_SA]);
3127 		if (!sa ||
3128 		    !mhp[SADB_EXT_ADDRESS_SRC] ||
3129 		    !mhp[SADB_EXT_ADDRESS_DST]) {
3130 			msg = next;
3131 			continue;
3132 		}
3133 		src = PFKEY_ADDR_SADDR(mhp[SADB_EXT_ADDRESS_SRC]);
3134 		dst = PFKEY_ADDR_SADDR(mhp[SADB_EXT_ADDRESS_DST]);
3135 
3136 		if (sa->sadb_sa_state != SADB_SASTATE_LARVAL &&
3137 		    sa->sadb_sa_state != SADB_SASTATE_MATURE &&
3138 		    sa->sadb_sa_state != SADB_SASTATE_DYING) {
3139 			msg = next;
3140 			continue;
3141 		}
3142 
3143 		/* check in/outbound SAs */
3144 		if ((CMPSADDR(iph1->local, src) || CMPSADDR(iph1->remote, dst)) &&
3145 			(CMPSADDR(iph1->local, dst) || CMPSADDR(iph1->remote, src))) {
3146 			msg = next;
3147 			continue;
3148 		}
3149 
3150 		proto_id = pfkey2ipsecdoi_proto(msg->sadb_msg_satype);
3151 		iph2 = getph2bysaidx(src, dst, proto_id, sa->sadb_sa_spi);
3152 
3153 		/* Check if there is another valid ISAKMP-SA */
3154 		if (new_iph1 != NULL) {
3155 
3156 			if (iph2 == NULL) {
3157 				/* No handler... still send a pfkey_delete message, but log this !*/
3158 				plog(LLV_INFO, LOCATION, NULL,
3159 					"Unknown IPsec-SA spi=%u, hmmmm?\n",
3160 					ntohl(sa->sadb_sa_spi));
3161 			}else{
3162 
3163 				/*
3164 				 * If we have a new ph1, do not purge IPsec-SAs binded
3165 				 *  to a different ISAKMP-SA
3166 				 */
3167 				if (iph2->ph1 != NULL && iph2->ph1 != iph1){
3168 					msg = next;
3169 					continue;
3170 				}
3171 
3172 				/* If the ph2handle is established, do not purge IPsec-SA */
3173 				if (iph2->status == PHASE2ST_ESTABLISHED ||
3174 					iph2->status == PHASE2ST_EXPIRED) {
3175 
3176 					plog(LLV_INFO, LOCATION, NULL,
3177 						 "keeping IPsec-SA spi=%u - found valid ISAKMP-SA spi=%s.\n",
3178 						 ntohl(sa->sadb_sa_spi),
3179 						 isakmp_pindex(&(new_iph1->index), new_iph1->msgid));
3180 					msg = next;
3181 					continue;
3182 				}
3183 			}
3184 		}
3185 
3186 
3187 		pfkey_send_delete(lcconf->sock_pfkey,
3188 				  msg->sadb_msg_satype,
3189 				  IPSEC_MODE_ANY,
3190 				  src, dst, sa->sadb_sa_spi);
3191 
3192 		/* delete a relative phase 2 handle. */
3193 		if (iph2 != NULL) {
3194 			delete_spd(iph2);
3195 			unbindph12(iph2);
3196 			remph2(iph2);
3197 			delph2(iph2);
3198 		}
3199 
3200 		plog(LLV_INFO, LOCATION, NULL,
3201 			 "purged IPsec-SA spi=%u.\n",
3202 			 ntohl(sa->sadb_sa_spi));
3203 
3204 		msg = next;
3205 	}
3206 
3207 	if (buf)
3208 		vfree(buf);
3209 
3210 	/* Mark the phase1 handler as EXPIRED */
3211 	plog(LLV_INFO, LOCATION, NULL,
3212 		 "purged ISAKMP-SA spi=%s.\n",
3213 		 isakmp_pindex(&(iph1->index), iph1->msgid));
3214 
3215 	if (iph1->sce)
3216 		SCHED_KILL(iph1->sce);
3217 
3218 	iph1->sce = sched_new(1, isakmp_ph1delete_stub, iph1);
3219 }
3220 
3221 void
3222 delete_spd(iph2)
3223 	struct ph2handle *iph2;
3224 {
3225 	if (iph2 == NULL)
3226 		return;
3227 
3228 	/* Delete the SPD entry if we generated it
3229 	 */
3230 	if (iph2->generated_spidx) {
3231 		struct policyindex spidx;
3232 		struct sockaddr_storage addr;
3233 		u_int8_t pref;
3234 		struct sockaddr *src = iph2->src;
3235 		struct sockaddr *dst = iph2->dst;
3236 		int error;
3237 		int idi2type = 0;/* switch whether copy IDs into id[src,dst]. */
3238 
3239 		plog(LLV_INFO, LOCATION, NULL,
3240 			 "generated policy, deleting it.\n");
3241 
3242 		memset(&spidx, 0, sizeof(spidx));
3243 		iph2->spidx_gen = (caddr_t )&spidx;
3244 
3245 		/* make inbound policy */
3246 		iph2->src = dst;
3247 		iph2->dst = src;
3248 		spidx.dir = IPSEC_DIR_INBOUND;
3249 		spidx.ul_proto = 0;
3250 
3251 		/*
3252 		 * Note: code from get_proposal_r
3253 		 */
3254 
3255 #define _XIDT(d) ((struct ipsecdoi_id_b *)(d)->v)->type
3256 
3257 		/*
3258 		 * make destination address in spidx from either ID payload
3259 		 * or phase 1 address into a address in spidx.
3260 		 */
3261 		if (iph2->id != NULL
3262 			&& (_XIDT(iph2->id) == IPSECDOI_ID_IPV4_ADDR
3263 			|| _XIDT(iph2->id) == IPSECDOI_ID_IPV6_ADDR
3264 			|| _XIDT(iph2->id) == IPSECDOI_ID_IPV4_ADDR_SUBNET
3265 			|| _XIDT(iph2->id) == IPSECDOI_ID_IPV6_ADDR_SUBNET)) {
3266 			/* get a destination address of a policy */
3267 			error = ipsecdoi_id2sockaddr(iph2->id,
3268 			    (struct sockaddr *)&spidx.dst,
3269 			    &spidx.prefd, &spidx.ul_proto);
3270 			if (error)
3271 				goto purge;
3272 
3273 #ifdef INET6
3274 			/*
3275 			 * get scopeid from the SA address.
3276 			 * note that the phase 1 source address is used as
3277 			 * a destination address to search for a inbound
3278 			 * policy entry because rcoon is responder.
3279 			 */
3280 			if (_XIDT(iph2->id) == IPSECDOI_ID_IPV6_ADDR) {
3281 				if ((error =
3282 				    setscopeid((struct sockaddr *)&spidx.dst,
3283 				   iph2->src)) != 0)
3284 					goto purge;
3285 			}
3286 #endif
3287 
3288 			if (_XIDT(iph2->id) == IPSECDOI_ID_IPV4_ADDR
3289 				|| _XIDT(iph2->id) == IPSECDOI_ID_IPV6_ADDR)
3290 				idi2type = _XIDT(iph2->id);
3291 
3292 		} else {
3293 
3294 			plog(LLV_DEBUG, LOCATION, NULL,
3295 				 "get a destination address of SP index "
3296 				 "from phase1 address "
3297 				 "due to no ID payloads found "
3298 				 "OR because ID type is not address.\n");
3299 
3300 			/*
3301 			 * copy the SOURCE address of IKE into the
3302 			 * DESTINATION address of the key to search the
3303 			 * SPD because the direction of policy is inbound.
3304 			 */
3305 			memcpy(&spidx.dst, iph2->src, sysdep_sa_len(iph2->src));
3306 			switch (spidx.dst.ss_family) {
3307 				case AF_INET:
3308 					spidx.prefd =
3309 					    sizeof(struct in_addr) << 3;
3310 					break;
3311 #ifdef INET6
3312 				case AF_INET6:
3313 					spidx.prefd =
3314 					    sizeof(struct in6_addr) << 3;
3315 					break;
3316 #endif
3317 				default:
3318 					spidx.prefd = 0;
3319 					break;
3320 			}
3321 		}
3322 
3323 		/* make source address in spidx */
3324 		if (iph2->id_p != NULL
3325 			&& (_XIDT(iph2->id_p) == IPSECDOI_ID_IPV4_ADDR
3326 			|| _XIDT(iph2->id_p) == IPSECDOI_ID_IPV6_ADDR
3327 			|| _XIDT(iph2->id_p) == IPSECDOI_ID_IPV4_ADDR_SUBNET
3328 			|| _XIDT(iph2->id_p) == IPSECDOI_ID_IPV6_ADDR_SUBNET)) {
3329 			/* get a source address of inbound SA */
3330 			error = ipsecdoi_id2sockaddr(iph2->id_p,
3331 			    (struct sockaddr *)&spidx.src,
3332 			    &spidx.prefs, &spidx.ul_proto);
3333 			if (error)
3334 				goto purge;
3335 
3336 #ifdef INET6
3337 			/*
3338 			 * get scopeid from the SA address.
3339 			 * for more detail, see above of this function.
3340 			 */
3341 			if (_XIDT(iph2->id_p) == IPSECDOI_ID_IPV6_ADDR) {
3342 				error =
3343 				    setscopeid((struct sockaddr *)&spidx.src,
3344 				    iph2->dst);
3345 				if (error)
3346 					goto purge;
3347 			}
3348 #endif
3349 
3350 			/* make id[src,dst] if both ID types are IP address and same */
3351 			if (_XIDT(iph2->id_p) == idi2type
3352 				&& spidx.dst.ss_family == spidx.src.ss_family) {
3353 				iph2->src_id =
3354 				    dupsaddr((struct sockaddr *)&spidx.dst);
3355 				iph2->dst_id =
3356 				    dupsaddr((struct sockaddr *)&spidx.src);
3357 			}
3358 
3359 		} else {
3360 			plog(LLV_DEBUG, LOCATION, NULL,
3361 				 "get a source address of SP index "
3362 				 "from phase1 address "
3363 				 "due to no ID payloads found "
3364 				 "OR because ID type is not address.\n");
3365 
3366 			/* see above comment. */
3367 			memcpy(&spidx.src, iph2->dst, sysdep_sa_len(iph2->dst));
3368 			switch (spidx.src.ss_family) {
3369 				case AF_INET:
3370 					spidx.prefs =
3371 					    sizeof(struct in_addr) << 3;
3372 					break;
3373 #ifdef INET6
3374 				case AF_INET6:
3375 					spidx.prefs =
3376 					    sizeof(struct in6_addr) << 3;
3377 					break;
3378 #endif
3379 				default:
3380 					spidx.prefs = 0;
3381 					break;
3382 			}
3383 		}
3384 
3385 #undef _XIDT
3386 
3387 		plog(LLV_DEBUG, LOCATION, NULL,
3388 			 "get a src address from ID payload "
3389 			 "%s prefixlen=%u ul_proto=%u\n",
3390 			 saddr2str((struct sockaddr *)&spidx.src),
3391 			 spidx.prefs, spidx.ul_proto);
3392 		plog(LLV_DEBUG, LOCATION, NULL,
3393 			 "get dst address from ID payload "
3394 			 "%s prefixlen=%u ul_proto=%u\n",
3395 			 saddr2str((struct sockaddr *)&spidx.dst),
3396 			 spidx.prefd, spidx.ul_proto);
3397 
3398 		/*
3399 		 * convert the ul_proto if it is 0
3400 		 * because 0 in ID payload means a wild card.
3401 		 */
3402 		if (spidx.ul_proto == 0)
3403 			spidx.ul_proto = IPSEC_ULPROTO_ANY;
3404 
3405 #undef _XIDT
3406 
3407 		/* End of code from get_proposal_r
3408 		 */
3409 
3410 		if (pk_sendspddelete(iph2) < 0) {
3411 			plog(LLV_ERROR, LOCATION, NULL,
3412 				 "pfkey spddelete(inbound) failed.\n");
3413 		}else{
3414 			plog(LLV_DEBUG, LOCATION, NULL,
3415 				 "pfkey spddelete(inbound) sent.\n");
3416 		}
3417 
3418 #ifdef HAVE_POLICY_FWD
3419 		/* make forward policy if required */
3420 		if (tunnel_mode_prop(iph2->approval)) {
3421 			spidx.dir = IPSEC_DIR_FWD;
3422 			if (pk_sendspddelete(iph2) < 0) {
3423 				plog(LLV_ERROR, LOCATION, NULL,
3424 					 "pfkey spddelete(forward) failed.\n");
3425 			}else{
3426 				plog(LLV_DEBUG, LOCATION, NULL,
3427 					 "pfkey spddelete(forward) sent.\n");
3428 			}
3429 		}
3430 #endif
3431 
3432 		/* make outbound policy */
3433 		iph2->src = src;
3434 		iph2->dst = dst;
3435 		spidx.dir = IPSEC_DIR_OUTBOUND;
3436 		addr = spidx.src;
3437 		spidx.src = spidx.dst;
3438 		spidx.dst = addr;
3439 		pref = spidx.prefs;
3440 		spidx.prefs = spidx.prefd;
3441 		spidx.prefd = pref;
3442 
3443 		if (pk_sendspddelete(iph2) < 0) {
3444 			plog(LLV_ERROR, LOCATION, NULL,
3445 				 "pfkey spddelete(outbound) failed.\n");
3446 		}else{
3447 			plog(LLV_DEBUG, LOCATION, NULL,
3448 				 "pfkey spddelete(outbound) sent.\n");
3449 		}
3450 purge:
3451 		iph2->spidx_gen=NULL;
3452 	}
3453 }
3454 
3455 #ifdef INET6
3456 u_int32_t
3457 setscopeid(sp_addr0, sa_addr0)
3458 	struct sockaddr *sp_addr0, *sa_addr0;
3459 {
3460 	struct sockaddr_in6 *sp_addr, *sa_addr;
3461 
3462 	sp_addr = (struct sockaddr_in6 *)sp_addr0;
3463 	sa_addr = (struct sockaddr_in6 *)sa_addr0;
3464 
3465 	if (!IN6_IS_ADDR_LINKLOCAL(&sp_addr->sin6_addr)
3466 	 && !IN6_IS_ADDR_SITELOCAL(&sp_addr->sin6_addr)
3467 	 && !IN6_IS_ADDR_MULTICAST(&sp_addr->sin6_addr))
3468 		return 0;
3469 
3470 	/* this check should not be here ? */
3471 	if (sa_addr->sin6_family != AF_INET6) {
3472 		plog(LLV_ERROR, LOCATION, NULL,
3473 			"can't get scope ID: family mismatch\n");
3474 		return -1;
3475 	}
3476 
3477 	if (!IN6_IS_ADDR_LINKLOCAL(&sa_addr->sin6_addr)) {
3478 		plog(LLV_ERROR, LOCATION, NULL,
3479 			"scope ID is not supported except of lladdr.\n");
3480 		return -1;
3481 	}
3482 
3483 	sp_addr->sin6_scope_id = sa_addr->sin6_scope_id;
3484 
3485 	return 0;
3486 }
3487 #endif
3488