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