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#ifdef ANDROID_CHANGES
120#define __linux
121#endif
122# endif /* __linux__ */
123# if defined(__NetBSD__) || defined(__FreeBSD__) ||	\
124  (defined(__APPLE__) && defined(__MACH__))
125#  include <netinet/in.h>
126#  include <netinet/udp.h>
127#  include <netinet/in_systm.h>
128#  include <netinet/ip.h>
129#  define SOL_UDP IPPROTO_UDP
130# endif /* __NetBSD__ / __FreeBSD__ */
131
132static int nostate1 __P((struct ph1handle *, vchar_t *));
133static int nostate2 __P((struct ph2handle *, vchar_t *));
134
135extern caddr_t val2str(const char *, size_t);
136
137static 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
164static 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
177static u_char r_ck0[] = { 0,0,0,0,0,0,0,0 }; /* used to verify the r_ck. */
178
179static int isakmp_main __P((vchar_t *, struct sockaddr *, struct sockaddr *));
180static int ph1_main __P((struct ph1handle *, vchar_t *));
181static int quick_main __P((struct ph2handle *, vchar_t *));
182static int isakmp_ph1begin_r __P((vchar_t *,
183	struct sockaddr *, struct sockaddr *, u_int8_t));
184static int isakmp_ph2begin_i __P((struct ph1handle *, struct ph2handle *));
185static int isakmp_ph2begin_r __P((struct ph1handle *, vchar_t *));
186static int etypesw1 __P((int));
187static int etypesw2 __P((int));
188#ifdef ENABLE_FRAG
189static int frag_handler(struct ph1handle *,
190    vchar_t *, struct sockaddr *, struct sockaddr *);
191#endif
192
193/*
194 * isakmp packet handler
195 */
196int
197isakmp_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
384end:
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 */
396static int
397isakmp_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 */
775static int
776ph1_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 */
944static int
945quick_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 */
1021int
1022isakmp_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 */
1116static int
1117isakmp_ph1begin_r(msg, remote, local, etype)
1118	vchar_t *msg;
1119	struct sockaddr *remote, *local;
1120	u_int8_t etype;
1121{
1122	struct isakmp *isakmp = (struct isakmp *)msg->v;
1123	struct remoteconf *rmconf;
1124	struct ph1handle *iph1;
1125	struct etypes *etypeok;
1126#ifdef ENABLE_STATS
1127	struct timeval start, end;
1128#endif
1129
1130	/* look for my configuration */
1131	rmconf = getrmconf(remote);
1132	if (rmconf == NULL) {
1133		plog(LLV_ERROR, LOCATION, remote,
1134			"couldn't find "
1135			"configuration.\n");
1136		return -1;
1137	}
1138
1139	/* check to be acceptable exchange type */
1140	etypeok = check_etypeok(rmconf, etype);
1141	if (etypeok == NULL) {
1142		plog(LLV_ERROR, LOCATION, remote,
1143			"not acceptable %s mode\n", s_isakmp_etype(etype));
1144		return -1;
1145	}
1146
1147	/* get new entry to isakmp status table. */
1148	iph1 = newph1();
1149	if (iph1 == NULL)
1150		return -1;
1151
1152	memcpy(&iph1->index.i_ck, &isakmp->i_ck, sizeof(iph1->index.i_ck));
1153	iph1->status = PHASE1ST_START;
1154	iph1->rmconf = rmconf;
1155	iph1->flags = 0;
1156	iph1->side = RESPONDER;
1157	iph1->etype = etypeok->type;
1158	iph1->version = isakmp->v;
1159	iph1->msgid = 0;
1160#ifdef HAVE_GSSAPI
1161	iph1->gssapi_state = NULL;
1162#endif
1163#ifdef ENABLE_HYBRID
1164	if ((iph1->mode_cfg = isakmp_cfg_mkstate()) == NULL) {
1165		delph1(iph1);
1166		return -1;
1167	}
1168#endif
1169#ifdef ENABLE_FRAG
1170	iph1->frag = 0;
1171	iph1->frag_chain = NULL;
1172#endif
1173	iph1->approval = NULL;
1174
1175#ifdef ENABLE_NATT
1176	/* RFC3947 says that we MUST accept new phases1 on NAT-T floated port.
1177	 * We have to setup this flag now to correctly generate the first reply.
1178	 * Don't know if a better check could be done for that ?
1179	 */
1180	if(extract_port(local) == lcconf->port_isakmp_natt)
1181		iph1->natt_flags |= (NAT_PORTS_CHANGED);
1182#endif
1183
1184	/* copy remote address */
1185	if (copy_ph1addresses(iph1, rmconf, remote, local) < 0) {
1186		delph1(iph1);
1187		return -1;
1188	}
1189	(void)insph1(iph1);
1190
1191	plog(LLV_DEBUG, LOCATION, NULL, "===\n");
1192    {
1193	char *a;
1194
1195	a = racoon_strdup(saddr2str(iph1->local));
1196	STRDUP_FATAL(a);
1197
1198	plog(LLV_INFO, LOCATION, NULL,
1199		"respond new phase 1 negotiation: %s<=>%s\n",
1200		a, saddr2str(iph1->remote));
1201	racoon_free(a);
1202    }
1203	plog(LLV_INFO, LOCATION, NULL,
1204		"begin %s mode.\n", s_isakmp_etype(etype));
1205
1206#ifdef ENABLE_STATS
1207	gettimeofday(&iph1->start, NULL);
1208	gettimeofday(&start, NULL);
1209#endif
1210
1211#ifndef ENABLE_FRAG
1212
1213	/* start exchange */
1214	if ((ph1exchange[etypesw1(iph1->etype)]
1215	                [iph1->side]
1216	                [iph1->status])(iph1, msg) < 0
1217	 || (ph1exchange[etypesw1(iph1->etype)]
1218			[iph1->side]
1219			[iph1->status])(iph1, msg) < 0) {
1220		plog(LLV_ERROR, LOCATION, remote,
1221			"failed to process packet.\n");
1222		remph1(iph1);
1223		delph1(iph1);
1224		return -1;
1225	}
1226
1227#ifdef ENABLE_STATS
1228	gettimeofday(&end, NULL);
1229	syslog(LOG_NOTICE, "%s(%s): %8.6f",
1230		"phase1",
1231		s_isakmp_state(iph1->etype, iph1->side, iph1->status),
1232		timedelta(&start, &end));
1233#endif
1234
1235	return 0;
1236
1237#else /* ENABLE_FRAG */
1238
1239	/* now that we have a phase1 handle, feed back into our
1240	 * main receive function to catch fragmented packets
1241	 */
1242
1243	return isakmp_main(msg, remote, local);
1244
1245#endif /* ENABLE_FRAG */
1246
1247}
1248
1249/* new negotiation of phase 2 for initiator */
1250static int
1251isakmp_ph2begin_i(iph1, iph2)
1252	struct ph1handle *iph1;
1253	struct ph2handle *iph2;
1254{
1255#ifdef ENABLE_HYBRID
1256	if (xauth_check(iph1) != 0) {
1257		plog(LLV_ERROR, LOCATION, NULL,
1258		    "Attempt to start phase 2 whereas Xauth failed\n");
1259		return -1;
1260	}
1261#endif
1262
1263	/* found ISAKMP-SA. */
1264	plog(LLV_DEBUG, LOCATION, NULL, "===\n");
1265	plog(LLV_DEBUG, LOCATION, NULL, "begin QUICK mode.\n");
1266    {
1267	char *a;
1268	a = racoon_strdup(saddr2str(iph2->src));
1269	STRDUP_FATAL(a);
1270
1271	plog(LLV_INFO, LOCATION, NULL,
1272		"initiate new phase 2 negotiation: %s<=>%s\n",
1273		a, saddr2str(iph2->dst));
1274	racoon_free(a);
1275    }
1276
1277#ifdef ENABLE_STATS
1278	gettimeofday(&iph2->start, NULL);
1279#endif
1280	/* found isakmp-sa */
1281	bindph12(iph1, iph2);
1282	iph2->status = PHASE2ST_STATUS2;
1283
1284	if ((ph2exchange[etypesw2(ISAKMP_ETYPE_QUICK)]
1285			 [iph2->side]
1286			 [iph2->status])(iph2, NULL) < 0) {
1287		unbindph12(iph2);
1288		/* release ipsecsa handler due to internal error. */
1289		remph2(iph2);
1290		return -1;
1291	}
1292	return 0;
1293}
1294
1295/* new negotiation of phase 2 for responder */
1296static int
1297isakmp_ph2begin_r(iph1, msg)
1298	struct ph1handle *iph1;
1299	vchar_t *msg;
1300{
1301	struct isakmp *isakmp = (struct isakmp *)msg->v;
1302	struct ph2handle *iph2 = 0;
1303	int error;
1304#ifdef ENABLE_STATS
1305	struct timeval start, end;
1306#endif
1307#ifdef ENABLE_HYBRID
1308	if (xauth_check(iph1) != 0) {
1309		plog(LLV_ERROR, LOCATION, NULL,
1310		    "Attempt to start phase 2 whereas Xauth failed\n");
1311		return -1;
1312	}
1313#endif
1314
1315	iph2 = newph2();
1316	if (iph2 == NULL) {
1317		plog(LLV_ERROR, LOCATION, NULL,
1318			"failed to allocate phase2 entry.\n");
1319		return -1;
1320	}
1321
1322	iph2->ph1 = iph1;
1323	iph2->side = RESPONDER;
1324	iph2->status = PHASE2ST_START;
1325	iph2->flags = isakmp->flags;
1326	iph2->msgid = isakmp->msgid;
1327	iph2->seq = pk_getseq();
1328	iph2->ivm = oakley_newiv2(iph1, iph2->msgid);
1329	if (iph2->ivm == NULL) {
1330		delph2(iph2);
1331		return -1;
1332	}
1333	iph2->dst = dupsaddr(iph1->remote);	/* XXX should be considered */
1334	if (iph2->dst == NULL) {
1335		delph2(iph2);
1336		return -1;
1337	}
1338	iph2->src = dupsaddr(iph1->local);	/* XXX should be considered */
1339	if (iph2->src == NULL) {
1340		delph2(iph2);
1341		return -1;
1342	}
1343#if (!defined(ENABLE_NATT)) || (defined(BROKEN_NATT))
1344	if (set_port(iph2->dst, 0) == NULL ||
1345	    set_port(iph2->src, 0) == NULL) {
1346		plog(LLV_ERROR, LOCATION, NULL,
1347		     "invalid family: %d\n", iph2->dst->sa_family);
1348		delph2(iph2);
1349		return -1;
1350	}
1351#endif
1352
1353	/* add new entry to isakmp status table */
1354	insph2(iph2);
1355	bindph12(iph1, iph2);
1356
1357	plog(LLV_DEBUG, LOCATION, NULL, "===\n");
1358    {
1359	char *a;
1360
1361	a = racoon_strdup(saddr2str(iph2->src));
1362	STRDUP_FATAL(a);
1363
1364	plog(LLV_INFO, LOCATION, NULL,
1365		"respond new phase 2 negotiation: %s<=>%s\n",
1366		a, saddr2str(iph2->dst));
1367	racoon_free(a);
1368    }
1369
1370#ifdef ENABLE_STATS
1371	gettimeofday(&start, NULL);
1372#endif
1373
1374	error = (ph2exchange[etypesw2(ISAKMP_ETYPE_QUICK)]
1375	                   [iph2->side]
1376	                   [iph2->status])(iph2, msg);
1377	if (error != 0) {
1378		plog(LLV_ERROR, LOCATION, iph1->remote,
1379			"failed to pre-process packet.\n");
1380		if (error != ISAKMP_INTERNAL_ERROR)
1381			isakmp_info_send_n1(iph2->ph1, error, NULL);
1382		/*
1383		 * release handler because it's wrong that ph2handle is kept
1384		 * after failed to check message for responder's.
1385		 */
1386		unbindph12(iph2);
1387		remph2(iph2);
1388		delph2(iph2);
1389		return -1;
1390	}
1391
1392	/* send */
1393	plog(LLV_DEBUG, LOCATION, NULL, "===\n");
1394	if ((ph2exchange[etypesw2(isakmp->etype)]
1395			[iph2->side]
1396			[iph2->status])(iph2, msg) < 0) {
1397		plog(LLV_ERROR, LOCATION, iph2->ph1->remote,
1398			"failed to process packet.\n");
1399		/* don't release handler */
1400		return -1;
1401	}
1402#ifdef ENABLE_STATS
1403	gettimeofday(&end, NULL);
1404	syslog(LOG_NOTICE, "%s(%s): %8.6f",
1405		"phase2",
1406		s_isakmp_state(ISAKMP_ETYPE_QUICK, iph2->side, iph2->status),
1407		timedelta(&start, &end));
1408#endif
1409
1410	return 0;
1411}
1412
1413/*
1414 * parse ISAKMP payloads, without ISAKMP base header.
1415 */
1416vchar_t *
1417isakmp_parsewoh(np0, gen, len)
1418	int np0;
1419	struct isakmp_gen *gen;
1420	int len;
1421{
1422	u_char np = np0 & 0xff;
1423	int tlen, plen;
1424	vchar_t *result;
1425	struct isakmp_parse_t *p, *ep;
1426
1427	plog(LLV_DEBUG, LOCATION, NULL, "begin.\n");
1428
1429	/*
1430	 * 5 is a magic number, but any value larger than 2 should be fine
1431	 * as we do vrealloc() in the following loop.
1432	 */
1433	result = vmalloc(sizeof(struct isakmp_parse_t) * 5);
1434	if (result == NULL) {
1435		plog(LLV_ERROR, LOCATION, NULL,
1436			"failed to get buffer.\n");
1437		return NULL;
1438	}
1439	p = (struct isakmp_parse_t *)result->v;
1440	ep = (struct isakmp_parse_t *)(result->v + result->l - sizeof(*ep));
1441
1442	tlen = len;
1443
1444	/* parse through general headers */
1445	while (0 < tlen && np != ISAKMP_NPTYPE_NONE) {
1446		if (tlen <= sizeof(struct isakmp_gen)) {
1447			/* don't send information, see isakmp_ident_r1() */
1448			plog(LLV_ERROR, LOCATION, NULL,
1449				"invalid length of payload\n");
1450			vfree(result);
1451			return NULL;
1452		}
1453
1454		plog(LLV_DEBUG, LOCATION, NULL,
1455			"seen nptype=%u(%s)\n", np, s_isakmp_nptype(np));
1456
1457		p->type = np;
1458		p->len = ntohs(gen->len);
1459		if (p->len < sizeof(struct isakmp_gen) || p->len > tlen) {
1460			plog(LLV_DEBUG, LOCATION, NULL,
1461				"invalid length of payload\n");
1462			vfree(result);
1463			return NULL;
1464		}
1465		p->ptr = gen;
1466		p++;
1467		if (ep <= p) {
1468			int off;
1469
1470			off = p - (struct isakmp_parse_t *)result->v;
1471			result = vrealloc(result, result->l * 2);
1472			if (result == NULL) {
1473				plog(LLV_DEBUG, LOCATION, NULL,
1474					"failed to realloc buffer.\n");
1475				vfree(result);
1476				return NULL;
1477			}
1478			ep = (struct isakmp_parse_t *)
1479				(result->v + result->l - sizeof(*ep));
1480			p = (struct isakmp_parse_t *)result->v;
1481			p += off;
1482		}
1483
1484		np = gen->np;
1485		plen = ntohs(gen->len);
1486		gen = (struct isakmp_gen *)((caddr_t)gen + plen);
1487		tlen -= plen;
1488	}
1489	p->type = ISAKMP_NPTYPE_NONE;
1490	p->len = 0;
1491	p->ptr = NULL;
1492
1493	plog(LLV_DEBUG, LOCATION, NULL, "succeed.\n");
1494
1495	return result;
1496}
1497
1498/*
1499 * parse ISAKMP payloads, including ISAKMP base header.
1500 */
1501vchar_t *
1502isakmp_parse(buf)
1503	vchar_t *buf;
1504{
1505	struct isakmp *isakmp = (struct isakmp *)buf->v;
1506	struct isakmp_gen *gen;
1507	int tlen;
1508	vchar_t *result;
1509	u_char np;
1510
1511	np = isakmp->np;
1512	gen = (struct isakmp_gen *)(buf->v + sizeof(*isakmp));
1513	tlen = buf->l - sizeof(struct isakmp);
1514	result = isakmp_parsewoh(np, gen, tlen);
1515
1516	return result;
1517}
1518
1519/* %%% */
1520int
1521isakmp_init()
1522{
1523	/* initialize a isakmp status table */
1524	initph1tree();
1525	initph2tree();
1526	initctdtree();
1527	init_recvdpkt();
1528
1529	if (isakmp_open() < 0)
1530		goto err;
1531
1532	return(0);
1533
1534err:
1535	isakmp_close();
1536	return(-1);
1537}
1538
1539/*
1540 * make strings containing i_cookie + r_cookie + msgid
1541 */
1542const char *
1543isakmp_pindex(index, msgid)
1544	const isakmp_index *index;
1545	const u_int32_t msgid;
1546{
1547	static char buf[64];
1548	const u_char *p;
1549	int i, j;
1550
1551	memset(buf, 0, sizeof(buf));
1552
1553	/* copy index */
1554	p = (const u_char *)index;
1555	for (j = 0, i = 0; i < sizeof(isakmp_index); i++) {
1556		snprintf((char *)&buf[j], sizeof(buf) - j, "%02x", p[i]);
1557		j += 2;
1558		switch (i) {
1559		case 7:
1560			buf[j++] = ':';
1561		}
1562	}
1563
1564	if (msgid == 0)
1565		return buf;
1566
1567	/* copy msgid */
1568	snprintf((char *)&buf[j], sizeof(buf) - j, ":%08x", ntohs(msgid));
1569
1570	return buf;
1571}
1572
1573/* open ISAKMP sockets. */
1574int
1575isakmp_open()
1576{
1577	const int yes = 1;
1578	int ifnum = 0, encap_ifnum = 0;
1579#ifdef INET6
1580	int pktinfo;
1581#endif
1582	struct myaddrs *p;
1583
1584	for (p = lcconf->myaddrs; p; p = p->next) {
1585		if (!p->addr)
1586			continue;
1587
1588		/* warn if wildcard address - should we forbid this? */
1589		switch (p->addr->sa_family) {
1590		case AF_INET:
1591			if (((struct sockaddr_in *)p->addr)->sin_addr.s_addr == 0)
1592				plog(LLV_WARNING, LOCATION, NULL,
1593					"listening to wildcard address,"
1594					"broadcast IKE packet may kill you\n");
1595			break;
1596#ifdef INET6
1597		case AF_INET6:
1598			if (IN6_IS_ADDR_UNSPECIFIED(&((struct sockaddr_in6 *)p->addr)->sin6_addr))
1599				plog(LLV_WARNING, LOCATION, NULL,
1600					"listening to wildcard address, "
1601					"broadcast IKE packet may kill you\n");
1602			break;
1603#endif
1604		default:
1605			plog(LLV_ERROR, LOCATION, NULL,
1606				"unsupported address family %d\n",
1607				lcconf->default_af);
1608			goto err_and_next;
1609		}
1610
1611#ifdef INET6
1612		if (p->addr->sa_family == AF_INET6 &&
1613		    IN6_IS_ADDR_MULTICAST(&((struct sockaddr_in6 *)
1614					    p->addr)->sin6_addr))
1615		{
1616			plog(LLV_DEBUG, LOCATION, NULL,
1617				"Ignoring multicast address %s\n",
1618				saddr2str(p->addr));
1619				racoon_free(p->addr);
1620				p->addr = NULL;
1621			continue;
1622		}
1623#endif
1624
1625		if ((p->sock = socket(p->addr->sa_family, SOCK_DGRAM, 0)) < 0) {
1626			plog(LLV_ERROR, LOCATION, NULL,
1627				"socket (%s)\n", strerror(errno));
1628			goto err_and_next;
1629		}
1630
1631		if (fcntl(p->sock, F_SETFL, O_NONBLOCK) == -1)
1632			plog(LLV_WARNING, LOCATION, NULL,
1633				"failed to put socket in non-blocking mode\n");
1634
1635		/* receive my interface address on inbound packets. */
1636		switch (p->addr->sa_family) {
1637		case AF_INET:
1638			if (setsockopt(p->sock, IPPROTO_IP,
1639#ifdef __linux__
1640				       IP_PKTINFO,
1641#else
1642				       IP_RECVDSTADDR,
1643#endif
1644					(const void *)&yes, sizeof(yes)) < 0) {
1645				plog(LLV_ERROR, LOCATION, NULL,
1646					"setsockopt IP_RECVDSTADDR (%s)\n",
1647					strerror(errno));
1648				goto err_and_next;
1649			}
1650			break;
1651#ifdef INET6
1652		case AF_INET6:
1653#ifdef INET6_ADVAPI
1654#ifdef IPV6_RECVPKTINFO
1655			pktinfo = IPV6_RECVPKTINFO;
1656#else  /* old adv. API */
1657			pktinfo = IPV6_PKTINFO;
1658#endif /* IPV6_RECVPKTINFO */
1659#else
1660			pktinfo = IPV6_RECVDSTADDR;
1661#endif
1662			if (setsockopt(p->sock, IPPROTO_IPV6, pktinfo,
1663					(const void *)&yes, sizeof(yes)) < 0)
1664			{
1665				plog(LLV_ERROR, LOCATION, NULL,
1666					"setsockopt IPV6_RECVDSTADDR (%d):%s\n",
1667					pktinfo, strerror(errno));
1668				goto err_and_next;
1669			}
1670			break;
1671#endif
1672		}
1673
1674#ifdef IPV6_USE_MIN_MTU
1675		if (p->addr->sa_family == AF_INET6 &&
1676		    setsockopt(p->sock, IPPROTO_IPV6, IPV6_USE_MIN_MTU,
1677		    (void *)&yes, sizeof(yes)) < 0) {
1678			plog(LLV_ERROR, LOCATION, NULL,
1679			    "setsockopt IPV6_USE_MIN_MTU (%s)\n",
1680			    strerror(errno));
1681			return -1;
1682		}
1683#endif
1684
1685		if (setsockopt_bypass(p->sock, p->addr->sa_family) < 0)
1686			goto err_and_next;
1687
1688		if (bind(p->sock, p->addr, sysdep_sa_len(p->addr)) < 0) {
1689			plog(LLV_ERROR, LOCATION, p->addr,
1690				"failed to bind to address %s (%s).\n",
1691				saddr2str(p->addr), strerror(errno));
1692			close(p->sock);
1693			goto err_and_next;
1694		}
1695
1696		ifnum++;
1697
1698		plog(LLV_INFO, LOCATION, NULL,
1699			"%s used as isakmp port (fd=%d)\n",
1700			saddr2str(p->addr), p->sock);
1701
1702#ifdef ENABLE_NATT
1703		if (p->addr->sa_family == AF_INET) {
1704			int option = -1;
1705
1706
1707			if(p->udp_encap)
1708				option = UDP_ENCAP_ESPINUDP;
1709#if defined(ENABLE_NATT_00) || defined(ENABLE_NATT_01)
1710			else
1711				option = UDP_ENCAP_ESPINUDP_NON_IKE;
1712#endif
1713			if(option != -1){
1714				if (setsockopt (p->sock, SOL_UDP,
1715				    UDP_ENCAP, &option, sizeof (option)) < 0) {
1716					plog(LLV_WARNING, LOCATION, NULL,
1717					    "setsockopt(%s): UDP_ENCAP %s\n",
1718					    option == UDP_ENCAP_ESPINUDP ? "UDP_ENCAP_ESPINUDP" : "UDP_ENCAP_ESPINUDP_NON_IKE",
1719						 strerror(errno));
1720					goto skip_encap;
1721				}
1722				else {
1723					plog(LLV_INFO, LOCATION, NULL,
1724						 "%s used for NAT-T\n",
1725						 saddr2str(p->addr));
1726					encap_ifnum++;
1727				}
1728			}
1729		}
1730skip_encap:
1731#endif
1732		continue;
1733
1734	err_and_next:
1735		racoon_free(p->addr);
1736		p->addr = NULL;
1737		if (! lcconf->autograbaddr && lcconf->strict_address)
1738			return -1;
1739		continue;
1740	}
1741
1742	if (!ifnum) {
1743		plog(LLV_ERROR, LOCATION, NULL,
1744			"no address could be bound.\n");
1745		return -1;
1746	}
1747
1748#ifdef ENABLE_NATT
1749	if (natt_enabled_in_rmconf() && !encap_ifnum) {
1750		plog(LLV_WARNING, LOCATION, NULL,
1751			"NAT-T is enabled in at least one remote{} section,\n");
1752		plog(LLV_WARNING, LOCATION, NULL,
1753			"but no 'isakmp_natt' address was specified!\n");
1754	}
1755#endif
1756
1757	return 0;
1758}
1759
1760void
1761isakmp_close()
1762{
1763#ifndef ANDROID_PATCHED
1764	struct myaddrs *p, *next;
1765
1766	for (p = lcconf->myaddrs; p; p = next) {
1767		next = p->next;
1768
1769		if (!p->addr) {
1770			racoon_free(p);
1771			continue;
1772		}
1773		close(p->sock);
1774		racoon_free(p->addr);
1775		racoon_free(p);
1776	}
1777
1778	lcconf->myaddrs = NULL;
1779#endif
1780}
1781
1782int
1783isakmp_send(iph1, sbuf)
1784	struct ph1handle *iph1;
1785	vchar_t *sbuf;
1786{
1787	int len = 0;
1788	int s;
1789	vchar_t *vbuf = NULL, swap;
1790
1791#ifdef ENABLE_NATT
1792	size_t extralen = NON_ESP_MARKER_USE(iph1) ? NON_ESP_MARKER_LEN : 0;
1793
1794	/* Check if NON_ESP_MARKER_LEN is already there (happens when resending packets)
1795	 */
1796	if(extralen == NON_ESP_MARKER_LEN &&
1797	   *(u_int32_t *)sbuf->v == 0)
1798		extralen = 0;
1799
1800#ifdef ENABLE_FRAG
1801	/*
1802	 * Do not add the non ESP marker for a packet that will
1803	 * be fragmented. The non ESP marker should appear in
1804	 * all fragment's packets, but not in the fragmented packet
1805	 */
1806	if (iph1->frag && sbuf->l > ISAKMP_FRAG_MAXLEN)
1807		extralen = 0;
1808#endif
1809	if (extralen)
1810		plog (LLV_DEBUG, LOCATION, NULL, "Adding NON-ESP marker\n");
1811
1812	/* If NAT-T port floating is in use, 4 zero bytes (non-ESP marker)
1813	   must added just before the packet itself. For this we must
1814	   allocate a new buffer and release it at the end. */
1815	if (extralen) {
1816		if ((vbuf = vmalloc (sbuf->l + extralen)) == NULL) {
1817			plog(LLV_ERROR, LOCATION, NULL,
1818			    "vbuf allocation failed\n");
1819			return -1;
1820		}
1821		*(u_int32_t *)vbuf->v = 0;
1822		memcpy (vbuf->v + extralen, sbuf->v, sbuf->l);
1823		/* ensures that the modified buffer will be sent back to the caller, so
1824		 * add_recvdpkt() will add the correct buffer
1825		 */
1826		swap = *sbuf;
1827		*sbuf = *vbuf;
1828		*vbuf = swap;
1829		vfree(vbuf);
1830	}
1831#endif
1832
1833	/* select the socket to be sent */
1834	s = getsockmyaddr(iph1->local);
1835	if (s == -1){
1836		return -1;
1837	}
1838
1839	plog (LLV_DEBUG, LOCATION, NULL, "%zu bytes %s\n", sbuf->l,
1840	      saddr2str_fromto("from %s to %s", iph1->local, iph1->remote));
1841
1842#ifdef ENABLE_FRAG
1843	if (iph1->frag && sbuf->l > ISAKMP_FRAG_MAXLEN) {
1844		if (isakmp_sendfrags(iph1, sbuf) == -1) {
1845			plog(LLV_ERROR, LOCATION, NULL,
1846			    "isakmp_sendfrags failed\n");
1847			return -1;
1848		}
1849	} else
1850#endif
1851	{
1852		len = sendfromto(s, sbuf->v, sbuf->l,
1853		    iph1->local, iph1->remote, lcconf->count_persend);
1854
1855		if (len == -1) {
1856			plog(LLV_ERROR, LOCATION, NULL, "sendfromto failed\n");
1857			return -1;
1858		}
1859	}
1860
1861	return 0;
1862}
1863
1864/* called from scheduler */
1865void
1866isakmp_ph1resend_stub(p)
1867	void *p;
1868{
1869	struct ph1handle *iph1;
1870
1871	iph1=(struct ph1handle *)p;
1872	if(isakmp_ph1resend(iph1) < 0){
1873		if(iph1->scr != NULL){
1874			/* Should not happen...
1875			 */
1876			sched_kill(iph1->scr);
1877			iph1->scr=NULL;
1878		}
1879
1880		remph1(iph1);
1881		delph1(iph1);
1882	}
1883}
1884
1885int
1886isakmp_ph1resend(iph1)
1887	struct ph1handle *iph1;
1888{
1889	/* Note: NEVER do the rem/del here, it will be done by the caller or by the _stub function
1890	 */
1891	if (iph1->retry_counter <= 0) {
1892		plog(LLV_ERROR, LOCATION, NULL,
1893			"phase1 negotiation failed due to time up. %s\n",
1894			isakmp_pindex(&iph1->index, iph1->msgid));
1895		EVT_PUSH(iph1->local, iph1->remote,
1896		    EVTT_PEER_NO_RESPONSE, NULL);
1897
1898		return -1;
1899	}
1900
1901	if (isakmp_send(iph1, iph1->sendbuf) < 0){
1902		plog(LLV_ERROR, LOCATION, NULL,
1903			 "phase1 negotiation failed due to send error. %s\n",
1904			 isakmp_pindex(&iph1->index, iph1->msgid));
1905		EVT_PUSH(iph1->local, iph1->remote,
1906				 EVTT_PEER_NO_RESPONSE, NULL);
1907		return -1;
1908	}
1909
1910	plog(LLV_DEBUG, LOCATION, NULL,
1911		"resend phase1 packet %s\n",
1912		isakmp_pindex(&iph1->index, iph1->msgid));
1913
1914	iph1->retry_counter--;
1915
1916	iph1->scr = sched_new(iph1->rmconf->retry_interval,
1917		isakmp_ph1resend_stub, iph1);
1918
1919	return 0;
1920}
1921
1922/* called from scheduler */
1923void
1924isakmp_ph2resend_stub(p)
1925	void *p;
1926{
1927	struct ph2handle *iph2;
1928
1929	iph2=(struct ph2handle *)p;
1930
1931	if(isakmp_ph2resend(iph2) < 0){
1932		unbindph12(iph2);
1933		remph2(iph2);
1934		delph2(iph2);
1935	}
1936}
1937
1938int
1939isakmp_ph2resend(iph2)
1940	struct ph2handle *iph2;
1941{
1942	/* Note: NEVER do the unbind/rem/del here, it will be done by the caller or by the _stub function
1943	 */
1944	if (iph2->ph1->status == PHASE1ST_EXPIRED){
1945		plog(LLV_ERROR, LOCATION, NULL,
1946			"phase2 negotiation failed due to phase1 expired. %s\n",
1947				isakmp_pindex(&iph2->ph1->index, iph2->msgid));
1948		return -1;
1949	}
1950
1951	if (iph2->retry_counter <= 0) {
1952		plog(LLV_ERROR, LOCATION, NULL,
1953			"phase2 negotiation failed due to time up. %s\n",
1954				isakmp_pindex(&iph2->ph1->index, iph2->msgid));
1955		EVT_PUSH(iph2->src, iph2->dst, EVTT_PEER_NO_RESPONSE, NULL);
1956		unbindph12(iph2);
1957		return -1;
1958	}
1959
1960	if (isakmp_send(iph2->ph1, iph2->sendbuf) < 0){
1961		plog(LLV_ERROR, LOCATION, NULL,
1962			"phase2 negotiation failed due to send error. %s\n",
1963				isakmp_pindex(&iph2->ph1->index, iph2->msgid));
1964		EVT_PUSH(iph2->src, iph2->dst, EVTT_PEER_NO_RESPONSE, NULL);
1965
1966		return -1;
1967	}
1968
1969	plog(LLV_DEBUG, LOCATION, NULL,
1970		"resend phase2 packet %s\n",
1971		isakmp_pindex(&iph2->ph1->index, iph2->msgid));
1972
1973	iph2->retry_counter--;
1974
1975	iph2->scr = sched_new(iph2->ph1->rmconf->retry_interval,
1976		isakmp_ph2resend_stub, iph2);
1977
1978	return 0;
1979}
1980
1981/* called from scheduler */
1982void
1983isakmp_ph1expire_stub(p)
1984	void *p;
1985{
1986
1987	isakmp_ph1expire((struct ph1handle *)p);
1988}
1989
1990void
1991isakmp_ph1expire(iph1)
1992	struct ph1handle *iph1;
1993{
1994	char *src, *dst;
1995
1996	SCHED_KILL(iph1->sce);
1997
1998	if(iph1->status != PHASE1ST_EXPIRED){
1999		src = racoon_strdup(saddr2str(iph1->local));
2000		dst = racoon_strdup(saddr2str(iph1->remote));
2001		STRDUP_FATAL(src);
2002		STRDUP_FATAL(dst);
2003
2004		plog(LLV_INFO, LOCATION, NULL,
2005			 "ISAKMP-SA expired %s-%s spi:%s\n",
2006			 src, dst,
2007			 isakmp_pindex(&iph1->index, 0));
2008		racoon_free(src);
2009		racoon_free(dst);
2010		iph1->status = PHASE1ST_EXPIRED;
2011	}
2012
2013	/*
2014	 * the phase1 deletion is postponed until there is no phase2.
2015	 */
2016	if (LIST_FIRST(&iph1->ph2tree) != NULL) {
2017		iph1->sce = sched_new(1, isakmp_ph1expire_stub, iph1);
2018		return;
2019	}
2020
2021	iph1->sce = sched_new(1, isakmp_ph1delete_stub, iph1);
2022}
2023
2024/* called from scheduler */
2025void
2026isakmp_ph1delete_stub(p)
2027	void *p;
2028{
2029
2030	isakmp_ph1delete((struct ph1handle *)p);
2031}
2032
2033void
2034isakmp_ph1delete(iph1)
2035	struct ph1handle *iph1;
2036{
2037	char *src, *dst;
2038
2039	SCHED_KILL(iph1->sce);
2040
2041	if (LIST_FIRST(&iph1->ph2tree) != NULL) {
2042		iph1->sce = sched_new(1, isakmp_ph1delete_stub, iph1);
2043		return;
2044	}
2045
2046	/* don't re-negosiation when the phase 1 SA expires. */
2047
2048	src = racoon_strdup(saddr2str(iph1->local));
2049	dst = racoon_strdup(saddr2str(iph1->remote));
2050	STRDUP_FATAL(src);
2051	STRDUP_FATAL(dst);
2052
2053	plog(LLV_INFO, LOCATION, NULL,
2054		"ISAKMP-SA deleted %s-%s spi:%s\n",
2055		src, dst, isakmp_pindex(&iph1->index, 0));
2056	EVT_PUSH(iph1->local, iph1->remote, EVTT_PHASE1_DOWN, NULL);
2057	racoon_free(src);
2058	racoon_free(dst);
2059
2060	remph1(iph1);
2061	delph1(iph1);
2062
2063	return;
2064}
2065
2066/* called from scheduler.
2067 * this function will call only isakmp_ph2delete().
2068 * phase 2 handler remain forever if kernel doesn't cry a expire of phase 2 SA
2069 * by something cause.  That's why this function is called after phase 2 SA
2070 * expires in the userland.
2071 */
2072void
2073isakmp_ph2expire_stub(p)
2074	void *p;
2075{
2076
2077	isakmp_ph2expire((struct ph2handle *)p);
2078}
2079
2080void
2081isakmp_ph2expire(iph2)
2082	struct ph2handle *iph2;
2083{
2084	char *src, *dst;
2085
2086	SCHED_KILL(iph2->sce);
2087
2088	src = racoon_strdup(saddrwop2str(iph2->src));
2089	dst = racoon_strdup(saddrwop2str(iph2->dst));
2090	STRDUP_FATAL(src);
2091	STRDUP_FATAL(dst);
2092
2093	plog(LLV_INFO, LOCATION, NULL,
2094		"phase2 sa expired %s-%s\n", src, dst);
2095	racoon_free(src);
2096	racoon_free(dst);
2097
2098	iph2->status = PHASE2ST_EXPIRED;
2099
2100	iph2->sce = sched_new(1, isakmp_ph2delete_stub, iph2);
2101
2102	return;
2103}
2104
2105/* called from scheduler */
2106void
2107isakmp_ph2delete_stub(p)
2108	void *p;
2109{
2110
2111	isakmp_ph2delete((struct ph2handle *)p);
2112}
2113
2114void
2115isakmp_ph2delete(iph2)
2116	struct ph2handle *iph2;
2117{
2118	char *src, *dst;
2119
2120	SCHED_KILL(iph2->sce);
2121
2122	src = racoon_strdup(saddrwop2str(iph2->src));
2123	dst = racoon_strdup(saddrwop2str(iph2->dst));
2124	STRDUP_FATAL(src);
2125	STRDUP_FATAL(dst);
2126
2127	plog(LLV_INFO, LOCATION, NULL,
2128		"phase2 sa deleted %s-%s\n", src, dst);
2129	racoon_free(src);
2130	racoon_free(dst);
2131
2132	unbindph12(iph2);
2133	remph2(iph2);
2134	delph2(iph2);
2135
2136	return;
2137}
2138
2139/* %%%
2140 * Interface between PF_KEYv2 and ISAKMP
2141 */
2142/*
2143 * receive ACQUIRE from kernel, and begin either phase1 or phase2.
2144 * if phase1 has been finished, begin phase2.
2145 */
2146int
2147isakmp_post_acquire(iph2)
2148	struct ph2handle *iph2;
2149{
2150	struct remoteconf *rmconf;
2151	struct ph1handle *iph1 = NULL;
2152
2153	plog(LLV_DEBUG, LOCATION, NULL, "in post_acquire\n");
2154
2155	/* search appropreate configuration with masking port. */
2156	rmconf = getrmconf(iph2->dst);
2157	if (rmconf == NULL) {
2158		plog(LLV_ERROR, LOCATION, NULL,
2159			"no configuration found for %s.\n",
2160			saddrwop2str(iph2->dst));
2161		return -1;
2162	}
2163
2164	/* if passive mode, ignore the acquire message */
2165	if (rmconf->passive) {
2166		plog(LLV_DEBUG, LOCATION, NULL,
2167			"because of passive mode, "
2168			"ignore the acquire message for %s.\n",
2169			saddrwop2str(iph2->dst));
2170		return 0;
2171	}
2172
2173	/*
2174	 * Search isakmp status table by address and port
2175	 * If NAT-T is in use, consider null ports as a
2176	 * wildcard and use IKE ports instead.
2177	 */
2178#ifdef ENABLE_NATT
2179	if (!extract_port(iph2->src) && !extract_port(iph2->dst)) {
2180		if ((iph1 = getph1byaddrwop(iph2->src, iph2->dst)) != NULL) {
2181			set_port(iph2->src, extract_port(iph1->local));
2182			set_port(iph2->dst, extract_port(iph1->remote));
2183		}
2184	} else {
2185		iph1 = getph1byaddr(iph2->src, iph2->dst, 0);
2186	}
2187#else
2188	iph1 = getph1byaddr(iph2->src, iph2->dst, 0);
2189#endif
2190
2191	/* no ISAKMP-SA found. */
2192	if (iph1 == NULL) {
2193		struct sched *sc;
2194
2195		iph2->retry_checkph1 = lcconf->retry_checkph1;
2196		sc = sched_new(1, isakmp_chkph1there_stub, iph2);
2197		plog(LLV_INFO, LOCATION, NULL,
2198			"IPsec-SA request for %s queued "
2199			"due to no phase1 found.\n",
2200			saddrwop2str(iph2->dst));
2201
2202		/* start phase 1 negotiation as a initiator. */
2203		if (isakmp_ph1begin_i(rmconf, iph2->dst, iph2->src) < 0) {
2204			SCHED_KILL(sc);
2205			return -1;
2206		}
2207
2208		return 0;
2209		/*NOTREACHED*/
2210	}
2211
2212	/* found ISAKMP-SA, but on negotiation. */
2213	if (iph1->status != PHASE1ST_ESTABLISHED) {
2214		iph2->retry_checkph1 = lcconf->retry_checkph1;
2215		sched_new(1, isakmp_chkph1there_stub, iph2);
2216		plog(LLV_INFO, LOCATION, iph2->dst,
2217			"request for establishing IPsec-SA was queued "
2218			"due to no phase1 found.\n");
2219		return 0;
2220		/*NOTREACHED*/
2221	}
2222
2223	/* found established ISAKMP-SA */
2224	/* i.e. iph1->status == PHASE1ST_ESTABLISHED */
2225
2226	/* found ISAKMP-SA. */
2227	plog(LLV_DEBUG, LOCATION, NULL, "begin QUICK mode.\n");
2228
2229	/* begin quick mode */
2230	if (isakmp_ph2begin_i(iph1, iph2))
2231		return -1;
2232
2233	return 0;
2234}
2235
2236/*
2237 * receive GETSPI from kernel.
2238 */
2239int
2240isakmp_post_getspi(iph2)
2241	struct ph2handle *iph2;
2242{
2243#ifdef ENABLE_STATS
2244	struct timeval start, end;
2245#endif
2246
2247	/* don't process it because there is no suitable phase1-sa. */
2248	if (iph2->ph1->status == PHASE1ST_EXPIRED) {
2249		plog(LLV_ERROR, LOCATION, iph2->ph1->remote,
2250			"the negotiation is stopped, "
2251			"because there is no suitable ISAKMP-SA.\n");
2252		return -1;
2253	}
2254
2255#ifdef ENABLE_STATS
2256	gettimeofday(&start, NULL);
2257#endif
2258	if ((ph2exchange[etypesw2(ISAKMP_ETYPE_QUICK)]
2259	                [iph2->side]
2260	                [iph2->status])(iph2, NULL) != 0)
2261		return -1;
2262#ifdef ENABLE_STATS
2263	gettimeofday(&end, NULL);
2264	syslog(LOG_NOTICE, "%s(%s): %8.6f",
2265		"phase2",
2266		s_isakmp_state(ISAKMP_ETYPE_QUICK, iph2->side, iph2->status),
2267		timedelta(&start, &end));
2268#endif
2269
2270	return 0;
2271}
2272
2273/* called by scheduler */
2274void
2275isakmp_chkph1there_stub(p)
2276	void *p;
2277{
2278	isakmp_chkph1there((struct ph2handle *)p);
2279}
2280
2281void
2282isakmp_chkph1there(iph2)
2283	struct ph2handle *iph2;
2284{
2285	struct ph1handle *iph1;
2286
2287	iph2->retry_checkph1--;
2288	if (iph2->retry_checkph1 < 0) {
2289		plog(LLV_ERROR, LOCATION, iph2->dst,
2290			"phase2 negotiation failed "
2291			"due to time up waiting for phase1. %s\n",
2292			sadbsecas2str(iph2->dst, iph2->src,
2293				iph2->satype, 0, 0));
2294		plog(LLV_INFO, LOCATION, NULL,
2295			"delete phase 2 handler.\n");
2296
2297		/* send acquire to kernel as error */
2298		pk_sendeacquire(iph2);
2299
2300		unbindph12(iph2);
2301		remph2(iph2);
2302		delph2(iph2);
2303
2304		return;
2305	}
2306
2307	/*
2308	 * Search isakmp status table by address and port
2309	 * If NAT-T is in use, consider null ports as a
2310	 * wildcard and use IKE ports instead.
2311	 */
2312#ifdef ENABLE_NATT
2313	if (!extract_port(iph2->src) && !extract_port(iph2->dst)) {
2314		plog(LLV_DEBUG2, LOCATION, NULL, "CHKPH1THERE: extract_port.\n");
2315		if( (iph1 = getph1byaddrwop(iph2->src, iph2->dst)) != NULL){
2316			plog(LLV_DEBUG2, LOCATION, NULL, "CHKPH1THERE: found a ph1 wop.\n");
2317		}
2318	} else {
2319		plog(LLV_DEBUG2, LOCATION, NULL, "CHKPH1THERE: searching byaddr.\n");
2320		iph1 = getph1byaddr(iph2->src, iph2->dst, 0);
2321		if(iph1 != NULL)
2322			plog(LLV_DEBUG2, LOCATION, NULL, "CHKPH1THERE: found byaddr.\n");
2323	}
2324#else
2325	iph1 = getph1byaddr(iph2->src, iph2->dst, 0);
2326#endif
2327
2328	/* XXX Even if ph1 as responder is there, should we not start
2329	 * phase 2 negotiation ? */
2330	if (iph1 != NULL
2331	 && iph1->status == PHASE1ST_ESTABLISHED) {
2332		/* found isakmp-sa */
2333
2334		plog(LLV_DEBUG2, LOCATION, NULL, "CHKPH1THERE: got a ph1 handler, setting ports.\n");
2335		plog(LLV_DEBUG2, LOCATION, NULL, "iph1->local: %s\n", saddr2str(iph1->local));
2336		plog(LLV_DEBUG2, LOCATION, NULL, "iph1->remote: %s\n", saddr2str(iph1->remote));
2337		plog(LLV_DEBUG2, LOCATION, NULL, "before:\n");
2338		plog(LLV_DEBUG2, LOCATION, NULL, "src: %s\n", saddr2str(iph2->src));
2339		plog(LLV_DEBUG2, LOCATION, NULL, "dst: %s\n", saddr2str(iph2->dst));
2340		set_port(iph2->src, extract_port(iph1->local));
2341		set_port(iph2->dst, extract_port(iph1->remote));
2342		plog(LLV_DEBUG2, LOCATION, NULL, "After:\n");
2343		plog(LLV_DEBUG2, LOCATION, NULL, "src: %s\n", saddr2str(iph2->src));
2344		plog(LLV_DEBUG2, LOCATION, NULL, "dst: %s\n", saddr2str(iph2->dst));
2345
2346		/* begin quick mode */
2347		(void)isakmp_ph2begin_i(iph1, iph2);
2348		return;
2349	}
2350
2351	plog(LLV_DEBUG2, LOCATION, NULL, "CHKPH1THERE: no established ph1 handler found\n");
2352
2353	/* no isakmp-sa found */
2354	sched_new(1, isakmp_chkph1there_stub, iph2);
2355
2356	return;
2357}
2358
2359/* copy variable data into ALLOCATED buffer. */
2360caddr_t
2361isakmp_set_attr_v(buf, type, val, len)
2362	caddr_t buf;
2363	int type;
2364	caddr_t val;
2365	int len;
2366{
2367	struct isakmp_data *data;
2368
2369	data = (struct isakmp_data *)buf;
2370	data->type = htons((u_int16_t)type | ISAKMP_GEN_TLV);
2371	data->lorv = htons((u_int16_t)len);
2372	memcpy(data + 1, val, len);
2373
2374	return buf + sizeof(*data) + len;
2375}
2376
2377/* copy fixed length data into ALLOCATED buffer. */
2378caddr_t
2379isakmp_set_attr_l(buf, type, val)
2380	caddr_t buf;
2381	int type;
2382	u_int32_t val;
2383{
2384	struct isakmp_data *data;
2385
2386	data = (struct isakmp_data *)buf;
2387	data->type = htons((u_int16_t)type | ISAKMP_GEN_TV);
2388	data->lorv = htons((u_int16_t)val);
2389
2390	return buf + sizeof(*data);
2391}
2392
2393/* add a variable data attribute to the buffer by reallocating it. */
2394vchar_t *
2395isakmp_add_attr_v(buf0, type, val, len)
2396	vchar_t *buf0;
2397	int type;
2398	caddr_t val;
2399	int len;
2400{
2401	vchar_t *buf = NULL;
2402	struct isakmp_data *data;
2403	int tlen;
2404	int oldlen = 0;
2405
2406	tlen = sizeof(*data) + len;
2407
2408	if (buf0) {
2409		oldlen = buf0->l;
2410		buf = vrealloc(buf0, oldlen + tlen);
2411	} else
2412		buf = vmalloc(tlen);
2413	if (!buf) {
2414		plog(LLV_ERROR, LOCATION, NULL,
2415			"failed to get a attribute buffer.\n");
2416		return NULL;
2417	}
2418
2419	data = (struct isakmp_data *)(buf->v + oldlen);
2420	data->type = htons((u_int16_t)type | ISAKMP_GEN_TLV);
2421	data->lorv = htons((u_int16_t)len);
2422	memcpy(data + 1, val, len);
2423
2424	return buf;
2425}
2426
2427/* add a fixed data attribute to the buffer by reallocating it. */
2428vchar_t *
2429isakmp_add_attr_l(buf0, type, val)
2430	vchar_t *buf0;
2431	int type;
2432	u_int32_t val;
2433{
2434	vchar_t *buf = NULL;
2435	struct isakmp_data *data;
2436	int tlen;
2437	int oldlen = 0;
2438
2439	tlen = sizeof(*data);
2440
2441	if (buf0) {
2442		oldlen = buf0->l;
2443		buf = vrealloc(buf0, oldlen + tlen);
2444	} else
2445		buf = vmalloc(tlen);
2446	if (!buf) {
2447		plog(LLV_ERROR, LOCATION, NULL,
2448			"failed to get a attribute buffer.\n");
2449		return NULL;
2450	}
2451
2452	data = (struct isakmp_data *)(buf->v + oldlen);
2453	data->type = htons((u_int16_t)type | ISAKMP_GEN_TV);
2454	data->lorv = htons((u_int16_t)val);
2455
2456	return buf;
2457}
2458
2459/*
2460 * calculate cookie and set.
2461 */
2462int
2463isakmp_newcookie(place, remote, local)
2464	caddr_t place;
2465	struct sockaddr *remote;
2466	struct sockaddr *local;
2467{
2468	vchar_t *buf = NULL, *buf2 = NULL;
2469	char *p;
2470	int blen;
2471	int alen;
2472	caddr_t sa1, sa2;
2473	time_t t;
2474	int error = -1;
2475	u_short port;
2476
2477
2478	if (remote->sa_family != local->sa_family) {
2479		plog(LLV_ERROR, LOCATION, NULL,
2480			"address family mismatch, remote:%d local:%d\n",
2481			remote->sa_family, local->sa_family);
2482		goto end;
2483	}
2484	switch (remote->sa_family) {
2485	case AF_INET:
2486		alen = sizeof(struct in_addr);
2487		sa1 = (caddr_t)&((struct sockaddr_in *)remote)->sin_addr;
2488		sa2 = (caddr_t)&((struct sockaddr_in *)local)->sin_addr;
2489		break;
2490#ifdef INET6
2491	case AF_INET6:
2492		alen = sizeof(struct in6_addr);
2493		sa1 = (caddr_t)&((struct sockaddr_in6 *)remote)->sin6_addr;
2494		sa2 = (caddr_t)&((struct sockaddr_in6 *)local)->sin6_addr;
2495		break;
2496#endif
2497	default:
2498		plog(LLV_ERROR, LOCATION, NULL,
2499			"invalid family: %d\n", remote->sa_family);
2500		goto end;
2501	}
2502	blen = (alen + sizeof(u_short)) * 2
2503		+ sizeof(time_t) + lcconf->secret_size;
2504	buf = vmalloc(blen);
2505	if (buf == NULL) {
2506		plog(LLV_ERROR, LOCATION, NULL,
2507			"failed to get a cookie.\n");
2508		goto end;
2509	}
2510	p = buf->v;
2511
2512	/* copy my address */
2513	memcpy(p, sa1, alen);
2514	p += alen;
2515	port = ((struct sockaddr_in *)remote)->sin_port;
2516	memcpy(p, &port, sizeof(u_short));
2517	p += sizeof(u_short);
2518
2519	/* copy target address */
2520	memcpy(p, sa2, alen);
2521	p += alen;
2522	port = ((struct sockaddr_in *)local)->sin_port;
2523	memcpy(p, &port, sizeof(u_short));
2524	p += sizeof(u_short);
2525
2526	/* copy time */
2527	t = time(0);
2528	memcpy(p, (caddr_t)&t, sizeof(t));
2529	p += sizeof(t);
2530
2531	/* copy random value */
2532	buf2 = eay_set_random(lcconf->secret_size);
2533	if (buf2 == NULL)
2534		goto end;
2535	memcpy(p, buf2->v, lcconf->secret_size);
2536	p += lcconf->secret_size;
2537	vfree(buf2);
2538
2539	buf2 = eay_sha1_one(buf);
2540	memcpy(place, buf2->v, sizeof(cookie_t));
2541
2542	sa1 = val2str(place, sizeof (cookie_t));
2543	plog(LLV_DEBUG, LOCATION, NULL, "new cookie:\n%s\n", sa1);
2544	racoon_free(sa1);
2545
2546	error = 0;
2547end:
2548	if (buf != NULL)
2549		vfree(buf);
2550	if (buf2 != NULL)
2551		vfree(buf2);
2552	return error;
2553}
2554
2555/*
2556 * save partner's(payload) data into phhandle.
2557 */
2558int
2559isakmp_p2ph(buf, gen)
2560	vchar_t **buf;
2561	struct isakmp_gen *gen;
2562{
2563	/* XXX to be checked in each functions for logging. */
2564	if (*buf) {
2565		plog(LLV_WARNING, LOCATION, NULL,
2566			"ignore this payload, same payload type exist.\n");
2567		return -1;
2568	}
2569
2570	*buf = vmalloc(ntohs(gen->len) - sizeof(*gen));
2571	if (*buf == NULL) {
2572		plog(LLV_ERROR, LOCATION, NULL,
2573			"failed to get buffer.\n");
2574		return -1;
2575	}
2576	memcpy((*buf)->v, gen + 1, (*buf)->l);
2577
2578	return 0;
2579}
2580
2581u_int32_t
2582isakmp_newmsgid2(iph1)
2583	struct ph1handle *iph1;
2584{
2585	u_int32_t msgid2;
2586
2587	do {
2588		msgid2 = eay_random();
2589	} while (getph2bymsgid(iph1, msgid2));
2590
2591	return msgid2;
2592}
2593
2594/*
2595 * set values into allocated buffer of isakmp header for phase 1
2596 */
2597static caddr_t
2598set_isakmp_header(vbuf, iph1, nptype, etype, flags, msgid)
2599	vchar_t *vbuf;
2600	struct ph1handle *iph1;
2601	int nptype;
2602	u_int8_t etype;
2603	u_int8_t flags;
2604	u_int32_t msgid;
2605{
2606	struct isakmp *isakmp;
2607
2608	if (vbuf->l < sizeof(*isakmp))
2609		return NULL;
2610
2611	isakmp = (struct isakmp *)vbuf->v;
2612
2613	memcpy(&isakmp->i_ck, &iph1->index.i_ck, sizeof(cookie_t));
2614	memcpy(&isakmp->r_ck, &iph1->index.r_ck, sizeof(cookie_t));
2615	isakmp->np = nptype;
2616	isakmp->v = iph1->version;
2617	isakmp->etype = etype;
2618	isakmp->flags = flags;
2619	isakmp->msgid = msgid;
2620	isakmp->len = htonl(vbuf->l);
2621
2622	return vbuf->v + sizeof(*isakmp);
2623}
2624
2625/*
2626 * set values into allocated buffer of isakmp header for phase 1
2627 */
2628caddr_t
2629set_isakmp_header1(vbuf, iph1, nptype)
2630	vchar_t *vbuf;
2631	struct ph1handle *iph1;
2632	int nptype;
2633{
2634	return set_isakmp_header (vbuf, iph1, nptype, iph1->etype, iph1->flags, iph1->msgid);
2635}
2636
2637/*
2638 * set values into allocated buffer of isakmp header for phase 2
2639 */
2640caddr_t
2641set_isakmp_header2(vbuf, iph2, nptype)
2642	vchar_t *vbuf;
2643	struct ph2handle *iph2;
2644	int nptype;
2645{
2646	return set_isakmp_header (vbuf, iph2->ph1, nptype, ISAKMP_ETYPE_QUICK, iph2->flags, iph2->msgid);
2647}
2648
2649/*
2650 * set values into allocated buffer of isakmp payload.
2651 */
2652caddr_t
2653set_isakmp_payload(buf, src, nptype)
2654	caddr_t buf;
2655	vchar_t *src;
2656	int nptype;
2657{
2658	struct isakmp_gen *gen;
2659	caddr_t p = buf;
2660
2661	plog(LLV_DEBUG, LOCATION, NULL, "add payload of len %zu, next type %d\n",
2662	    src->l, nptype);
2663
2664	gen = (struct isakmp_gen *)p;
2665	gen->np = nptype;
2666	gen->len = htons(sizeof(*gen) + src->l);
2667	p += sizeof(*gen);
2668	memcpy(p, src->v, src->l);
2669	p += src->l;
2670
2671	return p;
2672}
2673
2674static int
2675etypesw1(etype)
2676	int etype;
2677{
2678	switch (etype) {
2679	case ISAKMP_ETYPE_IDENT:
2680		return 1;
2681	case ISAKMP_ETYPE_AGG:
2682		return 2;
2683	case ISAKMP_ETYPE_BASE:
2684		return 3;
2685	default:
2686		return 0;
2687	}
2688	/*NOTREACHED*/
2689}
2690
2691static int
2692etypesw2(etype)
2693	int etype;
2694{
2695	switch (etype) {
2696	case ISAKMP_ETYPE_QUICK:
2697		return 1;
2698	default:
2699		return 0;
2700	}
2701	/*NOTREACHED*/
2702}
2703
2704#ifdef HAVE_PRINT_ISAKMP_C
2705/* for print-isakmp.c */
2706char *snapend;
2707extern void isakmp_print __P((const u_char *, u_int, const u_char *));
2708
2709char *getname __P((const u_char *));
2710#ifdef INET6
2711char *getname6 __P((const u_char *));
2712#endif
2713int safeputchar __P((int));
2714
2715/*
2716 * Return a name for the IP address pointed to by ap.  This address
2717 * is assumed to be in network byte order.
2718 */
2719char *
2720getname(ap)
2721	const u_char *ap;
2722{
2723	struct sockaddr_in addr;
2724	static char ntop_buf[NI_MAXHOST];
2725
2726	memset(&addr, 0, sizeof(addr));
2727#ifndef __linux__
2728	addr.sin_len = sizeof(struct sockaddr_in);
2729#endif
2730	addr.sin_family = AF_INET;
2731	memcpy(&addr.sin_addr, ap, sizeof(addr.sin_addr));
2732	if (getnameinfo((struct sockaddr *)&addr, sizeof(addr),
2733			ntop_buf, sizeof(ntop_buf), NULL, 0,
2734			NI_NUMERICHOST | niflags))
2735		strlcpy(ntop_buf, "?", sizeof(ntop_buf));
2736
2737	return ntop_buf;
2738}
2739
2740#ifdef INET6
2741/*
2742 * Return a name for the IP6 address pointed to by ap.  This address
2743 * is assumed to be in network byte order.
2744 */
2745char *
2746getname6(ap)
2747	const u_char *ap;
2748{
2749	struct sockaddr_in6 addr;
2750	static char ntop_buf[NI_MAXHOST];
2751
2752	memset(&addr, 0, sizeof(addr));
2753	addr.sin6_len = sizeof(struct sockaddr_in6);
2754	addr.sin6_family = AF_INET6;
2755	memcpy(&addr.sin6_addr, ap, sizeof(addr.sin6_addr));
2756	if (getnameinfo((struct sockaddr *)&addr, addr.sin6_len,
2757			ntop_buf, sizeof(ntop_buf), NULL, 0,
2758			NI_NUMERICHOST | niflags))
2759		strlcpy(ntop_buf, "?", sizeof(ntop_buf));
2760
2761	return ntop_buf;
2762}
2763#endif /* INET6 */
2764
2765int
2766safeputchar(c)
2767	int c;
2768{
2769	unsigned char ch;
2770
2771	ch = (unsigned char)(c & 0xff);
2772	if (c < 0x80 && isprint(c))
2773		return printf("%c", c & 0xff);
2774	else
2775		return printf("\\%03o", c & 0xff);
2776}
2777
2778void
2779isakmp_printpacket(msg, from, my, decoded)
2780	vchar_t *msg;
2781	struct sockaddr *from;
2782	struct sockaddr *my;
2783	int decoded;
2784{
2785#ifdef YIPS_DEBUG
2786	struct timeval tv;
2787	int s;
2788	char hostbuf[NI_MAXHOST];
2789	char portbuf[NI_MAXSERV];
2790	struct isakmp *isakmp;
2791	vchar_t *buf;
2792#endif
2793
2794	if (loglevel < LLV_DEBUG)
2795		return;
2796
2797#ifdef YIPS_DEBUG
2798	plog(LLV_DEBUG, LOCATION, NULL, "begin.\n");
2799
2800	gettimeofday(&tv, NULL);
2801	s = tv.tv_sec % 3600;
2802	printf("%02d:%02d.%06u ", s / 60, s % 60, (u_int32_t)tv.tv_usec);
2803
2804	if (from) {
2805		if (getnameinfo(from, sysdep_sa_len(from), hostbuf, sizeof(hostbuf),
2806				portbuf, sizeof(portbuf),
2807				NI_NUMERICHOST | NI_NUMERICSERV | niflags)) {
2808			strlcpy(hostbuf, "?", sizeof(hostbuf));
2809			strlcpy(portbuf, "?", sizeof(portbuf));
2810		}
2811		printf("%s:%s", hostbuf, portbuf);
2812	} else
2813		printf("?");
2814	printf(" -> ");
2815	if (my) {
2816		if (getnameinfo(my, sysdep_sa_len(my), hostbuf, sizeof(hostbuf),
2817				portbuf, sizeof(portbuf),
2818				NI_NUMERICHOST | NI_NUMERICSERV | niflags)) {
2819			strlcpy(hostbuf, "?", sizeof(hostbuf));
2820			strlcpy(portbuf, "?", sizeof(portbuf));
2821		}
2822		printf("%s:%s", hostbuf, portbuf);
2823	} else
2824		printf("?");
2825	printf(": ");
2826
2827	buf = vdup(msg);
2828	if (!buf) {
2829		printf("(malloc fail)\n");
2830		return;
2831	}
2832	if (decoded) {
2833		isakmp = (struct isakmp *)buf->v;
2834		if (isakmp->flags & ISAKMP_FLAG_E) {
2835#if 0
2836			int pad;
2837			pad = *(u_char *)(buf->v + buf->l - 1);
2838			if (buf->l < pad && 2 < vflag)
2839				printf("(wrong padding)");
2840#endif
2841			isakmp->flags &= ~ISAKMP_FLAG_E;
2842		}
2843	}
2844
2845	snapend = buf->v + buf->l;
2846	isakmp_print(buf->v, buf->l, NULL);
2847	vfree(buf);
2848	printf("\n");
2849	fflush(stdout);
2850
2851	return;
2852#endif
2853}
2854#endif /*HAVE_PRINT_ISAKMP_C*/
2855
2856int
2857copy_ph1addresses(iph1, rmconf, remote, local)
2858	struct ph1handle *iph1;
2859	struct remoteconf *rmconf;
2860	struct sockaddr *remote, *local;
2861{
2862	u_int16_t port;
2863
2864	/* address portion must be grabbed from real remote address "remote" */
2865	iph1->remote = dupsaddr(remote);
2866	if (iph1->remote == NULL)
2867		return -1;
2868
2869	/*
2870	 * if remote has no port # (in case of initiator - from ACQUIRE msg)
2871	 * - if remote.conf specifies port #, use that
2872	 * - if remote.conf does not, use 500
2873	 * if remote has port # (in case of responder - from recvfrom(2))
2874	 * respect content of "remote".
2875	 */
2876	if (extract_port(iph1->remote) == 0) {
2877		port = extract_port(rmconf->remote);
2878		if (port == 0)
2879			port = PORT_ISAKMP;
2880		set_port(iph1->remote, port);
2881	}
2882
2883	if (local == NULL)
2884		iph1->local = getlocaladdr(iph1->remote);
2885	else
2886		iph1->local = dupsaddr(local);
2887	if (iph1->local == NULL)
2888		return -1;
2889
2890	if (extract_port(iph1->local) == 0)
2891		set_port(iph1->local, PORT_ISAKMP);
2892
2893#ifdef ENABLE_NATT
2894	if (extract_port(iph1->local) == lcconf->port_isakmp_natt) {
2895		plog(LLV_DEBUG, LOCATION, NULL, "Marking ports as changed\n");
2896		iph1->natt_flags |= NAT_ADD_NON_ESP_MARKER;
2897	}
2898#endif
2899
2900	return 0;
2901}
2902
2903static int
2904nostate1(iph1, msg)
2905	struct ph1handle *iph1;
2906	vchar_t *msg;
2907{
2908	plog(LLV_ERROR, LOCATION, iph1->remote, "wrong state %u.\n",
2909			iph1->status);
2910	return -1;
2911}
2912
2913static int
2914nostate2(iph2, msg)
2915	struct ph2handle *iph2;
2916	vchar_t *msg;
2917{
2918	plog(LLV_ERROR, LOCATION, iph2->ph1->remote, "wrong state %u.\n",
2919		iph2->status);
2920	return -1;
2921}
2922
2923void
2924log_ph1established(iph1)
2925	const struct ph1handle *iph1;
2926{
2927	char *src, *dst;
2928
2929	src = racoon_strdup(saddr2str(iph1->local));
2930	dst = racoon_strdup(saddr2str(iph1->remote));
2931	STRDUP_FATAL(src);
2932	STRDUP_FATAL(dst);
2933
2934	plog(LLV_INFO, LOCATION, NULL,
2935		"ISAKMP-SA established %s-%s spi:%s\n",
2936		src, dst,
2937		isakmp_pindex(&iph1->index, 0));
2938
2939	EVT_PUSH(iph1->local, iph1->remote, EVTT_PHASE1_UP, NULL);
2940	if(!iph1->rmconf->mode_cfg)
2941		EVT_PUSH(iph1->local, iph1->remote, EVTT_NO_ISAKMP_CFG, NULL);
2942
2943	racoon_free(src);
2944	racoon_free(dst);
2945
2946	return;
2947}
2948
2949struct payload_list *
2950isakmp_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
2969vchar_t *
2970isakmp_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;
3013end:
3014	if (buf != NULL)
3015		vfree(buf);
3016	return NULL;
3017}
3018
3019#ifdef ENABLE_FRAG
3020int
3021frag_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
3042void
3043script_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
3106out:
3107	for (c = envp; *c; c++)
3108		racoon_free(*c);
3109
3110	racoon_free(envp);
3111
3112	return;
3113}
3114
3115int
3116script_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
3155int
3156script_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
3187void
3188purge_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
3338void
3339delete_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	}
3600purge:
3601	iph2->spidx_gen=NULL;
3602}
3603
3604
3605#ifdef INET6
3606u_int32_t
3607setscopeid(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