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