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__)
    120 #include <netinet/udp.h>
    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(vchar_t *msg, struct sockaddr *remote,
   1118                   struct sockaddr *local, u_int8_t etype)
   1119 {
   1120 	struct isakmp *isakmp = (struct isakmp *)msg->v;
   1121 	struct remoteconf *rmconf;
   1122 	struct ph1handle *iph1;
   1123 	struct etypes *etypeok;
   1124 #ifdef ENABLE_STATS
   1125 	struct timeval start, end;
   1126 #endif
   1127 
   1128 	/* look for my configuration */
   1129 	rmconf = getrmconf(remote);
   1130 	if (rmconf == NULL) {
   1131 		plog(LLV_ERROR, LOCATION, remote,
   1132 			"couldn't find "
   1133 			"configuration.\n");
   1134 		return -1;
   1135 	}
   1136 
   1137 	/* check to be acceptable exchange type */
   1138 	etypeok = check_etypeok(rmconf, etype);
   1139 	if (etypeok == NULL) {
   1140 		plog(LLV_ERROR, LOCATION, remote,
   1141 			"not acceptable %s mode\n", s_isakmp_etype(etype));
   1142 		return -1;
   1143 	}
   1144 
   1145 	/* get new entry to isakmp status table. */
   1146 	iph1 = newph1();
   1147 	if (iph1 == NULL)
   1148 		return -1;
   1149 
   1150 	memcpy(&iph1->index.i_ck, &isakmp->i_ck, sizeof(iph1->index.i_ck));
   1151 	iph1->status = PHASE1ST_START;
   1152 	iph1->rmconf = rmconf;
   1153 	iph1->flags = 0;
   1154 	iph1->side = RESPONDER;
   1155 	iph1->etype = etypeok->type;
   1156 	iph1->version = isakmp->v;
   1157 	iph1->msgid = 0;
   1158 #ifdef HAVE_GSSAPI
   1159 	iph1->gssapi_state = NULL;
   1160 #endif
   1161 #ifdef ENABLE_HYBRID
   1162 	if ((iph1->mode_cfg = isakmp_cfg_mkstate()) == NULL) {
   1163 		delph1(iph1);
   1164 		return -1;
   1165 	}
   1166 #endif
   1167 #ifdef ENABLE_FRAG
   1168 	iph1->frag = 0;
   1169 	iph1->frag_chain = NULL;
   1170 #endif
   1171 	iph1->approval = NULL;
   1172 
   1173 #ifdef ENABLE_NATT
   1174 	/* RFC3947 says that we MUST accept new phases1 on NAT-T floated port.
   1175 	 * We have to setup this flag now to correctly generate the first reply.
   1176 	 * Don't know if a better check could be done for that ?
   1177 	 */
   1178 	if(extract_port(local) == lcconf->port_isakmp_natt)
   1179 		iph1->natt_flags |= (NAT_PORTS_CHANGED);
   1180 #endif
   1181 
   1182 	/* copy remote address */
   1183 	if (copy_ph1addresses(iph1, rmconf, remote, local) < 0) {
   1184 		delph1(iph1);
   1185 		return -1;
   1186 	}
   1187 	(void)insph1(iph1);
   1188 
   1189 	plog(LLV_DEBUG, LOCATION, NULL, "===\n");
   1190     {
   1191 	char *a;
   1192 
   1193 	a = racoon_strdup(saddr2str(iph1->local));
   1194 	STRDUP_FATAL(a);
   1195 
   1196 	plog(LLV_INFO, LOCATION, NULL,
   1197 		"respond new phase 1 negotiation: %s<=>%s\n",
   1198 		a, saddr2str(iph1->remote));
   1199 	racoon_free(a);
   1200     }
   1201 	plog(LLV_INFO, LOCATION, NULL,
   1202 		"begin %s mode.\n", s_isakmp_etype(etype));
   1203 
   1204 #ifdef ENABLE_STATS
   1205 	gettimeofday(&iph1->start, NULL);
   1206 	gettimeofday(&start, NULL);
   1207 #endif
   1208 
   1209 #ifndef ENABLE_FRAG
   1210 
   1211 	/* start exchange */
   1212 	if ((ph1exchange[etypesw1(iph1->etype)]
   1213 	                [iph1->side]
   1214 	                [iph1->status])(iph1, msg) < 0
   1215 	 || (ph1exchange[etypesw1(iph1->etype)]
   1216 			[iph1->side]
   1217 			[iph1->status])(iph1, msg) < 0) {
   1218 		plog(LLV_ERROR, LOCATION, remote,
   1219 			"failed to process packet.\n");
   1220 		remph1(iph1);
   1221 		delph1(iph1);
   1222 		return -1;
   1223 	}
   1224 
   1225 #ifdef ENABLE_STATS
   1226 	gettimeofday(&end, NULL);
   1227 	syslog(LOG_NOTICE, "%s(%s): %8.6f",
   1228 		"phase1",
   1229 		s_isakmp_state(iph1->etype, iph1->side, iph1->status),
   1230 		timedelta(&start, &end));
   1231 #endif
   1232 
   1233 	return 0;
   1234 
   1235 #else /* ENABLE_FRAG */
   1236 
   1237 	/* now that we have a phase1 handle, feed back into our
   1238 	 * main receive function to catch fragmented packets
   1239 	 */
   1240 
   1241 	return isakmp_main(msg, remote, local);
   1242 
   1243 #endif /* ENABLE_FRAG */
   1244 
   1245 }
   1246 
   1247 /* new negotiation of phase 2 for initiator */
   1248 static int
   1249 isakmp_ph2begin_i(iph1, iph2)
   1250 	struct ph1handle *iph1;
   1251 	struct ph2handle *iph2;
   1252 {
   1253 #ifdef ENABLE_HYBRID
   1254 	if (xauth_check(iph1) != 0) {
   1255 		plog(LLV_ERROR, LOCATION, NULL,
   1256 		    "Attempt to start phase 2 whereas Xauth failed\n");
   1257 		return -1;
   1258 	}
   1259 #endif
   1260 
   1261 	/* found ISAKMP-SA. */
   1262 	plog(LLV_DEBUG, LOCATION, NULL, "===\n");
   1263 	plog(LLV_DEBUG, LOCATION, NULL, "begin QUICK mode.\n");
   1264     {
   1265 	char *a;
   1266 	a = racoon_strdup(saddr2str(iph2->src));
   1267 	STRDUP_FATAL(a);
   1268 
   1269 	plog(LLV_INFO, LOCATION, NULL,
   1270 		"initiate new phase 2 negotiation: %s<=>%s\n",
   1271 		a, saddr2str(iph2->dst));
   1272 	racoon_free(a);
   1273     }
   1274 
   1275 #ifdef ENABLE_STATS
   1276 	gettimeofday(&iph2->start, NULL);
   1277 #endif
   1278 	/* found isakmp-sa */
   1279 	bindph12(iph1, iph2);
   1280 	iph2->status = PHASE2ST_STATUS2;
   1281 
   1282 	if ((ph2exchange[etypesw2(ISAKMP_ETYPE_QUICK)]
   1283 			 [iph2->side]
   1284 			 [iph2->status])(iph2, NULL) < 0) {
   1285 		unbindph12(iph2);
   1286 		/* release ipsecsa handler due to internal error. */
   1287 		remph2(iph2);
   1288 		return -1;
   1289 	}
   1290 	return 0;
   1291 }
   1292 
   1293 /* new negotiation of phase 2 for responder */
   1294 static int
   1295 isakmp_ph2begin_r(iph1, msg)
   1296 	struct ph1handle *iph1;
   1297 	vchar_t *msg;
   1298 {
   1299 	struct isakmp *isakmp = (struct isakmp *)msg->v;
   1300 	struct ph2handle *iph2 = 0;
   1301 	int error;
   1302 #ifdef ENABLE_STATS
   1303 	struct timeval start, end;
   1304 #endif
   1305 #ifdef ENABLE_HYBRID
   1306 	if (xauth_check(iph1) != 0) {
   1307 		plog(LLV_ERROR, LOCATION, NULL,
   1308 		    "Attempt to start phase 2 whereas Xauth failed\n");
   1309 		return -1;
   1310 	}
   1311 #endif
   1312 
   1313 	iph2 = newph2();
   1314 	if (iph2 == NULL) {
   1315 		plog(LLV_ERROR, LOCATION, NULL,
   1316 			"failed to allocate phase2 entry.\n");
   1317 		return -1;
   1318 	}
   1319 
   1320 	iph2->ph1 = iph1;
   1321 	iph2->side = RESPONDER;
   1322 	iph2->status = PHASE2ST_START;
   1323 	iph2->flags = isakmp->flags;
   1324 	iph2->msgid = isakmp->msgid;
   1325 	iph2->seq = pk_getseq();
   1326 	iph2->ivm = oakley_newiv2(iph1, iph2->msgid);
   1327 	if (iph2->ivm == NULL) {
   1328 		delph2(iph2);
   1329 		return -1;
   1330 	}
   1331 	iph2->dst = dupsaddr(iph1->remote);	/* XXX should be considered */
   1332 	if (iph2->dst == NULL) {
   1333 		delph2(iph2);
   1334 		return -1;
   1335 	}
   1336 	iph2->src = dupsaddr(iph1->local);	/* XXX should be considered */
   1337 	if (iph2->src == NULL) {
   1338 		delph2(iph2);
   1339 		return -1;
   1340 	}
   1341 #if (!defined(ENABLE_NATT)) || (defined(BROKEN_NATT))
   1342 	if (set_port(iph2->dst, 0) == NULL ||
   1343 	    set_port(iph2->src, 0) == NULL) {
   1344 		plog(LLV_ERROR, LOCATION, NULL,
   1345 		     "invalid family: %d\n", iph2->dst->sa_family);
   1346 		delph2(iph2);
   1347 		return -1;
   1348 	}
   1349 #endif
   1350 
   1351 	/* add new entry to isakmp status table */
   1352 	insph2(iph2);
   1353 	bindph12(iph1, iph2);
   1354 
   1355 	plog(LLV_DEBUG, LOCATION, NULL, "===\n");
   1356     {
   1357 	char *a;
   1358 
   1359 	a = racoon_strdup(saddr2str(iph2->src));
   1360 	STRDUP_FATAL(a);
   1361 
   1362 	plog(LLV_INFO, LOCATION, NULL,
   1363 		"respond new phase 2 negotiation: %s<=>%s\n",
   1364 		a, saddr2str(iph2->dst));
   1365 	racoon_free(a);
   1366     }
   1367 
   1368 #ifdef ENABLE_STATS
   1369 	gettimeofday(&start, NULL);
   1370 #endif
   1371 
   1372 	error = (ph2exchange[etypesw2(ISAKMP_ETYPE_QUICK)]
   1373 	                   [iph2->side]
   1374 	                   [iph2->status])(iph2, msg);
   1375 	if (error != 0) {
   1376 		plog(LLV_ERROR, LOCATION, iph1->remote,
   1377 			"failed to pre-process packet.\n");
   1378 		if (error != ISAKMP_INTERNAL_ERROR)
   1379 			isakmp_info_send_n1(iph2->ph1, error, NULL);
   1380 		/*
   1381 		 * release handler because it's wrong that ph2handle is kept
   1382 		 * after failed to check message for responder's.
   1383 		 */
   1384 		unbindph12(iph2);
   1385 		remph2(iph2);
   1386 		delph2(iph2);
   1387 		return -1;
   1388 	}
   1389 
   1390 	/* send */
   1391 	plog(LLV_DEBUG, LOCATION, NULL, "===\n");
   1392 	if ((ph2exchange[etypesw2(isakmp->etype)]
   1393 			[iph2->side]
   1394 			[iph2->status])(iph2, msg) < 0) {
   1395 		plog(LLV_ERROR, LOCATION, iph2->ph1->remote,
   1396 			"failed to process packet.\n");
   1397 		/* don't release handler */
   1398 		return -1;
   1399 	}
   1400 #ifdef ENABLE_STATS
   1401 	gettimeofday(&end, NULL);
   1402 	syslog(LOG_NOTICE, "%s(%s): %8.6f",
   1403 		"phase2",
   1404 		s_isakmp_state(ISAKMP_ETYPE_QUICK, iph2->side, iph2->status),
   1405 		timedelta(&start, &end));
   1406 #endif
   1407 
   1408 	return 0;
   1409 }
   1410 
   1411 /*
   1412  * parse ISAKMP payloads, without ISAKMP base header.
   1413  */
   1414 vchar_t *
   1415 isakmp_parsewoh(np0, gen, len)
   1416 	int np0;
   1417 	struct isakmp_gen *gen;
   1418 	int len;
   1419 {
   1420 	u_char np = np0 & 0xff;
   1421 	int tlen, plen;
   1422 	vchar_t *result;
   1423 	struct isakmp_parse_t *p, *ep;
   1424 
   1425 	plog(LLV_DEBUG, LOCATION, NULL, "begin.\n");
   1426 
   1427 	/*
   1428 	 * 5 is a magic number, but any value larger than 2 should be fine
   1429 	 * as we do vrealloc() in the following loop.
   1430 	 */
   1431 	result = vmalloc(sizeof(struct isakmp_parse_t) * 5);
   1432 	if (result == NULL) {
   1433 		plog(LLV_ERROR, LOCATION, NULL,
   1434 			"failed to get buffer.\n");
   1435 		return NULL;
   1436 	}
   1437 	p = (struct isakmp_parse_t *)result->v;
   1438 	ep = (struct isakmp_parse_t *)(result->v + result->l - sizeof(*ep));
   1439 
   1440 	tlen = len;
   1441 
   1442 	/* parse through general headers */
   1443 	while (0 < tlen && np != ISAKMP_NPTYPE_NONE) {
   1444 		if (tlen <= sizeof(struct isakmp_gen)) {
   1445 			/* don't send information, see isakmp_ident_r1() */
   1446 			plog(LLV_ERROR, LOCATION, NULL,
   1447 				"invalid length of payload\n");
   1448 			vfree(result);
   1449 			return NULL;
   1450 		}
   1451 
   1452 		plog(LLV_DEBUG, LOCATION, NULL,
   1453 			"seen nptype=%u(%s)\n", np, s_isakmp_nptype(np));
   1454 
   1455 		p->type = np;
   1456 		p->len = ntohs(gen->len);
   1457 		if (p->len < sizeof(struct isakmp_gen) || p->len > tlen) {
   1458 			plog(LLV_DEBUG, LOCATION, NULL,
   1459 				"invalid length of payload\n");
   1460 			vfree(result);
   1461 			return NULL;
   1462 		}
   1463 		p->ptr = gen;
   1464 		p++;
   1465 		if (ep <= p) {
   1466 			int off;
   1467 
   1468 			off = p - (struct isakmp_parse_t *)result->v;
   1469 			result = vrealloc(result, result->l * 2);
   1470 			if (result == NULL) {
   1471 				plog(LLV_DEBUG, LOCATION, NULL,
   1472 					"failed to realloc buffer.\n");
   1473 				vfree(result);
   1474 				return NULL;
   1475 			}
   1476 			ep = (struct isakmp_parse_t *)
   1477 				(result->v + result->l - sizeof(*ep));
   1478 			p = (struct isakmp_parse_t *)result->v;
   1479 			p += off;
   1480 		}
   1481 
   1482 		np = gen->np;
   1483 		plen = ntohs(gen->len);
   1484 		gen = (struct isakmp_gen *)((caddr_t)gen + plen);
   1485 		tlen -= plen;
   1486 	}
   1487 	p->type = ISAKMP_NPTYPE_NONE;
   1488 	p->len = 0;
   1489 	p->ptr = NULL;
   1490 
   1491 	plog(LLV_DEBUG, LOCATION, NULL, "succeed.\n");
   1492 
   1493 	return result;
   1494 }
   1495 
   1496 /*
   1497  * parse ISAKMP payloads, including ISAKMP base header.
   1498  */
   1499 vchar_t *
   1500 isakmp_parse(buf)
   1501 	vchar_t *buf;
   1502 {
   1503 	struct isakmp *isakmp = (struct isakmp *)buf->v;
   1504 	struct isakmp_gen *gen;
   1505 	int tlen;
   1506 	vchar_t *result;
   1507 	u_char np;
   1508 
   1509 	np = isakmp->np;
   1510 	gen = (struct isakmp_gen *)(buf->v + sizeof(*isakmp));
   1511 	tlen = buf->l - sizeof(struct isakmp);
   1512 	result = isakmp_parsewoh(np, gen, tlen);
   1513 
   1514 	return result;
   1515 }
   1516 
   1517 /* %%% */
   1518 int
   1519 isakmp_init()
   1520 {
   1521 	/* initialize a isakmp status table */
   1522 	initph1tree();
   1523 	initph2tree();
   1524 	initctdtree();
   1525 	init_recvdpkt();
   1526 
   1527 	if (isakmp_open() < 0)
   1528 		goto err;
   1529 
   1530 	return(0);
   1531 
   1532 err:
   1533 	isakmp_close();
   1534 	return(-1);
   1535 }
   1536 
   1537 /*
   1538  * make strings containing i_cookie + r_cookie + msgid
   1539  */
   1540 const char *
   1541 isakmp_pindex(index, msgid)
   1542 	const isakmp_index *index;
   1543 	const u_int32_t msgid;
   1544 {
   1545 	static char buf[64];
   1546 	const u_char *p;
   1547 	int i, j;
   1548 
   1549 	memset(buf, 0, sizeof(buf));
   1550 
   1551 	/* copy index */
   1552 	p = (const u_char *)index;
   1553 	for (j = 0, i = 0; i < sizeof(isakmp_index); i++) {
   1554 		snprintf((char *)&buf[j], sizeof(buf) - j, "%02x", p[i]);
   1555 		j += 2;
   1556 		switch (i) {
   1557 		case 7:
   1558 			buf[j++] = ':';
   1559 		}
   1560 	}
   1561 
   1562 	if (msgid == 0)
   1563 		return buf;
   1564 
   1565 	/* copy msgid */
   1566 	snprintf((char *)&buf[j], sizeof(buf) - j, ":%08x", ntohs(msgid));
   1567 
   1568 	return buf;
   1569 }
   1570 
   1571 /* open ISAKMP sockets. */
   1572 int
   1573 isakmp_open()
   1574 {
   1575 	const int yes = 1;
   1576 	int ifnum = 0, encap_ifnum = 0;
   1577 #ifdef INET6
   1578 	int pktinfo;
   1579 #endif
   1580 	struct myaddrs *p;
   1581 
   1582 	for (p = lcconf->myaddrs; p; p = p->next) {
   1583 		if (!p->addr)
   1584 			continue;
   1585 
   1586 		/* warn if wildcard address - should we forbid this? */
   1587 		switch (p->addr->sa_family) {
   1588 		case AF_INET:
   1589 			if (((struct sockaddr_in *)p->addr)->sin_addr.s_addr == 0)
   1590 				plog(LLV_WARNING, LOCATION, NULL,
   1591 					"listening to wildcard address,"
   1592 					"broadcast IKE packet may kill you\n");
   1593 			break;
   1594 #ifdef INET6
   1595 		case AF_INET6:
   1596 			if (IN6_IS_ADDR_UNSPECIFIED(&((struct sockaddr_in6 *)p->addr)->sin6_addr))
   1597 				plog(LLV_WARNING, LOCATION, NULL,
   1598 					"listening to wildcard address, "
   1599 					"broadcast IKE packet may kill you\n");
   1600 			break;
   1601 #endif
   1602 		default:
   1603 			plog(LLV_ERROR, LOCATION, NULL,
   1604 				"unsupported address family %d\n",
   1605 				lcconf->default_af);
   1606 			goto err_and_next;
   1607 		}
   1608 
   1609 #ifdef INET6
   1610 		if (p->addr->sa_family == AF_INET6 &&
   1611 		    IN6_IS_ADDR_MULTICAST(&((struct sockaddr_in6 *)
   1612 					    p->addr)->sin6_addr))
   1613 		{
   1614 			plog(LLV_DEBUG, LOCATION, NULL,
   1615 				"Ignoring multicast address %s\n",
   1616 				saddr2str(p->addr));
   1617 				racoon_free(p->addr);
   1618 				p->addr = NULL;
   1619 			continue;
   1620 		}
   1621 #endif
   1622 
   1623 		if ((p->sock = socket(p->addr->sa_family, SOCK_DGRAM, 0)) < 0) {
   1624 			plog(LLV_ERROR, LOCATION, NULL,
   1625 				"socket (%s)\n", strerror(errno));
   1626 			goto err_and_next;
   1627 		}
   1628 
   1629 		if (fcntl(p->sock, F_SETFL, O_NONBLOCK) == -1)
   1630 			plog(LLV_WARNING, LOCATION, NULL,
   1631 				"failed to put socket in non-blocking mode\n");
   1632 
   1633 		/* receive my interface address on inbound packets. */
   1634 		switch (p->addr->sa_family) {
   1635 		case AF_INET:
   1636 			if (setsockopt(p->sock, IPPROTO_IP,
   1637 #ifdef __linux__
   1638 				       IP_PKTINFO,
   1639 #else
   1640 				       IP_RECVDSTADDR,
   1641 #endif
   1642 					(const void *)&yes, sizeof(yes)) < 0) {
   1643 				plog(LLV_ERROR, LOCATION, NULL,
   1644 					"setsockopt IP_RECVDSTADDR (%s)\n",
   1645 					strerror(errno));
   1646 				goto err_and_next;
   1647 			}
   1648 			break;
   1649 #ifdef INET6
   1650 		case AF_INET6:
   1651 #ifdef INET6_ADVAPI
   1652 #ifdef IPV6_RECVPKTINFO
   1653 			pktinfo = IPV6_RECVPKTINFO;
   1654 #else  /* old adv. API */
   1655 			pktinfo = IPV6_PKTINFO;
   1656 #endif /* IPV6_RECVPKTINFO */
   1657 #else
   1658 			pktinfo = IPV6_RECVDSTADDR;
   1659 #endif
   1660 			if (setsockopt(p->sock, IPPROTO_IPV6, pktinfo,
   1661 					(const void *)&yes, sizeof(yes)) < 0)
   1662 			{
   1663 				plog(LLV_ERROR, LOCATION, NULL,
   1664 					"setsockopt IPV6_RECVDSTADDR (%d):%s\n",
   1665 					pktinfo, strerror(errno));
   1666 				goto err_and_next;
   1667 			}
   1668 			break;
   1669 #endif
   1670 		}
   1671 
   1672 #ifdef IPV6_USE_MIN_MTU
   1673 		if (p->addr->sa_family == AF_INET6 &&
   1674 		    setsockopt(p->sock, IPPROTO_IPV6, IPV6_USE_MIN_MTU,
   1675 		    (void *)&yes, sizeof(yes)) < 0) {
   1676 			plog(LLV_ERROR, LOCATION, NULL,
   1677 			    "setsockopt IPV6_USE_MIN_MTU (%s)\n",
   1678 			    strerror(errno));
   1679 			return -1;
   1680 		}
   1681 #endif
   1682 
   1683 		if (setsockopt_bypass(p->sock, p->addr->sa_family) < 0)
   1684 			goto err_and_next;
   1685 
   1686 		if (bind(p->sock, p->addr, sysdep_sa_len(p->addr)) < 0) {
   1687 			plog(LLV_ERROR, LOCATION, p->addr,
   1688 				"failed to bind to address %s (%s).\n",
   1689 				saddr2str(p->addr), strerror(errno));
   1690 			close(p->sock);
   1691 			goto err_and_next;
   1692 		}
   1693 
   1694 		ifnum++;
   1695 
   1696 		plog(LLV_INFO, LOCATION, NULL,
   1697 			"%s used as isakmp port (fd=%d)\n",
   1698 			saddr2str(p->addr), p->sock);
   1699 
   1700 #ifdef ENABLE_NATT
   1701 		if (p->addr->sa_family == AF_INET) {
   1702 			int option = -1;
   1703 
   1704 
   1705 			if(p->udp_encap)
   1706 				option = UDP_ENCAP_ESPINUDP;
   1707 #if defined(ENABLE_NATT_00) || defined(ENABLE_NATT_01)
   1708 			else
   1709 				option = UDP_ENCAP_ESPINUDP_NON_IKE;
   1710 #endif
   1711 			if(option != -1){
   1712 				if (setsockopt (p->sock, SOL_UDP,
   1713 				    UDP_ENCAP, &option, sizeof (option)) < 0) {
   1714 					plog(LLV_WARNING, LOCATION, NULL,
   1715 					    "setsockopt(%s): UDP_ENCAP %s\n",
   1716 					    option == UDP_ENCAP_ESPINUDP ? "UDP_ENCAP_ESPINUDP" : "UDP_ENCAP_ESPINUDP_NON_IKE",
   1717 						 strerror(errno));
   1718 					goto skip_encap;
   1719 				}
   1720 				else {
   1721 					plog(LLV_INFO, LOCATION, NULL,
   1722 						 "%s used for NAT-T\n",
   1723 						 saddr2str(p->addr));
   1724 					encap_ifnum++;
   1725 				}
   1726 			}
   1727 		}
   1728 skip_encap:
   1729 #endif
   1730 		continue;
   1731 
   1732 	err_and_next:
   1733 		racoon_free(p->addr);
   1734 		p->addr = NULL;
   1735 		if (! lcconf->autograbaddr && lcconf->strict_address)
   1736 			return -1;
   1737 		continue;
   1738 	}
   1739 
   1740 	if (!ifnum) {
   1741 		plog(LLV_ERROR, LOCATION, NULL,
   1742 			"no address could be bound.\n");
   1743 		return -1;
   1744 	}
   1745 
   1746 #ifdef ENABLE_NATT
   1747 	if (natt_enabled_in_rmconf() && !encap_ifnum) {
   1748 		plog(LLV_WARNING, LOCATION, NULL,
   1749 			"NAT-T is enabled in at least one remote{} section,\n");
   1750 		plog(LLV_WARNING, LOCATION, NULL,
   1751 			"but no 'isakmp_natt' address was specified!\n");
   1752 	}
   1753 #endif
   1754 
   1755 	return 0;
   1756 }
   1757 
   1758 void
   1759 isakmp_close()
   1760 {
   1761 #ifndef ANDROID_PATCHED
   1762 	struct myaddrs *p, *next;
   1763 
   1764 	for (p = lcconf->myaddrs; p; p = next) {
   1765 		next = p->next;
   1766 
   1767 		if (!p->addr) {
   1768 			racoon_free(p);
   1769 			continue;
   1770 		}
   1771 		close(p->sock);
   1772 		racoon_free(p->addr);
   1773 		racoon_free(p);
   1774 	}
   1775 
   1776 	lcconf->myaddrs = NULL;
   1777 #endif
   1778 }
   1779 
   1780 int
   1781 isakmp_send(iph1, sbuf)
   1782 	struct ph1handle *iph1;
   1783 	vchar_t *sbuf;
   1784 {
   1785 	int len = 0;
   1786 	int s;
   1787 	vchar_t *vbuf = NULL, swap;
   1788 
   1789 #ifdef ENABLE_NATT
   1790 	size_t extralen = NON_ESP_MARKER_USE(iph1) ? NON_ESP_MARKER_LEN : 0;
   1791 
   1792 	/* Check if NON_ESP_MARKER_LEN is already there (happens when resending packets)
   1793 	 */
   1794 	if(extralen == NON_ESP_MARKER_LEN &&
   1795 	   *(u_int32_t *)sbuf->v == 0)
   1796 		extralen = 0;
   1797 
   1798 #ifdef ENABLE_FRAG
   1799 	/*
   1800 	 * Do not add the non ESP marker for a packet that will
   1801 	 * be fragmented. The non ESP marker should appear in
   1802 	 * all fragment's packets, but not in the fragmented packet
   1803 	 */
   1804 	if (iph1->frag && sbuf->l > ISAKMP_FRAG_MAXLEN)
   1805 		extralen = 0;
   1806 #endif
   1807 	if (extralen)
   1808 		plog (LLV_DEBUG, LOCATION, NULL, "Adding NON-ESP marker\n");
   1809 
   1810 	/* If NAT-T port floating is in use, 4 zero bytes (non-ESP marker)
   1811 	   must added just before the packet itself. For this we must
   1812 	   allocate a new buffer and release it at the end. */
   1813 	if (extralen) {
   1814 		if ((vbuf = vmalloc (sbuf->l + extralen)) == NULL) {
   1815 			plog(LLV_ERROR, LOCATION, NULL,
   1816 			    "vbuf allocation failed\n");
   1817 			return -1;
   1818 		}
   1819 		*(u_int32_t *)vbuf->v = 0;
   1820 		memcpy (vbuf->v + extralen, sbuf->v, sbuf->l);
   1821 		/* ensures that the modified buffer will be sent back to the caller, so
   1822 		 * add_recvdpkt() will add the correct buffer
   1823 		 */
   1824 		swap = *sbuf;
   1825 		*sbuf = *vbuf;
   1826 		*vbuf = swap;
   1827 		vfree(vbuf);
   1828 	}
   1829 #endif
   1830 
   1831 	/* select the socket to be sent */
   1832 	s = getsockmyaddr(iph1->local);
   1833 	if (s == -1){
   1834 		return -1;
   1835 	}
   1836 
   1837 	plog (LLV_DEBUG, LOCATION, NULL, "%zu bytes %s\n", sbuf->l,
   1838 	      saddr2str_fromto("from %s to %s", iph1->local, iph1->remote));
   1839 
   1840 #ifdef ENABLE_FRAG
   1841 	if (iph1->frag && sbuf->l > ISAKMP_FRAG_MAXLEN) {
   1842 		if (isakmp_sendfrags(iph1, sbuf) == -1) {
   1843 			plog(LLV_ERROR, LOCATION, NULL,
   1844 			    "isakmp_sendfrags failed\n");
   1845 			return -1;
   1846 		}
   1847 	} else
   1848 #endif
   1849 	{
   1850 		len = sendfromto(s, sbuf->v, sbuf->l,
   1851 		    iph1->local, iph1->remote, lcconf->count_persend);
   1852 
   1853 		if (len == -1) {
   1854 			plog(LLV_ERROR, LOCATION, NULL, "sendfromto failed\n");
   1855 			return -1;
   1856 		}
   1857 	}
   1858 
   1859 	return 0;
   1860 }
   1861 
   1862 /* called from scheduler */
   1863 void
   1864 isakmp_ph1resend_stub(p)
   1865 	void *p;
   1866 {
   1867 	struct ph1handle *iph1;
   1868 
   1869 	iph1=(struct ph1handle *)p;
   1870 	if(isakmp_ph1resend(iph1) < 0){
   1871 		if(iph1->scr != NULL){
   1872 			/* Should not happen...
   1873 			 */
   1874 			sched_kill(iph1->scr);
   1875 			iph1->scr=NULL;
   1876 		}
   1877 
   1878 		remph1(iph1);
   1879 		delph1(iph1);
   1880 	}
   1881 }
   1882 
   1883 int
   1884 isakmp_ph1resend(iph1)
   1885 	struct ph1handle *iph1;
   1886 {
   1887 	/* Note: NEVER do the rem/del here, it will be done by the caller or by the _stub function
   1888 	 */
   1889 	if (iph1->retry_counter <= 0) {
   1890 		plog(LLV_ERROR, LOCATION, NULL,
   1891 			"phase1 negotiation failed due to time up. %s\n",
   1892 			isakmp_pindex(&iph1->index, iph1->msgid));
   1893 		EVT_PUSH(iph1->local, iph1->remote,
   1894 		    EVTT_PEER_NO_RESPONSE, NULL);
   1895 
   1896 		return -1;
   1897 	}
   1898 
   1899 	if (isakmp_send(iph1, iph1->sendbuf) < 0){
   1900 		plog(LLV_ERROR, LOCATION, NULL,
   1901 			 "phase1 negotiation failed due to send error. %s\n",
   1902 			 isakmp_pindex(&iph1->index, iph1->msgid));
   1903 		EVT_PUSH(iph1->local, iph1->remote,
   1904 				 EVTT_PEER_NO_RESPONSE, NULL);
   1905 		return -1;
   1906 	}
   1907 
   1908 	plog(LLV_DEBUG, LOCATION, NULL,
   1909 		"resend phase1 packet %s\n",
   1910 		isakmp_pindex(&iph1->index, iph1->msgid));
   1911 
   1912 	iph1->retry_counter--;
   1913 
   1914 	iph1->scr = sched_new(iph1->rmconf->retry_interval,
   1915 		isakmp_ph1resend_stub, iph1);
   1916 
   1917 	return 0;
   1918 }
   1919 
   1920 /* called from scheduler */
   1921 void
   1922 isakmp_ph2resend_stub(p)
   1923 	void *p;
   1924 {
   1925 	struct ph2handle *iph2;
   1926 
   1927 	iph2=(struct ph2handle *)p;
   1928 
   1929 	if(isakmp_ph2resend(iph2) < 0){
   1930 		unbindph12(iph2);
   1931 		remph2(iph2);
   1932 		delph2(iph2);
   1933 	}
   1934 }
   1935 
   1936 int
   1937 isakmp_ph2resend(iph2)
   1938 	struct ph2handle *iph2;
   1939 {
   1940 	/* Note: NEVER do the unbind/rem/del here, it will be done by the caller or by the _stub function
   1941 	 */
   1942 	if (iph2->ph1->status == PHASE1ST_EXPIRED){
   1943 		plog(LLV_ERROR, LOCATION, NULL,
   1944 			"phase2 negotiation failed due to phase1 expired. %s\n",
   1945 				isakmp_pindex(&iph2->ph1->index, iph2->msgid));
   1946 		return -1;
   1947 	}
   1948 
   1949 	if (iph2->retry_counter <= 0) {
   1950 		plog(LLV_ERROR, LOCATION, NULL,
   1951 			"phase2 negotiation failed due to time up. %s\n",
   1952 				isakmp_pindex(&iph2->ph1->index, iph2->msgid));
   1953 		EVT_PUSH(iph2->src, iph2->dst, EVTT_PEER_NO_RESPONSE, NULL);
   1954 		unbindph12(iph2);
   1955 		return -1;
   1956 	}
   1957 
   1958 	if (isakmp_send(iph2->ph1, iph2->sendbuf) < 0){
   1959 		plog(LLV_ERROR, LOCATION, NULL,
   1960 			"phase2 negotiation failed due to send error. %s\n",
   1961 				isakmp_pindex(&iph2->ph1->index, iph2->msgid));
   1962 		EVT_PUSH(iph2->src, iph2->dst, EVTT_PEER_NO_RESPONSE, NULL);
   1963 
   1964 		return -1;
   1965 	}
   1966 
   1967 	plog(LLV_DEBUG, LOCATION, NULL,
   1968 		"resend phase2 packet %s\n",
   1969 		isakmp_pindex(&iph2->ph1->index, iph2->msgid));
   1970 
   1971 	iph2->retry_counter--;
   1972 
   1973 	iph2->scr = sched_new(iph2->ph1->rmconf->retry_interval,
   1974 		isakmp_ph2resend_stub, iph2);
   1975 
   1976 	return 0;
   1977 }
   1978 
   1979 /* called from scheduler */
   1980 void
   1981 isakmp_ph1expire_stub(p)
   1982 	void *p;
   1983 {
   1984 
   1985 	isakmp_ph1expire((struct ph1handle *)p);
   1986 }
   1987 
   1988 void
   1989 isakmp_ph1expire(iph1)
   1990 	struct ph1handle *iph1;
   1991 {
   1992 	char *src, *dst;
   1993 
   1994 	SCHED_KILL(iph1->sce);
   1995 
   1996 	if(iph1->status != PHASE1ST_EXPIRED){
   1997 		src = racoon_strdup(saddr2str(iph1->local));
   1998 		dst = racoon_strdup(saddr2str(iph1->remote));
   1999 		STRDUP_FATAL(src);
   2000 		STRDUP_FATAL(dst);
   2001 
   2002 		plog(LLV_INFO, LOCATION, NULL,
   2003 			 "ISAKMP-SA expired %s-%s spi:%s\n",
   2004 			 src, dst,
   2005 			 isakmp_pindex(&iph1->index, 0));
   2006 		racoon_free(src);
   2007 		racoon_free(dst);
   2008 		iph1->status = PHASE1ST_EXPIRED;
   2009 	}
   2010 
   2011 	/*
   2012 	 * the phase1 deletion is postponed until there is no phase2.
   2013 	 */
   2014 	if (LIST_FIRST(&iph1->ph2tree) != NULL) {
   2015 		iph1->sce = sched_new(1, isakmp_ph1expire_stub, iph1);
   2016 		return;
   2017 	}
   2018 
   2019 	iph1->sce = sched_new(1, isakmp_ph1delete_stub, iph1);
   2020 }
   2021 
   2022 /* called from scheduler */
   2023 void
   2024 isakmp_ph1delete_stub(p)
   2025 	void *p;
   2026 {
   2027 
   2028 	isakmp_ph1delete((struct ph1handle *)p);
   2029 }
   2030 
   2031 void
   2032 isakmp_ph1delete(iph1)
   2033 	struct ph1handle *iph1;
   2034 {
   2035 	char *src, *dst;
   2036 
   2037 	SCHED_KILL(iph1->sce);
   2038 
   2039 	if (LIST_FIRST(&iph1->ph2tree) != NULL) {
   2040 		iph1->sce = sched_new(1, isakmp_ph1delete_stub, iph1);
   2041 		return;
   2042 	}
   2043 
   2044 	/* don't re-negosiation when the phase 1 SA expires. */
   2045 
   2046 	src = racoon_strdup(saddr2str(iph1->local));
   2047 	dst = racoon_strdup(saddr2str(iph1->remote));
   2048 	STRDUP_FATAL(src);
   2049 	STRDUP_FATAL(dst);
   2050 
   2051 	plog(LLV_INFO, LOCATION, NULL,
   2052 		"ISAKMP-SA deleted %s-%s spi:%s\n",
   2053 		src, dst, isakmp_pindex(&iph1->index, 0));
   2054 	EVT_PUSH(iph1->local, iph1->remote, EVTT_PHASE1_DOWN, NULL);
   2055 	racoon_free(src);
   2056 	racoon_free(dst);
   2057 
   2058 	remph1(iph1);
   2059 	delph1(iph1);
   2060 
   2061 	return;
   2062 }
   2063 
   2064 /* called from scheduler.
   2065  * this function will call only isakmp_ph2delete().
   2066  * phase 2 handler remain forever if kernel doesn't cry a expire of phase 2 SA
   2067  * by something cause.  That's why this function is called after phase 2 SA
   2068  * expires in the userland.
   2069  */
   2070 void
   2071 isakmp_ph2expire_stub(p)
   2072 	void *p;
   2073 {
   2074 
   2075 	isakmp_ph2expire((struct ph2handle *)p);
   2076 }
   2077 
   2078 void
   2079 isakmp_ph2expire(iph2)
   2080 	struct ph2handle *iph2;
   2081 {
   2082 	char *src, *dst;
   2083 
   2084 	SCHED_KILL(iph2->sce);
   2085 
   2086 	src = racoon_strdup(saddrwop2str(iph2->src));
   2087 	dst = racoon_strdup(saddrwop2str(iph2->dst));
   2088 	STRDUP_FATAL(src);
   2089 	STRDUP_FATAL(dst);
   2090 
   2091 	plog(LLV_INFO, LOCATION, NULL,
   2092 		"phase2 sa expired %s-%s\n", src, dst);
   2093 	racoon_free(src);
   2094 	racoon_free(dst);
   2095 
   2096 	iph2->status = PHASE2ST_EXPIRED;
   2097 
   2098 	iph2->sce = sched_new(1, isakmp_ph2delete_stub, iph2);
   2099 
   2100 	return;
   2101 }
   2102 
   2103 /* called from scheduler */
   2104 void
   2105 isakmp_ph2delete_stub(p)
   2106 	void *p;
   2107 {
   2108 
   2109 	isakmp_ph2delete((struct ph2handle *)p);
   2110 }
   2111 
   2112 void
   2113 isakmp_ph2delete(iph2)
   2114 	struct ph2handle *iph2;
   2115 {
   2116 	char *src, *dst;
   2117 
   2118 	SCHED_KILL(iph2->sce);
   2119 
   2120 	src = racoon_strdup(saddrwop2str(iph2->src));
   2121 	dst = racoon_strdup(saddrwop2str(iph2->dst));
   2122 	STRDUP_FATAL(src);
   2123 	STRDUP_FATAL(dst);
   2124 
   2125 	plog(LLV_INFO, LOCATION, NULL,
   2126 		"phase2 sa deleted %s-%s\n", src, dst);
   2127 	racoon_free(src);
   2128 	racoon_free(dst);
   2129 
   2130 	unbindph12(iph2);
   2131 	remph2(iph2);
   2132 	delph2(iph2);
   2133 
   2134 	return;
   2135 }
   2136 
   2137 /* %%%
   2139  * Interface between PF_KEYv2 and ISAKMP
   2140  */
   2141 /*
   2142  * receive ACQUIRE from kernel, and begin either phase1 or phase2.
   2143  * if phase1 has been finished, begin phase2.
   2144  */
   2145 int
   2146 isakmp_post_acquire(iph2)
   2147 	struct ph2handle *iph2;
   2148 {
   2149 	struct remoteconf *rmconf;
   2150 	struct ph1handle *iph1 = NULL;
   2151 
   2152 	plog(LLV_DEBUG, LOCATION, NULL, "in post_acquire\n");
   2153 
   2154 	/* search appropreate configuration with masking port. */
   2155 	rmconf = getrmconf(iph2->dst);
   2156 	if (rmconf == NULL) {
   2157 		plog(LLV_ERROR, LOCATION, NULL,
   2158 			"no configuration found for %s.\n",
   2159 			saddrwop2str(iph2->dst));
   2160 		return -1;
   2161 	}
   2162 
   2163 	/* if passive mode, ignore the acquire message */
   2164 	if (rmconf->passive) {
   2165 		plog(LLV_DEBUG, LOCATION, NULL,
   2166 			"because of passive mode, "
   2167 			"ignore the acquire message for %s.\n",
   2168 			saddrwop2str(iph2->dst));
   2169 		return 0;
   2170 	}
   2171 
   2172 	/*
   2173 	 * Search isakmp status table by address and port
   2174 	 * If NAT-T is in use, consider null ports as a
   2175 	 * wildcard and use IKE ports instead.
   2176 	 */
   2177 #ifdef ENABLE_NATT
   2178 	if (!extract_port(iph2->src) && !extract_port(iph2->dst)) {
   2179 		if ((iph1 = getph1byaddrwop(iph2->src, iph2->dst)) != NULL) {
   2180 			set_port(iph2->src, extract_port(iph1->local));
   2181 			set_port(iph2->dst, extract_port(iph1->remote));
   2182 		}
   2183 	} else {
   2184 		iph1 = getph1byaddr(iph2->src, iph2->dst, 0);
   2185 	}
   2186 #else
   2187 	iph1 = getph1byaddr(iph2->src, iph2->dst, 0);
   2188 #endif
   2189 
   2190 	/* no ISAKMP-SA found. */
   2191 	if (iph1 == NULL) {
   2192 		struct sched *sc;
   2193 
   2194 		iph2->retry_checkph1 = lcconf->retry_checkph1;
   2195 		sc = sched_new(1, isakmp_chkph1there_stub, iph2);
   2196 		plog(LLV_INFO, LOCATION, NULL,
   2197 			"IPsec-SA request for %s queued "
   2198 			"due to no phase1 found.\n",
   2199 			saddrwop2str(iph2->dst));
   2200 
   2201 		/* start phase 1 negotiation as a initiator. */
   2202 		if (isakmp_ph1begin_i(rmconf, iph2->dst, iph2->src) < 0) {
   2203 			SCHED_KILL(sc);
   2204 			return -1;
   2205 		}
   2206 
   2207 		return 0;
   2208 		/*NOTREACHED*/
   2209 	}
   2210 
   2211 	/* found ISAKMP-SA, but on negotiation. */
   2212 	if (iph1->status != PHASE1ST_ESTABLISHED) {
   2213 		iph2->retry_checkph1 = lcconf->retry_checkph1;
   2214 		sched_new(1, isakmp_chkph1there_stub, iph2);
   2215 		plog(LLV_INFO, LOCATION, iph2->dst,
   2216 			"request for establishing IPsec-SA was queued "
   2217 			"due to no phase1 found.\n");
   2218 		return 0;
   2219 		/*NOTREACHED*/
   2220 	}
   2221 
   2222 	/* found established ISAKMP-SA */
   2223 	/* i.e. iph1->status == PHASE1ST_ESTABLISHED */
   2224 
   2225 	/* found ISAKMP-SA. */
   2226 	plog(LLV_DEBUG, LOCATION, NULL, "begin QUICK mode.\n");
   2227 
   2228 	/* begin quick mode */
   2229 	if (isakmp_ph2begin_i(iph1, iph2))
   2230 		return -1;
   2231 
   2232 	return 0;
   2233 }
   2234 
   2235 /*
   2236  * receive GETSPI from kernel.
   2237  */
   2238 int
   2239 isakmp_post_getspi(iph2)
   2240 	struct ph2handle *iph2;
   2241 {
   2242 #ifdef ENABLE_STATS
   2243 	struct timeval start, end;
   2244 #endif
   2245 
   2246 	/* don't process it because there is no suitable phase1-sa. */
   2247 	if (iph2->ph1->status == PHASE1ST_EXPIRED) {
   2248 		plog(LLV_ERROR, LOCATION, iph2->ph1->remote,
   2249 			"the negotiation is stopped, "
   2250 			"because there is no suitable ISAKMP-SA.\n");
   2251 		return -1;
   2252 	}
   2253 
   2254 #ifdef ENABLE_STATS
   2255 	gettimeofday(&start, NULL);
   2256 #endif
   2257 	if ((ph2exchange[etypesw2(ISAKMP_ETYPE_QUICK)]
   2258 	                [iph2->side]
   2259 	                [iph2->status])(iph2, NULL) != 0)
   2260 		return -1;
   2261 #ifdef ENABLE_STATS
   2262 	gettimeofday(&end, NULL);
   2263 	syslog(LOG_NOTICE, "%s(%s): %8.6f",
   2264 		"phase2",
   2265 		s_isakmp_state(ISAKMP_ETYPE_QUICK, iph2->side, iph2->status),
   2266 		timedelta(&start, &end));
   2267 #endif
   2268 
   2269 	return 0;
   2270 }
   2271 
   2272 /* called by scheduler */
   2273 void
   2274 isakmp_chkph1there_stub(p)
   2275 	void *p;
   2276 {
   2277 	isakmp_chkph1there((struct ph2handle *)p);
   2278 }
   2279 
   2280 void
   2281 isakmp_chkph1there(iph2)
   2282 	struct ph2handle *iph2;
   2283 {
   2284 	struct ph1handle *iph1;
   2285 
   2286 	iph2->retry_checkph1--;
   2287 	if (iph2->retry_checkph1 < 0) {
   2288 		plog(LLV_ERROR, LOCATION, iph2->dst,
   2289 			"phase2 negotiation failed "
   2290 			"due to time up waiting for phase1. %s\n",
   2291 			sadbsecas2str(iph2->dst, iph2->src,
   2292 				iph2->satype, 0, 0));
   2293 		plog(LLV_INFO, LOCATION, NULL,
   2294 			"delete phase 2 handler.\n");
   2295 
   2296 		/* send acquire to kernel as error */
   2297 		pk_sendeacquire(iph2);
   2298 
   2299 		unbindph12(iph2);
   2300 		remph2(iph2);
   2301 		delph2(iph2);
   2302 
   2303 		return;
   2304 	}
   2305 
   2306 	/*
   2307 	 * Search isakmp status table by address and port
   2308 	 * If NAT-T is in use, consider null ports as a
   2309 	 * wildcard and use IKE ports instead.
   2310 	 */
   2311 #ifdef ENABLE_NATT
   2312 	if (!extract_port(iph2->src) && !extract_port(iph2->dst)) {
   2313 		plog(LLV_DEBUG2, LOCATION, NULL, "CHKPH1THERE: extract_port.\n");
   2314 		if( (iph1 = getph1byaddrwop(iph2->src, iph2->dst)) != NULL){
   2315 			plog(LLV_DEBUG2, LOCATION, NULL, "CHKPH1THERE: found a ph1 wop.\n");
   2316 		}
   2317 	} else {
   2318 		plog(LLV_DEBUG2, LOCATION, NULL, "CHKPH1THERE: searching byaddr.\n");
   2319 		iph1 = getph1byaddr(iph2->src, iph2->dst, 0);
   2320 		if(iph1 != NULL)
   2321 			plog(LLV_DEBUG2, LOCATION, NULL, "CHKPH1THERE: found byaddr.\n");
   2322 	}
   2323 #else
   2324 	iph1 = getph1byaddr(iph2->src, iph2->dst, 0);
   2325 #endif
   2326 
   2327 	/* XXX Even if ph1 as responder is there, should we not start
   2328 	 * phase 2 negotiation ? */
   2329 	if (iph1 != NULL
   2330 	 && iph1->status == PHASE1ST_ESTABLISHED) {
   2331 		/* found isakmp-sa */
   2332 
   2333 		plog(LLV_DEBUG2, LOCATION, NULL, "CHKPH1THERE: got a ph1 handler, setting ports.\n");
   2334 		plog(LLV_DEBUG2, LOCATION, NULL, "iph1->local: %s\n", saddr2str(iph1->local));
   2335 		plog(LLV_DEBUG2, LOCATION, NULL, "iph1->remote: %s\n", saddr2str(iph1->remote));
   2336 		plog(LLV_DEBUG2, LOCATION, NULL, "before:\n");
   2337 		plog(LLV_DEBUG2, LOCATION, NULL, "src: %s\n", saddr2str(iph2->src));
   2338 		plog(LLV_DEBUG2, LOCATION, NULL, "dst: %s\n", saddr2str(iph2->dst));
   2339 		set_port(iph2->src, extract_port(iph1->local));
   2340 		set_port(iph2->dst, extract_port(iph1->remote));
   2341 		plog(LLV_DEBUG2, LOCATION, NULL, "After:\n");
   2342 		plog(LLV_DEBUG2, LOCATION, NULL, "src: %s\n", saddr2str(iph2->src));
   2343 		plog(LLV_DEBUG2, LOCATION, NULL, "dst: %s\n", saddr2str(iph2->dst));
   2344 
   2345 		/* begin quick mode */
   2346 		(void)isakmp_ph2begin_i(iph1, iph2);
   2347 		return;
   2348 	}
   2349 
   2350 	plog(LLV_DEBUG2, LOCATION, NULL, "CHKPH1THERE: no established ph1 handler found\n");
   2351 
   2352 	/* no isakmp-sa found */
   2353 	sched_new(1, isakmp_chkph1there_stub, iph2);
   2354 
   2355 	return;
   2356 }
   2357 
   2358 /* copy variable data into ALLOCATED buffer. */
   2359 caddr_t
   2360 isakmp_set_attr_v(buf, type, val, len)
   2361 	caddr_t buf;
   2362 	int type;
   2363 	caddr_t val;
   2364 	int len;
   2365 {
   2366 	struct isakmp_data *data;
   2367 
   2368 	data = (struct isakmp_data *)buf;
   2369 	data->type = htons((u_int16_t)type | ISAKMP_GEN_TLV);
   2370 	data->lorv = htons((u_int16_t)len);
   2371 	memcpy(data + 1, val, len);
   2372 
   2373 	return buf + sizeof(*data) + len;
   2374 }
   2375 
   2376 /* copy fixed length data into ALLOCATED buffer. */
   2377 caddr_t
   2378 isakmp_set_attr_l(buf, type, val)
   2379 	caddr_t buf;
   2380 	int type;
   2381 	u_int32_t val;
   2382 {
   2383 	struct isakmp_data *data;
   2384 
   2385 	data = (struct isakmp_data *)buf;
   2386 	data->type = htons((u_int16_t)type | ISAKMP_GEN_TV);
   2387 	data->lorv = htons((u_int16_t)val);
   2388 
   2389 	return buf + sizeof(*data);
   2390 }
   2391 
   2392 /* add a variable data attribute to the buffer by reallocating it. */
   2393 vchar_t *
   2394 isakmp_add_attr_v(buf0, type, val, len)
   2395 	vchar_t *buf0;
   2396 	int type;
   2397 	caddr_t val;
   2398 	int len;
   2399 {
   2400 	vchar_t *buf = NULL;
   2401 	struct isakmp_data *data;
   2402 	int tlen;
   2403 	int oldlen = 0;
   2404 
   2405 	tlen = sizeof(*data) + len;
   2406 
   2407 	if (buf0) {
   2408 		oldlen = buf0->l;
   2409 		buf = vrealloc(buf0, oldlen + tlen);
   2410 	} else
   2411 		buf = vmalloc(tlen);
   2412 	if (!buf) {
   2413 		plog(LLV_ERROR, LOCATION, NULL,
   2414 			"failed to get a attribute buffer.\n");
   2415 		return NULL;
   2416 	}
   2417 
   2418 	data = (struct isakmp_data *)(buf->v + oldlen);
   2419 	data->type = htons((u_int16_t)type | ISAKMP_GEN_TLV);
   2420 	data->lorv = htons((u_int16_t)len);
   2421 	memcpy(data + 1, val, len);
   2422 
   2423 	return buf;
   2424 }
   2425 
   2426 /* add a fixed data attribute to the buffer by reallocating it. */
   2427 vchar_t *
   2428 isakmp_add_attr_l(buf0, type, val)
   2429 	vchar_t *buf0;
   2430 	int type;
   2431 	u_int32_t val;
   2432 {
   2433 	vchar_t *buf = NULL;
   2434 	struct isakmp_data *data;
   2435 	int tlen;
   2436 	int oldlen = 0;
   2437 
   2438 	tlen = sizeof(*data);
   2439 
   2440 	if (buf0) {
   2441 		oldlen = buf0->l;
   2442 		buf = vrealloc(buf0, oldlen + tlen);
   2443 	} else
   2444 		buf = vmalloc(tlen);
   2445 	if (!buf) {
   2446 		plog(LLV_ERROR, LOCATION, NULL,
   2447 			"failed to get a attribute buffer.\n");
   2448 		return NULL;
   2449 	}
   2450 
   2451 	data = (struct isakmp_data *)(buf->v + oldlen);
   2452 	data->type = htons((u_int16_t)type | ISAKMP_GEN_TV);
   2453 	data->lorv = htons((u_int16_t)val);
   2454 
   2455 	return buf;
   2456 }
   2457 
   2458 /*
   2459  * calculate cookie and set.
   2460  */
   2461 int
   2462 isakmp_newcookie(place, remote, local)
   2463 	caddr_t place;
   2464 	struct sockaddr *remote;
   2465 	struct sockaddr *local;
   2466 {
   2467 	vchar_t *buf = NULL, *buf2 = NULL;
   2468 	char *p;
   2469 	int blen;
   2470 	int alen;
   2471 	caddr_t sa1, sa2;
   2472 	time_t t;
   2473 	int error = -1;
   2474 	u_short port;
   2475 
   2476 
   2477 	if (remote->sa_family != local->sa_family) {
   2478 		plog(LLV_ERROR, LOCATION, NULL,
   2479 			"address family mismatch, remote:%d local:%d\n",
   2480 			remote->sa_family, local->sa_family);
   2481 		goto end;
   2482 	}
   2483 	switch (remote->sa_family) {
   2484 	case AF_INET:
   2485 		alen = sizeof(struct in_addr);
   2486 		sa1 = (caddr_t)&((struct sockaddr_in *)remote)->sin_addr;
   2487 		sa2 = (caddr_t)&((struct sockaddr_in *)local)->sin_addr;
   2488 		break;
   2489 #ifdef INET6
   2490 	case AF_INET6:
   2491 		alen = sizeof(struct in6_addr);
   2492 		sa1 = (caddr_t)&((struct sockaddr_in6 *)remote)->sin6_addr;
   2493 		sa2 = (caddr_t)&((struct sockaddr_in6 *)local)->sin6_addr;
   2494 		break;
   2495 #endif
   2496 	default:
   2497 		plog(LLV_ERROR, LOCATION, NULL,
   2498 			"invalid family: %d\n", remote->sa_family);
   2499 		goto end;
   2500 	}
   2501 	blen = (alen + sizeof(u_short)) * 2
   2502 		+ sizeof(time_t) + lcconf->secret_size;
   2503 	buf = vmalloc(blen);
   2504 	if (buf == NULL) {
   2505 		plog(LLV_ERROR, LOCATION, NULL,
   2506 			"failed to get a cookie.\n");
   2507 		goto end;
   2508 	}
   2509 	p = buf->v;
   2510 
   2511 	/* copy my address */
   2512 	memcpy(p, sa1, alen);
   2513 	p += alen;
   2514 	port = ((struct sockaddr_in *)remote)->sin_port;
   2515 	memcpy(p, &port, sizeof(u_short));
   2516 	p += sizeof(u_short);
   2517 
   2518 	/* copy target address */
   2519 	memcpy(p, sa2, alen);
   2520 	p += alen;
   2521 	port = ((struct sockaddr_in *)local)->sin_port;
   2522 	memcpy(p, &port, sizeof(u_short));
   2523 	p += sizeof(u_short);
   2524 
   2525 	/* copy time */
   2526 	t = time(0);
   2527 	memcpy(p, (caddr_t)&t, sizeof(t));
   2528 	p += sizeof(t);
   2529 
   2530 	/* copy random value */
   2531 	buf2 = eay_set_random(lcconf->secret_size);
   2532 	if (buf2 == NULL)
   2533 		goto end;
   2534 	memcpy(p, buf2->v, lcconf->secret_size);
   2535 	p += lcconf->secret_size;
   2536 	vfree(buf2);
   2537 
   2538 	buf2 = eay_sha1_one(buf);
   2539 	memcpy(place, buf2->v, sizeof(cookie_t));
   2540 
   2541 	sa1 = val2str(place, sizeof (cookie_t));
   2542 	plog(LLV_DEBUG, LOCATION, NULL, "new cookie:\n%s\n", sa1);
   2543 	racoon_free(sa1);
   2544 
   2545 	error = 0;
   2546 end:
   2547 	if (buf != NULL)
   2548 		vfree(buf);
   2549 	if (buf2 != NULL)
   2550 		vfree(buf2);
   2551 	return error;
   2552 }
   2553 
   2554 /*
   2555  * save partner's(payload) data into phhandle.
   2556  */
   2557 int
   2558 isakmp_p2ph(buf, gen)
   2559 	vchar_t **buf;
   2560 	struct isakmp_gen *gen;
   2561 {
   2562 	/* XXX to be checked in each functions for logging. */
   2563 	if (*buf) {
   2564 		plog(LLV_WARNING, LOCATION, NULL,
   2565 			"ignore this payload, same payload type exist.\n");
   2566 		return -1;
   2567 	}
   2568 
   2569 	*buf = vmalloc(ntohs(gen->len) - sizeof(*gen));
   2570 	if (*buf == NULL) {
   2571 		plog(LLV_ERROR, LOCATION, NULL,
   2572 			"failed to get buffer.\n");
   2573 		return -1;
   2574 	}
   2575 	memcpy((*buf)->v, gen + 1, (*buf)->l);
   2576 
   2577 	return 0;
   2578 }
   2579 
   2580 u_int32_t
   2581 isakmp_newmsgid2(iph1)
   2582 	struct ph1handle *iph1;
   2583 {
   2584 	u_int32_t msgid2;
   2585 
   2586 	do {
   2587 		msgid2 = eay_random();
   2588 	} while (getph2bymsgid(iph1, msgid2));
   2589 
   2590 	return msgid2;
   2591 }
   2592 
   2593 /*
   2594  * set values into allocated buffer of isakmp header for phase 1
   2595  */
   2596 static caddr_t
   2597 set_isakmp_header(vbuf, iph1, nptype, etype, flags, msgid)
   2598 	vchar_t *vbuf;
   2599 	struct ph1handle *iph1;
   2600 	int nptype;
   2601 	u_int8_t etype;
   2602 	u_int8_t flags;
   2603 	u_int32_t msgid;
   2604 {
   2605 	struct isakmp *isakmp;
   2606 
   2607 	if (vbuf->l < sizeof(*isakmp))
   2608 		return NULL;
   2609 
   2610 	isakmp = (struct isakmp *)vbuf->v;
   2611 
   2612 	memcpy(&isakmp->i_ck, &iph1->index.i_ck, sizeof(cookie_t));
   2613 	memcpy(&isakmp->r_ck, &iph1->index.r_ck, sizeof(cookie_t));
   2614 	isakmp->np = nptype;
   2615 	isakmp->v = iph1->version;
   2616 	isakmp->etype = etype;
   2617 	isakmp->flags = flags;
   2618 	isakmp->msgid = msgid;
   2619 	isakmp->len = htonl(vbuf->l);
   2620 
   2621 	return vbuf->v + sizeof(*isakmp);
   2622 }
   2623 
   2624 /*
   2625  * set values into allocated buffer of isakmp header for phase 1
   2626  */
   2627 caddr_t
   2628 set_isakmp_header1(vbuf, iph1, nptype)
   2629 	vchar_t *vbuf;
   2630 	struct ph1handle *iph1;
   2631 	int nptype;
   2632 {
   2633 	return set_isakmp_header (vbuf, iph1, nptype, iph1->etype, iph1->flags, iph1->msgid);
   2634 }
   2635 
   2636 /*
   2637  * set values into allocated buffer of isakmp header for phase 2
   2638  */
   2639 caddr_t
   2640 set_isakmp_header2(vbuf, iph2, nptype)
   2641 	vchar_t *vbuf;
   2642 	struct ph2handle *iph2;
   2643 	int nptype;
   2644 {
   2645 	return set_isakmp_header (vbuf, iph2->ph1, nptype, ISAKMP_ETYPE_QUICK, iph2->flags, iph2->msgid);
   2646 }
   2647 
   2648 /*
   2649  * set values into allocated buffer of isakmp payload.
   2650  */
   2651 caddr_t
   2652 set_isakmp_payload(buf, src, nptype)
   2653 	caddr_t buf;
   2654 	vchar_t *src;
   2655 	int nptype;
   2656 {
   2657 	struct isakmp_gen *gen;
   2658 	caddr_t p = buf;
   2659 
   2660 	plog(LLV_DEBUG, LOCATION, NULL, "add payload of len %zu, next type %d\n",
   2661 	    src->l, nptype);
   2662 
   2663 	gen = (struct isakmp_gen *)p;
   2664 	gen->np = nptype;
   2665 	gen->len = htons(sizeof(*gen) + src->l);
   2666 	p += sizeof(*gen);
   2667 	memcpy(p, src->v, src->l);
   2668 	p += src->l;
   2669 
   2670 	return p;
   2671 }
   2672 
   2673 static int
   2674 etypesw1(etype)
   2675 	int etype;
   2676 {
   2677 	switch (etype) {
   2678 	case ISAKMP_ETYPE_IDENT:
   2679 		return 1;
   2680 	case ISAKMP_ETYPE_AGG:
   2681 		return 2;
   2682 	case ISAKMP_ETYPE_BASE:
   2683 		return 3;
   2684 	default:
   2685 		return 0;
   2686 	}
   2687 	/*NOTREACHED*/
   2688 }
   2689 
   2690 static int
   2691 etypesw2(etype)
   2692 	int etype;
   2693 {
   2694 	switch (etype) {
   2695 	case ISAKMP_ETYPE_QUICK:
   2696 		return 1;
   2697 	default:
   2698 		return 0;
   2699 	}
   2700 	/*NOTREACHED*/
   2701 }
   2702 
   2703 #ifdef HAVE_PRINT_ISAKMP_C
   2704 /* for print-isakmp.c */
   2705 char *snapend;
   2706 extern void isakmp_print __P((const u_char *, u_int, const u_char *));
   2707 
   2708 char *getname __P((const u_char *));
   2709 #ifdef INET6
   2710 char *getname6 __P((const u_char *));
   2711 #endif
   2712 int safeputchar __P((int));
   2713 
   2714 /*
   2715  * Return a name for the IP address pointed to by ap.  This address
   2716  * is assumed to be in network byte order.
   2717  */
   2718 char *
   2719 getname(ap)
   2720 	const u_char *ap;
   2721 {
   2722 	struct sockaddr_in addr;
   2723 	static char ntop_buf[NI_MAXHOST];
   2724 
   2725 	memset(&addr, 0, sizeof(addr));
   2726 #ifndef __linux__
   2727 	addr.sin_len = sizeof(struct sockaddr_in);
   2728 #endif
   2729 	addr.sin_family = AF_INET;
   2730 	memcpy(&addr.sin_addr, ap, sizeof(addr.sin_addr));
   2731 	if (getnameinfo((struct sockaddr *)&addr, sizeof(addr),
   2732 			ntop_buf, sizeof(ntop_buf), NULL, 0,
   2733 			NI_NUMERICHOST | niflags))
   2734 		strlcpy(ntop_buf, "?", sizeof(ntop_buf));
   2735 
   2736 	return ntop_buf;
   2737 }
   2738 
   2739 #ifdef INET6
   2740 /*
   2741  * Return a name for the IP6 address pointed to by ap.  This address
   2742  * is assumed to be in network byte order.
   2743  */
   2744 char *
   2745 getname6(ap)
   2746 	const u_char *ap;
   2747 {
   2748 	struct sockaddr_in6 addr;
   2749 	static char ntop_buf[NI_MAXHOST];
   2750 
   2751 	memset(&addr, 0, sizeof(addr));
   2752 	addr.sin6_len = sizeof(struct sockaddr_in6);
   2753 	addr.sin6_family = AF_INET6;
   2754 	memcpy(&addr.sin6_addr, ap, sizeof(addr.sin6_addr));
   2755 	if (getnameinfo((struct sockaddr *)&addr, addr.sin6_len,
   2756 			ntop_buf, sizeof(ntop_buf), NULL, 0,
   2757 			NI_NUMERICHOST | niflags))
   2758 		strlcpy(ntop_buf, "?", sizeof(ntop_buf));
   2759 
   2760 	return ntop_buf;
   2761 }
   2762 #endif /* INET6 */
   2763 
   2764 int
   2765 safeputchar(c)
   2766 	int c;
   2767 {
   2768 	unsigned char ch;
   2769 
   2770 	ch = (unsigned char)(c & 0xff);
   2771 	if (c < 0x80 && isprint(c))
   2772 		return printf("%c", c & 0xff);
   2773 	else
   2774 		return printf("\\%03o", c & 0xff);
   2775 }
   2776 
   2777 void
   2778 isakmp_printpacket(msg, from, my, decoded)
   2779 	vchar_t *msg;
   2780 	struct sockaddr *from;
   2781 	struct sockaddr *my;
   2782 	int decoded;
   2783 {
   2784 #ifdef YIPS_DEBUG
   2785 	struct timeval tv;
   2786 	int s;
   2787 	char hostbuf[NI_MAXHOST];
   2788 	char portbuf[NI_MAXSERV];
   2789 	struct isakmp *isakmp;
   2790 	vchar_t *buf;
   2791 #endif
   2792 
   2793 	if (loglevel < LLV_DEBUG)
   2794 		return;
   2795 
   2796 #ifdef YIPS_DEBUG
   2797 	plog(LLV_DEBUG, LOCATION, NULL, "begin.\n");
   2798 
   2799 	gettimeofday(&tv, NULL);
   2800 	s = tv.tv_sec % 3600;
   2801 	printf("%02d:%02d.%06u ", s / 60, s % 60, (u_int32_t)tv.tv_usec);
   2802 
   2803 	if (from) {
   2804 		if (getnameinfo(from, sysdep_sa_len(from), hostbuf, sizeof(hostbuf),
   2805 				portbuf, sizeof(portbuf),
   2806 				NI_NUMERICHOST | NI_NUMERICSERV | niflags)) {
   2807 			strlcpy(hostbuf, "?", sizeof(hostbuf));
   2808 			strlcpy(portbuf, "?", sizeof(portbuf));
   2809 		}
   2810 		printf("%s:%s", hostbuf, portbuf);
   2811 	} else
   2812 		printf("?");
   2813 	printf(" -> ");
   2814 	if (my) {
   2815 		if (getnameinfo(my, sysdep_sa_len(my), hostbuf, sizeof(hostbuf),
   2816 				portbuf, sizeof(portbuf),
   2817 				NI_NUMERICHOST | NI_NUMERICSERV | niflags)) {
   2818 			strlcpy(hostbuf, "?", sizeof(hostbuf));
   2819 			strlcpy(portbuf, "?", sizeof(portbuf));
   2820 		}
   2821 		printf("%s:%s", hostbuf, portbuf);
   2822 	} else
   2823 		printf("?");
   2824 	printf(": ");
   2825 
   2826 	buf = vdup(msg);
   2827 	if (!buf) {
   2828 		printf("(malloc fail)\n");
   2829 		return;
   2830 	}
   2831 	if (decoded) {
   2832 		isakmp = (struct isakmp *)buf->v;
   2833 		if (isakmp->flags & ISAKMP_FLAG_E) {
   2834 #if 0
   2835 			int pad;
   2836 			pad = *(u_char *)(buf->v + buf->l - 1);
   2837 			if (buf->l < pad && 2 < vflag)
   2838 				printf("(wrong padding)");
   2839 #endif
   2840 			isakmp->flags &= ~ISAKMP_FLAG_E;
   2841 		}
   2842 	}
   2843 
   2844 	snapend = buf->v + buf->l;
   2845 	isakmp_print(buf->v, buf->l, NULL);
   2846 	vfree(buf);
   2847 	printf("\n");
   2848 	fflush(stdout);
   2849 
   2850 	return;
   2851 #endif
   2852 }
   2853 #endif /*HAVE_PRINT_ISAKMP_C*/
   2854 
   2855 int
   2856 copy_ph1addresses(iph1, rmconf, remote, local)
   2857 	struct ph1handle *iph1;
   2858 	struct remoteconf *rmconf;
   2859 	struct sockaddr *remote, *local;
   2860 {
   2861 	u_int16_t port;
   2862 
   2863 	/* address portion must be grabbed from real remote address "remote" */
   2864 	iph1->remote = dupsaddr(remote);
   2865 	if (iph1->remote == NULL)
   2866 		return -1;
   2867 
   2868 	/*
   2869 	 * if remote has no port # (in case of initiator - from ACQUIRE msg)
   2870 	 * - if remote.conf specifies port #, use that
   2871 	 * - if remote.conf does not, use 500
   2872 	 * if remote has port # (in case of responder - from recvfrom(2))
   2873 	 * respect content of "remote".
   2874 	 */
   2875 	if (extract_port(iph1->remote) == 0) {
   2876 		port = extract_port(rmconf->remote);
   2877 		if (port == 0)
   2878 			port = PORT_ISAKMP;
   2879 		set_port(iph1->remote, port);
   2880 	}
   2881 
   2882 	if (local == NULL)
   2883 		iph1->local = getlocaladdr(iph1->remote);
   2884 	else
   2885 		iph1->local = dupsaddr(local);
   2886 	if (iph1->local == NULL)
   2887 		return -1;
   2888 
   2889 	if (extract_port(iph1->local) == 0)
   2890 		set_port(iph1->local, PORT_ISAKMP);
   2891 
   2892 #ifdef ENABLE_NATT
   2893 	if (extract_port(iph1->local) == lcconf->port_isakmp_natt) {
   2894 		plog(LLV_DEBUG, LOCATION, NULL, "Marking ports as changed\n");
   2895 		iph1->natt_flags |= NAT_ADD_NON_ESP_MARKER;
   2896 	}
   2897 #endif
   2898 
   2899 	return 0;
   2900 }
   2901 
   2902 static int
   2903 nostate1(iph1, msg)
   2904 	struct ph1handle *iph1;
   2905 	vchar_t *msg;
   2906 {
   2907 	plog(LLV_ERROR, LOCATION, iph1->remote, "wrong state %u.\n",
   2908 			iph1->status);
   2909 	return -1;
   2910 }
   2911 
   2912 static int
   2913 nostate2(iph2, msg)
   2914 	struct ph2handle *iph2;
   2915 	vchar_t *msg;
   2916 {
   2917 	plog(LLV_ERROR, LOCATION, iph2->ph1->remote, "wrong state %u.\n",
   2918 		iph2->status);
   2919 	return -1;
   2920 }
   2921 
   2922 void
   2923 log_ph1established(iph1)
   2924 	const struct ph1handle *iph1;
   2925 {
   2926 	char *src, *dst;
   2927 
   2928 	src = racoon_strdup(saddr2str(iph1->local));
   2929 	dst = racoon_strdup(saddr2str(iph1->remote));
   2930 	STRDUP_FATAL(src);
   2931 	STRDUP_FATAL(dst);
   2932 
   2933 	plog(LLV_INFO, LOCATION, NULL,
   2934 		"ISAKMP-SA established %s-%s spi:%s\n",
   2935 		src, dst,
   2936 		isakmp_pindex(&iph1->index, 0));
   2937 
   2938 	EVT_PUSH(iph1->local, iph1->remote, EVTT_PHASE1_UP, NULL);
   2939 	if(!iph1->rmconf->mode_cfg) {
   2940 		EVT_PUSH(iph1->local, iph1->remote, EVTT_NO_ISAKMP_CFG, NULL);
   2941 	}
   2942 
   2943 	racoon_free(src);
   2944 	racoon_free(dst);
   2945 
   2946 	return;
   2947 }
   2948 
   2949 struct payload_list *
   2950 isakmp_plist_append (struct payload_list *plist, vchar_t *payload, int payload_type)
   2951 {
   2952 	if (! plist) {
   2953 		plist = racoon_malloc (sizeof (struct payload_list));
   2954 		plist->prev = NULL;
   2955 	}
   2956 	else {
   2957 		plist->next = racoon_malloc (sizeof (struct payload_list));
   2958 		plist->next->prev = plist;
   2959 		plist = plist->next;
   2960 	}
   2961 
   2962 	plist->next = NULL;
   2963 	plist->payload = payload;
   2964 	plist->payload_type = payload_type;
   2965 
   2966 	return plist;
   2967 }
   2968 
   2969 vchar_t *
   2970 isakmp_plist_set_all (struct payload_list **plist, struct ph1handle *iph1)
   2971 {
   2972 	struct payload_list *ptr = *plist, *first;
   2973 	size_t tlen = sizeof (struct isakmp), n = 0;
   2974 	vchar_t *buf = NULL;
   2975 	char *p;
   2976 
   2977 	/* Seek to the first item.  */
   2978 	while (ptr->prev) ptr = ptr->prev;
   2979 	first = ptr;
   2980 
   2981 	/* Compute the whole length.  */
   2982 	while (ptr) {
   2983 		tlen += ptr->payload->l + sizeof (struct isakmp_gen);
   2984 		ptr = ptr->next;
   2985 	}
   2986 
   2987 	buf = vmalloc(tlen);
   2988 	if (buf == NULL) {
   2989 		plog(LLV_ERROR, LOCATION, NULL,
   2990 			"failed to get buffer to send.\n");
   2991 		goto end;
   2992 	}
   2993 
   2994 	ptr = first;
   2995 
   2996 	p = set_isakmp_header1(buf, iph1, ptr->payload_type);
   2997 	if (p == NULL)
   2998 		goto end;
   2999 
   3000 	while (ptr)
   3001 	{
   3002 		p = set_isakmp_payload (p, ptr->payload, ptr->next ? ptr->next->payload_type : ISAKMP_NPTYPE_NONE);
   3003 		first = ptr;
   3004 		ptr = ptr->next;
   3005 		racoon_free (first);
   3006 		/* ptr->prev = NULL; first = NULL; ... omitted.  */
   3007 		n++;
   3008 	}
   3009 
   3010 	*plist = NULL;
   3011 
   3012 	return buf;
   3013 end:
   3014 	if (buf != NULL)
   3015 		vfree(buf);
   3016 	return NULL;
   3017 }
   3018 
   3019 #ifdef ENABLE_FRAG
   3020 int
   3021 frag_handler(iph1, msg, remote, local)
   3022 	struct ph1handle *iph1;
   3023 	vchar_t *msg;
   3024 	struct sockaddr *remote;
   3025 	struct sockaddr *local;
   3026 {
   3027 	vchar_t *newmsg;
   3028 
   3029 	if (isakmp_frag_extract(iph1, msg) == 1) {
   3030 		if ((newmsg = isakmp_frag_reassembly(iph1)) == NULL) {
   3031 			plog(LLV_ERROR, LOCATION, remote,
   3032 			    "Packet reassembly failed\n");
   3033 			return -1;
   3034 		}
   3035 		return isakmp_main(newmsg, remote, local);
   3036 	}
   3037 
   3038 	return 0;
   3039 }
   3040 #endif
   3041 
   3042 void
   3043 script_hook(iph1, script)
   3044 	struct ph1handle *iph1;
   3045 	int script;
   3046 {
   3047 #define IP_MAX 40
   3048 #define PORT_MAX 6
   3049 	char addrstr[IP_MAX];
   3050 	char portstr[PORT_MAX];
   3051 	char **envp = NULL;
   3052 	int envc = 1;
   3053 	struct sockaddr_in *sin;
   3054 	char **c;
   3055 
   3056 	if (iph1 == NULL ||
   3057 		iph1->rmconf == NULL ||
   3058 		iph1->rmconf->script[script] == NULL)
   3059 		return;
   3060 
   3061 #ifdef ENABLE_HYBRID
   3062 	(void)isakmp_cfg_setenv(iph1, &envp, &envc);
   3063 #endif
   3064 
   3065 	/* local address */
   3066 	sin = (struct sockaddr_in *)iph1->local;
   3067 	inet_ntop(sin->sin_family, &sin->sin_addr, addrstr, IP_MAX);
   3068 	snprintf(portstr, PORT_MAX, "%d", ntohs(sin->sin_port));
   3069 
   3070 	if (script_env_append(&envp, &envc, "LOCAL_ADDR", addrstr) != 0) {
   3071 		plog(LLV_ERROR, LOCATION, NULL, "Cannot set LOCAL_ADDR\n");
   3072 		goto out;
   3073 	}
   3074 
   3075 	if (script_env_append(&envp, &envc, "LOCAL_PORT", portstr) != 0) {
   3076 		plog(LLV_ERROR, LOCATION, NULL, "Cannot set LOCAL_PORT\n");
   3077 		goto out;
   3078 	}
   3079 
   3080 	/* Peer address */
   3081 	if (iph1->remote != NULL) {
   3082 		sin = (struct sockaddr_in *)iph1->remote;
   3083 		inet_ntop(sin->sin_family, &sin->sin_addr, addrstr, IP_MAX);
   3084 		snprintf(portstr, PORT_MAX, "%d", ntohs(sin->sin_port));
   3085 
   3086 		if (script_env_append(&envp, &envc,
   3087 		    "REMOTE_ADDR", addrstr) != 0) {
   3088 			plog(LLV_ERROR, LOCATION, NULL,
   3089 			    "Cannot set REMOTE_ADDR\n");
   3090 			goto out;
   3091 		}
   3092 
   3093 		if (script_env_append(&envp, &envc,
   3094 		    "REMOTE_PORT", portstr) != 0) {
   3095 			plog(LLV_ERROR, LOCATION, NULL,
   3096 			    "Cannot set REMOTEL_PORT\n");
   3097 			goto out;
   3098 		}
   3099 	}
   3100 
   3101 	if (privsep_script_exec(iph1->rmconf->script[script]->v,
   3102 	    script, envp) != 0)
   3103 		plog(LLV_ERROR, LOCATION, NULL,
   3104 		    "Script %s execution failed\n", script_names[script]);
   3105 
   3106 out:
   3107 	for (c = envp; *c; c++)
   3108 		racoon_free(*c);
   3109 
   3110 	racoon_free(envp);
   3111 
   3112 	return;
   3113 }
   3114 
   3115 int
   3116 script_env_append(envp, envc, name, value)
   3117 	char ***envp;
   3118 	int *envc;
   3119 	char *name;
   3120 	char *value;
   3121 {
   3122 	char *envitem;
   3123 	char **newenvp;
   3124 	int newenvc;
   3125 
   3126 	if (value == NULL) {
   3127 	        value = "";
   3128 	}
   3129 
   3130 	envitem = racoon_malloc(strlen(name) + 1 + strlen(value) + 1);
   3131 	if (envitem == NULL) {
   3132 		plog(LLV_ERROR, LOCATION, NULL,
   3133 		    "Cannot allocate memory: %s\n", strerror(errno));
   3134 		return -1;
   3135 	}
   3136 	sprintf(envitem, "%s=%s", name, value);
   3137 
   3138 	newenvc = (*envc) + 1;
   3139 	newenvp = racoon_realloc(*envp, newenvc * sizeof(char *));
   3140 	if (newenvp == NULL) {
   3141 		plog(LLV_ERROR, LOCATION, NULL,
   3142 		    "Cannot allocate memory: %s\n", strerror(errno));
   3143 		racoon_free(envitem);
   3144 		return -1;
   3145 	}
   3146 
   3147 	newenvp[newenvc - 2] = envitem;
   3148 	newenvp[newenvc - 1] = NULL;
   3149 
   3150 	*envp = newenvp;
   3151 	*envc = newenvc;
   3152 	return 0;
   3153 }
   3154 
   3155 int
   3156 script_exec(script, name, envp)
   3157 	char *script;
   3158 	int name;
   3159 	char *const envp[];
   3160 {
   3161 	char *argv[] = { NULL, NULL, NULL };
   3162 
   3163 	argv[0] = script;
   3164 	argv[1] = script_names[name];
   3165 	argv[2] = NULL;
   3166 
   3167 	switch (fork()) {
   3168 	case 0:
   3169 		execve(argv[0], argv, envp);
   3170 		plog(LLV_ERROR, LOCATION, NULL,
   3171 		    "execve(\"%s\") failed: %s\n",
   3172 		    argv[0], strerror(errno));
   3173 		_exit(1);
   3174 		break;
   3175 	case -1:
   3176 		plog(LLV_ERROR, LOCATION, NULL,
   3177 		    "Cannot fork: %s\n", strerror(errno));
   3178 		return -1;
   3179 		break;
   3180 	default:
   3181 		break;
   3182 	}
   3183 	return 0;
   3184 
   3185 }
   3186 
   3187 void
   3188 purge_remote(iph1)
   3189 	struct ph1handle *iph1;
   3190 {
   3191 	vchar_t *buf = NULL;
   3192 	struct sadb_msg *msg, *next, *end;
   3193 	struct sadb_sa *sa;
   3194 	struct sockaddr *src, *dst;
   3195 	caddr_t mhp[SADB_EXT_MAX + 1];
   3196 	u_int proto_id;
   3197 	struct ph2handle *iph2;
   3198 	struct ph1handle *new_iph1;
   3199 
   3200 	plog(LLV_INFO, LOCATION, NULL,
   3201 		 "purging ISAKMP-SA spi=%s.\n",
   3202 		 isakmp_pindex(&(iph1->index), iph1->msgid));
   3203 
   3204 	/* Mark as expired. */
   3205 	iph1->status = PHASE1ST_EXPIRED;
   3206 
   3207 	/* Check if we have another, still valid, phase1 SA. */
   3208 	new_iph1 = getph1byaddr(iph1->local, iph1->remote, 1);
   3209 
   3210 	/*
   3211 	 * Delete all orphaned or binded to the deleting ph1handle phase2 SAs.
   3212 	 * Keep all others phase2 SAs.
   3213 	 */
   3214 	buf = pfkey_dump_sadb(SADB_SATYPE_UNSPEC);
   3215 	if (buf == NULL) {
   3216 		plog(LLV_DEBUG, LOCATION, NULL,
   3217 			"pfkey_dump_sadb returned nothing.\n");
   3218 		return;
   3219 	}
   3220 
   3221 	msg = (struct sadb_msg *)buf->v;
   3222 	end = (struct sadb_msg *)(buf->v + buf->l);
   3223 
   3224 	while (msg < end) {
   3225 		if ((msg->sadb_msg_len << 3) < sizeof(*msg))
   3226 			break;
   3227 		next = (struct sadb_msg *)((caddr_t)msg + (msg->sadb_msg_len << 3));
   3228 		if (msg->sadb_msg_type != SADB_DUMP) {
   3229 			msg = next;
   3230 			continue;
   3231 		}
   3232 
   3233 		if (pfkey_align(msg, mhp) || pfkey_check(mhp)) {
   3234 			plog(LLV_ERROR, LOCATION, NULL,
   3235 				"pfkey_check (%s)\n", ipsec_strerror());
   3236 			msg = next;
   3237 			continue;
   3238 		}
   3239 
   3240 		sa = (struct sadb_sa *)(mhp[SADB_EXT_SA]);
   3241 		if (!sa ||
   3242 		    !mhp[SADB_EXT_ADDRESS_SRC] ||
   3243 		    !mhp[SADB_EXT_ADDRESS_DST]) {
   3244 			msg = next;
   3245 			continue;
   3246 		}
   3247 		src = PFKEY_ADDR_SADDR(mhp[SADB_EXT_ADDRESS_SRC]);
   3248 		dst = PFKEY_ADDR_SADDR(mhp[SADB_EXT_ADDRESS_DST]);
   3249 
   3250 		if (sa->sadb_sa_state != SADB_SASTATE_LARVAL &&
   3251 		    sa->sadb_sa_state != SADB_SASTATE_MATURE &&
   3252 		    sa->sadb_sa_state != SADB_SASTATE_DYING) {
   3253 			msg = next;
   3254 			continue;
   3255 		}
   3256 
   3257 		/*
   3258 		 * check in/outbound SAs.
   3259 		 * Select only SAs where src == local and dst == remote (outgoing)
   3260 		 * or src == remote and dst == local (incoming).
   3261 		 */
   3262 		if ((CMPSADDR(iph1->local, src) || CMPSADDR(iph1->remote, dst)) &&
   3263 			(CMPSADDR(iph1->local, dst) || CMPSADDR(iph1->remote, src))) {
   3264 			msg = next;
   3265 			continue;
   3266 		}
   3267 
   3268 		proto_id = pfkey2ipsecdoi_proto(msg->sadb_msg_satype);
   3269 		iph2 = getph2bysaidx(src, dst, proto_id, sa->sadb_sa_spi);
   3270 
   3271 		/* Check if there is another valid ISAKMP-SA */
   3272 		if (new_iph1 != NULL) {
   3273 
   3274 			if (iph2 == NULL) {
   3275 				/* No handler... still send a pfkey_delete message, but log this !*/
   3276 				plog(LLV_INFO, LOCATION, NULL,
   3277 					"Unknown IPsec-SA spi=%u, hmmmm?\n",
   3278 					ntohl(sa->sadb_sa_spi));
   3279 			}else{
   3280 
   3281 				/*
   3282 				 * If we have a new ph1, do not purge IPsec-SAs binded
   3283 				 *  to a different ISAKMP-SA
   3284 				 */
   3285 				if (iph2->ph1 != NULL && iph2->ph1 != iph1){
   3286 					msg = next;
   3287 					continue;
   3288 				}
   3289 
   3290 				/* If the ph2handle is established, do not purge IPsec-SA */
   3291 				if (iph2->status == PHASE2ST_ESTABLISHED ||
   3292 					iph2->status == PHASE2ST_EXPIRED) {
   3293 
   3294 					plog(LLV_INFO, LOCATION, NULL,
   3295 						 "keeping IPsec-SA spi=%u - found valid ISAKMP-SA spi=%s.\n",
   3296 						 ntohl(sa->sadb_sa_spi),
   3297 						 isakmp_pindex(&(new_iph1->index), new_iph1->msgid));
   3298 					msg = next;
   3299 					continue;
   3300 				}
   3301 			}
   3302 		}
   3303 
   3304 
   3305 		pfkey_send_delete(lcconf->sock_pfkey,
   3306 				  msg->sadb_msg_satype,
   3307 				  IPSEC_MODE_ANY,
   3308 				  src, dst, sa->sadb_sa_spi);
   3309 
   3310 		/* delete a relative phase 2 handle. */
   3311 		if (iph2 != NULL) {
   3312 			delete_spd(iph2, 0);
   3313 			unbindph12(iph2);
   3314 			remph2(iph2);
   3315 			delph2(iph2);
   3316 		}
   3317 
   3318 		plog(LLV_INFO, LOCATION, NULL,
   3319 			 "purged IPsec-SA spi=%u.\n",
   3320 			 ntohl(sa->sadb_sa_spi));
   3321 
   3322 		msg = next;
   3323 	}
   3324 
   3325 	if (buf)
   3326 		vfree(buf);
   3327 
   3328 	/* Mark the phase1 handler as EXPIRED */
   3329 	plog(LLV_INFO, LOCATION, NULL,
   3330 		 "purged ISAKMP-SA spi=%s.\n",
   3331 		 isakmp_pindex(&(iph1->index), iph1->msgid));
   3332 
   3333 	SCHED_KILL(iph1->sce);
   3334 
   3335 	iph1->sce = sched_new(1, isakmp_ph1delete_stub, iph1);
   3336 }
   3337 
   3338 void
   3339 delete_spd(iph2, created)
   3340 	struct ph2handle *iph2;
   3341  	u_int64_t created;
   3342 {
   3343 	struct policyindex spidx;
   3344 	struct sockaddr_storage addr;
   3345 	u_int8_t pref;
   3346 	struct sockaddr *src;
   3347 	struct sockaddr *dst;
   3348 	int error;
   3349 	int idi2type = 0;/* switch whether copy IDs into id[src,dst]. */
   3350 
   3351 	if (iph2 == NULL)
   3352 		return;
   3353 
   3354 	/* Delete the SPD entry if we generated it
   3355 	 */
   3356 	if (! iph2->generated_spidx )
   3357 		return;
   3358 
   3359 	src = iph2->src;
   3360 	dst = iph2->dst;
   3361 
   3362 	plog(LLV_INFO, LOCATION, NULL,
   3363 		 "generated policy, deleting it.\n");
   3364 
   3365 	memset(&spidx, 0, sizeof(spidx));
   3366 	iph2->spidx_gen = (caddr_t )&spidx;
   3367 
   3368 	/* make inbound policy */
   3369 	iph2->src = dst;
   3370 	iph2->dst = src;
   3371 	spidx.dir = IPSEC_DIR_INBOUND;
   3372 	spidx.ul_proto = 0;
   3373 
   3374 	/*
   3375 	 * Note: code from get_proposal_r
   3376 	 */
   3377 
   3378 #define _XIDT(d) ((struct ipsecdoi_id_b *)(d)->v)->type
   3379 
   3380 	/*
   3381 	 * make destination address in spidx from either ID payload
   3382 	 * or phase 1 address into a address in spidx.
   3383 	 */
   3384 	if (iph2->id != NULL
   3385 		&& (_XIDT(iph2->id) == IPSECDOI_ID_IPV4_ADDR
   3386 			|| _XIDT(iph2->id) == IPSECDOI_ID_IPV6_ADDR
   3387 			|| _XIDT(iph2->id) == IPSECDOI_ID_IPV4_ADDR_SUBNET
   3388 			|| _XIDT(iph2->id) == IPSECDOI_ID_IPV6_ADDR_SUBNET)) {
   3389 		/* get a destination address of a policy */
   3390 		error = ipsecdoi_id2sockaddr(iph2->id,
   3391 									 (struct sockaddr *)&spidx.dst,
   3392 									 &spidx.prefd, &spidx.ul_proto);
   3393 		if (error)
   3394 			goto purge;
   3395 
   3396 #ifdef INET6
   3397 		/*
   3398 		 * get scopeid from the SA address.
   3399 		 * note that the phase 1 source address is used as
   3400 		 * a destination address to search for a inbound
   3401 		 * policy entry because rcoon is responder.
   3402 		 */
   3403 		if (_XIDT(iph2->id) == IPSECDOI_ID_IPV6_ADDR) {
   3404 			if ((error =
   3405 				 setscopeid((struct sockaddr *)&spidx.dst,
   3406 							iph2->src)) != 0)
   3407 				goto purge;
   3408 		}
   3409 #endif
   3410 
   3411 		if (_XIDT(iph2->id) == IPSECDOI_ID_IPV4_ADDR
   3412 			|| _XIDT(iph2->id) == IPSECDOI_ID_IPV6_ADDR)
   3413 			idi2type = _XIDT(iph2->id);
   3414 
   3415 	} else {
   3416 
   3417 		plog(LLV_DEBUG, LOCATION, NULL,
   3418 			 "get a destination address of SP index "
   3419 			 "from phase1 address "
   3420 			 "due to no ID payloads found "
   3421 			 "OR because ID type is not address.\n");
   3422 
   3423 		/*
   3424 		 * copy the SOURCE address of IKE into the
   3425 		 * DESTINATION address of the key to search the
   3426 		 * SPD because the direction of policy is inbound.
   3427 		 */
   3428 		memcpy(&spidx.dst, iph2->src, sysdep_sa_len(iph2->src));
   3429 		switch (spidx.dst.ss_family) {
   3430 		case AF_INET:
   3431 			spidx.prefd =
   3432 				sizeof(struct in_addr) << 3;
   3433 			break;
   3434 #ifdef INET6
   3435 		case AF_INET6:
   3436 			spidx.prefd =
   3437 				sizeof(struct in6_addr) << 3;
   3438 			break;
   3439 #endif
   3440 		default:
   3441 			spidx.prefd = 0;
   3442 			break;
   3443 		}
   3444 	}
   3445 
   3446 	/* make source address in spidx */
   3447 	if (iph2->id_p != NULL
   3448 		&& (_XIDT(iph2->id_p) == IPSECDOI_ID_IPV4_ADDR
   3449 			|| _XIDT(iph2->id_p) == IPSECDOI_ID_IPV6_ADDR
   3450 			|| _XIDT(iph2->id_p) == IPSECDOI_ID_IPV4_ADDR_SUBNET
   3451 			|| _XIDT(iph2->id_p) == IPSECDOI_ID_IPV6_ADDR_SUBNET)) {
   3452 		/* get a source address of inbound SA */
   3453 		error = ipsecdoi_id2sockaddr(iph2->id_p,
   3454 									 (struct sockaddr *)&spidx.src,
   3455 									 &spidx.prefs, &spidx.ul_proto);
   3456 		if (error)
   3457 			goto purge;
   3458 
   3459 #ifdef INET6
   3460 		/*
   3461 		 * get scopeid from the SA address.
   3462 		 * for more detail, see above of this function.
   3463 		 */
   3464 		if (_XIDT(iph2->id_p) == IPSECDOI_ID_IPV6_ADDR) {
   3465 			error =
   3466 				setscopeid((struct sockaddr *)&spidx.src,
   3467 						   iph2->dst);
   3468 			if (error)
   3469 				goto purge;
   3470 		}
   3471 #endif
   3472 
   3473 		/* make id[src,dst] if both ID types are IP address and same */
   3474 		if (_XIDT(iph2->id_p) == idi2type
   3475 			&& spidx.dst.ss_family == spidx.src.ss_family) {
   3476 			iph2->src_id =
   3477 				dupsaddr((struct sockaddr *)&spidx.dst);
   3478 			if (iph2->src_id == NULL) {
   3479 				plog(LLV_ERROR, LOCATION, NULL,
   3480 					 "allocation failed\n");
   3481 				goto purge;
   3482 			}
   3483 			iph2->dst_id =
   3484 				dupsaddr((struct sockaddr *)&spidx.src);
   3485 			if (iph2->dst_id == NULL) {
   3486 				plog(LLV_ERROR, LOCATION, NULL,
   3487 					 "allocation failed\n");
   3488 				goto purge;
   3489 			}
   3490 		}
   3491 
   3492 	} else {
   3493 		plog(LLV_DEBUG, LOCATION, NULL,
   3494 			 "get a source address of SP index "
   3495 			 "from phase1 address "
   3496 			 "due to no ID payloads found "
   3497 			 "OR because ID type is not address.\n");
   3498 
   3499 		/* see above comment. */
   3500 		memcpy(&spidx.src, iph2->dst, sysdep_sa_len(iph2->dst));
   3501 		switch (spidx.src.ss_family) {
   3502 		case AF_INET:
   3503 			spidx.prefs =
   3504 				sizeof(struct in_addr) << 3;
   3505 			break;
   3506 #ifdef INET6
   3507 		case AF_INET6:
   3508 			spidx.prefs =
   3509 				sizeof(struct in6_addr) << 3;
   3510 			break;
   3511 #endif
   3512 		default:
   3513 			spidx.prefs = 0;
   3514 			break;
   3515 		}
   3516 	}
   3517 
   3518 #undef _XIDT
   3519 
   3520 	plog(LLV_DEBUG, LOCATION, NULL,
   3521 		 "get a src address from ID payload "
   3522 		 "%s prefixlen=%u ul_proto=%u\n",
   3523 		 saddr2str((struct sockaddr *)&spidx.src),
   3524 		 spidx.prefs, spidx.ul_proto);
   3525 	plog(LLV_DEBUG, LOCATION, NULL,
   3526 		 "get dst address from ID payload "
   3527 		 "%s prefixlen=%u ul_proto=%u\n",
   3528 		 saddr2str((struct sockaddr *)&spidx.dst),
   3529 		 spidx.prefd, spidx.ul_proto);
   3530 
   3531 	/*
   3532 	 * convert the ul_proto if it is 0
   3533 	 * because 0 in ID payload means a wild card.
   3534 	 */
   3535 	if (spidx.ul_proto == 0)
   3536 		spidx.ul_proto = IPSEC_ULPROTO_ANY;
   3537 
   3538 #undef _XIDT
   3539 
   3540 	/* Check if the generated SPD has the same timestamp as the SA.
   3541 	 * If timestamps are different, this means that the SPD entry has been
   3542 	 * refreshed by another SA, and should NOT be deleted with the current SA.
   3543 	 */
   3544 	if( created ){
   3545 		struct secpolicy *p;
   3546 
   3547 		p = getsp(&spidx);
   3548 		if(p != NULL){
   3549 			/* just do no test if p is NULL, because this probably just means
   3550 			 * that the policy has already be deleted for some reason.
   3551 			 */
   3552 			if(p->spidx.created != created)
   3553 				goto purge;
   3554 		}
   3555 	}
   3556 
   3557 	/* End of code from get_proposal_r
   3558 	 */
   3559 
   3560 	if (pk_sendspddelete(iph2) < 0) {
   3561 		plog(LLV_ERROR, LOCATION, NULL,
   3562 			 "pfkey spddelete(inbound) failed.\n");
   3563 	}else{
   3564 		plog(LLV_DEBUG, LOCATION, NULL,
   3565 			 "pfkey spddelete(inbound) sent.\n");
   3566 	}
   3567 
   3568 #ifdef HAVE_POLICY_FWD
   3569 	/* make forward policy if required */
   3570 	if (tunnel_mode_prop(iph2->approval)) {
   3571 		spidx.dir = IPSEC_DIR_FWD;
   3572 		if (pk_sendspddelete(iph2) < 0) {
   3573 			plog(LLV_ERROR, LOCATION, NULL,
   3574 				 "pfkey spddelete(forward) failed.\n");
   3575 		}else{
   3576 			plog(LLV_DEBUG, LOCATION, NULL,
   3577 				 "pfkey spddelete(forward) sent.\n");
   3578 		}
   3579 	}
   3580 #endif
   3581 
   3582 	/* make outbound policy */
   3583 	iph2->src = src;
   3584 	iph2->dst = dst;
   3585 	spidx.dir = IPSEC_DIR_OUTBOUND;
   3586 	addr = spidx.src;
   3587 	spidx.src = spidx.dst;
   3588 	spidx.dst = addr;
   3589 	pref = spidx.prefs;
   3590 	spidx.prefs = spidx.prefd;
   3591 	spidx.prefd = pref;
   3592 
   3593 	if (pk_sendspddelete(iph2) < 0) {
   3594 		plog(LLV_ERROR, LOCATION, NULL,
   3595 			 "pfkey spddelete(outbound) failed.\n");
   3596 	}else{
   3597 		plog(LLV_DEBUG, LOCATION, NULL,
   3598 			 "pfkey spddelete(outbound) sent.\n");
   3599 	}
   3600 purge:
   3601 	iph2->spidx_gen=NULL;
   3602 }
   3603 
   3604 
   3605 #ifdef INET6
   3606 u_int32_t
   3607 setscopeid(sp_addr0, sa_addr0)
   3608 	struct sockaddr *sp_addr0, *sa_addr0;
   3609 {
   3610 	struct sockaddr_in6 *sp_addr, *sa_addr;
   3611 
   3612 	sp_addr = (struct sockaddr_in6 *)sp_addr0;
   3613 	sa_addr = (struct sockaddr_in6 *)sa_addr0;
   3614 
   3615 	if (!IN6_IS_ADDR_LINKLOCAL(&sp_addr->sin6_addr)
   3616 	 && !IN6_IS_ADDR_SITELOCAL(&sp_addr->sin6_addr)
   3617 	 && !IN6_IS_ADDR_MULTICAST(&sp_addr->sin6_addr))
   3618 		return 0;
   3619 
   3620 	/* this check should not be here ? */
   3621 	if (sa_addr->sin6_family != AF_INET6) {
   3622 		plog(LLV_ERROR, LOCATION, NULL,
   3623 			"can't get scope ID: family mismatch\n");
   3624 		return -1;
   3625 	}
   3626 
   3627 	if (!IN6_IS_ADDR_LINKLOCAL(&sa_addr->sin6_addr)) {
   3628 		plog(LLV_ERROR, LOCATION, NULL,
   3629 			"scope ID is not supported except of lladdr.\n");
   3630 		return -1;
   3631 	}
   3632 
   3633 	sp_addr->sin6_scope_id = sa_addr->sin6_scope_id;
   3634 
   3635 	return 0;
   3636 }
   3637 #endif
   3638