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