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