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