1 /*	$NetBSD: isakmp_inf.c,v 1.14.4.17 2009/05/18 17:07:46 tteras Exp $	*/
2 
3 /* Id: isakmp_inf.c,v 1.44 2006/05/06 20:45:52 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 
40 #include <net/pfkeyv2.h>
41 #include <netinet/in.h>
42 #include <sys/queue.h>
43 #include PATH_IPSEC_H
44 
45 #include <stdlib.h>
46 #include <stdio.h>
47 #include <string.h>
48 #include <errno.h>
49 #if TIME_WITH_SYS_TIME
50 # include <sys/time.h>
51 # include <time.h>
52 #else
53 # if HAVE_SYS_TIME_H
54 #  include <sys/time.h>
55 # else
56 #  include <time.h>
57 # endif
58 #endif
59 #ifdef ENABLE_HYBRID
60 #include <resolv.h>
61 #endif
62 
63 #include "libpfkey.h"
64 
65 #include "var.h"
66 #include "vmbuf.h"
67 #include "schedule.h"
68 #include "str2val.h"
69 #include "misc.h"
70 #include "plog.h"
71 #include "debug.h"
72 
73 #include "localconf.h"
74 #include "remoteconf.h"
75 #include "sockmisc.h"
76 #include "handler.h"
77 #include "policy.h"
78 #include "proposal.h"
79 #include "isakmp_var.h"
80 #include "evt.h"
81 #include "isakmp.h"
82 #ifdef ENABLE_HYBRID
83 #include "isakmp_xauth.h"
84 #include "isakmp_unity.h"
85 #include "isakmp_cfg.h"
86 #endif
87 #include "isakmp_inf.h"
88 #include "oakley.h"
89 #include "ipsec_doi.h"
90 #include "crypto_openssl.h"
91 #include "pfkey.h"
92 #include "policy.h"
93 #include "algorithm.h"
94 #include "proposal.h"
95 #include "admin.h"
96 #include "strnames.h"
97 #ifdef ENABLE_NATT
98 #include "nattraversal.h"
99 #endif
100 
101 /* information exchange */
102 static int isakmp_info_recv_n (struct ph1handle *, struct isakmp_pl_n *, u_int32_t, int);
103 static int isakmp_info_recv_d (struct ph1handle *, struct isakmp_pl_d *, u_int32_t, int);
104 
105 #ifdef ENABLE_DPD
106 static int isakmp_info_recv_r_u __P((struct ph1handle *,
107 	struct isakmp_pl_ru *, u_int32_t));
108 static int isakmp_info_recv_r_u_ack __P((struct ph1handle *,
109 	struct isakmp_pl_ru *, u_int32_t));
110 static void isakmp_info_send_r_u __P((void *));
111 #endif
112 
113 static void purge_isakmp_spi __P((int, isakmp_index *, size_t));
114 static void info_recv_initialcontact __P((struct ph1handle *));
115 
116 /* %%%
117  * Information Exchange
118  */
119 /*
120  * receive Information
121  */
122 int
isakmp_info_recv(iph1,msg0)123 isakmp_info_recv(iph1, msg0)
124 	struct ph1handle *iph1;
125 	vchar_t *msg0;
126 {
127 	vchar_t *msg = NULL;
128 	vchar_t *pbuf = NULL;
129 	u_int32_t msgid = 0;
130 	int error = -1;
131 	struct isakmp *isakmp;
132 	struct isakmp_gen *gen;
133 	struct isakmp_parse_t *pa, *pap;
134 	void *p;
135 	vchar_t *hash, *payload;
136 	struct isakmp_gen *nd;
137 	u_int8_t np;
138 	int encrypted;
139 
140 	plog(LLV_DEBUG, LOCATION, NULL, "receive Information.\n");
141 
142 	encrypted = ISSET(((struct isakmp *)msg0->v)->flags, ISAKMP_FLAG_E);
143 	msgid = ((struct isakmp *)msg0->v)->msgid;
144 
145 	/* Use new IV to decrypt Informational message. */
146 	if (encrypted) {
147 		struct isakmp_ivm *ivm;
148 
149 		if (iph1->ivm == NULL) {
150 			plog(LLV_ERROR, LOCATION, NULL, "iph1->ivm == NULL\n");
151 			return -1;
152 		}
153 
154 		/* compute IV */
155 		ivm = oakley_newiv2(iph1, ((struct isakmp *)msg0->v)->msgid);
156 		if (ivm == NULL)
157 			return -1;
158 
159 		msg = oakley_do_decrypt(iph1, msg0, ivm->iv, ivm->ive);
160 		oakley_delivm(ivm);
161 		if (msg == NULL)
162 			return -1;
163 
164 	} else
165 		msg = vdup(msg0);
166 
167 	/* Safety check */
168 	if (msg->l < sizeof(*isakmp) + sizeof(*gen)) {
169 		plog(LLV_ERROR, LOCATION, NULL,
170 			"ignore information because the "
171 			"message is way too short - %zu byte(s).\n", msg->l);
172 		goto end;
173 	}
174 
175 	isakmp = (struct isakmp *)msg->v;
176 	gen = (struct isakmp_gen *)((caddr_t)isakmp + sizeof(struct isakmp));
177 	np = gen->np;
178 
179 	if (encrypted) {
180 		if (isakmp->np != ISAKMP_NPTYPE_HASH) {
181 			plog(LLV_ERROR, LOCATION, NULL,
182 			    "ignore information because the"
183 			    "message has no hash payload.\n");
184 			goto end;
185 		}
186 
187 		if (iph1->status != PHASE1ST_ESTABLISHED) {
188 			plog(LLV_ERROR, LOCATION, NULL,
189 			    "ignore information because ISAKMP-SA"
190 			    "has not been established yet.\n");
191 			goto end;
192 		}
193 
194 		/* Safety check */
195 		if (msg->l < sizeof(*isakmp) + ntohs(gen->len) + sizeof(*nd)) {
196 			plog(LLV_ERROR, LOCATION, NULL,
197 				"ignore information because the "
198 				"message is too short - %zu byte(s).\n", msg->l);
199 			goto end;
200 		}
201 
202 		p = (caddr_t) gen + sizeof(struct isakmp_gen);
203 		nd = (struct isakmp_gen *) ((caddr_t) gen + ntohs(gen->len));
204 
205 		/* nd length check */
206 		if (ntohs(nd->len) > msg->l - (sizeof(struct isakmp) +
207 		    ntohs(gen->len))) {
208 			plog(LLV_ERROR, LOCATION, NULL,
209 				 "too long payload length (broken message?)\n");
210 			goto end;
211 		}
212 
213 		if (ntohs(nd->len) < sizeof(*nd)) {
214 			plog(LLV_ERROR, LOCATION, NULL,
215 				"too short payload length (broken message?)\n");
216 			goto end;
217 		}
218 
219 		payload = vmalloc(ntohs(nd->len));
220 		if (payload == NULL) {
221 			plog(LLV_ERROR, LOCATION, NULL,
222 			    "cannot allocate memory\n");
223 			goto end;
224 		}
225 
226 		memcpy(payload->v, (caddr_t) nd, ntohs(nd->len));
227 
228 		/* compute HASH */
229 		hash = oakley_compute_hash1(iph1, isakmp->msgid, payload);
230 		if (hash == NULL) {
231 			plog(LLV_ERROR, LOCATION, NULL,
232 			    "cannot compute hash\n");
233 
234 			vfree(payload);
235 			goto end;
236 		}
237 
238 		if (ntohs(gen->len) - sizeof(struct isakmp_gen) != hash->l) {
239 			plog(LLV_ERROR, LOCATION, NULL,
240 			    "ignore information due to hash length mismatch\n");
241 
242 			vfree(hash);
243 			vfree(payload);
244 			goto end;
245 		}
246 
247 		if (memcmp(p, hash->v, hash->l) != 0) {
248 			plog(LLV_ERROR, LOCATION, NULL,
249 			    "ignore information due to hash mismatch\n");
250 
251 			vfree(hash);
252 			vfree(payload);
253 			goto end;
254 		}
255 
256 		plog(LLV_DEBUG, LOCATION, NULL, "hash validated.\n");
257 
258 		vfree(hash);
259 		vfree(payload);
260 	} else {
261 		/* make sure the packet was encrypted after the beginning of phase 1. */
262 		switch (iph1->etype) {
263 		case ISAKMP_ETYPE_AGG:
264 		case ISAKMP_ETYPE_BASE:
265 		case ISAKMP_ETYPE_IDENT:
266 			if ((iph1->side == INITIATOR && iph1->status < PHASE1ST_MSG3SENT)
267 			 || (iph1->side == RESPONDER && iph1->status < PHASE1ST_MSG2SENT)) {
268 				break;
269 			}
270 			/*FALLTHRU*/
271 		default:
272 			plog(LLV_ERROR, LOCATION, iph1->remote,
273 				"%s message must be encrypted\n",
274 				s_isakmp_nptype(np));
275 			error = 0;
276 			goto end;
277 		}
278 	}
279 
280 	if (!(pbuf = isakmp_parse(msg))) {
281 		error = -1;
282 		goto end;
283 	}
284 
285 	error = 0;
286 	for (pa = (struct isakmp_parse_t *)pbuf->v; pa->type; pa++) {
287 		switch (pa->type) {
288 		case ISAKMP_NPTYPE_HASH:
289 			/* Handled above */
290 			break;
291 		case ISAKMP_NPTYPE_N:
292 			error = isakmp_info_recv_n(iph1,
293 				(struct isakmp_pl_n *)pa->ptr,
294 				msgid, encrypted);
295 			break;
296 		case ISAKMP_NPTYPE_D:
297 			error = isakmp_info_recv_d(iph1,
298 				(struct isakmp_pl_d *)pa->ptr,
299 				msgid, encrypted);
300 			break;
301 		case ISAKMP_NPTYPE_NONCE:
302 			/* XXX to be 6.4.2 ike-01.txt */
303 			/* XXX IV is to be synchronized. */
304 			plog(LLV_ERROR, LOCATION, iph1->remote,
305 				"ignore Acknowledged Informational\n");
306 			break;
307 		default:
308 			/* don't send information, see isakmp_ident_r1() */
309 			error = 0;
310 			plog(LLV_ERROR, LOCATION, iph1->remote,
311 				"reject the packet, "
312 				"received unexpected payload type %s.\n",
313 				s_isakmp_nptype(gen->np));
314 		}
315 		if (error < 0)
316 			break;
317 	}
318     end:
319 	if (msg != NULL)
320 		vfree(msg);
321 	if (pbuf != NULL)
322 		vfree(pbuf);
323 	return error;
324 }
325 
326 /*
327  * handling of Notification payload
328  */
329 static int
isakmp_info_recv_n(iph1,notify,msgid,encrypted)330 isakmp_info_recv_n(iph1, notify, msgid, encrypted)
331 	struct ph1handle *iph1;
332 	struct isakmp_pl_n *notify;
333 	u_int32_t msgid;
334 	int encrypted;
335 {
336 	u_int type;
337 	vchar_t *pbuf;
338 	char *nraw, *ndata;
339 	size_t l;
340 	char *spi;
341 
342 	type = ntohs(notify->type);
343 
344 	switch (type) {
345 	case ISAKMP_NTYPE_CONNECTED:
346 	case ISAKMP_NTYPE_RESPONDER_LIFETIME:
347 	case ISAKMP_NTYPE_REPLAY_STATUS:
348 #ifdef ENABLE_HYBRID
349 	case ISAKMP_NTYPE_UNITY_HEARTBEAT:
350 #endif
351 		/* do something */
352 		break;
353 	case ISAKMP_NTYPE_INITIAL_CONTACT:
354 		if (encrypted)
355 			info_recv_initialcontact(iph1);
356 			return 0;
357 		break;
358 #ifdef ENABLE_DPD
359 	case ISAKMP_NTYPE_R_U_THERE:
360 		if (encrypted)
361 			return isakmp_info_recv_r_u(iph1,
362 				(struct isakmp_pl_ru *)notify, msgid);
363 		break;
364 	case ISAKMP_NTYPE_R_U_THERE_ACK:
365 		if (encrypted)
366 			return isakmp_info_recv_r_u_ack(iph1,
367 				(struct isakmp_pl_ru *)notify, msgid);
368 		break;
369 #endif
370 	default:
371 	    {
372 		/* XXX there is a potential of dos attack. */
373 		if(type >= ISAKMP_NTYPE_MINERROR &&
374 		   type <= ISAKMP_NTYPE_MAXERROR) {
375 			if (msgid == 0) {
376 				/* don't think this realy deletes ph1 ? */
377 				plog(LLV_ERROR, LOCATION, iph1->remote,
378 					"delete phase1 handle.\n");
379 				return -1;
380 			} else {
381 				if (getph2bymsgid(iph1, msgid) == NULL) {
382 					plog(LLV_ERROR, LOCATION, iph1->remote,
383 						"fatal %s notify messsage, "
384 						"phase1 should be deleted.\n",
385 						s_isakmp_notify_msg(type));
386 				} else {
387 					plog(LLV_ERROR, LOCATION, iph1->remote,
388 						"fatal %s notify messsage, "
389 						"phase2 should be deleted.\n",
390 						s_isakmp_notify_msg(type));
391 				}
392 			}
393 		} else {
394 			plog(LLV_ERROR, LOCATION, iph1->remote,
395 				"unhandled notify message %s, "
396 				"no phase2 handle found.\n",
397 				s_isakmp_notify_msg(type));
398 		}
399 	    }
400 	    break;
401 	}
402 
403 	/* get spi if specified and allocate */
404 	if(notify->spi_size > 0) {
405 		if (ntohs(notify->h.len) < sizeof(*notify) + notify->spi_size) {
406 			plog(LLV_ERROR, LOCATION, iph1->remote,
407 				"invalid spi_size in notification payload.\n");
408 			return -1;
409 		}
410 		spi = val2str((char *)(notify + 1), notify->spi_size);
411 
412 		plog(LLV_DEBUG, LOCATION, iph1->remote,
413 			"notification message %d:%s, "
414 			"doi=%d proto_id=%d spi=%s(size=%d).\n",
415 			type, s_isakmp_notify_msg(type),
416 			ntohl(notify->doi), notify->proto_id, spi, notify->spi_size);
417 
418 		racoon_free(spi);
419 	}
420 
421 	/* Send the message data to the logs */
422 	if(type >= ISAKMP_NTYPE_MINERROR &&
423 	   type <= ISAKMP_NTYPE_MAXERROR) {
424 		l = ntohs(notify->h.len) - sizeof(*notify) - notify->spi_size;
425 		if (l > 0) {
426 			nraw = (char*)notify;
427 			nraw += sizeof(*notify) + notify->spi_size;
428 			ndata = binsanitize(nraw, l);
429 			if (ndata != NULL) {
430 				plog(LLV_ERROR, LOCATION, iph1->remote,
431 				    "Message: '%s'.\n",
432 				    ndata);
433 				racoon_free(ndata);
434 			} else {
435 				plog(LLV_ERROR, LOCATION, iph1->remote,
436 				    "Cannot allocate memory\n");
437 			}
438 		}
439 	}
440 	return 0;
441 }
442 
443 /*
444  * handling of Deletion payload
445  */
446 static int
isakmp_info_recv_d(iph1,delete,msgid,encrypted)447 isakmp_info_recv_d(iph1, delete, msgid, encrypted)
448 	struct ph1handle *iph1;
449 	struct isakmp_pl_d *delete;
450 	u_int32_t msgid;
451 	int encrypted;
452 {
453 	int tlen, num_spi;
454 	vchar_t *pbuf;
455 	int protected = 0;
456 	struct ph1handle *del_ph1;
457 	struct ph2handle *iph2;
458 	union {
459 		u_int32_t spi32;
460 		u_int16_t spi16[2];
461 	} spi;
462 
463 	if (ntohl(delete->doi) != IPSEC_DOI) {
464 		plog(LLV_ERROR, LOCATION, iph1->remote,
465 			"delete payload with invalid doi:%d.\n",
466 			ntohl(delete->doi));
467 #ifdef ENABLE_HYBRID
468 		/*
469 		 * At deconnexion time, Cisco VPN client does this
470 		 * with a zero DOI. Don't give up in that situation.
471 		 */
472 		if (((iph1->mode_cfg->flags &
473 		    ISAKMP_CFG_VENDORID_UNITY) == 0) || (delete->doi != 0))
474 			return 0;
475 #else
476 		return 0;
477 #endif
478 	}
479 
480 	num_spi = ntohs(delete->num_spi);
481 	tlen = ntohs(delete->h.len) - sizeof(struct isakmp_pl_d);
482 
483 	if (tlen != num_spi * delete->spi_size) {
484 		plog(LLV_ERROR, LOCATION, iph1->remote,
485 			"deletion payload with invalid length.\n");
486 		return 0;
487 	}
488 
489 	plog(LLV_DEBUG, LOCATION, iph1->remote,
490 		"delete payload for protocol %s\n",
491 		s_ipsecdoi_proto(delete->proto_id));
492 
493 	if(!iph1->rmconf->weak_phase1_check && !encrypted) {
494 		plog(LLV_WARNING, LOCATION, iph1->remote,
495 			"Ignoring unencrypted delete payload "
496 			"(check the weak_phase1_check option)\n");
497 		return 0;
498 	}
499 
500 	switch (delete->proto_id) {
501 	case IPSECDOI_PROTO_ISAKMP:
502 		if (delete->spi_size != sizeof(isakmp_index)) {
503 			plog(LLV_ERROR, LOCATION, iph1->remote,
504 				"delete payload with strange spi "
505 				"size %d(proto_id:%d)\n",
506 				delete->spi_size, delete->proto_id);
507 			return 0;
508 		}
509 
510 		del_ph1=getph1byindex((isakmp_index *)(delete + 1));
511 		if(del_ph1 != NULL){
512 
513 			EVT_PUSH(del_ph1->local, del_ph1->remote,
514 			EVTT_PEERPH1_NOPROP, NULL);
515 			if (del_ph1->scr)
516 				SCHED_KILL(del_ph1->scr);
517 
518 			/*
519 			 * Do not delete IPsec SAs when receiving an IKE delete notification.
520 			 * Just delete the IKE SA.
521 			 */
522 			isakmp_ph1expire(del_ph1);
523 		}
524 		break;
525 
526 	case IPSECDOI_PROTO_IPSEC_AH:
527 	case IPSECDOI_PROTO_IPSEC_ESP:
528 		if (delete->spi_size != sizeof(u_int32_t)) {
529 			plog(LLV_ERROR, LOCATION, iph1->remote,
530 				"delete payload with strange spi "
531 				"size %d(proto_id:%d)\n",
532 				delete->spi_size, delete->proto_id);
533 			return 0;
534 		}
535 		EVT_PUSH(iph1->local, iph1->remote,
536 		    EVTT_PEER_DELETE, NULL);
537 		purge_ipsec_spi(iph1->remote, delete->proto_id,
538 		    (u_int32_t *)(delete + 1), num_spi);
539 		break;
540 
541 	case IPSECDOI_PROTO_IPCOMP:
542 		/* need to handle both 16bit/32bit SPI */
543 		memset(&spi, 0, sizeof(spi));
544 		if (delete->spi_size == sizeof(spi.spi16[1])) {
545 			memcpy(&spi.spi16[1], delete + 1,
546 			    sizeof(spi.spi16[1]));
547 		} else if (delete->spi_size == sizeof(spi.spi32))
548 			memcpy(&spi.spi32, delete + 1, sizeof(spi.spi32));
549 		else {
550 			plog(LLV_ERROR, LOCATION, iph1->remote,
551 				"delete payload with strange spi "
552 				"size %d(proto_id:%d)\n",
553 				delete->spi_size, delete->proto_id);
554 			return 0;
555 		}
556 		purge_ipsec_spi(iph1->remote, delete->proto_id,
557 		    &spi.spi32, num_spi);
558 		break;
559 
560 	default:
561 		plog(LLV_ERROR, LOCATION, iph1->remote,
562 			"deletion message received, "
563 			"invalid proto_id: %d\n",
564 			delete->proto_id);
565 		return 0;
566 	}
567 
568 	plog(LLV_DEBUG, LOCATION, NULL, "purged SAs.\n");
569 
570 	return 0;
571 }
572 
573 /*
574  * send Delete payload (for ISAKMP SA) in Informational exchange.
575  */
576 int
isakmp_info_send_d1(iph1)577 isakmp_info_send_d1(iph1)
578 	struct ph1handle *iph1;
579 {
580 	struct isakmp_pl_d *d;
581 	vchar_t *payload = NULL;
582 	int tlen;
583 	int error = 0;
584 
585 	if (iph1->status != PHASE2ST_ESTABLISHED)
586 		return 0;
587 
588 	/* create delete payload */
589 
590 	/* send SPIs of inbound SAs. */
591 	/* XXX should send outbound SAs's ? */
592 	tlen = sizeof(*d) + sizeof(isakmp_index);
593 	payload = vmalloc(tlen);
594 	if (payload == NULL) {
595 		plog(LLV_ERROR, LOCATION, NULL,
596 			"failed to get buffer for payload.\n");
597 		return errno;
598 	}
599 
600 	d = (struct isakmp_pl_d *)payload->v;
601 	d->h.np = ISAKMP_NPTYPE_NONE;
602 	d->h.len = htons(tlen);
603 	d->doi = htonl(IPSEC_DOI);
604 	d->proto_id = IPSECDOI_PROTO_ISAKMP;
605 	d->spi_size = sizeof(isakmp_index);
606 	d->num_spi = htons(1);
607 	memcpy(d + 1, &iph1->index, sizeof(isakmp_index));
608 
609 	error = isakmp_info_send_common(iph1, payload,
610 					ISAKMP_NPTYPE_D, 0);
611 	vfree(payload);
612 
613 	return error;
614 }
615 
616 /*
617  * send Delete payload (for IPsec SA) in Informational exchange, based on
618  * pfkey msg.  It sends always single SPI.
619  */
620 int
isakmp_info_send_d2(iph2)621 isakmp_info_send_d2(iph2)
622 	struct ph2handle *iph2;
623 {
624 	struct ph1handle *iph1;
625 	struct saproto *pr;
626 	struct isakmp_pl_d *d;
627 	vchar_t *payload = NULL;
628 	int tlen;
629 	int error = 0;
630 	u_int8_t *spi;
631 
632 	if (iph2->status != PHASE2ST_ESTABLISHED)
633 		return 0;
634 
635 	/*
636 	 * don't send delete information if there is no phase 1 handler.
637 	 * It's nonsensical to negotiate phase 1 to send the information.
638 	 */
639 	iph1 = getph1byaddr(iph2->src, iph2->dst, 0);
640 	if (iph1 == NULL){
641 		plog(LLV_DEBUG2, LOCATION, NULL,
642 			 "No ph1 handler found, could not send DELETE_SA\n");
643 		return 0;
644 	}
645 
646 	/* create delete payload */
647 	for (pr = iph2->approval->head; pr != NULL; pr = pr->next) {
648 
649 		/* send SPIs of inbound SAs. */
650 		/*
651 		 * XXX should I send outbound SAs's ?
652 		 * I send inbound SAs's SPI only at the moment because I can't
653 		 * decode any more if peer send encoded packet without aware of
654 		 * deletion of SA.  Outbound SAs don't come under the situation.
655 		 */
656 		tlen = sizeof(*d) + pr->spisize;
657 		payload = vmalloc(tlen);
658 		if (payload == NULL) {
659 			plog(LLV_ERROR, LOCATION, NULL,
660 				"failed to get buffer for payload.\n");
661 			return errno;
662 		}
663 
664 		d = (struct isakmp_pl_d *)payload->v;
665 		d->h.np = ISAKMP_NPTYPE_NONE;
666 		d->h.len = htons(tlen);
667 		d->doi = htonl(IPSEC_DOI);
668 		d->proto_id = pr->proto_id;
669 		d->spi_size = pr->spisize;
670 		d->num_spi = htons(1);
671 		/*
672 		 * XXX SPI bits are left-filled, for use with IPComp.
673 		 * we should be switching to variable-length spi field...
674 		 */
675 		spi = (u_int8_t *)&pr->spi;
676 		spi += sizeof(pr->spi);
677 		spi -= pr->spisize;
678 		memcpy(d + 1, spi, pr->spisize);
679 
680 		error = isakmp_info_send_common(iph1, payload,
681 						ISAKMP_NPTYPE_D, 0);
682 		vfree(payload);
683 	}
684 
685 	return error;
686 }
687 
688 /*
689  * send Notification payload (for without ISAKMP SA) in Informational exchange
690  */
691 int
isakmp_info_send_nx(isakmp,remote,local,type,data)692 isakmp_info_send_nx(isakmp, remote, local, type, data)
693 	struct isakmp *isakmp;
694 	struct sockaddr *remote, *local;
695 	int type;
696 	vchar_t *data;
697 {
698 	struct ph1handle *iph1 = NULL;
699 	struct remoteconf *rmconf;
700 	vchar_t *payload = NULL;
701 	int tlen;
702 	int error = -1;
703 	struct isakmp_pl_n *n;
704 	int spisiz = 0;		/* see below */
705 
706 	/* search appropreate configuration */
707 	rmconf = getrmconf(remote);
708 	if (rmconf == NULL) {
709 		plog(LLV_ERROR, LOCATION, remote,
710 			"no configuration found for peer address.\n");
711 		goto end;
712 	}
713 
714 	/* add new entry to isakmp status table. */
715 	iph1 = newph1();
716 	if (iph1 == NULL)
717 		return -1;
718 
719 	memcpy(&iph1->index.i_ck, &isakmp->i_ck, sizeof(cookie_t));
720 	isakmp_newcookie((char *)&iph1->index.r_ck, remote, local);
721 	iph1->status = PHASE1ST_START;
722 	iph1->rmconf = rmconf;
723 	iph1->side = INITIATOR;
724 	iph1->version = isakmp->v;
725 	iph1->flags = 0;
726 	iph1->msgid = 0;	/* XXX */
727 #ifdef ENABLE_HYBRID
728 	if ((iph1->mode_cfg = isakmp_cfg_mkstate()) == NULL)
729 		goto end;
730 #endif
731 #ifdef ENABLE_FRAG
732 	iph1->frag = 0;
733 	iph1->frag_chain = NULL;
734 #endif
735 
736 	/* copy remote address */
737 	if (copy_ph1addresses(iph1, rmconf, remote, local) < 0)
738 		goto end;
739 
740 	tlen = sizeof(*n) + spisiz;
741 	if (data)
742 		tlen += data->l;
743 	payload = vmalloc(tlen);
744 	if (payload == NULL) {
745 		plog(LLV_ERROR, LOCATION, NULL,
746 			"failed to get buffer to send.\n");
747 		goto end;
748 	}
749 
750 	n = (struct isakmp_pl_n *)payload->v;
751 	n->h.np = ISAKMP_NPTYPE_NONE;
752 	n->h.len = htons(tlen);
753 	n->doi = htonl(IPSEC_DOI);
754 	n->proto_id = IPSECDOI_KEY_IKE;
755 	n->spi_size = spisiz;
756 	n->type = htons(type);
757 	if (spisiz)
758 		memset(n + 1, 0, spisiz);	/* XXX spisiz is always 0 */
759 	if (data)
760 		memcpy((caddr_t)(n + 1) + spisiz, data->v, data->l);
761 
762 	error = isakmp_info_send_common(iph1, payload, ISAKMP_NPTYPE_N, 0);
763 	vfree(payload);
764 
765     end:
766 	if (iph1 != NULL)
767 		delph1(iph1);
768 
769 	return error;
770 }
771 
772 /*
773  * send Notification payload (for ISAKMP SA) in Informational exchange
774  */
775 int
isakmp_info_send_n1(iph1,type,data)776 isakmp_info_send_n1(iph1, type, data)
777 	struct ph1handle *iph1;
778 	int type;
779 	vchar_t *data;
780 {
781 	vchar_t *payload = NULL;
782 	int tlen;
783 	int error = 0;
784 	struct isakmp_pl_n *n;
785 	int spisiz;
786 
787 	/*
788 	 * note on SPI size: which description is correct?  I have chosen
789 	 * this to be 0.
790 	 *
791 	 * RFC2408 3.1, 2nd paragraph says: ISAKMP SA is identified by
792 	 * Initiator/Responder cookie and SPI has no meaning, SPI size = 0.
793 	 * RFC2408 3.1, first paragraph on page 40: ISAKMP SA is identified
794 	 * by cookie and SPI has no meaning, 0 <= SPI size <= 16.
795 	 * RFC2407 4.6.3.3, INITIAL-CONTACT is required to set to 16.
796 	 */
797 	if (type == ISAKMP_NTYPE_INITIAL_CONTACT)
798 		spisiz = sizeof(isakmp_index);
799 	else
800 		spisiz = 0;
801 
802 	tlen = sizeof(*n) + spisiz;
803 	if (data)
804 		tlen += data->l;
805 	payload = vmalloc(tlen);
806 	if (payload == NULL) {
807 		plog(LLV_ERROR, LOCATION, NULL,
808 			"failed to get buffer to send.\n");
809 		return errno;
810 	}
811 
812 	n = (struct isakmp_pl_n *)payload->v;
813 	n->h.np = ISAKMP_NPTYPE_NONE;
814 	n->h.len = htons(tlen);
815 	n->doi = htonl(iph1->rmconf->doitype);
816 	n->proto_id = IPSECDOI_PROTO_ISAKMP; /* XXX to be configurable ? */
817 	n->spi_size = spisiz;
818 	n->type = htons(type);
819 	if (spisiz)
820 		memcpy(n + 1, &iph1->index, sizeof(isakmp_index));
821 	if (data)
822 		memcpy((caddr_t)(n + 1) + spisiz, data->v, data->l);
823 
824 	error = isakmp_info_send_common(iph1, payload, ISAKMP_NPTYPE_N, iph1->flags);
825 	vfree(payload);
826 
827 	return error;
828 }
829 
830 /*
831  * send Notification payload (for IPsec SA) in Informational exchange
832  */
833 int
isakmp_info_send_n2(iph2,type,data)834 isakmp_info_send_n2(iph2, type, data)
835 	struct ph2handle *iph2;
836 	int type;
837 	vchar_t *data;
838 {
839 	struct ph1handle *iph1 = iph2->ph1;
840 	vchar_t *payload = NULL;
841 	int tlen;
842 	int error = 0;
843 	struct isakmp_pl_n *n;
844 	struct saproto *pr;
845 
846 	if (!iph2->approval)
847 		return EINVAL;
848 
849 	pr = iph2->approval->head;
850 
851 	/* XXX must be get proper spi */
852 	tlen = sizeof(*n) + pr->spisize;
853 	if (data)
854 		tlen += data->l;
855 	payload = vmalloc(tlen);
856 	if (payload == NULL) {
857 		plog(LLV_ERROR, LOCATION, NULL,
858 			"failed to get buffer to send.\n");
859 		return errno;
860 	}
861 
862 	n = (struct isakmp_pl_n *)payload->v;
863 	n->h.np = ISAKMP_NPTYPE_NONE;
864 	n->h.len = htons(tlen);
865 	n->doi = htonl(IPSEC_DOI);		/* IPSEC DOI (1) */
866 	n->proto_id = pr->proto_id;		/* IPSEC AH/ESP/whatever*/
867 	n->spi_size = pr->spisize;
868 	n->type = htons(type);
869 	*(u_int32_t *)(n + 1) = pr->spi;
870 	if (data)
871 		memcpy((caddr_t)(n + 1) + pr->spisize, data->v, data->l);
872 
873 	iph2->flags |= ISAKMP_FLAG_E;	/* XXX Should we do FLAG_A ? */
874 	error = isakmp_info_send_common(iph1, payload, ISAKMP_NPTYPE_N, iph2->flags);
875 	vfree(payload);
876 
877 	return error;
878 }
879 
880 /*
881  * send Information
882  * When ph1->skeyid_a == NULL, send message without encoding.
883  */
884 int
isakmp_info_send_common(iph1,payload,np,flags)885 isakmp_info_send_common(iph1, payload, np, flags)
886 	struct ph1handle *iph1;
887 	vchar_t *payload;
888 	u_int32_t np;
889 	int flags;
890 {
891 	struct ph2handle *iph2 = NULL;
892 	vchar_t *hash = NULL;
893 	struct isakmp *isakmp;
894 	struct isakmp_gen *gen;
895 	char *p;
896 	int tlen;
897 	int error = -1;
898 
899 	/* add new entry to isakmp status table */
900 	iph2 = newph2();
901 	if (iph2 == NULL)
902 		goto end;
903 
904 	iph2->dst = dupsaddr(iph1->remote);
905 	if (iph2->dst == NULL) {
906 		delph2(iph2);
907 		goto end;
908 	}
909 	iph2->src = dupsaddr(iph1->local);
910 	if (iph2->src == NULL) {
911 		delph2(iph2);
912 		goto end;
913 	}
914 #if (!defined(ENABLE_NATT)) || (defined(BROKEN_NATT))
915 	if (set_port(iph2->dst, 0) == NULL ||
916 	    set_port(iph2->src, 0) == NULL) {
917 		plog(LLV_ERROR, LOCATION, NULL,
918 		     "invalid family: %d\n", iph1->remote->sa_family);
919 		delph2(iph2);
920 		goto end;
921 	}
922 #endif
923 	iph2->ph1 = iph1;
924 	iph2->side = INITIATOR;
925 	iph2->status = PHASE2ST_START;
926 	iph2->msgid = isakmp_newmsgid2(iph1);
927 
928 	/* get IV and HASH(1) if skeyid_a was generated. */
929 	if (iph1->skeyid_a != NULL) {
930 		iph2->ivm = oakley_newiv2(iph1, iph2->msgid);
931 		if (iph2->ivm == NULL) {
932 			delph2(iph2);
933 			goto end;
934 		}
935 
936 		/* generate HASH(1) */
937 		hash = oakley_compute_hash1(iph2->ph1, iph2->msgid, payload);
938 		if (hash == NULL) {
939 			delph2(iph2);
940 			goto end;
941 		}
942 
943 		/* initialized total buffer length */
944 		tlen = hash->l;
945 		tlen += sizeof(*gen);
946 	} else {
947 		/* IKE-SA is not established */
948 		hash = NULL;
949 
950 		/* initialized total buffer length */
951 		tlen = 0;
952 	}
953 	if ((flags & ISAKMP_FLAG_A) == 0)
954 		iph2->flags = (hash == NULL ? 0 : ISAKMP_FLAG_E);
955 	else
956 		iph2->flags = (hash == NULL ? 0 : ISAKMP_FLAG_A);
957 
958 	insph2(iph2);
959 	bindph12(iph1, iph2);
960 
961 	tlen += sizeof(*isakmp) + payload->l;
962 
963 	/* create buffer for isakmp payload */
964 	iph2->sendbuf = vmalloc(tlen);
965 	if (iph2->sendbuf == NULL) {
966 		plog(LLV_ERROR, LOCATION, NULL,
967 			"failed to get buffer to send.\n");
968 		goto err;
969 	}
970 
971 	/* create isakmp header */
972 	isakmp = (struct isakmp *)iph2->sendbuf->v;
973 	memcpy(&isakmp->i_ck, &iph1->index.i_ck, sizeof(cookie_t));
974 	memcpy(&isakmp->r_ck, &iph1->index.r_ck, sizeof(cookie_t));
975 	isakmp->np = hash == NULL ? (np & 0xff) : ISAKMP_NPTYPE_HASH;
976 	isakmp->v = iph1->version;
977 	isakmp->etype = ISAKMP_ETYPE_INFO;
978 	isakmp->flags = iph2->flags;
979 	memcpy(&isakmp->msgid, &iph2->msgid, sizeof(isakmp->msgid));
980 	isakmp->len   = htonl(tlen);
981 	p = (char *)(isakmp + 1);
982 
983 	/* create HASH payload */
984 	if (hash != NULL) {
985 		gen = (struct isakmp_gen *)p;
986 		gen->np = np & 0xff;
987 		gen->len = htons(sizeof(*gen) + hash->l);
988 		p += sizeof(*gen);
989 		memcpy(p, hash->v, hash->l);
990 		p += hash->l;
991 	}
992 
993 	/* add payload */
994 	memcpy(p, payload->v, payload->l);
995 	p += payload->l;
996 
997 #ifdef HAVE_PRINT_ISAKMP_C
998 	isakmp_printpacket(iph2->sendbuf, iph1->local, iph1->remote, 1);
999 #endif
1000 
1001 	/* encoding */
1002 	if (ISSET(isakmp->flags, ISAKMP_FLAG_E)) {
1003 		vchar_t *tmp;
1004 
1005 		tmp = oakley_do_encrypt(iph2->ph1, iph2->sendbuf, iph2->ivm->ive,
1006 				iph2->ivm->iv);
1007 		VPTRINIT(iph2->sendbuf);
1008 		if (tmp == NULL)
1009 			goto err;
1010 		iph2->sendbuf = tmp;
1011 	}
1012 
1013 	/* HDR*, HASH(1), N */
1014 	if (isakmp_send(iph2->ph1, iph2->sendbuf) < 0) {
1015 		VPTRINIT(iph2->sendbuf);
1016 		goto err;
1017 	}
1018 
1019 	plog(LLV_DEBUG, LOCATION, NULL,
1020 		"sendto Information %s.\n", s_isakmp_nptype(np));
1021 
1022 	/*
1023 	 * don't resend notify message because peer can use Acknowledged
1024 	 * Informational if peer requires the reply of the notify message.
1025 	 */
1026 
1027 	/* XXX If Acknowledged Informational required, don't delete ph2handle */
1028 	error = 0;
1029 	VPTRINIT(iph2->sendbuf);
1030 	goto err;	/* XXX */
1031 
1032 end:
1033 	if (hash)
1034 		vfree(hash);
1035 	return error;
1036 
1037 err:
1038 	unbindph12(iph2);
1039 	remph2(iph2);
1040 	delph2(iph2);
1041 	goto end;
1042 }
1043 
1044 /*
1045  * add a notify payload to buffer by reallocating buffer.
1046  * If buf == NULL, the function only create a notify payload.
1047  *
1048  * XXX Which is SPI to be included, inbound or outbound ?
1049  */
1050 vchar_t *
isakmp_add_pl_n(buf0,np_p,type,pr,data)1051 isakmp_add_pl_n(buf0, np_p, type, pr, data)
1052 	vchar_t *buf0;
1053 	u_int8_t **np_p;
1054 	int type;
1055 	struct saproto *pr;
1056 	vchar_t *data;
1057 {
1058 	vchar_t *buf = NULL;
1059 	struct isakmp_pl_n *n;
1060 	int tlen;
1061 	int oldlen = 0;
1062 
1063 	if (*np_p)
1064 		**np_p = ISAKMP_NPTYPE_N;
1065 
1066 	tlen = sizeof(*n) + pr->spisize;
1067 
1068 	if (data)
1069 		tlen += data->l;
1070 	if (buf0) {
1071 		oldlen = buf0->l;
1072 		buf = vrealloc(buf0, buf0->l + tlen);
1073 	} else
1074 		buf = vmalloc(tlen);
1075 	if (!buf) {
1076 		plog(LLV_ERROR, LOCATION, NULL,
1077 			"failed to get a payload buffer.\n");
1078 		return NULL;
1079 	}
1080 
1081 	n = (struct isakmp_pl_n *)(buf->v + oldlen);
1082 	n->h.np = ISAKMP_NPTYPE_NONE;
1083 	n->h.len = htons(tlen);
1084 	n->doi = htonl(IPSEC_DOI);		/* IPSEC DOI (1) */
1085 	n->proto_id = pr->proto_id;		/* IPSEC AH/ESP/whatever*/
1086 	n->spi_size = pr->spisize;
1087 	n->type = htons(type);
1088 	*(u_int32_t *)(n + 1) = pr->spi;	/* XXX */
1089 	if (data)
1090 		memcpy((caddr_t)(n + 1) + pr->spisize, data->v, data->l);
1091 
1092 	/* save the pointer of next payload type */
1093 	*np_p = &n->h.np;
1094 
1095 	return buf;
1096 }
1097 
1098 static void
purge_isakmp_spi(proto,spi,n)1099 purge_isakmp_spi(proto, spi, n)
1100 	int proto;
1101 	isakmp_index *spi;	/*network byteorder*/
1102 	size_t n;
1103 {
1104 	struct ph1handle *iph1;
1105 	size_t i;
1106 
1107 	for (i = 0; i < n; i++) {
1108 		iph1 = getph1byindex(&spi[i]);
1109 		if (!iph1)
1110 			continue;
1111 
1112 		plog(LLV_INFO, LOCATION, NULL,
1113 			"purged ISAKMP-SA proto_id=%s spi=%s.\n",
1114 			s_ipsecdoi_proto(proto),
1115 			isakmp_pindex(&spi[i], 0));
1116 
1117 		SCHED_KILL(iph1->sce);
1118 		iph1->status = PHASE1ST_EXPIRED;
1119 		iph1->sce = sched_new(1, isakmp_ph1delete_stub, iph1);
1120 	}
1121 }
1122 
1123 
1124 
1125 void
purge_ipsec_spi(dst0,proto,spi,n)1126 purge_ipsec_spi(dst0, proto, spi, n)
1127 	struct sockaddr *dst0;
1128 	int proto;
1129 	u_int32_t *spi;	/*network byteorder*/
1130 	size_t n;
1131 {
1132 	vchar_t *buf = NULL;
1133 	struct sadb_msg *msg, *next, *end;
1134 	struct sadb_sa *sa;
1135 	struct sadb_lifetime *lt;
1136 	struct sockaddr *src, *dst;
1137 	struct ph2handle *iph2;
1138 	u_int64_t created;
1139 	size_t i;
1140 	caddr_t mhp[SADB_EXT_MAX + 1];
1141 #ifdef ENABLE_NATT
1142 	struct sadb_x_nat_t_type *natt_type;
1143 	struct sadb_x_nat_t_port *natt_port;
1144 #endif
1145 
1146 	plog(LLV_DEBUG2, LOCATION, NULL,
1147 		 "purge_ipsec_spi:\n");
1148 	plog(LLV_DEBUG2, LOCATION, NULL, "dst0: %s\n", saddr2str(dst0));
1149 	plog(LLV_DEBUG2, LOCATION, NULL, "SPI: %08X\n", ntohl(spi[0]));
1150 
1151 	buf = pfkey_dump_sadb(ipsecdoi2pfkey_proto(proto));
1152 	if (buf == NULL) {
1153 		plog(LLV_DEBUG, LOCATION, NULL,
1154 			"pfkey_dump_sadb returned nothing.\n");
1155 		return;
1156 	}
1157 
1158 	msg = (struct sadb_msg *)buf->v;
1159 	end = (struct sadb_msg *)(buf->v + buf->l);
1160 
1161 	while (msg < end) {
1162 		if ((msg->sadb_msg_len << 3) < sizeof(*msg))
1163 			break;
1164 		next = (struct sadb_msg *)((caddr_t)msg + (msg->sadb_msg_len << 3));
1165 		if (msg->sadb_msg_type != SADB_DUMP) {
1166 			msg = next;
1167 			continue;
1168 		}
1169 
1170 		if (pfkey_align(msg, mhp) || pfkey_check(mhp)) {
1171 			plog(LLV_ERROR, LOCATION, NULL,
1172 				"pfkey_check (%s)\n", ipsec_strerror());
1173 			msg = next;
1174 			continue;
1175 		}
1176 
1177 		sa = (struct sadb_sa *)(mhp[SADB_EXT_SA]);
1178 		if (!sa
1179 		 || !mhp[SADB_EXT_ADDRESS_SRC]
1180 		 || !mhp[SADB_EXT_ADDRESS_DST]) {
1181 			msg = next;
1182 			continue;
1183 		}
1184 		src = PFKEY_ADDR_SADDR(mhp[SADB_EXT_ADDRESS_SRC]);
1185 		dst = PFKEY_ADDR_SADDR(mhp[SADB_EXT_ADDRESS_DST]);
1186 		lt = (struct sadb_lifetime*)mhp[SADB_EXT_LIFETIME_HARD];
1187 		if(lt != NULL)
1188 			created = lt->sadb_lifetime_addtime;
1189 		else
1190 			created = 0;
1191 
1192 		if (sa->sadb_sa_state != SADB_SASTATE_MATURE
1193 		 && sa->sadb_sa_state != SADB_SASTATE_DYING) {
1194 			msg = next;
1195 			continue;
1196 		}
1197 #ifdef ENABLE_NATT
1198 		natt_type = (void *)mhp[SADB_X_EXT_NAT_T_TYPE];
1199 		if (natt_type && natt_type->sadb_x_nat_t_type_type) {
1200 			/* NAT-T is enabled for this SADB entry; copy
1201 			 * the ports from NAT-T extensions */
1202 			natt_port = (void *)mhp[SADB_X_EXT_NAT_T_SPORT];
1203 			if (extract_port(src) == 0 && natt_port != NULL)
1204 				set_port(src, ntohs(natt_port->sadb_x_nat_t_port_port));
1205 
1206 			natt_port = (void *)mhp[SADB_X_EXT_NAT_T_DPORT];
1207 			if (extract_port(dst) == 0 && natt_port != NULL)
1208 				set_port(dst, ntohs(natt_port->sadb_x_nat_t_port_port));
1209 		}else{
1210 			/* Force default UDP ports, so CMPSADDR will match SAs with NO encapsulation
1211 			 */
1212 			set_port(src, PORT_ISAKMP);
1213 			set_port(dst, PORT_ISAKMP);
1214 		}
1215 #endif
1216 		plog(LLV_DEBUG2, LOCATION, NULL, "src: %s\n", saddr2str(src));
1217 		plog(LLV_DEBUG2, LOCATION, NULL, "dst: %s\n", saddr2str(dst));
1218 
1219 		/* XXX n^2 algorithm, inefficient */
1220 
1221 		/* don't delete inbound SAs at the moment */
1222 		/* XXX should we remove SAs with opposite direction as well? */
1223 		if (CMPSADDR(dst0, dst)) {
1224 			msg = next;
1225 			continue;
1226 		}
1227 
1228 #ifdef ENABLE_NATT
1229 		if (natt_type == NULL ||
1230 			! natt_type->sadb_x_nat_t_type_type) {
1231 			/* Set back port to 0 if it was forced to default UDP port
1232 			 */
1233 			set_port(src, 0);
1234 			set_port(dst, 0);
1235 		}
1236 #endif
1237 		for (i = 0; i < n; i++) {
1238 			plog(LLV_DEBUG, LOCATION, NULL,
1239 				"check spi(packet)=%u spi(db)=%u.\n",
1240 				ntohl(spi[i]), ntohl(sa->sadb_sa_spi));
1241 			if (spi[i] != sa->sadb_sa_spi)
1242 				continue;
1243 
1244 			pfkey_send_delete(lcconf->sock_pfkey,
1245 				msg->sadb_msg_satype,
1246 				IPSEC_MODE_ANY,
1247 				src, dst, sa->sadb_sa_spi);
1248 
1249 			/*
1250 			 * delete a relative phase 2 handler.
1251 			 * continue to process if no relative phase 2 handler
1252 			 * exists.
1253 			 */
1254 			iph2 = getph2bysaidx(src, dst, proto, spi[i]);
1255 			if(iph2 != NULL){
1256 				delete_spd(iph2, created);
1257 				unbindph12(iph2);
1258 				remph2(iph2);
1259 				delph2(iph2);
1260 			}
1261 
1262 			plog(LLV_INFO, LOCATION, NULL,
1263 				"purged IPsec-SA proto_id=%s spi=%u.\n",
1264 				s_ipsecdoi_proto(proto),
1265 				ntohl(spi[i]));
1266 		}
1267 
1268 		msg = next;
1269 	}
1270 
1271 	if (buf)
1272 		vfree(buf);
1273 }
1274 
1275 /*
1276  * delete all phase2 sa relatived to the destination address.
1277  * Don't delete Phase 1 handlers on INITIAL-CONTACT, and don't ignore
1278  * an INITIAL-CONTACT if we have contacted the peer.  This matches the
1279  * Sun IKE behavior, and makes rekeying work much better when the peer
1280  * restarts.
1281  */
1282 static void
info_recv_initialcontact(iph1)1283 info_recv_initialcontact(iph1)
1284 	struct ph1handle *iph1;
1285 {
1286 	vchar_t *buf = NULL;
1287 	struct sadb_msg *msg, *next, *end;
1288 	struct sadb_sa *sa;
1289 	struct sockaddr *src, *dst;
1290 	caddr_t mhp[SADB_EXT_MAX + 1];
1291 	int proto_id, i;
1292 	struct ph2handle *iph2;
1293 #if 0
1294 	char *loc, *rem;
1295 #endif
1296 
1297 	if (f_local)
1298 		return;
1299 
1300 #if 0
1301 	loc = racoon_strdup(saddrwop2str(iph1->local));
1302 	rem = racoon_strdup(saddrwop2str(iph1->remote));
1303 	STRDUP_FATAL(loc);
1304 	STRDUP_FATAL(rem);
1305 
1306 	/*
1307 	 * Purge all IPSEC-SAs for the peer.  We can do this
1308 	 * the easy way (using a PF_KEY SADB_DELETE extension)
1309 	 * or we can do it the hard way.
1310 	 */
1311 	for (i = 0; i < pfkey_nsatypes; i++) {
1312 		proto_id = pfkey2ipsecdoi_proto(pfkey_satypes[i].ps_satype);
1313 
1314 		plog(LLV_INFO, LOCATION, NULL,
1315 		    "purging %s SAs for %s -> %s\n",
1316 		    pfkey_satypes[i].ps_name, loc, rem);
1317 		if (pfkey_send_delete_all(lcconf->sock_pfkey,
1318 		    pfkey_satypes[i].ps_satype, IPSEC_MODE_ANY,
1319 		    iph1->local, iph1->remote) == -1) {
1320 			plog(LLV_ERROR, LOCATION, NULL,
1321 			    "delete_all %s -> %s failed for %s (%s)\n",
1322 			    loc, rem,
1323 			    pfkey_satypes[i].ps_name, ipsec_strerror());
1324 			goto the_hard_way;
1325 		}
1326 
1327 		deleteallph2(iph1->local, iph1->remote, proto_id);
1328 
1329 		plog(LLV_INFO, LOCATION, NULL,
1330 		    "purging %s SAs for %s -> %s\n",
1331 		    pfkey_satypes[i].ps_name, rem, loc);
1332 		if (pfkey_send_delete_all(lcconf->sock_pfkey,
1333 		    pfkey_satypes[i].ps_satype, IPSEC_MODE_ANY,
1334 		    iph1->remote, iph1->local) == -1) {
1335 			plog(LLV_ERROR, LOCATION, NULL,
1336 			    "delete_all %s -> %s failed for %s (%s)\n",
1337 			    rem, loc,
1338 			    pfkey_satypes[i].ps_name, ipsec_strerror());
1339 			goto the_hard_way;
1340 		}
1341 
1342 		deleteallph2(iph1->remote, iph1->local, proto_id);
1343 	}
1344 
1345 	racoon_free(loc);
1346 	racoon_free(rem);
1347 	return;
1348 
1349  the_hard_way:
1350 	racoon_free(loc);
1351 	racoon_free(rem);
1352 #endif
1353 
1354 	buf = pfkey_dump_sadb(SADB_SATYPE_UNSPEC);
1355 	if (buf == NULL) {
1356 		plog(LLV_DEBUG, LOCATION, NULL,
1357 			"pfkey_dump_sadb returned nothing.\n");
1358 		return;
1359 	}
1360 
1361 	msg = (struct sadb_msg *)buf->v;
1362 	end = (struct sadb_msg *)(buf->v + buf->l);
1363 
1364 	while (msg < end) {
1365 		if ((msg->sadb_msg_len << 3) < sizeof(*msg))
1366 			break;
1367 		next = (struct sadb_msg *)((caddr_t)msg + (msg->sadb_msg_len << 3));
1368 		if (msg->sadb_msg_type != SADB_DUMP) {
1369 			msg = next;
1370 			continue;
1371 		}
1372 
1373 		if (pfkey_align(msg, mhp) || pfkey_check(mhp)) {
1374 			plog(LLV_ERROR, LOCATION, NULL,
1375 				"pfkey_check (%s)\n", ipsec_strerror());
1376 			msg = next;
1377 			continue;
1378 		}
1379 
1380 		if (mhp[SADB_EXT_SA] == NULL
1381 		 || mhp[SADB_EXT_ADDRESS_SRC] == NULL
1382 		 || mhp[SADB_EXT_ADDRESS_DST] == NULL) {
1383 			msg = next;
1384 			continue;
1385 		}
1386 		sa = (struct sadb_sa *)mhp[SADB_EXT_SA];
1387 		src = PFKEY_ADDR_SADDR(mhp[SADB_EXT_ADDRESS_SRC]);
1388 		dst = PFKEY_ADDR_SADDR(mhp[SADB_EXT_ADDRESS_DST]);
1389 
1390 		if (sa->sadb_sa_state != SADB_SASTATE_MATURE
1391 		 && sa->sadb_sa_state != SADB_SASTATE_DYING) {
1392 			msg = next;
1393 			continue;
1394 		}
1395 
1396 		/*
1397 		 * RFC2407 4.6.3.3 INITIAL-CONTACT is the message that
1398 		 * announces the sender of the message was rebooted.
1399 		 * it is interpreted to delete all SAs which source address
1400 		 * is the sender of the message.
1401 		 * racoon only deletes SA which is matched both the
1402 		 * source address and the destination accress.
1403 		 */
1404 #ifdef ENABLE_NATT
1405 		/*
1406 		 * XXX RFC 3947 says that whe MUST NOT use IP+port to find old SAs
1407 		 * from this peer !
1408 		 */
1409 		if(iph1->natt_flags & NAT_DETECTED){
1410 			if (CMPSADDR(iph1->local, src) == 0 &&
1411 				CMPSADDR(iph1->remote, dst) == 0)
1412 				;
1413 			else if (CMPSADDR(iph1->remote, src) == 0 &&
1414 					 CMPSADDR(iph1->local, dst) == 0)
1415 				;
1416 			else {
1417 				msg = next;
1418 				continue;
1419 			}
1420 		} else
1421 #endif
1422 		/* If there is no NAT-T, we don't have to check addr + port...
1423 		 * XXX what about a configuration with a remote peers which is not
1424 		 * NATed, but which NATs some other peers ?
1425 		 * Here, the INITIAl-CONTACT would also flush all those NATed peers !!
1426 		 */
1427 		if (cmpsaddrwop(iph1->local, src) == 0 &&
1428 		    cmpsaddrwop(iph1->remote, dst) == 0)
1429 			;
1430 		else if (cmpsaddrwop(iph1->remote, src) == 0 &&
1431 		    cmpsaddrwop(iph1->local, dst) == 0)
1432 			;
1433 		else {
1434 			msg = next;
1435 			continue;
1436 		}
1437 
1438 		/*
1439 		 * Make sure this is an SATYPE that we manage.
1440 		 * This is gross; too bad we couldn't do it the
1441 		 * easy way.
1442 		 */
1443 		for (i = 0; i < pfkey_nsatypes; i++) {
1444 			if (pfkey_satypes[i].ps_satype ==
1445 			    msg->sadb_msg_satype)
1446 				break;
1447 		}
1448 		if (i == pfkey_nsatypes) {
1449 			msg = next;
1450 			continue;
1451 		}
1452 
1453 		plog(LLV_INFO, LOCATION, NULL,
1454 			"purging spi=%u.\n", ntohl(sa->sadb_sa_spi));
1455 		pfkey_send_delete(lcconf->sock_pfkey,
1456 			msg->sadb_msg_satype,
1457 			IPSEC_MODE_ANY, src, dst, sa->sadb_sa_spi);
1458 
1459 		/*
1460 		 * delete a relative phase 2 handler.
1461 		 * continue to process if no relative phase 2 handler
1462 		 * exists.
1463 		 */
1464 		proto_id = pfkey2ipsecdoi_proto(msg->sadb_msg_satype);
1465 		iph2 = getph2bysaidx(src, dst, proto_id, sa->sadb_sa_spi);
1466 		if (iph2) {
1467 			delete_spd(iph2, 0);
1468 			unbindph12(iph2);
1469 			remph2(iph2);
1470 			delph2(iph2);
1471 		}
1472 
1473 		msg = next;
1474 	}
1475 
1476 	vfree(buf);
1477 }
1478 
1479 void
isakmp_check_notify(gen,iph1)1480 isakmp_check_notify(gen, iph1)
1481 	struct isakmp_gen *gen;		/* points to Notify payload */
1482 	struct ph1handle *iph1;
1483 {
1484 	struct isakmp_pl_n *notify = (struct isakmp_pl_n *)gen;
1485 
1486 	plog(LLV_DEBUG, LOCATION, iph1->remote,
1487 		"Notify Message received\n");
1488 
1489 	switch (ntohs(notify->type)) {
1490 	case ISAKMP_NTYPE_CONNECTED:
1491 	case ISAKMP_NTYPE_RESPONDER_LIFETIME:
1492 	case ISAKMP_NTYPE_REPLAY_STATUS:
1493 	case ISAKMP_NTYPE_HEARTBEAT:
1494 #ifdef ENABLE_HYBRID
1495 	case ISAKMP_NTYPE_UNITY_HEARTBEAT:
1496 #endif
1497 		plog(LLV_WARNING, LOCATION, iph1->remote,
1498 			"ignore %s notification.\n",
1499 			s_isakmp_notify_msg(ntohs(notify->type)));
1500 		break;
1501 	case ISAKMP_NTYPE_INITIAL_CONTACT:
1502 		plog(LLV_WARNING, LOCATION, iph1->remote,
1503 			"ignore INITIAL-CONTACT notification, "
1504 			"because it is only accepted after phase1.\n");
1505 		break;
1506 	default:
1507 		isakmp_info_send_n1(iph1, ISAKMP_NTYPE_INVALID_PAYLOAD_TYPE, NULL);
1508 		plog(LLV_ERROR, LOCATION, iph1->remote,
1509 			"received unknown notification type %s.\n",
1510 			s_isakmp_notify_msg(ntohs(notify->type)));
1511 	}
1512 
1513 	return;
1514 }
1515 
1516 
1517 #ifdef ENABLE_DPD
1518 static int
isakmp_info_recv_r_u(iph1,ru,msgid)1519 isakmp_info_recv_r_u (iph1, ru, msgid)
1520 	struct ph1handle *iph1;
1521 	struct isakmp_pl_ru *ru;
1522 	u_int32_t msgid;
1523 {
1524 	struct isakmp_pl_ru *ru_ack;
1525 	vchar_t *payload = NULL;
1526 	int tlen;
1527 	int error = 0;
1528 
1529 	plog(LLV_DEBUG, LOCATION, iph1->remote,
1530 		 "DPD R-U-There received\n");
1531 
1532 	/* XXX should compare cookies with iph1->index?
1533 	   Or is this already done by calling function?  */
1534 	tlen = sizeof(*ru_ack);
1535 	payload = vmalloc(tlen);
1536 	if (payload == NULL) {
1537 		plog(LLV_ERROR, LOCATION, NULL,
1538 			"failed to get buffer to send.\n");
1539 		return errno;
1540 	}
1541 
1542 	ru_ack = (struct isakmp_pl_ru *)payload->v;
1543 	ru_ack->h.np = ISAKMP_NPTYPE_NONE;
1544 	ru_ack->h.len = htons(tlen);
1545 	ru_ack->doi = htonl(IPSEC_DOI);
1546 	ru_ack->type = htons(ISAKMP_NTYPE_R_U_THERE_ACK);
1547 	ru_ack->proto_id = IPSECDOI_PROTO_ISAKMP; /* XXX ? */
1548 	ru_ack->spi_size = sizeof(isakmp_index);
1549 	memcpy(ru_ack->i_ck, ru->i_ck, sizeof(cookie_t));
1550 	memcpy(ru_ack->r_ck, ru->r_ck, sizeof(cookie_t));
1551 	ru_ack->data = ru->data;
1552 
1553 	/* XXX Should we do FLAG_A ?  */
1554 	error = isakmp_info_send_common(iph1, payload, ISAKMP_NPTYPE_N,
1555 					ISAKMP_FLAG_E);
1556 	vfree(payload);
1557 
1558 	plog(LLV_DEBUG, LOCATION, NULL, "received a valid R-U-THERE, ACK sent\n");
1559 
1560 	/* Should we mark tunnel as active ? */
1561 	return error;
1562 }
1563 
1564 static int
isakmp_info_recv_r_u_ack(iph1,ru,msgid)1565 isakmp_info_recv_r_u_ack (iph1, ru, msgid)
1566 	struct ph1handle *iph1;
1567 	struct isakmp_pl_ru *ru;
1568 	u_int32_t msgid;
1569 {
1570 
1571 	plog(LLV_DEBUG, LOCATION, iph1->remote,
1572 		 "DPD R-U-There-Ack received\n");
1573 
1574 	/* XXX Maintain window of acceptable sequence numbers ?
1575 	 * => ru->data <= iph2->dpd_seq &&
1576 	 *    ru->data >= iph2->dpd_seq - iph2->dpd_fails ? */
1577 	if (ntohl(ru->data) != iph1->dpd_seq-1) {
1578 		plog(LLV_ERROR, LOCATION, iph1->remote,
1579 			 "Wrong DPD sequence number (%d, %d expected).\n",
1580 			 ntohl(ru->data), iph1->dpd_seq-1);
1581 		return 0;
1582 	}
1583 
1584 	if (memcmp(ru->i_ck, iph1->index.i_ck, sizeof(cookie_t)) ||
1585 	    memcmp(ru->r_ck, iph1->index.r_ck, sizeof(cookie_t))) {
1586 		plog(LLV_ERROR, LOCATION, iph1->remote,
1587 			 "Cookie mismatch in DPD ACK!.\n");
1588 		return 0;
1589 	}
1590 
1591 	iph1->dpd_fails = 0;
1592 
1593 	/* Useless ??? */
1594 	iph1->dpd_lastack = time(NULL);
1595 
1596 	SCHED_KILL(iph1->dpd_r_u);
1597 
1598 	isakmp_sched_r_u(iph1, 0);
1599 
1600 	plog(LLV_DEBUG, LOCATION, NULL, "received an R-U-THERE-ACK\n");
1601 
1602 	return 0;
1603 }
1604 
1605 
1606 
1607 
1608 /*
1609  * send DPD R-U-THERE payload in Informational exchange.
1610  */
1611 static void
isakmp_info_send_r_u(arg)1612 isakmp_info_send_r_u(arg)
1613 	void *arg;
1614 {
1615 	struct ph1handle *iph1 = arg;
1616 
1617 	/* create R-U-THERE payload */
1618 	struct isakmp_pl_ru *ru;
1619 	vchar_t *payload = NULL;
1620 	int tlen;
1621 	int error = 0;
1622 
1623 	plog(LLV_DEBUG, LOCATION, iph1->remote, "DPD monitoring....\n");
1624 
1625 	iph1->dpd_r_u=NULL;
1626 
1627 	if (iph1->dpd_fails >= iph1->rmconf->dpd_maxfails) {
1628 
1629 		plog(LLV_INFO, LOCATION, iph1->remote,
1630 			"DPD: remote (ISAKMP-SA spi=%s) seems to be dead.\n",
1631 			isakmp_pindex(&iph1->index, 0));
1632 
1633 		EVT_PUSH(iph1->local, iph1->remote, EVTT_DPD_TIMEOUT, NULL);
1634 		purge_remote(iph1);
1635 
1636 		/* Do not reschedule here: phase1 is deleted,
1637 		 * DPD will be reactivated when a new ph1 will be negociated
1638 		 */
1639 		return;
1640 	}
1641 
1642 	/* TODO: check recent activity to avoid useless sends... */
1643 
1644 	tlen = sizeof(*ru);
1645 	payload = vmalloc(tlen);
1646 	if (payload == NULL) {
1647 		plog(LLV_ERROR, LOCATION, NULL,
1648 			 "failed to get buffer for payload.\n");
1649 		return;
1650 	}
1651 	ru = (struct isakmp_pl_ru *)payload->v;
1652 	ru->h.np = ISAKMP_NPTYPE_NONE;
1653 	ru->h.len = htons(tlen);
1654 	ru->doi = htonl(IPSEC_DOI);
1655 	ru->type = htons(ISAKMP_NTYPE_R_U_THERE);
1656 	ru->proto_id = IPSECDOI_PROTO_ISAKMP; /* XXX ?*/
1657 	ru->spi_size = sizeof(isakmp_index);
1658 
1659 	memcpy(ru->i_ck, iph1->index.i_ck, sizeof(cookie_t));
1660 	memcpy(ru->r_ck, iph1->index.r_ck, sizeof(cookie_t));
1661 
1662 	if (iph1->dpd_seq == 0){
1663 		/* generate a random seq which is not too big */
1664 		srand(time(NULL));
1665 		iph1->dpd_seq = rand() & 0x0fff;
1666 	}
1667 
1668 	ru->data = htonl(iph1->dpd_seq);
1669 
1670 	error = isakmp_info_send_common(iph1, payload, ISAKMP_NPTYPE_N, 0);
1671 	vfree(payload);
1672 
1673 	plog(LLV_DEBUG, LOCATION, iph1->remote,
1674 		 "DPD R-U-There sent (%d)\n", error);
1675 
1676 	/* will be decreased if ACK received... */
1677 	iph1->dpd_fails++;
1678 
1679 	/* XXX should be increased only when ACKed ? */
1680 	iph1->dpd_seq++;
1681 
1682 	/* Reschedule the r_u_there with a short delay,
1683 	 * will be deleted/rescheduled if ACK received before */
1684 	isakmp_sched_r_u(iph1, 1);
1685 
1686 	plog(LLV_DEBUG, LOCATION, iph1->remote,
1687 		 "rescheduling send_r_u (%d).\n", iph1->rmconf->dpd_retry);
1688 }
1689 
1690 /* Schedule a new R-U-THERE */
1691 int
isakmp_sched_r_u(iph1,retry)1692 isakmp_sched_r_u(iph1, retry)
1693 	struct ph1handle *iph1;
1694 	int retry;
1695 {
1696 	if(iph1 == NULL ||
1697 	   iph1->rmconf == NULL)
1698 		return 1;
1699 
1700 
1701 	if(iph1->dpd_support == 0 ||
1702 	   iph1->rmconf->dpd_interval == 0)
1703 		return 0;
1704 
1705 	if(retry)
1706 		iph1->dpd_r_u = sched_new(iph1->rmconf->dpd_retry,
1707 								  isakmp_info_send_r_u, iph1);
1708 	else
1709 		iph1->dpd_r_u = sched_new(iph1->rmconf->dpd_interval,
1710 								  isakmp_info_send_r_u, iph1);
1711 
1712 	return 0;
1713 }
1714 #endif
1715