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