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