xref: /openbsd-src/sbin/isakmpd/exchange.c (revision f2da64fbbbf1b03f09f390ab01267c93dfd77c4c)
1 /* $OpenBSD: exchange.c,v 1.138 2016/03/10 07:32:16 yasuoka Exp $	 */
2 /* $EOM: exchange.c,v 1.143 2000/12/04 00:02:25 angelos Exp $	 */
3 
4 /*
5  * Copyright (c) 1998, 1999, 2000, 2001 Niklas Hallqvist.  All rights reserved.
6  * Copyright (c) 1999, 2001 Angelos D. Keromytis.  All rights reserved.
7  * Copyright (c) 1999, 2000, 2002 H�kan Olsson.  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  *
18  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
19  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
20  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
21  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
22  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
23  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
27  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28  */
29 
30 /*
31  * This code was written under funding by Ericsson Radio Systems.
32  */
33 
34 #include <sys/types.h>
35 #include <sys/socket.h>
36 #include <netinet/in.h>
37 #include <arpa/inet.h>
38 #include <stdlib.h>
39 #include <string.h>
40 #include <regex.h>
41 #include <keynote.h>
42 
43 #include "cert.h"
44 #include "conf.h"
45 #include "connection.h"
46 #include "constants.h"
47 #include "cookie.h"
48 #include "crypto.h"
49 #include "doi.h"
50 #include "exchange.h"
51 #include "ipsec_num.h"
52 #include "isakmp.h"
53 #include "isakmp_cfg.h"
54 #include "libcrypto.h"
55 #include "log.h"
56 #include "message.h"
57 #include "timer.h"
58 #include "transport.h"
59 #include "ipsec.h"
60 #include "sa.h"
61 #include "ui.h"
62 #include "util.h"
63 #include "key.h"
64 #include "dpd.h"
65 
66 /* Initial number of bits from the cookies used as hash.  */
67 #define INITIAL_BUCKET_BITS 6
68 
69 /*
70  * Don't try to use more bits than this as a hash.
71  * We only XOR 16 bits so going above that means changing the code below
72  * too.
73  */
74 #define MAX_BUCKET_BITS 16
75 
76 static void     exchange_dump(char *, struct exchange *);
77 static void     exchange_free_aux(void *);
78 static struct exchange *exchange_lookup_active(char *, int);
79 
80 static
81 LIST_HEAD(exchange_list, exchange) *exchange_tab;
82 
83 /* Works both as a maximum index and a mask.  */
84 static int      bucket_mask;
85 
86 /*
87  * Validation scripts used to test messages for correct content of
88  * payloads depending on the exchange type.
89  */
90 int16_t script_base[] = {
91 	ISAKMP_PAYLOAD_SA,	/* Initiator -> responder.  */
92 	ISAKMP_PAYLOAD_NONCE,
93 	EXCHANGE_SCRIPT_SWITCH,
94 	ISAKMP_PAYLOAD_SA,	/* Responder -> initiator.  */
95 	ISAKMP_PAYLOAD_NONCE,
96 	EXCHANGE_SCRIPT_SWITCH,
97 	ISAKMP_PAYLOAD_KEY_EXCH,	/* Initiator -> responder.  */
98 	ISAKMP_PAYLOAD_ID,
99 	EXCHANGE_SCRIPT_AUTH,
100 	EXCHANGE_SCRIPT_SWITCH,
101 	ISAKMP_PAYLOAD_KEY_EXCH,	/* Responder -> initiator.  */
102 	ISAKMP_PAYLOAD_ID,
103 	EXCHANGE_SCRIPT_AUTH,
104 	EXCHANGE_SCRIPT_END
105 };
106 
107 int16_t script_identity_protection[] = {
108 	ISAKMP_PAYLOAD_SA,	/* Initiator -> responder.  */
109 	EXCHANGE_SCRIPT_SWITCH,
110 	ISAKMP_PAYLOAD_SA,	/* Responder -> initiator.  */
111 	EXCHANGE_SCRIPT_SWITCH,
112 	ISAKMP_PAYLOAD_KEY_EXCH,	/* Initiator -> responder.  */
113 	ISAKMP_PAYLOAD_NONCE,
114 	EXCHANGE_SCRIPT_SWITCH,
115 	ISAKMP_PAYLOAD_KEY_EXCH,	/* Responder -> initiator.  */
116 	ISAKMP_PAYLOAD_NONCE,
117 	EXCHANGE_SCRIPT_SWITCH,
118 	ISAKMP_PAYLOAD_ID,	/* Initiator -> responder.  */
119 	EXCHANGE_SCRIPT_AUTH,
120 	EXCHANGE_SCRIPT_SWITCH,
121 	ISAKMP_PAYLOAD_ID,	/* Responder -> initiator.  */
122 	EXCHANGE_SCRIPT_AUTH,
123 	EXCHANGE_SCRIPT_END
124 };
125 
126 int16_t script_authentication_only[] = {
127 	ISAKMP_PAYLOAD_SA,	/* Initiator -> responder.  */
128 	ISAKMP_PAYLOAD_NONCE,
129 	EXCHANGE_SCRIPT_SWITCH,
130 	ISAKMP_PAYLOAD_SA,	/* Responder -> initiator.  */
131 	ISAKMP_PAYLOAD_NONCE,
132 	ISAKMP_PAYLOAD_ID,
133 	EXCHANGE_SCRIPT_AUTH,
134 	EXCHANGE_SCRIPT_SWITCH,
135 	ISAKMP_PAYLOAD_ID,	/* Initiator -> responder.  */
136 	EXCHANGE_SCRIPT_AUTH,
137 	EXCHANGE_SCRIPT_END
138 };
139 
140 int16_t script_aggressive[] = {
141 	ISAKMP_PAYLOAD_SA,	/* Initiator -> responder.  */
142 	ISAKMP_PAYLOAD_KEY_EXCH,
143 	ISAKMP_PAYLOAD_NONCE,
144 	ISAKMP_PAYLOAD_ID,
145 	EXCHANGE_SCRIPT_SWITCH,
146 	ISAKMP_PAYLOAD_SA,	/* Responder -> initiator.  */
147 	ISAKMP_PAYLOAD_KEY_EXCH,
148 	ISAKMP_PAYLOAD_NONCE,
149 	ISAKMP_PAYLOAD_ID,
150 	EXCHANGE_SCRIPT_AUTH,
151 	EXCHANGE_SCRIPT_SWITCH,
152 	EXCHANGE_SCRIPT_AUTH,	/* Initiator -> responder.  */
153 	EXCHANGE_SCRIPT_END
154 };
155 
156 int16_t script_informational[] = {
157 	EXCHANGE_SCRIPT_INFO,	/* Initiator -> responder.  */
158 	EXCHANGE_SCRIPT_END
159 };
160 
161 /*
162  * Check what exchange SA is negotiated with and return a suitable validation
163  * script.
164  */
165 int16_t *
166 exchange_script(struct exchange *exchange)
167 {
168 	switch (exchange->type) {
169 	case ISAKMP_EXCH_BASE:
170 		return script_base;
171 	case ISAKMP_EXCH_ID_PROT:
172 		return script_identity_protection;
173 	case ISAKMP_EXCH_AUTH_ONLY:
174 		return script_authentication_only;
175 	case ISAKMP_EXCH_AGGRESSIVE:
176 		return script_aggressive;
177 	case ISAKMP_EXCH_INFO:
178 		return script_informational;
179 	case ISAKMP_EXCH_TRANSACTION:
180 		return script_transaction;
181 	default:
182 		if (exchange->type >= ISAKMP_EXCH_DOI_MIN)
183 			return exchange->doi->exchange_script(exchange->type);
184 	}
185 	return 0;
186 }
187 
188 /*
189  * Validate the message MSG's contents wrt what payloads the exchange type
190  * requires at this point in the dialogue.  Return -1 if the validation fails,
191  * 0 if it succeeds and the script is not finished and 1 if it's ready.
192  */
193 static int
194 exchange_validate(struct message *msg)
195 {
196 	struct exchange *exchange = msg->exchange;
197 	int16_t		*pc = exchange->exch_pc;
198 
199 	while (*pc != EXCHANGE_SCRIPT_END && *pc != EXCHANGE_SCRIPT_SWITCH) {
200 		LOG_DBG((LOG_EXCHANGE, 90,
201 		    "exchange_validate: checking for required %s",
202 		    *pc >= ISAKMP_PAYLOAD_NONE
203 		    ? constant_name(isakmp_payload_cst, *pc)
204 		    : constant_name(exchange_script_cst, *pc)));
205 
206 		/* Check for existence of the required payloads.  */
207 		if ((*pc > 0 && !payload_first(msg, *pc)) ||
208 		    (*pc == EXCHANGE_SCRIPT_AUTH &&
209 		    !payload_first(msg, ISAKMP_PAYLOAD_HASH) &&
210 		    !payload_first(msg, ISAKMP_PAYLOAD_SIG)) ||
211 		    (*pc == EXCHANGE_SCRIPT_INFO &&
212 		    ((!payload_first(msg, ISAKMP_PAYLOAD_NOTIFY) &&
213 		    !payload_first(msg, ISAKMP_PAYLOAD_DELETE)) ||
214 		    (payload_first(msg, ISAKMP_PAYLOAD_DELETE) &&
215 		    !payload_first(msg, ISAKMP_PAYLOAD_HASH))))) {
216 			/* Missing payload.  */
217 			LOG_DBG((LOG_MESSAGE, 70,
218 			    "exchange_validate: msg %p requires missing %s",
219 			    msg, *pc >= ISAKMP_PAYLOAD_NONE
220 			    ? constant_name(isakmp_payload_cst, *pc)
221 			    : constant_name(exchange_script_cst, *pc)));
222 			return -1;
223 		}
224 		pc++;
225 	}
226 	if (*pc == EXCHANGE_SCRIPT_END)
227 		/* Cleanup.  */
228 		return 1;
229 
230 	return 0;
231 }
232 
233 /* Feed unhandled payloads to the DOI for handling. Help for exchange_run(). */
234 static void
235 exchange_handle_leftover_payloads(struct message *msg)
236 {
237 	struct exchange *exchange = msg->exchange;
238 	struct doi	*doi = exchange->doi;
239 	struct payload	*p;
240 	int	i;
241 
242 	for (i = ISAKMP_PAYLOAD_SA; i < ISAKMP_PAYLOAD_MAX; i++) {
243 		if (i == ISAKMP_PAYLOAD_PROPOSAL ||
244 		    i == ISAKMP_PAYLOAD_TRANSFORM)
245 			continue;
246 		TAILQ_FOREACH(p, &msg->payload[i], link) {
247 			if (p->flags & PL_MARK)
248 				continue;
249 			if (!doi->handle_leftover_payload ||
250 			    doi->handle_leftover_payload(msg, i, p))
251 				LOG_DBG((LOG_EXCHANGE, 10,
252 				    "exchange_handle_leftover_payloads: "
253 				    "unexpected payload %s",
254 				    constant_name(isakmp_payload_cst, i)));
255 		}
256 	}
257 }
258 
259 /*
260  * Run the exchange script from a point given by the "program counter"
261  * upto either the script's end or a transmittal of a message.  If we are
262  * at the point of a reception of a message, that message should be handed
263  * in here in the MSG argument.  Otherwise we are the initiator and should
264  * expect MSG to be a half-cooked message without payloads.
265  */
266 void
267 exchange_run(struct message *msg)
268 {
269 	struct exchange *exchange = msg->exchange;
270 	struct doi	*doi = exchange->doi;
271 	int             (*handler)(struct message *) = exchange->initiator ?
272 			    doi->initiator : doi->responder;
273 	int              done = 0;
274 
275 	while (!done) {
276 		/*
277 		 * It's our turn if we're either the initiator on an even step,
278 		 * or the responder on an odd step of the dialogue.
279 		 */
280 		if (exchange->initiator ^ (exchange->step % 2)) {
281 			done = 1;
282 			if (exchange->step)
283 				msg = message_alloc_reply(msg);
284 			message_setup_header(msg, exchange->type, 0,
285 			    exchange->message_id);
286 			if (handler(msg)) {
287 				/*
288 				 * This can happen when transient starvation
289 				 * of memory occurs.
290 				 * XXX The peer's retransmit ought to
291 				 * kick-start this exchange again.  If he's
292 				 * stopped retransmitting he's likely dropped
293 				 * the SA at his side so we need to do that
294 				 * too, i.e.  implement automatic SA teardown
295 				 * after a certain amount of inactivity.
296 				 */
297 				log_print("exchange_run: doi->%s (%p) failed",
298 				    exchange->initiator ? "initiator" :
299 				    "responder", msg);
300 				message_free(msg);
301 				return;
302 			}
303 			switch (exchange_validate(msg)) {
304 			case 1:
305 				/*
306 				 * The last message of a multi-message
307 				 * exchange should not be retransmitted other
308 				 * than "on-demand", i.e. if we see
309 				 * retransmits of the last message of the peer
310 				 * later.
311 				 */
312 				msg->flags |= MSG_LAST;
313 				if (exchange->step > 0) {
314 					if (exchange->last_sent)
315 						message_free(exchange->last_sent);
316 					exchange->last_sent = msg;
317 				}
318 				/*
319 				 * After we physically have sent our last
320 				 * message we need to do SA-specific
321 				 * finalization, like telling our application
322 				 * the SA is ready to be used, or issuing a
323 				 * CONNECTED notify if we set the COMMIT bit.
324 				 */
325 				message_register_post_send(msg,
326 				    exchange_finalize);
327 
328 				/* FALLTHROUGH */
329 
330 			case 0:
331 				/*
332 				 * Don't retransmit responses for
333 				 * unauthenticated messages.
334 				 */
335 				if ((exchange->type == ISAKMP_EXCH_ID_PROT ||
336 				    exchange->type == ISAKMP_EXCH_AGGRESSIVE) &&
337 				    exchange->phase == 1 && exchange->step == 1)
338 					msg->flags |= MSG_DONTRETRANSMIT;
339 
340 				/* XXX error handling.  */
341 				message_send(msg);
342 				break;
343 
344 			default:
345 				log_print("exchange_run: exchange_validate "
346 				    "failed, DOI error");
347 				exchange_free(exchange);
348 				message_free(msg);
349 				return;
350 			}
351 		} else {
352 			done = exchange_validate(msg);
353 			switch (done) {
354 			case 0:
355 			case 1:
356 				/* Feed the message to the DOI.  */
357 				if (handler(msg)) {
358 					/*
359 					 * Trust the peer to retransmit.
360 					 * XXX We have to implement SA aging
361 					 * with automatic teardown.
362 					 */
363 					message_free(msg);
364 					return;
365 				}
366 				/*
367 				 * Go over the yet unhandled payloads and feed
368 				 * them to DOI for handling.
369 				 */
370 				exchange_handle_leftover_payloads(msg);
371 
372 				/*
373 				 * We have advanced the state.  If we have
374 				 * been processing an incoming message, record
375 				 * that message as the one to do duplication
376 				 * tests against.
377 				 */
378 				if (exchange->last_received)
379 					message_free(exchange->last_received);
380 				exchange->last_received = msg;
381 				if (exchange->flags & EXCHANGE_FLAG_ENCRYPT)
382 					crypto_update_iv(exchange->keystate);
383 
384 				if (done) {
385 					exchange_finalize(msg);
386 					return;
387 				}
388 				break;
389 
390 			case -1:
391 				log_print("exchange_run: exchange_validate "
392 				    "failed");
393 				/*
394 				 * XXX Is this the best error notification
395 				 * type?
396 				 */
397 				message_drop(msg,
398 				    ISAKMP_NOTIFY_PAYLOAD_MALFORMED, 0, 1, 1);
399 				return;
400 			}
401 		}
402 
403 		LOG_DBG((LOG_EXCHANGE, 40,
404 		    "exchange_run: exchange %p finished step %d, advancing...",
405 		    exchange, exchange->step));
406 		exchange->step++;
407 		while (*exchange->exch_pc != EXCHANGE_SCRIPT_SWITCH &&
408 		    *exchange->exch_pc != EXCHANGE_SCRIPT_END)
409 			exchange->exch_pc++;
410 		exchange->exch_pc++;
411 	}
412 }
413 
414 void
415 exchange_init(void)
416 {
417 	int	i;
418 
419 	bucket_mask = (1 << INITIAL_BUCKET_BITS) - 1;
420 	exchange_tab = calloc(bucket_mask + 1, sizeof(struct exchange_list));
421 	if (!exchange_tab)
422 		log_fatal("exchange_init: out of memory");
423 	for (i = 0; i <= bucket_mask; i++)
424 		LIST_INIT(&exchange_tab[i]);
425 }
426 
427 /* Lookup a phase 1 exchange out of just the initiator cookie.  */
428 struct exchange *
429 exchange_lookup_from_icookie(u_int8_t *cookie)
430 {
431 	struct exchange *exchange;
432 	int	i;
433 
434 	for (i = 0; i <= bucket_mask; i++)
435 		for (exchange = LIST_FIRST(&exchange_tab[i]); exchange;
436 		    exchange = LIST_NEXT(exchange, link))
437 			if (memcmp(exchange->cookies, cookie,
438 			    ISAKMP_HDR_ICOOKIE_LEN) == 0 &&
439 			    exchange->phase == 1)
440 				return exchange;
441 	return 0;
442 }
443 
444 /* Lookup an exchange out of the name and phase.  */
445 struct exchange *
446 exchange_lookup_by_name(char *name, int phase)
447 {
448 	struct exchange *exchange;
449 	int	i;
450 
451 	/* If we search for nothing, we will find nothing.  */
452 	if (!name)
453 		return 0;
454 
455 	for (i = 0; i <= bucket_mask; i++)
456 		for (exchange = LIST_FIRST(&exchange_tab[i]); exchange;
457 		    exchange = LIST_NEXT(exchange, link)) {
458 			LOG_DBG((LOG_EXCHANGE, 90,
459 			    "exchange_lookup_by_name: %s == %s && %d == %d?",
460 			    name, exchange->name ? exchange->name :
461 			    "<unnamed>", phase, exchange->phase));
462 
463 			/*
464 			 * Match by name, but don't select finished exchanges,
465 			 * i.e where MSG_LAST are set in last_sent msg.
466 			 */
467 			if (exchange->name &&
468 			    strcasecmp(exchange->name, name) == 0 &&
469 			    exchange->phase == phase &&
470 			    (!exchange->last_sent ||
471 				(exchange->last_sent->flags & MSG_LAST) == 0))
472 				return exchange;
473 		}
474 	return 0;
475 }
476 
477 /* Lookup an exchange out of the name, phase and step > 1.  */
478 static struct exchange *
479 exchange_lookup_active(char *name, int phase)
480 {
481 	struct exchange *exchange;
482 	int	i;
483 
484 	/* XXX Almost identical to exchange_lookup_by_name.  */
485 
486 	if (!name)
487 		return 0;
488 
489 	for (i = 0; i <= bucket_mask; i++)
490 		for (exchange = LIST_FIRST(&exchange_tab[i]); exchange;
491 		    exchange = LIST_NEXT(exchange, link)) {
492 			LOG_DBG((LOG_EXCHANGE, 90,
493 			    "exchange_lookup_active: %s == %s && %d == %d?",
494 			    name, exchange->name ? exchange->name :
495 			    "<unnamed>", phase, exchange->phase));
496 			if (exchange->name &&
497 			    strcasecmp(exchange->name, name) == 0 &&
498 			    exchange->phase == phase) {
499 				if (exchange->step > 1)
500 					return exchange;
501 				else
502 					LOG_DBG((LOG_EXCHANGE, 80,
503 					    "exchange_lookup_active: avoided "
504 					    "early (pre-step 1) exchange %p",
505 					    exchange));
506 			}
507 		}
508 	return 0;
509 }
510 
511 static void
512 exchange_enter(struct exchange *exchange)
513 {
514 	u_int16_t	bucket = 0;
515 	u_int8_t       *cp;
516 	int             i;
517 
518 	/* XXX We might resize if we are crossing a certain threshold */
519 
520 	for (i = 0; i < ISAKMP_HDR_COOKIES_LEN; i += 2) {
521 		cp = exchange->cookies + i;
522 		/* Doing it this way avoids alignment problems.  */
523 		bucket ^= cp[0] | cp[1] << 8;
524 	}
525 	for (i = 0; i < ISAKMP_HDR_MESSAGE_ID_LEN; i += 2) {
526 		cp = exchange->message_id + i;
527 		/* Doing it this way avoids alignment problems.  */
528 		bucket ^= cp[0] | cp[1] << 8;
529 	}
530 	bucket &= bucket_mask;
531 	LIST_INSERT_HEAD(&exchange_tab[bucket], exchange, link);
532 }
533 
534 /*
535  * Lookup the exchange given by the header fields MSG.  PHASE2 is false when
536  * looking for phase 1 exchanges and true otherwise.
537  */
538 struct exchange *
539 exchange_lookup(u_int8_t *msg, int phase2)
540 {
541 	struct exchange *exchange;
542 	u_int16_t       bucket = 0;
543 	u_int8_t       *cp;
544 	int             i;
545 
546 	/*
547          * We use the cookies to get bits to use as an index into exchange_tab,
548 	 * as at least one (our cookie) is a good hash, xoring all the bits,
549 	 * 16 at a time, and then masking, should do.  Doing it this way means
550 	 * we can validate cookies very fast thus delimiting the effects of
551 	 * "Denial of service"-attacks using packet flooding.
552          */
553 	for (i = 0; i < ISAKMP_HDR_COOKIES_LEN; i += 2) {
554 		cp = msg + ISAKMP_HDR_COOKIES_OFF + i;
555 		/* Doing it this way avoids alignment problems.  */
556 		bucket ^= cp[0] | cp[1] << 8;
557 	}
558 	if (phase2)
559 		for (i = 0; i < ISAKMP_HDR_MESSAGE_ID_LEN; i += 2) {
560 			cp = msg + ISAKMP_HDR_MESSAGE_ID_OFF + i;
561 			/* Doing it this way avoids alignment problems.  */
562 			bucket ^= cp[0] | cp[1] << 8;
563 		}
564 	bucket &= bucket_mask;
565 	for (exchange = LIST_FIRST(&exchange_tab[bucket]);
566 	    exchange && (memcmp(msg + ISAKMP_HDR_COOKIES_OFF,
567 		exchange->cookies, ISAKMP_HDR_COOKIES_LEN) != 0 ||
568 		(phase2 && memcmp(msg + ISAKMP_HDR_MESSAGE_ID_OFF,
569 		    exchange->message_id, ISAKMP_HDR_MESSAGE_ID_LEN) != 0) ||
570 		(!phase2 && !zero_test(msg + ISAKMP_HDR_MESSAGE_ID_OFF,
571 		    ISAKMP_HDR_MESSAGE_ID_LEN)));
572 	    exchange = LIST_NEXT(exchange, link))
573 		;
574 
575 	return exchange;
576 }
577 
578 /*
579  * Create a phase PHASE exchange where INITIATOR denotes our role.  DOI
580  * is the domain of interpretation identifier and TYPE tells what exchange
581  * type to use per either the DOI document or the ISAKMP spec proper.
582  * NSA tells how many SAs we should pre-allocate, and should be zero
583  * when we have the responder role.
584  */
585 static struct exchange *
586 exchange_create(int phase, int initiator, int doi, int type)
587 {
588 	struct exchange *exchange;
589 	struct timeval	 expiration;
590 	int	delta;
591 
592 	/*
593          * We want the exchange zeroed for exchange_free to be able to find
594          * out what fields have been filled-in.
595          */
596 	exchange = calloc(1, sizeof *exchange);
597 	if (!exchange) {
598 		log_error("exchange_create: calloc (1, %lu) failed",
599 		    (unsigned long)sizeof *exchange);
600 		return 0;
601 	}
602 	exchange->phase = phase;
603 	exchange->step = 0;
604 	exchange->initiator = initiator;
605 	bzero(exchange->cookies, ISAKMP_HDR_COOKIES_LEN);
606 	bzero(exchange->message_id, ISAKMP_HDR_MESSAGE_ID_LEN);
607 	exchange->doi = doi_lookup(doi);
608 	exchange->type = type;
609 	exchange->policy_id = -1;
610 	exchange->exch_pc = exchange_script(exchange);
611 	exchange->last_sent = exchange->last_received = 0;
612 	TAILQ_INIT(&exchange->sa_list);
613 	TAILQ_INIT(&exchange->aca_list);
614 
615 	/* Allocate the DOI-specific structure and initialize it to zeroes.  */
616 	if (exchange->doi->exchange_size) {
617 		exchange->data = calloc(1, exchange->doi->exchange_size);
618 		if (!exchange->data) {
619 			log_error("exchange_create: calloc (1, %lu) failed",
620 			    (unsigned long)exchange->doi->exchange_size);
621 			exchange_free(exchange);
622 			return 0;
623 		}
624 	}
625 	gettimeofday(&expiration, 0);
626 	delta = conf_get_num("General", "Exchange-max-time",
627 	    EXCHANGE_MAX_TIME);
628 	expiration.tv_sec += delta;
629 	exchange->death = timer_add_event("exchange_free_aux",
630 	    exchange_free_aux, exchange, &expiration);
631 	if (!exchange->death) {
632 		/* If we don't give up we might start leaking...  */
633 		exchange_free_aux(exchange);
634 		return 0;
635 	}
636 	return exchange;
637 }
638 
639 struct exchange_finalization_node {
640 	void	(*first)(struct exchange *, void *, int);
641 	void	*first_arg;
642 	void	(*second)(struct exchange *, void *, int);
643 	void	*second_arg;
644 };
645 
646 /* Run the finalization functions of ARG.  */
647 static void
648 exchange_run_finalizations(struct exchange *exchange, void *arg, int fail)
649 {
650 	struct exchange_finalization_node *node = arg;
651 
652 	node->first(exchange, node->first_arg, fail);
653 	node->second(exchange, node->second_arg, fail);
654 	free(node);
655 }
656 
657 /*
658  * Add a finalization function FINALIZE with argument ARG to the tail
659  * of the finalization function list of EXCHANGE.
660  */
661 static void
662 exchange_add_finalization(struct exchange *exchange,
663     void (*finalize)(struct exchange *, void *, int), void *arg)
664 {
665 	struct exchange_finalization_node *node;
666 
667 	if (!finalize)
668 		return;
669 
670 	if (!exchange->finalize) {
671 		exchange->finalize = finalize;
672 		exchange->finalize_arg = arg;
673 		return;
674 	}
675 	node = malloc(sizeof *node);
676 	if (!node) {
677 		log_error("exchange_add_finalization: malloc (%lu) failed",
678 		    (unsigned long)sizeof *node);
679 		free(arg);
680 		return;
681 	}
682 	node->first = exchange->finalize;
683 	node->first_arg = exchange->finalize_arg;
684 	node->second = finalize;
685 	node->second_arg = arg;
686 	exchange->finalize = exchange_run_finalizations;
687 	exchange->finalize_arg = node;
688 }
689 
690 static void
691 exchange_establish_transaction(struct exchange *exchange, void *arg, int fail)
692 {
693 	/* Establish a TRANSACTION exchange.  */
694 	struct exchange_finalization_node *node =
695 	    (struct exchange_finalization_node *)arg;
696 	struct sa *isakmp_sa = sa_lookup_by_name((char *) node->second_arg, 1);
697 
698 	if (isakmp_sa && !fail)
699 		exchange_establish_p2(isakmp_sa, ISAKMP_EXCH_TRANSACTION, 0, 0,
700 		    node->first, node->first_arg);
701 
702 	free(node);
703 }
704 
705 /* Establish a phase 1 exchange.  */
706 void
707 exchange_establish_p1(struct transport *t, u_int8_t type, u_int32_t doi,
708     char *name, void *args, void (*finalize)(struct exchange *, void *, int),
709     void *arg, int stayalive)
710 {
711 	struct exchange		*exchange;
712 	struct message		*msg;
713 	struct conf_list	*flags;
714 	struct conf_list_node	*flag;
715 	char	*tag = 0;
716 	char	*str;
717 
718 	if (name) {
719 		/* If no exchange type given, fetch from the configuration.  */
720 		if (type == 0) {
721 			/*
722 			 * XXX Similar code can be found in
723 			 * exchange_setup_p1.  Share?
724 			 */
725 
726 			/* Find out our phase 1 mode.  */
727 			tag = conf_get_str(name, "Configuration");
728 			if (!tag) {
729 				/* Use default setting.  */
730 				tag = CONF_DFLT_TAG_PHASE1_CONFIG;
731 			}
732 			/* Figure out the DOI.  XXX Factor out?  */
733 			str = conf_get_str(tag, "DOI");
734 			if (!str || strcasecmp(str, "IPSEC") == 0)
735 				doi = IPSEC_DOI_IPSEC;
736 			else if (strcasecmp(str, "ISAKMP") == 0)
737 				doi = ISAKMP_DOI_ISAKMP;
738 			else {
739 				log_print("exchange_establish_p1: "
740 				    "DOI \"%s\" unsupported", str);
741 				return;
742 			}
743 
744 			/* What exchange type do we want?  */
745 			str = conf_get_str(tag, "EXCHANGE_TYPE");
746 			if (!str) {
747 				log_print("exchange_establish_p1: "
748 				    "no \"EXCHANGE_TYPE\" tag in [%s] section",
749 				    tag);
750 				return;
751 			}
752 			type = constant_value(isakmp_exch_cst, str);
753 			if (!type) {
754 				log_print("exchange_establish_p1: "
755 				    "unknown exchange type %s", str);
756 				return;
757 			}
758 		}
759 	}
760 	exchange = exchange_create(1, 1, doi, type);
761 	if (!exchange) {
762 		/* XXX Do something here?  */
763 		return;
764 	}
765 	if (name) {
766 		exchange->name = strdup(name);
767 		if (!exchange->name) {
768 			log_error("exchange_establish_p1: "
769 			    "strdup (\"%s\") failed", name);
770 			exchange_free(exchange);
771 			return;
772 		}
773 	}
774 	exchange->policy = name ? conf_get_str(name, "Configuration") : 0;
775 	if (!exchange->policy && name)
776 		exchange->policy = CONF_DFLT_TAG_PHASE1_CONFIG;
777 
778 	if (name && (flags = conf_get_list(name, "Flags")) != NULL) {
779 		for (flag = TAILQ_FIRST(&flags->fields); flag;
780 		    flag = TAILQ_NEXT(flag, link))
781 			if (strcasecmp(flag->field, "ikecfg") == 0) {
782 				struct exchange_finalization_node *node;
783 
784 				node = calloc(1, (unsigned long)sizeof *node);
785 				if (!node) {
786 					log_print("exchange_establish_p1: "
787 					    "calloc (1, %lu) failed",
788 					    (unsigned long)sizeof(*node));
789 					exchange_free(exchange);
790 					return;
791 				}
792 				/*
793 				 * Insert this finalization inbetween
794 				 * the original.
795 				 */
796 				node->first = finalize;
797 				node->first_arg = arg;
798 				node->second_arg = name;
799 				exchange_add_finalization(exchange,
800 				    exchange_establish_transaction,
801 				    node);
802 				finalize = 0;
803 			}
804 		conf_free_list(flags);
805 	}
806 
807 	exchange_add_finalization(exchange, finalize, arg);
808 	cookie_gen(t, exchange, exchange->cookies, ISAKMP_HDR_ICOOKIE_LEN);
809 	exchange_enter(exchange);
810 	exchange_dump("exchange_establish_p1", exchange);
811 
812 	msg = message_alloc(t, 0, ISAKMP_HDR_SZ);
813 	if (!msg) {
814 		log_print("exchange_establish_p1: message_alloc () failed");
815 		exchange_free(exchange);
816 		return;
817 	}
818 	msg->exchange = exchange;
819 
820 	/* Do not create SA for an information or transaction exchange. */
821 	if (exchange->type != ISAKMP_EXCH_INFO &&
822 	    exchange->type != ISAKMP_EXCH_TRANSACTION) {
823 		/*
824 		 * Don't install a transport into this SA as it will be an
825 		 * INADDR_ANY address in the local end, which is not good at
826 		 * all.  Let the reply packet install the transport instead.
827 		 */
828 		sa_create(exchange, 0);
829 		msg->isakmp_sa = TAILQ_FIRST(&exchange->sa_list);
830 		if (!msg->isakmp_sa) {
831 			/* XXX Do something more here?  */
832 			message_free(msg);
833 			exchange_free(exchange);
834 			return;
835 		}
836 		sa_reference(msg->isakmp_sa);
837 
838 		if (stayalive)
839 			msg->isakmp_sa->flags |= SA_FLAG_STAYALIVE;
840 	}
841 	msg->extra = args;
842 
843 	exchange_run(msg);
844 }
845 
846 /* Establish a phase 2 exchange.  XXX With just one SA for now.  */
847 void
848 exchange_establish_p2(struct sa *isakmp_sa, u_int8_t type, char *name,
849     void *args, void (*finalize)(struct exchange *, void *, int), void *arg)
850 {
851 	struct exchange *exchange;
852 	struct message	*msg;
853 	u_int32_t        doi = ISAKMP_DOI_ISAKMP;
854 	u_int32_t        seq = 0;
855 	int              i;
856 	char		*tag, *str;
857 
858 	if (isakmp_sa)
859 		doi = isakmp_sa->doi->id;
860 
861 	if (name) {
862 		/* Find out our phase 2 modes.  */
863 		tag = conf_get_str(name, "Configuration");
864 		if (!tag) {
865 			log_print("exchange_establish_p2: "
866 			    "no configuration for peer \"%s\"", name);
867 			return;
868 		}
869 		seq = (u_int32_t)conf_get_num(name, "Acquire-ID", 0);
870 
871 		/* Figure out the DOI.  */
872 		str = conf_get_str(tag, "DOI");
873 		if (!str || strcasecmp(str, "IPSEC") == 0)
874 			doi = IPSEC_DOI_IPSEC;
875 		else if (strcasecmp(str, "ISAKMP") == 0)
876 			doi = ISAKMP_DOI_ISAKMP;
877 		else {
878 			log_print("exchange_establish_p2: "
879 			    "DOI \"%s\" unsupported", str);
880 			return;
881 		}
882 
883 		/* What exchange type do we want?  */
884 		if (!type) {
885 			str = conf_get_str(tag, "EXCHANGE_TYPE");
886 			if (!str) {
887 				log_print("exchange_establish_p2: "
888 				    "no \"EXCHANGE_TYPE\" tag in [%s] section",
889 				    tag);
890 				return;
891 			}
892 			/* XXX IKE dependent.  */
893 			type = constant_value(ike_exch_cst, str);
894 			if (!type) {
895 				log_print("exchange_establish_p2: unknown "
896 				    "exchange type %s", str);
897 				return;
898 			}
899 		}
900 	}
901 	exchange = exchange_create(2, 1, doi, type);
902 	if (!exchange) {
903 		/* XXX Do something here?  */
904 		return;
905 	}
906 	if (name) {
907 		exchange->name = strdup(name);
908 		if (!exchange->name) {
909 			log_error("exchange_establish_p2: "
910 			    "strdup (\"%s\") failed", name);
911 			exchange_free(exchange);
912 			return;
913 		}
914 	}
915 	exchange->policy = name ? conf_get_str(name, "Configuration") : 0;
916 	exchange->finalize = finalize;
917 	exchange->finalize_arg = arg;
918 	exchange->seq = seq;
919 	memcpy(exchange->cookies, isakmp_sa->cookies, ISAKMP_HDR_COOKIES_LEN);
920 	arc4random_buf(exchange->message_id, ISAKMP_HDR_MESSAGE_ID_LEN);
921 	exchange->flags |= EXCHANGE_FLAG_ENCRYPT;
922 	if (isakmp_sa->flags & SA_FLAG_NAT_T_ENABLE)
923 		exchange->flags |= EXCHANGE_FLAG_NAT_T_ENABLE;
924 	if (isakmp_sa->flags & SA_FLAG_NAT_T_KEEPALIVE)
925 		exchange->flags |= EXCHANGE_FLAG_NAT_T_KEEPALIVE;
926 	exchange_enter(exchange);
927 	exchange_dump("exchange_establish_p2", exchange);
928 
929 	/*
930          * Do not create SA's for informational exchanges.
931          * XXX How to handle new group mode?
932          */
933 	if (exchange->type != ISAKMP_EXCH_INFO &&
934 	    exchange->type != ISAKMP_EXCH_TRANSACTION) {
935 		/* XXX Number of SAs should come from the args structure.  */
936 		for (i = 0; i < 1; i++)
937 			if (sa_create(exchange, isakmp_sa->transport)) {
938 				exchange_free(exchange);
939 				return;
940 			}
941 	}
942 	msg = message_alloc(isakmp_sa->transport, 0, ISAKMP_HDR_SZ);
943 	msg->isakmp_sa = isakmp_sa;
944 	sa_reference(isakmp_sa);
945 
946 	msg->extra = args;
947 
948 	/* This needs to be done late or else get_keystate won't work right. */
949 	msg->exchange = exchange;
950 
951 	exchange_run(msg);
952 }
953 
954 /* Out of an incoming phase 1 message, setup an exchange.  */
955 struct exchange *
956 exchange_setup_p1(struct message *msg, u_int32_t doi)
957 {
958 	struct transport	*t = msg->transport;
959 	struct exchange		*exchange;
960 	struct sockaddr		*dst;
961 	struct conf_list	*flags;
962 	struct conf_list_node	*flag;
963 	char		*name = 0, *policy = 0, *str;
964 	u_int32_t        want_doi;
965 	u_int8_t         type;
966 
967 	/* XXX Similar code can be found in exchange_establish_p1.  Share?  */
968 
969 	/*
970 	 * Unless this is an informational exchange, look up our policy for
971 	 * this peer.
972          */
973 	type = GET_ISAKMP_HDR_EXCH_TYPE(msg->iov[0].iov_base);
974 	if (type != ISAKMP_EXCH_INFO) {
975 		/*
976 		 * Find out our inbound phase 1 mode.
977 		 */
978 		t->vtbl->get_dst(t, &dst);
979 		if (sockaddr2text(dst, &str, 0) == -1)
980 			return 0;
981 		name = conf_get_str("Phase 1", str);
982 		free(str);
983 		if (name) {
984 			/*
985 			 * If another phase 1 exchange is ongoing don't bother
986 			 * returning the call. However, we will need to
987 			 * continue responding if our phase 1 exchange is
988 			 * still waiting for step 1 (i.e still half-open).
989 			 */
990 			exchange = exchange_lookup_active(name, 1);
991 			if (exchange) {
992 				LOG_DBG((LOG_EXCHANGE, 40,
993 				    "exchange_establish: %s exchange already "
994 				    "exists as %p", name, exchange));
995 				return 0;
996 			}
997 		} else {
998 			name = conf_get_str("Phase 1", "Default");
999 			if (!name) {
1000 				log_print("exchange_setup_p1: no \"Default\" "
1001 				    "tag in [Phase 1] section");
1002 				return 0;
1003 			}
1004 		}
1005 
1006 		policy = conf_get_str(name, "Configuration");
1007 		if (!policy)
1008 			policy = CONF_DFLT_TAG_PHASE1_CONFIG;
1009 
1010 		/* Figure out the DOI.  */
1011 		str = conf_get_str(policy, "DOI");
1012 		if (!str || strcasecmp(str, "IPSEC") == 0) {
1013 			want_doi = IPSEC_DOI_IPSEC;
1014 			str = "IPSEC";
1015 		}
1016 		else if (strcasecmp(str, "ISAKMP") == 0)
1017 			want_doi = ISAKMP_DOI_ISAKMP;
1018 		else {
1019 			log_print("exchange_setup_p1: "
1020 			    "DOI \"%s\" unsupported", str);
1021 			return 0;
1022 		}
1023 		if (want_doi != doi) {
1024 			/* XXX Should I tell what DOI I got?  */
1025 			log_print("exchange_setup_p1: expected %s DOI", str);
1026 			return 0;
1027 		}
1028 		/* What exchange type do we want?  */
1029 		str = conf_get_str(policy, "EXCHANGE_TYPE");
1030 		if (!str) {
1031 			log_print("exchange_setup_p1: no \"EXCHANGE_TYPE\" "
1032 			    "tag in [%s] section", policy);
1033 			return 0;
1034 		}
1035 		type = constant_value(isakmp_exch_cst, str);
1036 		if (!type) {
1037 			log_print("exchange_setup_p1: "
1038 			    "unknown exchange type %s", str);
1039 			return 0;
1040 		}
1041 		if (type != GET_ISAKMP_HDR_EXCH_TYPE(msg->iov[0].iov_base)) {
1042 			log_print("exchange_setup_p1: "
1043 			    "expected exchange type %s got %s", str,
1044 			    constant_name(isakmp_exch_cst,
1045 				GET_ISAKMP_HDR_EXCH_TYPE(msg->iov[0].iov_base)));
1046 			return 0;
1047 		}
1048 	}
1049 	exchange = exchange_create(1, 0, doi, type);
1050 	if (!exchange)
1051 		return 0;
1052 
1053 	exchange->name = name ? strdup(name) : 0;
1054 	if (name && !exchange->name) {
1055 		log_error("exchange_setup_p1: strdup (\"%s\") failed", name);
1056 		exchange_free(exchange);
1057 		return 0;
1058 	}
1059 	exchange->policy = policy;
1060 
1061 	if (name && (flags = conf_get_list(name, "Flags")) != NULL) {
1062 		for (flag = TAILQ_FIRST(&flags->fields); flag;
1063 		    flag = TAILQ_NEXT(flag, link))
1064 			if (strcasecmp(flag->field, "ikecfg") == 0) {
1065 				struct exchange_finalization_node *node;
1066 
1067 				node = calloc(1, (unsigned long)sizeof *node);
1068 				if (!node) {
1069 					log_print("exchange_establish_p1: "
1070 					    "calloc (1, %lu) failed",
1071 					    (unsigned long)sizeof(*node));
1072 					exchange_free(exchange);
1073 					return 0;
1074 				}
1075 				/*
1076 				 * Insert this finalization inbetween
1077 				 * the original.
1078 				 */
1079 				node->first = 0;
1080 				node->first_arg = 0;
1081 				node->second_arg = name;
1082 				exchange_add_finalization(exchange,
1083 				    exchange_establish_transaction,
1084 				    node);
1085 			}
1086 		conf_free_list(flags);
1087 	}
1088 
1089 	cookie_gen(msg->transport, exchange, exchange->cookies +
1090 	    ISAKMP_HDR_ICOOKIE_LEN, ISAKMP_HDR_RCOOKIE_LEN);
1091 	GET_ISAKMP_HDR_ICOOKIE(msg->iov[0].iov_base, exchange->cookies);
1092 	exchange_enter(exchange);
1093 	exchange_dump("exchange_setup_p1", exchange);
1094 	return exchange;
1095 }
1096 
1097 /* Out of an incoming phase 2 message, setup an exchange.  */
1098 struct exchange *
1099 exchange_setup_p2(struct message *msg, u_int8_t doi)
1100 {
1101 	struct exchange *exchange;
1102 	u_int8_t	*buf = msg->iov[0].iov_base;
1103 
1104 	exchange = exchange_create(2, 0, doi, GET_ISAKMP_HDR_EXCH_TYPE(buf));
1105 	if (!exchange)
1106 		return 0;
1107 	GET_ISAKMP_HDR_ICOOKIE(buf, exchange->cookies);
1108 	GET_ISAKMP_HDR_RCOOKIE(buf,
1109 	    exchange->cookies + ISAKMP_HDR_ICOOKIE_LEN);
1110 	GET_ISAKMP_HDR_MESSAGE_ID(buf, exchange->message_id);
1111 	if (msg->isakmp_sa && (msg->isakmp_sa->flags & SA_FLAG_NAT_T_ENABLE))
1112 		exchange->flags |= EXCHANGE_FLAG_NAT_T_ENABLE;
1113 	if (msg->isakmp_sa && (msg->isakmp_sa->flags & SA_FLAG_NAT_T_KEEPALIVE))
1114 		exchange->flags |= EXCHANGE_FLAG_NAT_T_KEEPALIVE;
1115 	exchange_enter(exchange);
1116 	exchange_dump("exchange_setup_p2", exchange);
1117 	return exchange;
1118 }
1119 
1120 /* Dump interesting data about an exchange.  */
1121 static void
1122 exchange_dump_real(char *header, struct exchange *exchange, int class,
1123     int level)
1124 {
1125 	struct sa	*sa;
1126 	char             buf[LOG_SIZE];
1127 	/* Don't risk overflowing the final log buffer.  */
1128 	size_t           bufsize_max = LOG_SIZE - strlen(header) - 32;
1129 
1130 	LOG_DBG((class, level,
1131 	    "%s: %p %s %s policy %s phase %d doi %d exchange %d step %d",
1132 	    header, exchange, exchange->name ? exchange->name : "<unnamed>",
1133 	    exchange->policy ? exchange->policy : "<no policy>",
1134 	    exchange->initiator ? "initiator" : "responder", exchange->phase,
1135 	    exchange->doi->id, exchange->type, exchange->step));
1136 	LOG_DBG((class, level, "%s: icookie %08x%08x rcookie %08x%08x", header,
1137 	    decode_32(exchange->cookies), decode_32(exchange->cookies + 4),
1138 	    decode_32(exchange->cookies + 8),
1139 	    decode_32(exchange->cookies + 12)));
1140 
1141 	/* Include phase 2 SA list for this exchange */
1142 	if (exchange->phase == 2) {
1143 		snprintf(buf, bufsize_max, "sa_list ");
1144 		for (sa = TAILQ_FIRST(&exchange->sa_list);
1145 		    sa && strlen(buf) < bufsize_max; sa = TAILQ_NEXT(sa, next))
1146 			snprintf(buf + strlen(buf), bufsize_max - strlen(buf),
1147 			    "%p ", sa);
1148 		if (sa)
1149 			strlcat(buf, "...", bufsize_max);
1150 	} else
1151 		buf[0] = '\0';
1152 
1153 	LOG_DBG((class, level, "%s: msgid %08x %s", header,
1154 	    decode_32(exchange->message_id), buf));
1155 }
1156 
1157 static void
1158 exchange_dump(char *header, struct exchange *exchange)
1159 {
1160 	exchange_dump_real(header, exchange, LOG_EXCHANGE, 10);
1161 }
1162 
1163 void
1164 exchange_report(void)
1165 {
1166 	struct exchange	*exchange;
1167 	int	i;
1168 
1169 	for (i = 0; i <= bucket_mask; i++)
1170 		for (exchange = LIST_FIRST(&exchange_tab[i]); exchange;
1171 		    exchange = LIST_NEXT(exchange, link))
1172 			exchange_dump_real("exchange_report", exchange,
1173 			    LOG_REPORT, 0);
1174 }
1175 
1176 /*
1177  * Release all resources this exchange is using *except* for the "death"
1178  * event.  When removing an exchange from the expiration handler that event
1179  * will be dealt with therein instead.
1180  */
1181 static void
1182 exchange_free_aux(void *v_exch)
1183 {
1184 	struct exchange		*exchange = v_exch;
1185 	struct sa		*sa, *next_sa;
1186 	struct cert_handler	*handler;
1187 
1188 	LOG_DBG((LOG_EXCHANGE, 80, "exchange_free_aux: freeing exchange %p",
1189 	    exchange));
1190 
1191 	if (exchange->last_received)
1192 		message_free(exchange->last_received);
1193 	if (exchange->last_sent)
1194 		message_free(exchange->last_sent);
1195 	if (exchange->in_transit &&
1196 	    exchange->in_transit != exchange->last_sent)
1197 		message_free(exchange->in_transit);
1198 	free(exchange->nonce_i);
1199 	free(exchange->nonce_r);
1200 	free(exchange->id_i);
1201 	free(exchange->id_r);
1202 	free(exchange->keystate);
1203 	if (exchange->doi && exchange->doi->free_exchange_data)
1204 		exchange->doi->free_exchange_data(exchange->data);
1205 	free(exchange->data);
1206 	free(exchange->name);
1207 	if (exchange->recv_cert) {
1208 		handler = cert_get(exchange->recv_certtype);
1209 		if (handler)
1210 			handler->cert_free(exchange->recv_cert);
1211 	}
1212 	if (exchange->sent_cert) {
1213 		handler = cert_get(exchange->sent_certtype);
1214 		if (handler)
1215 			handler->cert_free(exchange->sent_cert);
1216 	}
1217 	if (exchange->recv_key)
1218 		key_free(exchange->recv_keytype, ISAKMP_KEYTYPE_PUBLIC,
1219 		    exchange->recv_key);
1220 	free(exchange->keynote_key);	/* This is just a string */
1221 
1222 	if (exchange->policy_id != -1)
1223 		kn_close(exchange->policy_id);
1224 
1225 	exchange_free_aca_list(exchange);
1226 	LIST_REMOVE(exchange, link);
1227 
1228 	/* Tell potential finalize routine we never got there.  */
1229 	if (exchange->finalize)
1230 		exchange->finalize(exchange, exchange->finalize_arg, 1);
1231 
1232 	/* Remove any SAs that have not been disassociated from us.  */
1233 	for (sa = TAILQ_FIRST(&exchange->sa_list); sa; sa = next_sa) {
1234 		next_sa = TAILQ_NEXT(sa, next);
1235 		/* One for the reference in exchange->sa_list.  */
1236 		sa_release(sa);
1237 		/* And two more for the expiration and SA linked list.  */
1238 		sa_free(sa);
1239 	}
1240 
1241 	free(exchange);
1242 }
1243 
1244 /* Release all resources this exchange is using.  */
1245 void
1246 exchange_free(struct exchange *exchange)
1247 {
1248 	if (exchange->death)
1249 		timer_remove_event(exchange->death);
1250 	exchange_free_aux(exchange);
1251 }
1252 
1253 /*
1254  * Upgrade the phase 1 exchange and its ISAKMP SA with the rcookie of our
1255  * peer (found in his recently sent message MSG).
1256  */
1257 void
1258 exchange_upgrade_p1(struct message *msg)
1259 {
1260 	struct exchange *exchange = msg->exchange;
1261 
1262 	LIST_REMOVE(exchange, link);
1263 	GET_ISAKMP_HDR_RCOOKIE(msg->iov[0].iov_base, exchange->cookies +
1264 	    ISAKMP_HDR_ICOOKIE_LEN);
1265 	exchange_enter(exchange);
1266 	sa_isakmp_upgrade(msg);
1267 }
1268 
1269 static int
1270 exchange_check_old_sa(struct sa *sa, void *v_arg)
1271 {
1272 	struct sa	*new_sa = v_arg;
1273 	char		 res1[1024];
1274 
1275 	if (sa == new_sa || !sa->name || !(sa->flags & SA_FLAG_READY) ||
1276 	    (sa->flags & SA_FLAG_REPLACED))
1277 		return 0;
1278 
1279 	if (sa->phase != new_sa->phase || new_sa->name == 0 ||
1280 	    strcasecmp(sa->name, new_sa->name))
1281 		return 0;
1282 
1283 	if (sa->initiator)
1284 		strlcpy(res1, ipsec_decode_ids("%s %s", sa->id_i, sa->id_i_len,
1285 		    sa->id_r, sa->id_r_len, 0), sizeof res1);
1286 	else
1287 		strlcpy(res1, ipsec_decode_ids("%s %s", sa->id_r, sa->id_r_len,
1288 		    sa->id_i, sa->id_i_len, 0), sizeof res1);
1289 
1290 	LOG_DBG((LOG_EXCHANGE, 30,
1291 	    "checking whether new SA replaces existing SA with IDs %s", res1));
1292 
1293 	if (new_sa->initiator)
1294 		return strcasecmp(res1, ipsec_decode_ids("%s %s", new_sa->id_i,
1295 		    new_sa->id_i_len, new_sa->id_r, new_sa->id_r_len, 0)) == 0;
1296 	else
1297 		return strcasecmp(res1, ipsec_decode_ids("%s %s", new_sa->id_r,
1298 		    new_sa->id_r_len, new_sa->id_i, new_sa->id_i_len, 0)) == 0;
1299 }
1300 
1301 void
1302 exchange_finalize(struct message *msg)
1303 {
1304 	struct exchange		*exchange = msg->exchange;
1305 	struct sa		*sa, *old_sa;
1306 	struct proto		*proto;
1307 	struct conf_list	*attrs;
1308 	struct conf_list_node	*attr;
1309 	struct cert_handler	*handler;
1310 	int	 i;
1311 	char	*id_doi, *id_trp;
1312 
1313 	exchange_dump("exchange_finalize", exchange);
1314 
1315 	/* Copy the ID from phase 1 to exchange or phase 2 SA.  */
1316 	if (msg->isakmp_sa) {
1317 		if (exchange->id_i && exchange->id_r) {
1318 			ipsec_clone_id(&msg->isakmp_sa->id_i,
1319 			    &msg->isakmp_sa->id_i_len, exchange->id_i,
1320 			    exchange->id_i_len);
1321 			ipsec_clone_id(&msg->isakmp_sa->id_r,
1322 			    &msg->isakmp_sa->id_r_len, exchange->id_r,
1323 			    exchange->id_r_len);
1324 		} else if (msg->isakmp_sa->id_i && msg->isakmp_sa->id_r) {
1325 			ipsec_clone_id(&exchange->id_i, &exchange->id_i_len,
1326 			    msg->isakmp_sa->id_i, msg->isakmp_sa->id_i_len);
1327 			ipsec_clone_id(&exchange->id_r, &exchange->id_r_len,
1328 			    msg->isakmp_sa->id_r, msg->isakmp_sa->id_r_len);
1329 		}
1330 	}
1331 	/*
1332          * Walk over all the SAs and noting them as ready.  If we set the
1333          * COMMIT bit, tell the peer each SA is connected.
1334          *
1335          * XXX The decision should really be based on if a SA was installed
1336          * successfully.
1337          */
1338 	for (sa = TAILQ_FIRST(&exchange->sa_list); sa;
1339 	    sa = TAILQ_NEXT(sa, next)) {
1340 		/* Move over the name to the SA.  */
1341 		sa->name = exchange->name ? strdup(exchange->name) : 0;
1342 
1343 		if (exchange->flags & EXCHANGE_FLAG_I_COMMITTED) {
1344 			for (proto = TAILQ_FIRST(&sa->protos); proto;
1345 			    proto = TAILQ_NEXT(proto, link))
1346 				for (i = 0; i < 2; i++)
1347 					message_send_notification(exchange->last_received,
1348 					    msg->isakmp_sa,
1349 					    ISAKMP_NOTIFY_STATUS_CONNECTED,
1350 					    proto, i);
1351 		}
1352 		/*
1353 		 * Locate any old SAs and mark them replaced
1354 		 * (SA_FLAG_REPLACED).
1355 		 */
1356 		sa->initiator = exchange->initiator;
1357 		while ((old_sa = sa_find(exchange_check_old_sa, sa)) != 0)
1358 			sa_mark_replaced(old_sa);
1359 
1360 		/* Setup the SA flags.  */
1361 		sa->flags |= SA_FLAG_READY;
1362 		if (exchange->name) {
1363 			attrs = conf_get_list(exchange->name, "Flags");
1364 			if (attrs) {
1365 				for (attr = TAILQ_FIRST(&attrs->fields); attr;
1366 				    attr = TAILQ_NEXT(attr, link))
1367 					sa->flags |= sa_flag(attr->field);
1368 				conf_free_list(attrs);
1369 			}
1370 			/* 'Connections' should stay alive.  */
1371 			if (connection_exist(exchange->name)) {
1372 				sa->flags |= SA_FLAG_STAYALIVE;
1373 
1374 				/*
1375 				 * ISAKMP SA of this connection should also
1376 				 * stay alive.
1377 				 */
1378 				if (exchange->phase == 2 && msg->isakmp_sa)
1379 					msg->isakmp_sa->flags |=
1380 					    SA_FLAG_STAYALIVE;
1381 			}
1382 		}
1383 		sa->seq = exchange->seq;
1384 		sa->exch_type = exchange->type;
1385 	}
1386 
1387 	/*
1388 	 * If this was an phase 1 SA negotiation, save the keystate in the
1389 	 * ISAKMP SA structure for future initialization of phase 2 exchanges'
1390 	 * keystates.  Also save the Phase 1 ID and authentication
1391 	 * information.
1392          */
1393 	if (exchange->phase == 1 && msg->isakmp_sa) {
1394 		msg->isakmp_sa->keystate = exchange->keystate;
1395 		exchange->keystate = 0;
1396 
1397 		msg->isakmp_sa->recv_certtype = exchange->recv_certtype;
1398 		msg->isakmp_sa->sent_certtype = exchange->sent_certtype;
1399 		msg->isakmp_sa->recv_keytype = exchange->recv_keytype;
1400 		msg->isakmp_sa->recv_key = exchange->recv_key;
1401 		msg->isakmp_sa->keynote_key = exchange->keynote_key;
1402 		/* Reset.  */
1403 		exchange->recv_key = 0;
1404 		exchange->keynote_key = 0;
1405 		msg->isakmp_sa->policy_id = exchange->policy_id;
1406 		exchange->policy_id = -1;
1407 		msg->isakmp_sa->initiator = exchange->initiator;
1408 
1409 		if (exchange->recv_certtype && exchange->recv_cert) {
1410 			handler = cert_get(exchange->recv_certtype);
1411 			if (handler)
1412 				msg->isakmp_sa->recv_cert =
1413 				    handler->cert_dup(exchange->recv_cert);
1414 		}
1415 		if (exchange->sent_certtype) {
1416 			handler = cert_get(exchange->sent_certtype);
1417 			if (handler)
1418 				msg->isakmp_sa->sent_cert =
1419 				    handler->cert_dup(exchange->sent_cert);
1420 		}
1421 		if (exchange->doi)
1422 			id_doi = exchange->doi->decode_ids(
1423 			    "initiator id %s, responder id %s",
1424 			    exchange->id_i, exchange->id_i_len,
1425 			    exchange->id_r, exchange->id_r_len, 0);
1426 		else
1427 			id_doi = "<no doi>";
1428 
1429 		if (msg->isakmp_sa->transport)
1430 			id_trp =
1431 			    msg->isakmp_sa->transport->vtbl->decode_ids(msg->isakmp_sa->transport);
1432 		else
1433 			id_trp = "<no transport>";
1434 
1435 		if (exchange->flags & EXCHANGE_FLAG_NAT_T_ENABLE)
1436 			msg->isakmp_sa->flags |= SA_FLAG_NAT_T_ENABLE;
1437 		if (exchange->flags & EXCHANGE_FLAG_NAT_T_KEEPALIVE)
1438 			msg->isakmp_sa->flags |= SA_FLAG_NAT_T_KEEPALIVE;
1439 
1440 		LOG_DBG((LOG_EXCHANGE, 10,
1441 		    "exchange_finalize: phase 1 done: %s, %s", id_doi,
1442 		    id_trp));
1443 
1444 		log_verbose("isakmpd: phase 1 done%s: %s, %s",
1445 			(exchange->initiator == 0) ? " (as responder)" : "",
1446 			id_doi, id_trp);
1447 	}
1448 	exchange->doi->finalize_exchange(msg);
1449 	if (exchange->finalize)
1450 		exchange->finalize(exchange, exchange->finalize_arg, 0);
1451 	exchange->finalize = 0;
1452 
1453 	/*
1454          * There is no reason to keep the SAs connected to us anymore, in fact
1455          * it can hurt us if we have short lifetimes on the SAs and we try
1456          * to call exchange_report, where the SA list will be walked and
1457          * references to freed SAs can occur.
1458          */
1459 	while (TAILQ_FIRST(&exchange->sa_list)) {
1460 		sa = TAILQ_FIRST(&exchange->sa_list);
1461 
1462 		if (exchange->id_i && exchange->id_r) {
1463 			ipsec_clone_id(&sa->id_i, &sa->id_i_len,
1464 			    exchange->id_i, exchange->id_i_len);
1465 			ipsec_clone_id(&sa->id_r, &sa->id_r_len,
1466 			    exchange->id_r, exchange->id_r_len);
1467 		}
1468 		TAILQ_REMOVE(&exchange->sa_list, sa, next);
1469 		sa_release(sa);
1470 	}
1471 	/*
1472 	 * Start sending DPD messages after all SAs have been released.
1473 	 * Otherwise we have a race between exchange_free_aux() and
1474 	 * dpd_check_event() where both will call sa_free().
1475 	 */
1476 	if (exchange->phase == 1 && msg->isakmp_sa &&
1477 	    (exchange->flags & EXCHANGE_FLAG_DPD_CAP_PEER))
1478 		dpd_start(msg->isakmp_sa);
1479 
1480 	/* If we have nothing to retransmit we can safely remove ourselves.  */
1481 	if (!exchange->last_sent)
1482 		exchange_free(exchange);
1483 }
1484 
1485 /* Stash a nonce into the exchange data.  */
1486 static int
1487 exchange_nonce(struct exchange *exchange, int peer, size_t nonce_sz,
1488     u_int8_t *buf)
1489 {
1490 	u_int8_t      **nonce;
1491 	size_t         *nonce_len;
1492 	int		initiator = exchange->initiator ^ peer;
1493 	char            header[32];
1494 
1495 	if (nonce_sz < 8 || nonce_sz > 256) {
1496 		/*
1497 		 * RFC2409, ch 5: The length of nonce payload MUST be
1498 		 * between 8 and 256 bytes inclusive.
1499 		 * XXX I'm assuming the generic payload header is not included.
1500 		 */
1501 		LOG_DBG((LOG_EXCHANGE, 20,
1502 		    "exchange_nonce: invalid nonce length %lu",
1503 		    (unsigned long)nonce_sz));
1504 		return -1;
1505 	}
1506 
1507 	nonce = initiator ? &exchange->nonce_i : &exchange->nonce_r;
1508 	nonce_len =
1509 	    initiator ? &exchange->nonce_i_len : &exchange->nonce_r_len;
1510 	*nonce_len = nonce_sz;
1511 	*nonce = malloc(nonce_sz);
1512 	if (!*nonce) {
1513 		log_error("exchange_nonce: malloc (%lu) failed",
1514 		    (unsigned long)nonce_sz);
1515 		return -1;
1516 	}
1517 	memcpy(*nonce, buf, nonce_sz);
1518 	snprintf(header, sizeof header, "exchange_nonce: NONCE_%c",
1519 	    initiator ? 'i' : 'r');
1520 	LOG_DBG_BUF((LOG_EXCHANGE, 80, header, *nonce, nonce_sz));
1521 	return 0;
1522 }
1523 
1524 /* Generate our NONCE.  */
1525 int
1526 exchange_gen_nonce(struct message *msg, size_t nonce_sz)
1527 {
1528 	struct exchange *exchange = msg->exchange;
1529 	u_int8_t	*buf;
1530 
1531 	buf = malloc(ISAKMP_NONCE_SZ + nonce_sz);
1532 	if (!buf) {
1533 		log_error("exchange_gen_nonce: malloc (%lu) failed",
1534 		    ISAKMP_NONCE_SZ + (unsigned long)nonce_sz);
1535 		return -1;
1536 	}
1537 	arc4random_buf(buf + ISAKMP_NONCE_DATA_OFF, nonce_sz);
1538 	if (message_add_payload(msg, ISAKMP_PAYLOAD_NONCE, buf,
1539 	    ISAKMP_NONCE_SZ + nonce_sz, 1)) {
1540 		free(buf);
1541 		return -1;
1542 	}
1543 	return exchange_nonce(exchange, 0, nonce_sz,
1544 	    buf + ISAKMP_NONCE_DATA_OFF);
1545 }
1546 
1547 /* Save the peer's NONCE.  */
1548 int
1549 exchange_save_nonce(struct message *msg)
1550 {
1551 	struct payload	*noncep;
1552 	struct exchange *exchange = msg->exchange;
1553 
1554 	noncep = payload_first(msg, ISAKMP_PAYLOAD_NONCE);
1555 	noncep->flags |= PL_MARK;
1556 	return exchange_nonce(exchange, 1, GET_ISAKMP_GEN_LENGTH(noncep->p) -
1557 	    ISAKMP_NONCE_DATA_OFF, noncep->p + ISAKMP_NONCE_DATA_OFF);
1558 }
1559 
1560 /* Save the peer's CERT REQuests.  */
1561 int
1562 exchange_save_certreq(struct message *msg)
1563 {
1564 	struct payload	*cp;
1565 	struct exchange	*exchange = msg->exchange;
1566 	struct certreq_aca *aca;
1567 
1568 	TAILQ_FOREACH(cp, &msg->payload[ISAKMP_PAYLOAD_CERT_REQ], link) {
1569 		cp->flags |= PL_MARK;
1570 		aca = certreq_decode(GET_ISAKMP_CERTREQ_TYPE(cp->p), cp->p +
1571 		    ISAKMP_CERTREQ_AUTHORITY_OFF, GET_ISAKMP_GEN_LENGTH(cp->p)
1572 		    - ISAKMP_CERTREQ_AUTHORITY_OFF);
1573 		if (aca)
1574 			TAILQ_INSERT_TAIL(&exchange->aca_list, aca, link);
1575 	}
1576 
1577 	return 0;
1578 }
1579 
1580 /* Free the list of pending CERTREQs.  */
1581 void
1582 exchange_free_aca_list(struct exchange *exchange)
1583 {
1584 	struct certreq_aca *aca;
1585 
1586 	for (aca = TAILQ_FIRST(&exchange->aca_list); aca;
1587 	    aca = TAILQ_FIRST(&exchange->aca_list)) {
1588 		free(aca->raw_ca);
1589 		if (aca->data) {
1590 			if (aca->handler)
1591 				aca->handler->free_aca(aca->data);
1592 			free(aca->data);
1593 		}
1594 		TAILQ_REMOVE(&exchange->aca_list, aca, link);
1595 		free(aca);
1596 	}
1597 }
1598 
1599 /* Add any CERTREQs we should send.  */
1600 int
1601 exchange_add_certreqs(struct message *msg)
1602 {
1603 	struct exchange *exchange = msg->exchange;
1604 	struct certreq_aca *aca;
1605 	u_int8_t *buf;
1606 
1607 	/*
1608 	 * Some peers (e.g. Cisco IOS) won't send their cert unless we
1609 	 * specifically ask beforehand with CERTREQ.  We reflect any
1610 	 * CERTREQs we receive from the initiator in order to do this.
1611 	 * This avoids leaking information about which CAs we trust,
1612 	 * and works in the most common case where both ends trust the
1613 	 * same CA.
1614 	 */
1615 	for (aca = TAILQ_FIRST(&exchange->aca_list); aca;
1616 	    aca = TAILQ_NEXT(aca, link)) {
1617 
1618 		/* But only do this if we have at least one CA */
1619 		if (aca->handler != NULL && aca->handler->ca_count() == 0) {
1620 			LOG_DBG((LOG_EXCHANGE, 10,
1621 			    "exchange_add_certreqs: no CA, so not "
1622 			    "sending a CERTREQ"));
1623 			continue;
1624 		}
1625 
1626 		if (aca->raw_ca_len) {
1627 			buf = malloc(ISAKMP_CERTREQ_SZ + aca->raw_ca_len);
1628 			if (buf == NULL) {
1629 				log_error("exchange_add_certreqs: "
1630 				    "malloc (%lu) failed",
1631 				    ISAKMP_CERTREQ_SZ +
1632 				    (unsigned long)aca->raw_ca_len);
1633 				return -1;
1634 			}
1635 
1636 			buf[ISAKMP_CERTREQ_TYPE_OFF] = aca->id;
1637 			memcpy(buf + ISAKMP_CERTREQ_AUTHORITY_OFF,
1638 			    aca->raw_ca, aca->raw_ca_len);
1639 
1640 			if (message_add_payload(msg, ISAKMP_PAYLOAD_CERT_REQ,
1641 			    buf, ISAKMP_CERTREQ_SZ + aca->raw_ca_len, 1)) {
1642 				free(buf);
1643 				return -1;
1644 			}
1645 		}
1646 	}
1647 
1648 	return 0;
1649 }
1650 
1651 /* Obtain certificates from acceptable certification authority.  */
1652 int
1653 exchange_add_certs(struct message *msg)
1654 {
1655 	struct exchange *exchange = msg->exchange;
1656 	struct certreq_aca *aca;
1657 	u_int8_t       *cert = 0, *new_cert = 0;
1658 	u_int32_t       certlen;
1659 	u_int8_t       *id;
1660 	size_t          id_len;
1661 
1662 	id = exchange->initiator ? exchange->id_r : exchange->id_i;
1663 	id_len = exchange->initiator ? exchange->id_r_len : exchange->id_i_len;
1664 
1665 	/*
1666          * Without IDs we cannot handle this yet. Keep the aca_list around for
1667          * a later step/retry to see if we got the ID by then.
1668          * Note: A 'return -1' breaks X509-auth interop in the responder case
1669          *       with some IPsec clients that send CERTREQs early (such as
1670 	 *       the SSH Sentinel).
1671          */
1672 	if (!id)
1673 		return 0;
1674 
1675 	for (aca = TAILQ_FIRST(&exchange->aca_list); aca;
1676 	    aca = TAILQ_NEXT(aca, link)) {
1677 		/* XXX? If we can not satisfy a CERTREQ we drop the message. */
1678 		if (!aca->handler->cert_obtain(id, id_len, aca->data, &cert,
1679 		    &certlen)) {
1680 			log_print("exchange_add_certs: could not obtain cert "
1681 			    "for a type %d cert request", aca->id);
1682 			free(cert);
1683 			return -1;
1684 		}
1685 		new_cert = realloc(cert, ISAKMP_CERT_SZ + certlen);
1686 		if (!new_cert) {
1687 			log_error("exchange_add_certs: realloc (%p, %d) "
1688 			    "failed", cert, ISAKMP_CERT_SZ + certlen);
1689 			free(cert);
1690 			return -1;
1691 		}
1692 		cert = new_cert;
1693 		memmove(cert + ISAKMP_CERT_DATA_OFF, cert, certlen);
1694 		SET_ISAKMP_CERT_ENCODING(cert, aca->id);
1695 		if (message_add_payload(msg, ISAKMP_PAYLOAD_CERT, cert,
1696 		    ISAKMP_CERT_SZ + certlen, 1)) {
1697 			free(cert);
1698 			return -1;
1699 		}
1700 		/*
1701 		 * We need to reset cert here, as it is now controlled by
1702 		 * message_add_payload() (i.e. we must not free() it), and
1703 		 * it is possible for the next iteration of the aca loop
1704 		 * to fail early in cert_obtain before it writes to &cert.
1705 		 */
1706 		cert = NULL;
1707 	}
1708 
1709 	/* We dont need the CERT REQs any more, they are answered.  */
1710 	exchange_free_aca_list(exchange);
1711 
1712 	return 0;
1713 }
1714 
1715 static void
1716 exchange_establish_finalize(struct exchange *exchange, void *arg, int fail)
1717 {
1718 	char	*name = arg;
1719 
1720 	LOG_DBG((LOG_EXCHANGE, 20, "exchange_establish_finalize: "
1721 	    "finalizing exchange %p with arg %p (%s) & fail = %d",
1722 	    exchange, arg, name ? name : "<unnamed>", fail));
1723 
1724 	if (!fail)
1725 		exchange_establish(name, 0, 0, 0);
1726 	free(name);
1727 }
1728 
1729 /*
1730  * Establish an exchange named NAME, and record the FINALIZE function
1731  * taking ARG as an argument to be run after the exchange is ready.
1732  */
1733 void
1734 exchange_establish(char *name, void (*finalize)(struct exchange *, void *,
1735     int), void *arg, int stayalive)
1736 {
1737 	struct transport	*transport;
1738 	struct sa		*isakmp_sa;
1739 	struct exchange		*exchange;
1740 	int	 phase;
1741 	char	*trpt, *peer;
1742 
1743 	phase = conf_get_num(name, "Phase", 0);
1744 
1745 	if (ui_daemon_passive) {
1746 		LOG_DBG((LOG_EXCHANGE, 40, "exchange_establish:"
1747 		    " returning in passive mode for exchange %s phase %d",
1748 		    name, phase));
1749 		return;
1750 	}
1751 
1752 	/*
1753 	 * First of all, never try to establish anything if another exchange
1754 	 * of the same kind is running.
1755          */
1756 	exchange = exchange_lookup_by_name(name, phase);
1757 	if (exchange) {
1758 		LOG_DBG((LOG_EXCHANGE, 40,
1759 		    "exchange_establish: %s exchange already exists as %p",
1760 		    name, exchange));
1761 		exchange_add_finalization(exchange, finalize, arg);
1762 		return;
1763 	}
1764 	switch (phase) {
1765 	case 1:
1766 		trpt = conf_get_str(name, "Transport");
1767 		if (!trpt) {
1768 			/* Phase 1 transport defaults to "udp".  */
1769 			trpt = ISAKMP_DEFAULT_TRANSPORT;
1770 		}
1771 		transport = transport_create(trpt, name);
1772 		if (!transport) {
1773 			log_print("exchange_establish: transport \"%s\" for "
1774 			    "peer \"%s\" could not be created", trpt, name);
1775 			return;
1776 		}
1777 		exchange_establish_p1(transport, 0, 0, name, 0, finalize, arg,
1778 		    stayalive);
1779 		break;
1780 
1781 	case 2:
1782 		peer = conf_get_str(name, "ISAKMP-peer");
1783 		if (!peer) {
1784 			log_print("exchange_establish: No ISAKMP-peer given "
1785 			    "for \"%s\"", name);
1786 			return;
1787 		}
1788 		isakmp_sa = sa_lookup_by_name(peer, 1);
1789 		if (!isakmp_sa) {
1790 			name = strdup(name);
1791 			if (!name) {
1792 				log_error("exchange_establish: "
1793 				    "strdup (\"%s\") failed", name);
1794 				return;
1795 			}
1796 			if (conf_get_num(peer, "Phase", 0) != 1) {
1797 				log_print("exchange_establish: "
1798 				    "[%s]:ISAKMP-peer's (%s) phase is not 1",
1799 				    name, peer);
1800 				free(name);
1801 				return;
1802 			}
1803 			/*
1804 			 * XXX We're losing information here (what the
1805 			 * original finalize routine was. As a result, if an
1806 			 * exchange does not manage to get through, there may
1807 			 * be application-specific information that won't get
1808 			 * cleaned up, since no error signaling will be done.
1809 			 * This is the case with dynamic SAs and PFKEY.
1810 			 */
1811 			exchange_establish(peer, exchange_establish_finalize,
1812 			    name, 0);
1813 			exchange = exchange_lookup_by_name(peer, 1);
1814 			/*
1815 			 * If the exchange was correctly initialized, add the
1816 			 * original finalization routine; otherwise, call it
1817 			 * directly.
1818 			 */
1819 			if (exchange)
1820 				exchange_add_finalization(exchange, finalize,
1821 				    arg);
1822 			else {
1823 				/* Indicate failure */
1824 				if (finalize)
1825 					finalize(0, arg, 1);
1826 				free(name);
1827 			}
1828 			return;
1829 		} else
1830 			exchange_establish_p2(isakmp_sa, 0, name, 0, finalize,
1831 			    arg);
1832 		break;
1833 
1834 	default:
1835 		log_print("exchange_establish: "
1836 		    "peer \"%s\" does not have a correct phase (%d)",
1837 		    name, phase);
1838 		break;
1839 	}
1840 }
1841