xref: /openbsd-src/sbin/isakmpd/ike_quick_mode.c (revision d13be5d47e4149db2549a9828e244d59dbc43f15)
1 /* $OpenBSD: ike_quick_mode.c,v 1.106 2011/04/23 03:17:04 lum Exp $	 */
2 /* $EOM: ike_quick_mode.c,v 1.139 2001/01/26 10:43:17 niklas Exp $	 */
3 
4 /*
5  * Copyright (c) 1998, 1999, 2000, 2001 Niklas Hallqvist.  All rights reserved.
6  * Copyright (c) 1999, 2000, 2001 Angelos D. Keromytis.  All rights reserved.
7  * Copyright (c) 2000, 2001, 2004 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 <stdlib.h>
35 #include <string.h>
36 
37 #include <sys/types.h>
38 #include <regex.h>
39 #include <keynote.h>
40 
41 #include "attribute.h"
42 #include "conf.h"
43 #include "connection.h"
44 #include "dh.h"
45 #include "doi.h"
46 #include "exchange.h"
47 #include "hash.h"
48 #include "ike_quick_mode.h"
49 #include "ipsec.h"
50 #include "log.h"
51 #include "message.h"
52 #include "policy.h"
53 #include "prf.h"
54 #include "sa.h"
55 #include "transport.h"
56 #include "util.h"
57 #include "key.h"
58 #include "x509.h"
59 
60 static void     gen_g_xy(struct message *);
61 static int      initiator_send_HASH_SA_NONCE(struct message *);
62 static int      initiator_recv_HASH_SA_NONCE(struct message *);
63 static int      initiator_send_HASH(struct message *);
64 static void     post_quick_mode(struct message *);
65 static int      responder_recv_HASH_SA_NONCE(struct message *);
66 static int      responder_send_HASH_SA_NONCE(struct message *);
67 static int      responder_recv_HASH(struct message *);
68 
69 static int      check_policy(struct exchange *, struct sa *, struct sa *);
70 
71 int	(*ike_quick_mode_initiator[])(struct message *) = {
72 	initiator_send_HASH_SA_NONCE,
73 	initiator_recv_HASH_SA_NONCE,
74 	initiator_send_HASH
75 };
76 
77 int	(*ike_quick_mode_responder[])(struct message *) = {
78 	responder_recv_HASH_SA_NONCE,
79 	responder_send_HASH_SA_NONCE,
80 	responder_recv_HASH
81 };
82 
83 /* How many return values will policy handle -- true/false for now */
84 #define RETVALUES_NUM 2
85 
86 /*
87  * Given an exchange and our policy, check whether the SA and IDs are
88  * acceptable.
89  */
90 static int
91 check_policy(struct exchange *exchange, struct sa *sa, struct sa *isakmp_sa)
92 {
93 	char           *return_values[RETVALUES_NUM];
94 	char          **principal = 0;
95 	int             i, len, result = 0, nprinc = 0;
96 	int            *x509_ids = 0, *keynote_ids = 0;
97 	unsigned char   hashbuf[20];	/* Set to the largest digest result */
98 	struct keynote_deckey dc;
99 	X509_NAME      *subject;
100 
101 	/* Do we want to use keynote policies? */
102 	if (ignore_policy ||
103 	    strncmp("yes", conf_get_str("General", "Use-Keynote"), 3))
104 		return 1;
105 
106 	/* Initialize if necessary -- e.g., if pre-shared key auth was used */
107 	if (isakmp_sa->policy_id < 0) {
108 		if ((isakmp_sa->policy_id = kn_init()) == -1) {
109 			log_print("check_policy: "
110 			    "failed to initialize policy session");
111 			return 0;
112 		}
113 	}
114 	/* Add the callback that will handle attributes.  */
115 	if (kn_add_action(isakmp_sa->policy_id, ".*", (char *)policy_callback,
116 	    ENVIRONMENT_FLAG_FUNC | ENVIRONMENT_FLAG_REGEX) == -1) {
117 		log_print("check_policy: "
118 		    "kn_add_action (%d, \".*\", %p, FUNC | REGEX) failed",
119 		    isakmp_sa->policy_id, policy_callback);
120 		kn_close(isakmp_sa->policy_id);
121 		isakmp_sa->policy_id = -1;
122 		return 0;
123 	}
124 	if (policy_asserts_num) {
125 		keynote_ids = calloc(policy_asserts_num, sizeof *keynote_ids);
126 		if (!keynote_ids) {
127 			log_error("check_policy: calloc (%d, %lu) failed",
128 			    policy_asserts_num,
129 			    (unsigned long)sizeof *keynote_ids);
130 			kn_close(isakmp_sa->policy_id);
131 			isakmp_sa->policy_id = -1;
132 			return 0;
133 		}
134 	}
135 	/* Add the policy assertions */
136 	for (i = 0; i < policy_asserts_num; i++)
137 		keynote_ids[i] = kn_add_assertion(isakmp_sa->policy_id,
138 		    policy_asserts[i],
139 		    strlen(policy_asserts[i]), ASSERT_FLAG_LOCAL);
140 
141 	/* Initialize -- we'll let the callback do all the work.  */
142 	policy_exchange = exchange;
143 	policy_sa = sa;
144 	policy_isakmp_sa = isakmp_sa;
145 
146 	/* Set the return values; true/false for now at least.  */
147 	return_values[0] = "false";	/* Order of values in array is
148 					 * important.  */
149 	return_values[1] = "true";
150 
151 	/* Create a principal (authorizer) for the SA/ID request.  */
152 	switch (isakmp_sa->recv_certtype) {
153 	case ISAKMP_CERTENC_NONE:
154 		/*
155 		 * For shared keys, just duplicate the passphrase with the
156 		 * appropriate prefix tag.
157 		 */
158 		nprinc = 3;
159 		principal = calloc(nprinc, sizeof *principal);
160 		if (!principal) {
161 			log_error("check_policy: calloc (%d, %lu) failed",
162 			    nprinc, (unsigned long)sizeof *principal);
163 			goto policydone;
164 		}
165 		len = strlen(isakmp_sa->recv_key) + sizeof "passphrase:";
166 		principal[0] = calloc(len, sizeof(char));
167 		if (!principal[0]) {
168 			log_error("check_policy: calloc (%d, %lu) failed", len,
169 			    (unsigned long)sizeof(char));
170 			goto policydone;
171 		}
172 		/*
173 		 * XXX Consider changing the magic hash lengths with
174 		 * constants.
175 		 */
176 		strlcpy(principal[0], "passphrase:", len);
177 		memcpy(principal[0] + sizeof "passphrase:" - 1,
178 		    isakmp_sa->recv_key, strlen(isakmp_sa->recv_key));
179 
180 		len = sizeof "passphrase-md5-hex:" + 2 * 16;
181 		principal[1] = calloc(len, sizeof(char));
182 		if (!principal[1]) {
183 			log_error("check_policy: calloc (%d, %lu) failed", len,
184 			    (unsigned long)sizeof(char));
185 			goto policydone;
186 		}
187 		strlcpy(principal[1], "passphrase-md5-hex:", len);
188 		MD5(isakmp_sa->recv_key, strlen(isakmp_sa->recv_key), hashbuf);
189 		for (i = 0; i < 16; i++)
190 			snprintf(principal[1] + 2 * i +
191 			    sizeof "passphrase-md5-hex:" - 1, 3, "%02x",
192 			    hashbuf[i]);
193 
194 		len = sizeof "passphrase-sha1-hex:" + 2 * 20;
195 		principal[2] = calloc(len, sizeof(char));
196 		if (!principal[2]) {
197 			log_error("check_policy: calloc (%d, %lu) failed", len,
198 			    (unsigned long)sizeof(char));
199 			goto policydone;
200 		}
201 		strlcpy(principal[2], "passphrase-sha1-hex:", len);
202 		SHA1(isakmp_sa->recv_key, strlen(isakmp_sa->recv_key),
203 		    hashbuf);
204 		for (i = 0; i < 20; i++)
205 			snprintf(principal[2] + 2 * i +
206 			    sizeof "passphrase-sha1-hex:" - 1, 3, "%02x",
207 			    hashbuf[i]);
208 		break;
209 
210 	case ISAKMP_CERTENC_KEYNOTE:
211 		nprinc = 1;
212 
213 		principal = calloc(nprinc, sizeof *principal);
214 		if (!principal) {
215 			log_error("check_policy: calloc (%d, %lu) failed",
216 			    nprinc, (unsigned long)sizeof *principal);
217 			goto policydone;
218 		}
219 		/* Dup the keys */
220 		principal[0] = strdup(isakmp_sa->keynote_key);
221 		if (!principal[0]) {
222 			log_error("check_policy: calloc (%lu, %lu) failed",
223 			    (unsigned long)strlen(isakmp_sa->keynote_key),
224 			    (unsigned long)sizeof(char));
225 			goto policydone;
226 		}
227 		break;
228 
229 	case ISAKMP_CERTENC_X509_SIG:
230 		principal = calloc(2, sizeof *principal);
231 		if (!principal) {
232 			log_error("check_policy: calloc (2, %lu) failed",
233 			    (unsigned long)sizeof *principal);
234 			goto policydone;
235 		}
236 		if (isakmp_sa->recv_keytype == ISAKMP_KEY_RSA)
237 			dc.dec_algorithm = KEYNOTE_ALGORITHM_RSA;
238 		else {
239 			log_error("check_policy: "
240 			    "unknown/unsupported public key algorithm %d",
241 			    isakmp_sa->recv_keytype);
242 			goto policydone;
243 		}
244 
245 		dc.dec_key = isakmp_sa->recv_key;
246 		principal[0] = kn_encode_key(&dc, INTERNAL_ENC_PKCS1,
247 		    ENCODING_HEX, KEYNOTE_PUBLIC_KEY);
248 		if (keynote_errno == ERROR_MEMORY) {
249 			log_print("check_policy: "
250 			    "failed to get memory for public key");
251 			goto policydone;
252 		}
253 		if (!principal[0]) {
254 			log_print("check_policy: "
255 			    "failed to allocate memory for principal");
256 			goto policydone;
257 		}
258 		if (asprintf(&principal[1], "rsa-hex:%s", principal[0]) == -1) {
259 			log_error("check_policy: asprintf() failed");
260 			goto policydone;
261 		}
262 		free(principal[0]);
263 		principal[0] = principal[1];
264 		principal[1] = 0;
265 
266 		/* Generate a "DN:" principal.  */
267 		subject = X509_get_subject_name(isakmp_sa->recv_cert);
268 		if (subject) {
269 			principal[1] = calloc(259, sizeof(char));
270 			if (!principal[1]) {
271 				log_error("check_policy: "
272 				    "calloc (259, %lu) failed",
273 				    (unsigned long)sizeof(char));
274 				goto policydone;
275 			}
276 			strlcpy(principal[1], "DN:", 259);
277 			X509_NAME_oneline(subject, principal[1] + 3, 256);
278 			nprinc = 2;
279 		} else {
280 			nprinc = 1;
281 		}
282 		break;
283 
284 		/* XXX Eventually handle these.  */
285 	case ISAKMP_CERTENC_PKCS:
286 	case ISAKMP_CERTENC_PGP:
287 	case ISAKMP_CERTENC_DNS:
288 	case ISAKMP_CERTENC_X509_KE:
289 	case ISAKMP_CERTENC_KERBEROS:
290 	case ISAKMP_CERTENC_CRL:
291 	case ISAKMP_CERTENC_ARL:
292 	case ISAKMP_CERTENC_SPKI:
293 	case ISAKMP_CERTENC_X509_ATTR:
294 	default:
295 		log_print("check_policy: "
296 		    "unknown/unsupported certificate/authentication method %d",
297 		    isakmp_sa->recv_certtype);
298 		goto policydone;
299 	}
300 
301 	/*
302 	 * Add the authorizer (who is requesting the SA/ID);
303 	 * this may be a public or a secret key, depending on
304 	 * what mode of authentication we used in Phase 1.
305          */
306 	for (i = 0; i < nprinc; i++) {
307 		LOG_DBG((LOG_POLICY, 40, "check_policy: "
308 		    "adding authorizer [%s]", principal[i]));
309 
310 		if (kn_add_authorizer(isakmp_sa->policy_id, principal[i])
311 		    == -1) {
312 			int	j;
313 
314 			for (j = 0; j < i; j++)
315 				kn_remove_authorizer(isakmp_sa->policy_id,
316 				    principal[j]);
317 			log_print("check_policy: kn_add_authorizer failed");
318 			goto policydone;
319 		}
320 	}
321 
322 	/* Ask policy */
323 	result = kn_do_query(isakmp_sa->policy_id, return_values,
324 	    RETVALUES_NUM);
325 	LOG_DBG((LOG_POLICY, 40, "check_policy: kn_do_query returned %d",
326 	    result));
327 
328 	/* Cleanup environment */
329 	kn_cleanup_action_environment(isakmp_sa->policy_id);
330 
331 	/* Remove authorizers from the session */
332 	for (i = 0; i < nprinc; i++) {
333 		kn_remove_authorizer(isakmp_sa->policy_id, principal[i]);
334 		free(principal[i]);
335 	}
336 
337 	free(principal);
338 	principal = 0;
339 	nprinc = 0;
340 
341 	/* Check what policy said.  */
342 	if (result < 0) {
343 		LOG_DBG((LOG_POLICY, 40, "check_policy: proposal refused"));
344 		result = 0;
345 		goto policydone;
346 	}
347 policydone:
348 	for (i = 0; i < nprinc; i++)
349 		if (principal && principal[i])
350 			free(principal[i]);
351 
352 	free(principal);
353 
354 	/* Remove the policies */
355 	for (i = 0; i < policy_asserts_num; i++) {
356 		if (keynote_ids[i] != -1)
357 			kn_remove_assertion(isakmp_sa->policy_id,
358 			    keynote_ids[i]);
359 	}
360 
361 	free(keynote_ids);
362 
363 	free(x509_ids);
364 
365 	/*
366 	 * XXX Currently, check_policy() is only called from
367 	 * message_negotiate_sa(), and so this log message reflects this.
368 	 * Change to something better?
369          */
370 	if (result == 0)
371 		log_print("check_policy: negotiated SA failed policy check");
372 
373 	/*
374 	 * Given that we have only 2 return values from policy (true/false)
375 	 * we can just return the query result directly (no pre-processing
376 	 * needed).
377          */
378 	return result;
379 }
380 
381 /*
382  * Offer several sets of transforms to the responder.
383  * XXX Split this huge function up and look for common code with main mode.
384  */
385 static int
386 initiator_send_HASH_SA_NONCE(struct message *msg)
387 {
388 	struct exchange *exchange = msg->exchange;
389 	struct doi     *doi = exchange->doi;
390 	struct ipsec_exch *ie = exchange->data;
391 	u_int8_t     ***transform = 0, ***new_transform;
392 	u_int8_t      **proposal = 0, **new_proposal;
393 	u_int8_t       *sa_buf = 0, *attr, *saved_nextp_sa, *saved_nextp_prop,
394 	               *id, *spi;
395 	size_t          spi_sz, sz;
396 	size_t          proposal_len = 0, proposals_len = 0, sa_len;
397 	size_t        **transform_len = 0, **new_transform_len;
398 	size_t         *transforms_len = 0, *new_transforms_len;
399 	u_int32_t      *transform_cnt = 0, *new_transform_cnt;
400 	u_int32_t       suite_no, prop_no, prot_no, xf_no, prop_cnt = 0;
401 	u_int32_t       i;
402 	int             value, update_nextp, protocol_num, proto_id;
403 	struct proto   *proto;
404 	struct conf_list *suite_conf, *prot_conf = 0, *xf_conf = 0, *life_conf;
405 	struct conf_list_node *suite, *prot, *xf, *life;
406 	struct constant_map *id_map;
407 	char           *protocol_id, *transform_id;
408 	char           *local_id, *remote_id;
409 	int             group_desc = -1, new_group_desc;
410 	struct ipsec_sa *isa = msg->isakmp_sa->data;
411 	struct hash    *hash = hash_get(isa->hash);
412 	struct sockaddr *src;
413 	struct proto_attr *pa;
414 
415 	if (!ipsec_add_hash_payload(msg, hash->hashsize))
416 		return -1;
417 
418 	/* Get the list of protocol suites.  */
419 	suite_conf = conf_get_list(exchange->policy, "Suites");
420 	if (!suite_conf)
421 		return -1;
422 
423 	for (suite = TAILQ_FIRST(&suite_conf->fields), suite_no = prop_no = 0;
424 	    suite_no < suite_conf->cnt;
425 	    suite_no++, suite = TAILQ_NEXT(suite, link)) {
426 		/* Now get each protocol in this specific protocol suite.  */
427 		prot_conf = conf_get_list(suite->field, "Protocols");
428 		if (!prot_conf)
429 			goto bail_out;
430 
431 		for (prot = TAILQ_FIRST(&prot_conf->fields), prot_no = 0;
432 		    prot_no < prot_conf->cnt;
433 		    prot_no++, prot = TAILQ_NEXT(prot, link)) {
434 			/* Make sure we have a proposal/transform vectors.  */
435 			if (prop_no >= prop_cnt) {
436 				/*
437 				 * This resize algorithm is completely
438 				 * arbitrary.
439 				 */
440 				prop_cnt = 2 * prop_cnt + 10;
441 				new_proposal = realloc(proposal,
442 				    prop_cnt * sizeof *proposal);
443 				if (!new_proposal) {
444 					log_error(
445 					    "initiator_send_HASH_SA_NONCE: "
446 					    "realloc (%p, %lu) failed",
447 					    proposal,
448 					    prop_cnt * (unsigned long)sizeof *proposal);
449 					goto bail_out;
450 				}
451 				proposal = new_proposal;
452 
453 				new_transforms_len = realloc(transforms_len,
454 				    prop_cnt * sizeof *transforms_len);
455 				if (!new_transforms_len) {
456 					log_error(
457 					    "initiator_send_HASH_SA_NONCE: "
458 					    "realloc (%p, %lu) failed",
459 					    transforms_len,
460 					    prop_cnt * (unsigned long)sizeof *transforms_len);
461 					goto bail_out;
462 				}
463 				transforms_len = new_transforms_len;
464 
465 				new_transform = realloc(transform,
466 				    prop_cnt * sizeof *transform);
467 				if (!new_transform) {
468 					log_error(
469 					    "initiator_send_HASH_SA_NONCE: "
470 					    "realloc (%p, %lu) failed",
471 					    transform,
472 					    prop_cnt * (unsigned long)sizeof *transform);
473 					goto bail_out;
474 				}
475 				transform = new_transform;
476 
477 				new_transform_cnt = realloc(transform_cnt,
478 				    prop_cnt * sizeof *transform_cnt);
479 				if (!new_transform_cnt) {
480 					log_error(
481 					    "initiator_send_HASH_SA_NONCE: "
482 					    "realloc (%p, %lu) failed",
483 					    transform_cnt,
484 					    prop_cnt * (unsigned long)sizeof *transform_cnt);
485 					goto bail_out;
486 				}
487 				transform_cnt = new_transform_cnt;
488 
489 				new_transform_len = realloc(transform_len,
490 				    prop_cnt * sizeof *transform_len);
491 				if (!new_transform_len) {
492 					log_error(
493 					    "initiator_send_HASH_SA_NONCE: "
494 					    "realloc (%p, %lu) failed",
495 					    transform_len,
496 					    prop_cnt * (unsigned long)sizeof *transform_len);
497 					goto bail_out;
498 				}
499 				transform_len = new_transform_len;
500 			}
501 			protocol_id = conf_get_str(prot->field, "PROTOCOL_ID");
502 			if (!protocol_id)
503 				goto bail_out;
504 
505 			proto_id = constant_value(ipsec_proto_cst,
506 			    protocol_id);
507 			switch (proto_id) {
508 			case IPSEC_PROTO_IPSEC_AH:
509 				id_map = ipsec_ah_cst;
510 				break;
511 
512 			case IPSEC_PROTO_IPSEC_ESP:
513 				id_map = ipsec_esp_cst;
514 				break;
515 
516 			case IPSEC_PROTO_IPCOMP:
517 				id_map = ipsec_ipcomp_cst;
518 				break;
519 
520 			default:
521 			    {
522 				log_print("initiator_send_HASH_SA_NONCE: "
523 				    "invalid PROTCOL_ID: %s", protocol_id);
524 				goto bail_out;
525 			    }
526 			}
527 
528 			/* Now get each transform we offer for this protocol.*/
529 			xf_conf = conf_get_list(prot->field, "Transforms");
530 			if (!xf_conf)
531 				goto bail_out;
532 			transform_cnt[prop_no] = xf_conf->cnt;
533 
534 			transform[prop_no] = calloc(transform_cnt[prop_no],
535 			    sizeof **transform);
536 			if (!transform[prop_no]) {
537 				log_error("initiator_send_HASH_SA_NONCE: "
538 				    "calloc (%d, %lu) failed",
539 				    transform_cnt[prop_no],
540 				    (unsigned long)sizeof **transform);
541 				goto bail_out;
542 			}
543 			transform_len[prop_no] = calloc(transform_cnt[prop_no],
544 			    sizeof **transform_len);
545 			if (!transform_len[prop_no]) {
546 				log_error("initiator_send_HASH_SA_NONCE: "
547 				    "calloc (%d, %lu) failed",
548 				    transform_cnt[prop_no],
549 				    (unsigned long)sizeof **transform_len);
550 				goto bail_out;
551 			}
552 			transforms_len[prop_no] = 0;
553 			for (xf = TAILQ_FIRST(&xf_conf->fields), xf_no = 0;
554 			    xf_no < transform_cnt[prop_no];
555 			    xf_no++, xf = TAILQ_NEXT(xf, link)) {
556 
557 				/* XXX The sizing needs to be dynamic.  */
558 				transform[prop_no][xf_no] =
559 				    calloc(ISAKMP_TRANSFORM_SA_ATTRS_OFF +
560 				    9 * ISAKMP_ATTR_VALUE_OFF, 1);
561 				if (!transform[prop_no][xf_no]) {
562 					log_error(
563 					    "initiator_send_HASH_SA_NONCE: "
564 					    "calloc (%d, 1) failed",
565 					    ISAKMP_TRANSFORM_SA_ATTRS_OFF +
566 					    9 * ISAKMP_ATTR_VALUE_OFF);
567 					goto bail_out;
568 				}
569 				SET_ISAKMP_TRANSFORM_NO(transform[prop_no][xf_no],
570 				    xf_no + 1);
571 
572 				transform_id = conf_get_str(xf->field,
573 				    "TRANSFORM_ID");
574 				if (!transform_id)
575 					goto bail_out;
576 				SET_ISAKMP_TRANSFORM_ID(transform[prop_no][xf_no],
577 				    constant_value(id_map, transform_id));
578 				SET_ISAKMP_TRANSFORM_RESERVED(transform[prop_no][xf_no], 0);
579 
580 				attr = transform[prop_no][xf_no] +
581 				    ISAKMP_TRANSFORM_SA_ATTRS_OFF;
582 
583 				/*
584 				 * Life durations are special, we should be
585 				 * able to specify several, one per type.
586 				 */
587 				life_conf = conf_get_list(xf->field, "Life");
588 				if (life_conf) {
589 					for (life = TAILQ_FIRST(&life_conf->fields);
590 					    life; life = TAILQ_NEXT(life, link)) {
591 						attribute_set_constant(
592 						    life->field, "LIFE_TYPE",
593 						    ipsec_duration_cst,
594 						    IPSEC_ATTR_SA_LIFE_TYPE,
595 						    &attr);
596 
597 						/*
598 						 * XXX Deals with 16 and 32
599 						 * bit lifetimes only
600 						 */
601 						value =
602 						    conf_get_num(life->field,
603 							"LIFE_DURATION", 0);
604 						if (value) {
605 							if (value <= 0xffff)
606 								attr =
607 								    attribute_set_basic(
608 									attr,
609 									IPSEC_ATTR_SA_LIFE_DURATION,
610 									value);
611 							else {
612 								value = htonl(value);
613 								attr =
614 								    attribute_set_var(
615 									attr,
616 									IPSEC_ATTR_SA_LIFE_DURATION,
617 									(u_int8_t *)&value,
618 									sizeof value);
619 							}
620 						}
621 					}
622 					conf_free_list(life_conf);
623 				}
624 				attribute_set_constant(xf->field,
625 				    "ENCAPSULATION_MODE", ipsec_encap_cst,
626 				    IPSEC_ATTR_ENCAPSULATION_MODE, &attr);
627 
628 				if (proto_id != IPSEC_PROTO_IPCOMP) {
629 					attribute_set_constant(xf->field,
630 					    "AUTHENTICATION_ALGORITHM",
631 					    ipsec_auth_cst,
632 					    IPSEC_ATTR_AUTHENTICATION_ALGORITHM,
633 					    &attr);
634 
635 					attribute_set_constant(xf->field,
636 					    "GROUP_DESCRIPTION",
637 					    ike_group_desc_cst,
638 					    IPSEC_ATTR_GROUP_DESCRIPTION, &attr);
639 
640 					value = conf_get_num(xf->field,
641 					    "KEY_LENGTH", 0);
642 					if (value)
643 						attr = attribute_set_basic(
644 						    attr,
645 						    IPSEC_ATTR_KEY_LENGTH,
646 						    value);
647 
648 					value = conf_get_num(xf->field,
649 					    "KEY_ROUNDS", 0);
650 					if (value)
651 						attr = attribute_set_basic(
652 						    attr,
653 						    IPSEC_ATTR_KEY_ROUNDS,
654 						    value);
655 				} else {
656 					value = conf_get_num(xf->field,
657 					    "COMPRESS_DICTIONARY_SIZE", 0);
658 					if (value)
659 						attr = attribute_set_basic(
660 						    attr,
661 						    IPSEC_ATTR_COMPRESS_DICTIONARY_SIZE,
662 						    value);
663 
664 					value = conf_get_num(xf->field,
665 					   "COMPRESS_PRIVATE_ALGORITHM", 0);
666 					if (value)
667 						attr = attribute_set_basic(
668 						    attr,
669 						    IPSEC_ATTR_COMPRESS_PRIVATE_ALGORITHM,
670 						    value);
671 				}
672 
673 				value = conf_get_num(xf->field, "ECN_TUNNEL",
674 				    0);
675 				if (value)
676 					attr = attribute_set_basic(attr,
677 					    IPSEC_ATTR_ECN_TUNNEL, value);
678 
679 				/* Record the real transform size.  */
680 				transforms_len[prop_no] +=
681 				    (transform_len[prop_no][xf_no]
682 					= attr - transform[prop_no][xf_no]);
683 
684 				if (proto_id != IPSEC_PROTO_IPCOMP) {
685 					/*
686 					 * Make sure that if a group
687 					 * description is specified, it is
688 					 * specified for all transforms
689 					 * equally.
690 					 */
691 					attr =
692 					    (u_int8_t *)conf_get_str(xf->field,
693 						"GROUP_DESCRIPTION");
694 					new_group_desc
695 					    = attr ? constant_value(ike_group_desc_cst,
696 						(char *)attr) : 0;
697 					if (group_desc == -1)
698 						group_desc = new_group_desc;
699 					else if (group_desc != new_group_desc) {
700 						log_print("initiator_send_HASH_SA_NONCE: "
701 						    "differing group descriptions in a proposal");
702 						goto bail_out;
703 					}
704 				}
705 			}
706 			conf_free_list(xf_conf);
707 			xf_conf = 0;
708 
709 			/*
710 			 * Get SPI from application.
711 			 * XXX Should we care about unknown constants?
712 			 */
713 			protocol_num = constant_value(ipsec_proto_cst,
714 			    protocol_id);
715 			spi = doi->get_spi(&spi_sz, protocol_num, msg);
716 			if (spi_sz && !spi) {
717 				log_print("initiator_send_HASH_SA_NONCE: "
718 				    "doi->get_spi failed");
719 				goto bail_out;
720 			}
721 			proposal_len = ISAKMP_PROP_SPI_OFF + spi_sz;
722 			proposals_len +=
723 			    proposal_len + transforms_len[prop_no];
724 			proposal[prop_no] = malloc(proposal_len);
725 			if (!proposal[prop_no]) {
726 				log_error("initiator_send_HASH_SA_NONCE: "
727 				    "malloc (%lu) failed",
728 				    (unsigned long)proposal_len);
729 				goto bail_out;
730 			}
731 			SET_ISAKMP_PROP_NO(proposal[prop_no], suite_no + 1);
732 			SET_ISAKMP_PROP_PROTO(proposal[prop_no], protocol_num);
733 
734 			/* XXX I would like to see this factored out.  */
735 			proto = calloc(1, sizeof *proto);
736 			if (!proto) {
737 				log_error("initiator_send_HASH_SA_NONCE: "
738 				    "calloc (1, %lu) failed",
739 				    (unsigned long)sizeof *proto);
740 				goto bail_out;
741 			}
742 			if (doi->proto_size) {
743 				proto->data = calloc(1, doi->proto_size);
744 				if (!proto->data) {
745 					free(proto);
746 					log_error(
747 					    "initiator_send_HASH_SA_NONCE: "
748 					    "calloc (1, %lu) failed",
749 					    (unsigned long)doi->proto_size);
750 					goto bail_out;
751 				}
752 			}
753 			proto->no = suite_no + 1;
754 			proto->proto = protocol_num;
755 			proto->sa = TAILQ_FIRST(&exchange->sa_list);
756 			proto->xf_cnt = transform_cnt[prop_no];
757 			TAILQ_INIT(&proto->xfs);
758 			for (xf_no = 0; xf_no < proto->xf_cnt; xf_no++) {
759 				pa = (struct proto_attr *)calloc(1,
760 				    sizeof *pa);
761 				if (!pa) {
762 					if (proto->data)
763 						free(proto->data);
764 					free(proto);
765 					goto bail_out;
766 				}
767 				pa->len = transform_len[prop_no][xf_no];
768 				pa->attrs = (u_int8_t *)malloc(pa->len);
769 				if (!pa->attrs) {
770 					if (proto->data)
771 						free(proto->data);
772 					free(proto);
773 					free(pa);
774 					goto bail_out;
775 				}
776 				memcpy(pa->attrs, transform[prop_no][xf_no],
777 				    pa->len);
778 				TAILQ_INSERT_TAIL(&proto->xfs, pa, next);
779 			}
780 			TAILQ_INSERT_TAIL(&TAILQ_FIRST(&exchange->sa_list)->protos,
781 			    proto, link);
782 
783 			/* Setup the incoming SPI.  */
784 			SET_ISAKMP_PROP_SPI_SZ(proposal[prop_no], spi_sz);
785 			memcpy(proposal[prop_no] + ISAKMP_PROP_SPI_OFF, spi,
786 			    spi_sz);
787 			proto->spi_sz[1] = spi_sz;
788 			proto->spi[1] = spi;
789 
790 			/*
791 			 * Let the DOI get at proto for initializing its own
792 			 * data.
793 			 */
794 			if (doi->proto_init)
795 				doi->proto_init(proto, prot->field);
796 
797 			SET_ISAKMP_PROP_NTRANSFORMS(proposal[prop_no],
798 						    transform_cnt[prop_no]);
799 			prop_no++;
800 		}
801 		conf_free_list(prot_conf);
802 		prot_conf = 0;
803 	}
804 
805 	sa_len = ISAKMP_SA_SIT_OFF + IPSEC_SIT_SIT_LEN;
806 	sa_buf = malloc(sa_len);
807 	if (!sa_buf) {
808 		log_error("initiator_send_HASH_SA_NONCE: malloc (%lu) failed",
809 			  (unsigned long)sa_len);
810 		goto bail_out;
811 	}
812 	SET_ISAKMP_SA_DOI(sa_buf, IPSEC_DOI_IPSEC);
813 	SET_IPSEC_SIT_SIT(sa_buf + ISAKMP_SA_SIT_OFF, IPSEC_SIT_IDENTITY_ONLY);
814 
815 	/*
816 	 * Add the payloads.  As this is a SA, we need to recompute the
817 	 * lengths of the payloads containing others.  We also need to
818 	 * reset these payload's "next payload type" field.
819          */
820 	if (message_add_payload(msg, ISAKMP_PAYLOAD_SA, sa_buf, sa_len, 1))
821 		goto bail_out;
822 	SET_ISAKMP_GEN_LENGTH(sa_buf, sa_len + proposals_len);
823 	sa_buf = 0;
824 
825 	update_nextp = 0;
826 	saved_nextp_sa = msg->nextp;
827 	for (i = 0; i < prop_no; i++) {
828 		if (message_add_payload(msg, ISAKMP_PAYLOAD_PROPOSAL,
829 		    proposal[i], proposal_len, update_nextp))
830 			goto bail_out;
831 		SET_ISAKMP_GEN_LENGTH(proposal[i],
832 		    proposal_len + transforms_len[i]);
833 		proposal[i] = 0;
834 
835 		update_nextp = 0;
836 		saved_nextp_prop = msg->nextp;
837 		for (xf_no = 0; xf_no < transform_cnt[i]; xf_no++) {
838 			if (message_add_payload(msg, ISAKMP_PAYLOAD_TRANSFORM,
839 			    transform[i][xf_no],
840 			    transform_len[i][xf_no], update_nextp))
841 				goto bail_out;
842 			update_nextp = 1;
843 			transform[i][xf_no] = 0;
844 		}
845 		msg->nextp = saved_nextp_prop;
846 		update_nextp = 1;
847 	}
848 	msg->nextp = saved_nextp_sa;
849 
850 	/*
851 	 * Save SA payload body in ie->sa_i_b, length ie->sa_i_b_len.
852          */
853 	ie->sa_i_b = message_copy(msg, ISAKMP_GEN_SZ, &ie->sa_i_b_len);
854 	if (!ie->sa_i_b)
855 		goto bail_out;
856 
857 	/*
858 	 * Generate a nonce, and add it to the message.
859 	 * XXX I want a better way to specify the nonce's size.
860          */
861 	if (exchange_gen_nonce(msg, 16))
862 		return -1;
863 
864 	/* Generate optional KEY_EXCH payload.  */
865 	if (group_desc > 0) {
866 		ie->group = group_get(group_desc);
867 		ie->g_x_len = dh_getlen(ie->group);
868 
869 		if (ipsec_gen_g_x(msg)) {
870 			group_free(ie->group);
871 			ie->group = 0;
872 			return -1;
873 		}
874 	}
875 	/* Generate optional client ID payloads.  XXX Share with responder.  */
876 	local_id = conf_get_str(exchange->name, "Local-ID");
877 	remote_id = conf_get_str(exchange->name, "Remote-ID");
878 	if (local_id && remote_id) {
879 		id = ipsec_build_id(local_id, &sz);
880 		if (!id)
881 			return -1;
882 		LOG_DBG_BUF((LOG_NEGOTIATION, 90,
883 		    "initiator_send_HASH_SA_NONCE: IDic", id, sz));
884 		if (message_add_payload(msg, ISAKMP_PAYLOAD_ID, id, sz, 1)) {
885 			free(id);
886 			return -1;
887 		}
888 		id = ipsec_build_id(remote_id, &sz);
889 		if (!id)
890 			return -1;
891 		LOG_DBG_BUF((LOG_NEGOTIATION, 90,
892 		    "initiator_send_HASH_SA_NONCE: IDrc", id, sz));
893 		if (message_add_payload(msg, ISAKMP_PAYLOAD_ID, id, sz, 1)) {
894 			free(id);
895 			return -1;
896 		}
897 	}
898 	/* XXX I do not judge these as errors, are they?  */
899 	else if (local_id)
900 		log_print("initiator_send_HASH_SA_NONCE: "
901 			  "Local-ID given without Remote-ID for \"%s\"",
902 			  exchange->name);
903 	else if (remote_id)
904 		/*
905 		 * This code supports the "road warrior" case, where the
906 		 * initiator doesn't have a fixed IP address, but wants to
907 		 * specify a particular remote network to talk to. -- Adrian
908 		 * Close <adrian@esec.com.au>
909 		 */
910 	{
911 		log_print("initiator_send_HASH_SA_NONCE: "
912 			  "Remote-ID given without Local-ID for \"%s\"",
913 			  exchange->name);
914 
915 		/*
916 		 * If we're here, then we are the initiator, so use initiator
917 		 * address for local ID
918 		 */
919 		msg->transport->vtbl->get_src(msg->transport, &src);
920 		sz = ISAKMP_ID_SZ + sockaddr_addrlen(src);
921 
922 		id = calloc(sz, sizeof(char));
923 		if (!id) {
924 			log_error("initiator_send_HASH_SA_NONCE: "
925 			    "calloc (%lu, %lu) failed", (unsigned long)sz,
926 			    (unsigned long)sizeof(char));
927 			return -1;
928 		}
929 		switch (src->sa_family) {
930 		case AF_INET6:
931 			SET_ISAKMP_ID_TYPE(id, IPSEC_ID_IPV6_ADDR);
932 			break;
933 		case AF_INET:
934 			SET_ISAKMP_ID_TYPE(id, IPSEC_ID_IPV4_ADDR);
935 			break;
936 		default:
937 			log_error("initiator_send_HASH_SA_NONCE: "
938 			    "unknown sa_family %d", src->sa_family);
939 			free(id);
940 			return -1;
941 		}
942 		memcpy(id + ISAKMP_ID_DATA_OFF, sockaddr_addrdata(src),
943 		    sockaddr_addrlen(src));
944 
945 		LOG_DBG_BUF((LOG_NEGOTIATION, 90,
946 		    "initiator_send_HASH_SA_NONCE: IDic", id, sz));
947 		if (message_add_payload(msg, ISAKMP_PAYLOAD_ID, id, sz, 1)) {
948 			free(id);
949 			return -1;
950 		}
951 		/* Send supplied remote_id */
952 		id = ipsec_build_id(remote_id, &sz);
953 		if (!id)
954 			return -1;
955 		LOG_DBG_BUF((LOG_NEGOTIATION, 90,
956 		    "initiator_send_HASH_SA_NONCE: IDrc", id, sz));
957 		if (message_add_payload(msg, ISAKMP_PAYLOAD_ID, id, sz, 1)) {
958 			free(id);
959 			return -1;
960 		}
961 	}
962 	if (ipsec_fill_in_hash(msg))
963 		goto bail_out;
964 
965 	conf_free_list(suite_conf);
966 	for (i = 0; i < prop_no; i++) {
967 		free(transform[i]);
968 		free(transform_len[i]);
969 	}
970 	free(proposal);
971 	free(transform);
972 	free(transforms_len);
973 	free(transform_len);
974 	free(transform_cnt);
975 	return 0;
976 
977 bail_out:
978 	free(sa_buf);
979 	if (proposal) {
980 		for (i = 0; i < prop_no; i++) {
981 			free(proposal[i]);
982 			if (transform[i]) {
983 				for (xf_no = 0; xf_no < transform_cnt[i];
984 				    xf_no++)
985 					free(transform[i][xf_no]);
986 				free(transform[i]);
987 			}
988 			free(transform_len[i]);
989 		}
990 		free(proposal);
991 		free(transforms_len);
992 		free(transform);
993 		free(transform_len);
994 		free(transform_cnt);
995 	}
996 	if (xf_conf)
997 		conf_free_list(xf_conf);
998 	if (prot_conf)
999 		conf_free_list(prot_conf);
1000 	conf_free_list(suite_conf);
1001 	return -1;
1002 }
1003 
1004 /* Figure out what transform the responder chose.  */
1005 static int
1006 initiator_recv_HASH_SA_NONCE(struct message *msg)
1007 {
1008 	struct exchange *exchange = msg->exchange;
1009 	struct ipsec_exch *ie = exchange->data;
1010 	struct sa      *sa;
1011 	struct proto   *proto, *next_proto;
1012 	struct payload *sa_p = payload_first(msg, ISAKMP_PAYLOAD_SA);
1013 	struct payload *xf, *idp;
1014 	struct payload *hashp = payload_first(msg, ISAKMP_PAYLOAD_HASH);
1015 	struct payload *kep = payload_first(msg, ISAKMP_PAYLOAD_KEY_EXCH);
1016 	struct prf     *prf;
1017 	struct sa      *isakmp_sa = msg->isakmp_sa;
1018 	struct ipsec_sa *isa = isakmp_sa->data;
1019 	struct hash    *hash = hash_get(isa->hash);
1020 	u_int8_t       *rest;
1021 	size_t          rest_len;
1022 	struct sockaddr *src, *dst;
1023 
1024 	/* Allocate the prf and start calculating our HASH(1).  XXX Share?  */
1025 	LOG_DBG_BUF((LOG_NEGOTIATION, 90, "initiator_recv_HASH_SA_NONCE: "
1026 	    "SKEYID_a", (u_int8_t *)isa->skeyid_a, isa->skeyid_len));
1027 	prf = prf_alloc(isa->prf_type, hash->type, isa->skeyid_a,
1028 	    isa->skeyid_len);
1029 	if (!prf)
1030 		return -1;
1031 
1032 	prf->Init(prf->prfctx);
1033 	LOG_DBG_BUF((LOG_NEGOTIATION, 90,
1034 	    "initiator_recv_HASH_SA_NONCE: message_id",
1035 	    exchange->message_id, ISAKMP_HDR_MESSAGE_ID_LEN));
1036 	prf->Update(prf->prfctx, exchange->message_id,
1037 	    ISAKMP_HDR_MESSAGE_ID_LEN);
1038 	LOG_DBG_BUF((LOG_NEGOTIATION, 90, "initiator_recv_HASH_SA_NONCE: "
1039 	    "NONCE_I_b", exchange->nonce_i, exchange->nonce_i_len));
1040 	prf->Update(prf->prfctx, exchange->nonce_i, exchange->nonce_i_len);
1041 	rest = hashp->p + GET_ISAKMP_GEN_LENGTH(hashp->p);
1042 	rest_len = (GET_ISAKMP_HDR_LENGTH(msg->iov[0].iov_base)
1043 	    - (rest - (u_int8_t *)msg->iov[0].iov_base));
1044 	LOG_DBG_BUF((LOG_NEGOTIATION, 90,
1045 	    "initiator_recv_HASH_SA_NONCE: payloads after HASH(2)", rest,
1046 	    rest_len));
1047 	prf->Update(prf->prfctx, rest, rest_len);
1048 	prf->Final(hash->digest, prf->prfctx);
1049 	prf_free(prf);
1050 	LOG_DBG_BUF((LOG_NEGOTIATION, 80,
1051 	    "initiator_recv_HASH_SA_NONCE: computed HASH(2)", hash->digest,
1052 	    hash->hashsize));
1053 	if (memcmp(hashp->p + ISAKMP_HASH_DATA_OFF, hash->digest,
1054 	    hash->hashsize) != 0) {
1055 		message_drop(msg, ISAKMP_NOTIFY_INVALID_HASH_INFORMATION, 0, 1,
1056 		    0);
1057 		return -1;
1058 	}
1059 	/* Mark the HASH as handled.  */
1060 	hashp->flags |= PL_MARK;
1061 
1062 	/* Mark message as authenticated. */
1063 	msg->flags |= MSG_AUTHENTICATED;
1064 
1065 	/*
1066 	 * As we are getting an answer on our transform offer, only one
1067 	 * transform should be given.
1068          *
1069 	 * XXX Currently we only support negotiating one SA per quick mode run.
1070          */
1071 	if (TAILQ_NEXT(sa_p, link)) {
1072 		log_print("initiator_recv_HASH_SA_NONCE: "
1073 		    "multiple SA payloads in quick mode not supported yet");
1074 		return -1;
1075 	}
1076 	sa = TAILQ_FIRST(&exchange->sa_list);
1077 
1078 	/* This is here for the policy check */
1079 	if (kep)
1080 		ie->pfs = 1;
1081 
1082 	/* Drop message when it contains ID types we do not implement yet.  */
1083 	TAILQ_FOREACH(idp, &msg->payload[ISAKMP_PAYLOAD_ID], link) {
1084 		switch (GET_ISAKMP_ID_TYPE(idp->p)) {
1085 		case IPSEC_ID_IPV4_ADDR:
1086 		case IPSEC_ID_IPV4_ADDR_SUBNET:
1087 		case IPSEC_ID_IPV6_ADDR:
1088 		case IPSEC_ID_IPV6_ADDR_SUBNET:
1089 			break;
1090 
1091 		default:
1092 			message_drop(msg, ISAKMP_NOTIFY_INVALID_ID_INFORMATION,
1093 			    0, 1, 0);
1094 			return -1;
1095 		}
1096 	}
1097 
1098 	/* Handle optional client ID payloads.  */
1099 	idp = payload_first(msg, ISAKMP_PAYLOAD_ID);
1100 	if (idp) {
1101 		/* If IDci is there, IDcr must be too.  */
1102 		if (!TAILQ_NEXT(idp, link)) {
1103 			/* XXX Is this a good notify type?  */
1104 			message_drop(msg, ISAKMP_NOTIFY_PAYLOAD_MALFORMED, 0,
1105 			    1, 0);
1106 			return -1;
1107 		}
1108 		/* XXX We should really compare, not override.  */
1109 		ie->id_ci_sz = GET_ISAKMP_GEN_LENGTH(idp->p);
1110 		ie->id_ci = malloc(ie->id_ci_sz);
1111 		if (!ie->id_ci) {
1112 			log_error("initiator_recv_HASH_SA_NONCE: "
1113 			    "malloc (%lu) failed",
1114 			    (unsigned long)ie->id_ci_sz);
1115 			return -1;
1116 		}
1117 		memcpy(ie->id_ci, idp->p, ie->id_ci_sz);
1118 		idp->flags |= PL_MARK;
1119 		LOG_DBG_BUF((LOG_NEGOTIATION, 90,
1120 		    "initiator_recv_HASH_SA_NONCE: IDci",
1121 		    ie->id_ci + ISAKMP_GEN_SZ, ie->id_ci_sz - ISAKMP_GEN_SZ));
1122 
1123 		idp = TAILQ_NEXT(idp, link);
1124 		ie->id_cr_sz = GET_ISAKMP_GEN_LENGTH(idp->p);
1125 		ie->id_cr = malloc(ie->id_cr_sz);
1126 		if (!ie->id_cr) {
1127 			log_error("initiator_recv_HASH_SA_NONCE: "
1128 			    "malloc (%lu) failed",
1129 			    (unsigned long)ie->id_cr_sz);
1130 			return -1;
1131 		}
1132 		memcpy(ie->id_cr, idp->p, ie->id_cr_sz);
1133 		idp->flags |= PL_MARK;
1134 		LOG_DBG_BUF((LOG_NEGOTIATION, 90,
1135 		    "initiator_recv_HASH_SA_NONCE: IDcr",
1136 		    ie->id_cr + ISAKMP_GEN_SZ, ie->id_cr_sz - ISAKMP_GEN_SZ));
1137 	} else {
1138 		/*
1139 		 * If client identifiers are not present in the exchange,
1140 		 * we fake them. RFC 2409 states:
1141 		 *    The identities of the SAs negotiated in Quick Mode are
1142 		 *    implicitly assumed to be the IP addresses of the ISAKMP
1143 		 *    peers, without any constraints on the protocol or port
1144 		 *    numbers allowed, unless client identifiers are specified
1145 		 *    in Quick Mode.
1146 		 *
1147 		 * -- Michael Paddon (mwp@aba.net.au)
1148 		 */
1149 
1150 		ie->flags = IPSEC_EXCH_FLAG_NO_ID;
1151 
1152 		/* Get initiator and responder addresses.  */
1153 		msg->transport->vtbl->get_src(msg->transport, &src);
1154 		msg->transport->vtbl->get_dst(msg->transport, &dst);
1155 		ie->id_ci_sz = ISAKMP_ID_DATA_OFF + sockaddr_addrlen(src);
1156 		ie->id_cr_sz = ISAKMP_ID_DATA_OFF + sockaddr_addrlen(dst);
1157 		ie->id_ci = calloc(ie->id_ci_sz, sizeof(char));
1158 		ie->id_cr = calloc(ie->id_cr_sz, sizeof(char));
1159 
1160 		if (!ie->id_ci || !ie->id_cr) {
1161 			log_error("initiator_recv_HASH_SA_NONCE: "
1162 			    "calloc (%lu, %lu) failed",
1163 			    (unsigned long)ie->id_cr_sz,
1164 			    (unsigned long)sizeof(char));
1165 			free(ie->id_ci);
1166 			ie->id_ci = 0;
1167 			free(ie->id_cr);
1168 			ie->id_cr = 0;
1169 			return -1;
1170 		}
1171 		if (src->sa_family != dst->sa_family) {
1172 			log_error("initiator_recv_HASH_SA_NONCE: "
1173 			    "sa_family mismatch");
1174 			free(ie->id_ci);
1175 			ie->id_ci = 0;
1176 			free(ie->id_cr);
1177 			ie->id_cr = 0;
1178 			return -1;
1179 		}
1180 		switch (src->sa_family) {
1181 		case AF_INET:
1182 			SET_ISAKMP_ID_TYPE(ie->id_ci, IPSEC_ID_IPV4_ADDR);
1183 			SET_ISAKMP_ID_TYPE(ie->id_cr, IPSEC_ID_IPV4_ADDR);
1184 			break;
1185 
1186 		case AF_INET6:
1187 			SET_ISAKMP_ID_TYPE(ie->id_ci, IPSEC_ID_IPV6_ADDR);
1188 			SET_ISAKMP_ID_TYPE(ie->id_cr, IPSEC_ID_IPV6_ADDR);
1189 			break;
1190 
1191 		default:
1192 			log_error("initiator_recv_HASH_SA_NONCE: "
1193 			    "unknown sa_family %d", src->sa_family);
1194 			free(ie->id_ci);
1195 			ie->id_ci = 0;
1196 			free(ie->id_cr);
1197 			ie->id_cr = 0;
1198 			return -1;
1199 		}
1200 		memcpy(ie->id_ci + ISAKMP_ID_DATA_OFF, sockaddr_addrdata(src),
1201 		    sockaddr_addrlen(src));
1202 		memcpy(ie->id_cr + ISAKMP_ID_DATA_OFF, sockaddr_addrdata(dst),
1203 		    sockaddr_addrlen(dst));
1204 	}
1205 
1206 	/* Build the protection suite in our SA.  */
1207 	TAILQ_FOREACH(xf, &msg->payload[ISAKMP_PAYLOAD_TRANSFORM], link) {
1208 		/*
1209 		 * XXX We could check that the proposal each transform
1210 		 * belongs to is unique.
1211 		 */
1212 
1213 		if (sa_add_transform(sa, xf, exchange->initiator, &proto))
1214 			return -1;
1215 
1216 		/* XXX Check that the chosen transform matches an offer.  */
1217 
1218 		ipsec_decode_transform(msg, sa, proto, xf->p);
1219 	}
1220 
1221 	/* Now remove offers that we don't need anymore.  */
1222 	for (proto = TAILQ_FIRST(&sa->protos); proto; proto = next_proto) {
1223 		next_proto = TAILQ_NEXT(proto, link);
1224 		if (!proto->chosen)
1225 			proto_free(proto);
1226 	}
1227 
1228 	if (!check_policy(exchange, sa, msg->isakmp_sa)) {
1229 		message_drop(msg, ISAKMP_NOTIFY_NO_PROPOSAL_CHOSEN, 0, 1, 0);
1230 		log_print("initiator_recv_HASH_SA_NONCE: policy check failed");
1231 		return -1;
1232 	}
1233 
1234 	/* Mark the SA as handled.  */
1235 	sa_p->flags |= PL_MARK;
1236 
1237 	isa = sa->data;
1238 	if ((isa->group_desc &&
1239 	    (!ie->group || ie->group->id != isa->group_desc)) ||
1240 	    (!isa->group_desc && ie->group)) {
1241 		log_print("initiator_recv_HASH_SA_NONCE: disagreement on PFS");
1242 		return -1;
1243 	}
1244 	/* Copy out the initiator's nonce.  */
1245 	if (exchange_save_nonce(msg))
1246 		return -1;
1247 
1248 	/* Handle the optional KEY_EXCH payload.  */
1249 	if (kep && ipsec_save_g_x(msg))
1250 		return -1;
1251 
1252 	return 0;
1253 }
1254 
1255 static int
1256 initiator_send_HASH(struct message *msg)
1257 {
1258 	struct exchange *exchange = msg->exchange;
1259 	struct ipsec_exch *ie = exchange->data;
1260 	struct sa      *isakmp_sa = msg->isakmp_sa;
1261 	struct ipsec_sa *isa = isakmp_sa->data;
1262 	struct prf     *prf;
1263 	u_int8_t       *buf;
1264 	struct hash    *hash = hash_get(isa->hash);
1265 
1266 	/*
1267 	 * We want a HASH payload to start with.  XXX Share with
1268 	 * ike_main_mode.c?
1269 	 */
1270 	buf = malloc(ISAKMP_HASH_SZ + hash->hashsize);
1271 	if (!buf) {
1272 		log_error("initiator_send_HASH: malloc (%lu) failed",
1273 		    ISAKMP_HASH_SZ + (unsigned long)hash->hashsize);
1274 		return -1;
1275 	}
1276 	if (message_add_payload(msg, ISAKMP_PAYLOAD_HASH, buf,
1277 	    ISAKMP_HASH_SZ + hash->hashsize, 1)) {
1278 		free(buf);
1279 		return -1;
1280 	}
1281 	/* Allocate the prf and start calculating our HASH(3).  XXX Share?  */
1282 	LOG_DBG_BUF((LOG_NEGOTIATION, 90, "initiator_send_HASH: SKEYID_a",
1283 	    isa->skeyid_a, isa->skeyid_len));
1284 	prf = prf_alloc(isa->prf_type, isa->hash, isa->skeyid_a,
1285 	    isa->skeyid_len);
1286 	if (!prf)
1287 		return -1;
1288 	prf->Init(prf->prfctx);
1289 	prf->Update(prf->prfctx, (unsigned char *)"\0", 1);
1290 	LOG_DBG_BUF((LOG_NEGOTIATION, 90, "initiator_send_HASH: message_id",
1291 	    exchange->message_id, ISAKMP_HDR_MESSAGE_ID_LEN));
1292 	prf->Update(prf->prfctx, exchange->message_id,
1293 	    ISAKMP_HDR_MESSAGE_ID_LEN);
1294 	LOG_DBG_BUF((LOG_NEGOTIATION, 90, "initiator_send_HASH: NONCE_I_b",
1295 	    exchange->nonce_i, exchange->nonce_i_len));
1296 	prf->Update(prf->prfctx, exchange->nonce_i, exchange->nonce_i_len);
1297 	LOG_DBG_BUF((LOG_NEGOTIATION, 90, "initiator_send_HASH: NONCE_R_b",
1298 	    exchange->nonce_r, exchange->nonce_r_len));
1299 	prf->Update(prf->prfctx, exchange->nonce_r, exchange->nonce_r_len);
1300 	prf->Final(buf + ISAKMP_GEN_SZ, prf->prfctx);
1301 	prf_free(prf);
1302 	LOG_DBG_BUF((LOG_NEGOTIATION, 90, "initiator_send_HASH: HASH(3)",
1303 	    buf + ISAKMP_GEN_SZ, hash->hashsize));
1304 
1305 	if (ie->group)
1306 		message_register_post_send(msg, gen_g_xy);
1307 
1308 	message_register_post_send(msg, post_quick_mode);
1309 
1310 	return 0;
1311 }
1312 
1313 static void
1314 post_quick_mode(struct message *msg)
1315 {
1316 	struct sa      *isakmp_sa = msg->isakmp_sa;
1317 	struct ipsec_sa *isa = isakmp_sa->data;
1318 	struct exchange *exchange = msg->exchange;
1319 	struct ipsec_exch *ie = exchange->data;
1320 	struct prf     *prf;
1321 	struct sa      *sa;
1322 	struct proto   *proto;
1323 	struct ipsec_proto *iproto;
1324 	u_int8_t       *keymat;
1325 	int             i;
1326 
1327 	/*
1328 	 * Loop over all SA negotiations and do both an in- and an outgoing SA
1329 	 * per protocol.
1330          */
1331 	for (sa = TAILQ_FIRST(&exchange->sa_list); sa;
1332 	    sa = TAILQ_NEXT(sa, next)) {
1333 		for (proto = TAILQ_FIRST(&sa->protos); proto;
1334 		    proto = TAILQ_NEXT(proto, link)) {
1335 			if (proto->proto == IPSEC_PROTO_IPCOMP)
1336 				continue;
1337 
1338 			iproto = proto->data;
1339 
1340 			/*
1341 			 * There are two SAs for each SA negotiation,
1342 			 * incoming and outgoing.
1343 			 */
1344 			for (i = 0; i < 2; i++) {
1345 				prf = prf_alloc(isa->prf_type, isa->hash,
1346 				    isa->skeyid_d, isa->skeyid_len);
1347 				if (!prf) {
1348 					/* XXX What to do?  */
1349 					continue;
1350 				}
1351 				ie->keymat_len = ipsec_keymat_length(proto);
1352 
1353 				/*
1354 				 * We need to roundup the length of the key
1355 				 * material buffer to a multiple of the PRF's
1356 				 * blocksize as it is generated in chunks of
1357 				 * that blocksize.
1358 				 */
1359 				iproto->keymat[i]
1360 					= malloc(((ie->keymat_len + prf->blocksize - 1)
1361 					/ prf->blocksize) * prf->blocksize);
1362 				if (!iproto->keymat[i]) {
1363 					log_error("post_quick_mode: "
1364 					    "malloc (%lu) failed",
1365 					    (((unsigned long)ie->keymat_len +
1366 						prf->blocksize - 1) / prf->blocksize) *
1367 					    prf->blocksize);
1368 					/* XXX What more to do?  */
1369 					free(prf);
1370 					continue;
1371 				}
1372 				for (keymat = iproto->keymat[i];
1373 				keymat < iproto->keymat[i] + ie->keymat_len;
1374 				    keymat += prf->blocksize) {
1375 					prf->Init(prf->prfctx);
1376 
1377 					if (keymat != iproto->keymat[i]) {
1378 						/*
1379 						 * Hash in last round's
1380 						 * KEYMAT.
1381 						 */
1382 						LOG_DBG_BUF((LOG_NEGOTIATION,
1383 						    90, "post_quick_mode: "
1384 						    "last KEYMAT",
1385 						    keymat - prf->blocksize,
1386 						    prf->blocksize));
1387 						prf->Update(prf->prfctx,
1388 						    keymat - prf->blocksize,
1389 						    prf->blocksize);
1390 					}
1391 					/* If PFS is used hash in g^xy.  */
1392 					if (ie->g_xy) {
1393 						LOG_DBG_BUF((LOG_NEGOTIATION,
1394 						    90, "post_quick_mode: "
1395 						    "g^xy", ie->g_xy,
1396 						    ie->g_x_len));
1397 						prf->Update(prf->prfctx,
1398 						    ie->g_xy, ie->g_x_len);
1399 					}
1400 					LOG_DBG((LOG_NEGOTIATION, 90,
1401 					    "post_quick_mode: "
1402 					    "suite %d proto %d", proto->no,
1403 					    proto->proto));
1404 					prf->Update(prf->prfctx, &proto->proto,
1405 					    1);
1406 					LOG_DBG_BUF((LOG_NEGOTIATION, 90,
1407 					    "post_quick_mode: SPI",
1408 					    proto->spi[i], proto->spi_sz[i]));
1409 					prf->Update(prf->prfctx,
1410 					    proto->spi[i], proto->spi_sz[i]);
1411 					LOG_DBG_BUF((LOG_NEGOTIATION, 90,
1412 					    "post_quick_mode: Ni_b",
1413 					    exchange->nonce_i,
1414 					    exchange->nonce_i_len));
1415 					prf->Update(prf->prfctx,
1416 					    exchange->nonce_i,
1417 					    exchange->nonce_i_len);
1418 					LOG_DBG_BUF((LOG_NEGOTIATION, 90,
1419 					    "post_quick_mode: Nr_b",
1420 					    exchange->nonce_r,
1421 					    exchange->nonce_r_len));
1422 					prf->Update(prf->prfctx,
1423 					    exchange->nonce_r,
1424 					    exchange->nonce_r_len);
1425 					prf->Final(keymat, prf->prfctx);
1426 				}
1427 				prf_free(prf);
1428 				LOG_DBG_BUF((LOG_NEGOTIATION, 90,
1429 				    "post_quick_mode: KEYMAT",
1430 				    iproto->keymat[i], ie->keymat_len));
1431 			}
1432 		}
1433 	}
1434 
1435 	log_verbose("isakmpd: quick mode done%s: %s",
1436 	    (exchange->initiator == 0) ? " (as responder)" : "",
1437 	    !msg->isakmp_sa || !msg->isakmp_sa->transport ? "<no transport>"
1438 	    : msg->isakmp_sa->transport->vtbl->decode_ids
1439 	    (msg->isakmp_sa->transport));
1440 }
1441 
1442 /*
1443  * Accept a set of transforms offered by the initiator and chose one we can
1444  * handle.
1445  * XXX Describe in more detail.
1446  */
1447 static int
1448 responder_recv_HASH_SA_NONCE(struct message *msg)
1449 {
1450 	struct payload *hashp, *kep, *idp;
1451 	struct sa      *sa;
1452 	struct sa      *isakmp_sa = msg->isakmp_sa;
1453 	struct ipsec_sa *isa = isakmp_sa->data;
1454 	struct exchange *exchange = msg->exchange;
1455 	struct ipsec_exch *ie = exchange->data;
1456 	struct prf     *prf;
1457 	u_int8_t       *hash, *my_hash = 0;
1458 	size_t          hash_len;
1459 	u_int8_t       *pkt = msg->iov[0].iov_base;
1460 	u_int8_t        group_desc = 0;
1461 	int             retval = -1;
1462 	struct proto   *proto;
1463 	struct sockaddr *src, *dst;
1464 	char           *name;
1465 
1466 	hashp = payload_first(msg, ISAKMP_PAYLOAD_HASH);
1467 	hash = hashp->p;
1468 	hashp->flags |= PL_MARK;
1469 
1470 	/* The HASH payload should be the first one.  */
1471 	if (hash != pkt + ISAKMP_HDR_SZ) {
1472 		/* XXX Is there a better notification type?  */
1473 		message_drop(msg, ISAKMP_NOTIFY_PAYLOAD_MALFORMED, 0, 1, 0);
1474 		goto cleanup;
1475 	}
1476 	hash_len = GET_ISAKMP_GEN_LENGTH(hash);
1477 	my_hash = malloc(hash_len - ISAKMP_GEN_SZ);
1478 	if (!my_hash) {
1479 		log_error("responder_recv_HASH_SA_NONCE: malloc (%lu) failed",
1480 		    (unsigned long)hash_len - ISAKMP_GEN_SZ);
1481 		goto cleanup;
1482 	}
1483 	/*
1484 	 * Check the payload's integrity.
1485 	 * XXX Share with ipsec_fill_in_hash?
1486          */
1487 	LOG_DBG_BUF((LOG_NEGOTIATION, 90, "responder_recv_HASH_SA_NONCE: "
1488 	    "SKEYID_a", isa->skeyid_a, isa->skeyid_len));
1489 	prf = prf_alloc(isa->prf_type, isa->hash, isa->skeyid_a,
1490 	    isa->skeyid_len);
1491 	if (!prf)
1492 		goto cleanup;
1493 	prf->Init(prf->prfctx);
1494 	LOG_DBG_BUF((LOG_NEGOTIATION, 90,
1495 	    "responder_recv_HASH_SA_NONCE: message_id",
1496 	    exchange->message_id, ISAKMP_HDR_MESSAGE_ID_LEN));
1497 	prf->Update(prf->prfctx, exchange->message_id,
1498 	    ISAKMP_HDR_MESSAGE_ID_LEN);
1499 	LOG_DBG_BUF((LOG_NEGOTIATION, 90,
1500 	    "responder_recv_HASH_SA_NONCE: message after HASH",
1501 	    hash + hash_len,
1502 	    msg->iov[0].iov_len - ISAKMP_HDR_SZ - hash_len));
1503 	prf->Update(prf->prfctx, hash + hash_len,
1504 	    msg->iov[0].iov_len - ISAKMP_HDR_SZ - hash_len);
1505 	prf->Final(my_hash, prf->prfctx);
1506 	prf_free(prf);
1507 	LOG_DBG_BUF((LOG_NEGOTIATION, 90,
1508 	    "responder_recv_HASH_SA_NONCE: computed HASH(1)", my_hash,
1509 	    hash_len - ISAKMP_GEN_SZ));
1510 	if (memcmp(hash + ISAKMP_GEN_SZ, my_hash, hash_len - ISAKMP_GEN_SZ)
1511 	    != 0) {
1512 		message_drop(msg, ISAKMP_NOTIFY_INVALID_HASH_INFORMATION, 0,
1513 		    1, 0);
1514 		goto cleanup;
1515 	}
1516 	free(my_hash);
1517 	my_hash = 0;
1518 
1519 	/* Mark message as authenticated. */
1520 	msg->flags |= MSG_AUTHENTICATED;
1521 
1522 	kep = payload_first(msg, ISAKMP_PAYLOAD_KEY_EXCH);
1523 	if (kep)
1524 		ie->pfs = 1;
1525 
1526 	/* Drop message when it contains ID types we do not implement yet.  */
1527 	TAILQ_FOREACH(idp, &msg->payload[ISAKMP_PAYLOAD_ID], link) {
1528 		switch (GET_ISAKMP_ID_TYPE(idp->p)) {
1529 		case IPSEC_ID_IPV4_ADDR:
1530 		case IPSEC_ID_IPV4_ADDR_SUBNET:
1531 		case IPSEC_ID_IPV6_ADDR:
1532 		case IPSEC_ID_IPV6_ADDR_SUBNET:
1533 			break;
1534 
1535 		default:
1536 			message_drop(msg, ISAKMP_NOTIFY_INVALID_ID_INFORMATION,
1537 			    0, 1, 0);
1538 			goto cleanup;
1539 		}
1540 	}
1541 
1542 	/* Handle optional client ID payloads.  */
1543 	idp = payload_first(msg, ISAKMP_PAYLOAD_ID);
1544 	if (idp) {
1545 		/* If IDci is there, IDcr must be too.  */
1546 		if (!TAILQ_NEXT(idp, link)) {
1547 			/* XXX Is this a good notify type?  */
1548 			message_drop(msg, ISAKMP_NOTIFY_PAYLOAD_MALFORMED, 0,
1549 			    1, 0);
1550 			goto cleanup;
1551 		}
1552 		ie->id_ci_sz = GET_ISAKMP_GEN_LENGTH(idp->p);
1553 		ie->id_ci = malloc(ie->id_ci_sz);
1554 		if (!ie->id_ci) {
1555 			log_error("responder_recv_HASH_SA_NONCE: "
1556 			    "malloc (%lu) failed",
1557 			    (unsigned long)ie->id_ci_sz);
1558 			goto cleanup;
1559 		}
1560 		memcpy(ie->id_ci, idp->p, ie->id_ci_sz);
1561 		idp->flags |= PL_MARK;
1562 		LOG_DBG_BUF((LOG_NEGOTIATION, 90,
1563 		    "responder_recv_HASH_SA_NONCE: IDci",
1564 		    ie->id_ci + ISAKMP_GEN_SZ, ie->id_ci_sz - ISAKMP_GEN_SZ));
1565 
1566 		idp = TAILQ_NEXT(idp, link);
1567 		ie->id_cr_sz = GET_ISAKMP_GEN_LENGTH(idp->p);
1568 		ie->id_cr = malloc(ie->id_cr_sz);
1569 		if (!ie->id_cr) {
1570 			log_error("responder_recv_HASH_SA_NONCE: "
1571 			    "malloc (%lu) failed",
1572 			    (unsigned long)ie->id_cr_sz);
1573 			goto cleanup;
1574 		}
1575 		memcpy(ie->id_cr, idp->p, ie->id_cr_sz);
1576 		idp->flags |= PL_MARK;
1577 		LOG_DBG_BUF((LOG_NEGOTIATION, 90,
1578 		    "responder_recv_HASH_SA_NONCE: IDcr",
1579 		    ie->id_cr + ISAKMP_GEN_SZ, ie->id_cr_sz - ISAKMP_GEN_SZ));
1580 	} else {
1581 		/*
1582 		 * If client identifiers are not present in the exchange,
1583 		 * we fake them. RFC 2409 states:
1584 		 *    The identities of the SAs negotiated in Quick Mode are
1585 		 *    implicitly assumed to be the IP addresses of the ISAKMP
1586 		 *    peers, without any constraints on the protocol or port
1587 		 *    numbers allowed, unless client identifiers are specified
1588 		 *    in Quick Mode.
1589 		 *
1590 		 * -- Michael Paddon (mwp@aba.net.au)
1591 		 */
1592 
1593 		ie->flags = IPSEC_EXCH_FLAG_NO_ID;
1594 
1595 		/* Get initiator and responder addresses.  */
1596 		msg->transport->vtbl->get_src(msg->transport, &src);
1597 		msg->transport->vtbl->get_dst(msg->transport, &dst);
1598 		ie->id_ci_sz = ISAKMP_ID_DATA_OFF + sockaddr_addrlen(src);
1599 		ie->id_cr_sz = ISAKMP_ID_DATA_OFF + sockaddr_addrlen(dst);
1600 		ie->id_ci = calloc(ie->id_ci_sz, sizeof(char));
1601 		ie->id_cr = calloc(ie->id_cr_sz, sizeof(char));
1602 
1603 		if (!ie->id_ci || !ie->id_cr) {
1604 			log_error("responder_recv_HASH_SA_NONCE: "
1605 			    "calloc (%lu, %lu) failed",
1606 			    (unsigned long)ie->id_ci_sz,
1607 			    (unsigned long)sizeof(char));
1608 			goto cleanup;
1609 		}
1610 		if (src->sa_family != dst->sa_family) {
1611 			log_error("initiator_recv_HASH_SA_NONCE: "
1612 			    "sa_family mismatch");
1613 			goto cleanup;
1614 		}
1615 		switch (src->sa_family) {
1616 		case AF_INET:
1617 			SET_ISAKMP_ID_TYPE(ie->id_ci, IPSEC_ID_IPV4_ADDR);
1618 			SET_ISAKMP_ID_TYPE(ie->id_cr, IPSEC_ID_IPV4_ADDR);
1619 			break;
1620 
1621 		case AF_INET6:
1622 			SET_ISAKMP_ID_TYPE(ie->id_ci, IPSEC_ID_IPV6_ADDR);
1623 			SET_ISAKMP_ID_TYPE(ie->id_cr, IPSEC_ID_IPV6_ADDR);
1624 			break;
1625 
1626 		default:
1627 			log_error("initiator_recv_HASH_SA_NONCE: "
1628 			    "unknown sa_family %d", src->sa_family);
1629 			goto cleanup;
1630 		}
1631 
1632 		memcpy(ie->id_cr + ISAKMP_ID_DATA_OFF, sockaddr_addrdata(src),
1633 		    sockaddr_addrlen(src));
1634 		memcpy(ie->id_ci + ISAKMP_ID_DATA_OFF, sockaddr_addrdata(dst),
1635 		    sockaddr_addrlen(dst));
1636 	}
1637 
1638 	if (message_negotiate_sa(msg, check_policy))
1639 		goto cleanup;
1640 
1641 	for (sa = TAILQ_FIRST(&exchange->sa_list); sa;
1642 	    sa = TAILQ_NEXT(sa, next)) {
1643 		for (proto = TAILQ_FIRST(&sa->protos); proto;
1644 		    proto = TAILQ_NEXT(proto, link)) {
1645 			/*
1646 			 * XXX we need to have some attributes per proto, not
1647 			 * all per SA.
1648 			 */
1649 			ipsec_decode_transform(msg, sa, proto,
1650 			    proto->chosen->p);
1651 			if (proto->proto == IPSEC_PROTO_IPSEC_AH &&
1652 			    !((struct ipsec_proto *)proto->data)->auth) {
1653 				log_print("responder_recv_HASH_SA_NONCE: "
1654 				    "AH proposed without an algorithm "
1655 				    "attribute");
1656 				message_drop(msg,
1657 				    ISAKMP_NOTIFY_NO_PROPOSAL_CHOSEN, 0, 1, 0);
1658 				goto next_sa;
1659 			}
1660 		}
1661 
1662 		isa = sa->data;
1663 
1664 		/*
1665 		 * The group description is mandatory if we got a KEY_EXCH
1666 		 * payload.
1667 		 */
1668 		if (kep) {
1669 			if (!isa->group_desc) {
1670 				log_print("responder_recv_HASH_SA_NONCE: "
1671 				    "KEY_EXCH payload without a group "
1672 				    "desc. attribute");
1673 				message_drop(msg,
1674 				    ISAKMP_NOTIFY_NO_PROPOSAL_CHOSEN, 0, 1, 0);
1675 				continue;
1676 			}
1677 			/* Also, all SAs must have equal groups.  */
1678 			if (!group_desc)
1679 				group_desc = isa->group_desc;
1680 			else if (group_desc != isa->group_desc) {
1681 				log_print("responder_recv_HASH_SA_NONCE: "
1682 				  "differing group descriptions in one QM");
1683 				message_drop(msg,
1684 				    ISAKMP_NOTIFY_NO_PROPOSAL_CHOSEN, 0, 1, 0);
1685 				continue;
1686 			}
1687 		}
1688 		/* At least one SA was accepted.  */
1689 		retval = 0;
1690 
1691 next_sa:
1692 		;	/* XXX gcc3 wants this. */
1693 	}
1694 
1695 	if (kep) {
1696 		ie->group = group_get(group_desc);
1697 		if (!ie->group) {
1698 			/*
1699 			 * XXX If the error was due to an out-of-range group
1700 			 * description we should notify our peer, but this
1701 			 * should probably be done by the attribute
1702 			 * validation.  Is it?
1703 			 */
1704 			goto cleanup;
1705 		}
1706 	}
1707 	/* Copy out the initiator's nonce.  */
1708 	if (exchange_save_nonce(msg))
1709 		goto cleanup;
1710 
1711 	/* Handle the optional KEY_EXCH payload.  */
1712 	if (kep && ipsec_save_g_x(msg))
1713 		goto cleanup;
1714 
1715 	/*
1716 	 * Try to find and set the connection name on the exchange.
1717          */
1718 
1719 	/*
1720 	 * Check for accepted identities as well as lookup the connection
1721 	 * name and set it on the exchange.
1722 	 *
1723 	 * When not using policies make sure the peer proposes sane IDs.
1724 	 * Otherwise this is done by KeyNote.
1725          */
1726 	name = connection_passive_lookup_by_ids(ie->id_ci, ie->id_cr);
1727 	if (name) {
1728 		exchange->name = strdup(name);
1729 		if (!exchange->name) {
1730 			log_error("responder_recv_HASH_SA_NONCE: "
1731 			    "strdup (\"%s\") failed", name);
1732 			goto cleanup;
1733 		}
1734 	} else if (
1735 	    ignore_policy ||
1736 	    strncmp("yes", conf_get_str("General", "Use-Keynote"), 3)) {
1737 		log_print("responder_recv_HASH_SA_NONCE: peer proposed "
1738 		    "invalid phase 2 IDs: %s",
1739 		    (exchange->doi->decode_ids("initiator id %s, responder"
1740 		    " id %s", ie->id_ci, ie->id_ci_sz, ie->id_cr,
1741 		    ie->id_cr_sz, 1)));
1742 		message_drop(msg, ISAKMP_NOTIFY_INVALID_ID_INFORMATION, 0, 1,
1743 		    0);
1744 		goto cleanup;
1745 	}
1746 
1747 	return retval;
1748 
1749 cleanup:
1750 	/* Remove all potential protocols that have been added to the SAs.  */
1751 	for (sa = TAILQ_FIRST(&exchange->sa_list); sa;
1752 	    sa = TAILQ_NEXT(sa, next))
1753 		while ((proto = TAILQ_FIRST(&sa->protos)) != 0)
1754 			proto_free(proto);
1755 	free(my_hash);
1756 	free(ie->id_ci);
1757 	ie->id_ci = 0;
1758 	free(ie->id_cr);
1759 	ie->id_cr = 0;
1760 	return -1;
1761 }
1762 
1763 /* Reply with the transform we chose.  */
1764 static int
1765 responder_send_HASH_SA_NONCE(struct message *msg)
1766 {
1767 	struct exchange *exchange = msg->exchange;
1768 	struct ipsec_exch *ie = exchange->data;
1769 	struct sa      *isakmp_sa = msg->isakmp_sa;
1770 	struct ipsec_sa *isa = isakmp_sa->data;
1771 	struct prf     *prf;
1772 	struct hash    *hash = hash_get(isa->hash);
1773 	size_t          nonce_sz = exchange->nonce_i_len;
1774 	u_int8_t       *buf;
1775 	int             initiator = exchange->initiator;
1776 	char            header[80];
1777 	u_int32_t       i;
1778 	u_int8_t       *id;
1779 	size_t          sz;
1780 
1781 	/*
1782 	 * We want a HASH payload to start with.  XXX Share with
1783 	 * ike_main_mode.c?
1784 	 */
1785 	buf = malloc(ISAKMP_HASH_SZ + hash->hashsize);
1786 	if (!buf) {
1787 		log_error("responder_send_HASH_SA_NONCE: malloc (%lu) failed",
1788 			  ISAKMP_HASH_SZ + (unsigned long)hash->hashsize);
1789 		return -1;
1790 	}
1791 	if (message_add_payload(msg, ISAKMP_PAYLOAD_HASH, buf,
1792 	    ISAKMP_HASH_SZ + hash->hashsize, 1)) {
1793 		free(buf);
1794 		return -1;
1795 	}
1796 	/* Add the SA payload(s) with the transform(s) that was/were chosen. */
1797 	if (message_add_sa_payload(msg))
1798 		return -1;
1799 
1800 	/* Generate a nonce, and add it to the message.  */
1801 	if (exchange_gen_nonce(msg, nonce_sz))
1802 		return -1;
1803 
1804 	/* Generate optional KEY_EXCH payload.  This is known as PFS.  */
1805 	if (ie->group && ipsec_gen_g_x(msg))
1806 		return -1;
1807 
1808 	/*
1809 	 * If the initiator client ID's were acceptable, just mirror them
1810 	 * back.
1811 	 */
1812 	if (!(ie->flags & IPSEC_EXCH_FLAG_NO_ID)) {
1813 		sz = ie->id_ci_sz;
1814 		id = malloc(sz);
1815 		if (!id) {
1816 			log_error("responder_send_HASH_SA_NONCE: "
1817 			    "malloc (%lu) failed", (unsigned long)sz);
1818 			return -1;
1819 		}
1820 		memcpy(id, ie->id_ci, sz);
1821 		LOG_DBG_BUF((LOG_NEGOTIATION, 90,
1822 		    "responder_send_HASH_SA_NONCE: IDic", id, sz));
1823 		if (message_add_payload(msg, ISAKMP_PAYLOAD_ID, id, sz, 1)) {
1824 			free(id);
1825 			return -1;
1826 		}
1827 		sz = ie->id_cr_sz;
1828 		id = malloc(sz);
1829 		if (!id) {
1830 			log_error("responder_send_HASH_SA_NONCE: "
1831 			    "malloc (%lu) failed", (unsigned long)sz);
1832 			return -1;
1833 		}
1834 		memcpy(id, ie->id_cr, sz);
1835 		LOG_DBG_BUF((LOG_NEGOTIATION, 90,
1836 		    "responder_send_HASH_SA_NONCE: IDrc", id, sz));
1837 		if (message_add_payload(msg, ISAKMP_PAYLOAD_ID, id, sz, 1)) {
1838 			free(id);
1839 			return -1;
1840 		}
1841 	}
1842 	/* Allocate the prf and start calculating our HASH(2).  XXX Share?  */
1843 	LOG_DBG((LOG_NEGOTIATION, 90, "responder_recv_HASH: "
1844 	    "isakmp_sa %p isa %p", isakmp_sa, isa));
1845 	LOG_DBG_BUF((LOG_NEGOTIATION, 90, "responder_send_HASH_SA_NONCE: "
1846 	    "SKEYID_a", isa->skeyid_a, isa->skeyid_len));
1847 	prf = prf_alloc(isa->prf_type, hash->type, isa->skeyid_a,
1848 	    isa->skeyid_len);
1849 	if (!prf)
1850 		return -1;
1851 	prf->Init(prf->prfctx);
1852 	LOG_DBG_BUF((LOG_NEGOTIATION, 90,
1853 	    "responder_send_HASH_SA_NONCE: message_id",
1854 	    exchange->message_id, ISAKMP_HDR_MESSAGE_ID_LEN));
1855 	prf->Update(prf->prfctx, exchange->message_id,
1856 	    ISAKMP_HDR_MESSAGE_ID_LEN);
1857 	LOG_DBG_BUF((LOG_NEGOTIATION, 90, "responder_send_HASH_SA_NONCE: "
1858 	    "NONCE_I_b", exchange->nonce_i, exchange->nonce_i_len));
1859 	prf->Update(prf->prfctx, exchange->nonce_i, exchange->nonce_i_len);
1860 
1861 	/* Loop over all payloads after HASH(2).  */
1862 	for (i = 2; i < msg->iovlen; i++) {
1863 		/* XXX Misleading payload type printouts.  */
1864 		snprintf(header, sizeof header,
1865 		   "responder_send_HASH_SA_NONCE: payload %d after HASH(2)",
1866 			 i - 1);
1867 		LOG_DBG_BUF((LOG_NEGOTIATION, 90, header, msg->iov[i].iov_base,
1868 		    msg->iov[i].iov_len));
1869 		prf->Update(prf->prfctx, msg->iov[i].iov_base,
1870 		    msg->iov[i].iov_len);
1871 	}
1872 	prf->Final(buf + ISAKMP_HASH_DATA_OFF, prf->prfctx);
1873 	prf_free(prf);
1874 	snprintf(header, sizeof header, "responder_send_HASH_SA_NONCE: "
1875 	    "HASH_%c", initiator ? 'I' : 'R');
1876 	LOG_DBG_BUF((LOG_NEGOTIATION, 80, header, buf + ISAKMP_HASH_DATA_OFF,
1877 	    hash->hashsize));
1878 
1879 	if (ie->group)
1880 		message_register_post_send(msg, gen_g_xy);
1881 
1882 	return 0;
1883 }
1884 
1885 static void
1886 gen_g_xy(struct message *msg)
1887 {
1888 	struct exchange *exchange = msg->exchange;
1889 	struct ipsec_exch *ie = exchange->data;
1890 
1891 	/* Compute Diffie-Hellman shared value.  */
1892 	ie->g_xy = malloc(ie->g_x_len);
1893 	if (!ie->g_xy) {
1894 		log_error("gen_g_xy: malloc (%lu) failed",
1895 		    (unsigned long)ie->g_x_len);
1896 		return;
1897 	}
1898 	if (dh_create_shared(ie->group, ie->g_xy,
1899 	    exchange->initiator ? ie->g_xr : ie->g_xi)) {
1900 		log_print("gen_g_xy: dh_create_shared failed");
1901 		return;
1902 	}
1903 	LOG_DBG_BUF((LOG_NEGOTIATION, 80, "gen_g_xy: g^xy", ie->g_xy,
1904 	    ie->g_x_len));
1905 }
1906 
1907 static int
1908 responder_recv_HASH(struct message *msg)
1909 {
1910 	struct exchange *exchange = msg->exchange;
1911 	struct sa      *isakmp_sa = msg->isakmp_sa;
1912 	struct ipsec_sa *isa = isakmp_sa->data;
1913 	struct prf     *prf;
1914 	u_int8_t       *hash, *my_hash = 0;
1915 	size_t          hash_len;
1916 	struct payload *hashp;
1917 
1918 	/* Find HASH(3) and create our own hash, just as big.  */
1919 	hashp = payload_first(msg, ISAKMP_PAYLOAD_HASH);
1920 	hash = hashp->p;
1921 	hashp->flags |= PL_MARK;
1922 	hash_len = GET_ISAKMP_GEN_LENGTH(hash);
1923 	my_hash = malloc(hash_len - ISAKMP_GEN_SZ);
1924 	if (!my_hash) {
1925 		log_error("responder_recv_HASH: malloc (%lu) failed",
1926 			  (unsigned long)hash_len - ISAKMP_GEN_SZ);
1927 		goto cleanup;
1928 	}
1929 	/* Allocate the prf and start calculating our HASH(3).  XXX Share?  */
1930 	LOG_DBG((LOG_NEGOTIATION, 90, "responder_recv_HASH: "
1931 	    "isakmp_sa %p isa %p", isakmp_sa, isa));
1932 	LOG_DBG_BUF((LOG_NEGOTIATION, 90, "responder_recv_HASH: SKEYID_a",
1933 	    isa->skeyid_a, isa->skeyid_len));
1934 	prf = prf_alloc(isa->prf_type, isa->hash, isa->skeyid_a,
1935 	    isa->skeyid_len);
1936 	if (!prf)
1937 		goto cleanup;
1938 	prf->Init(prf->prfctx);
1939 	prf->Update(prf->prfctx, (unsigned char *)"\0", 1);
1940 	LOG_DBG_BUF((LOG_NEGOTIATION, 90, "responder_recv_HASH: message_id",
1941 	    exchange->message_id, ISAKMP_HDR_MESSAGE_ID_LEN));
1942 	prf->Update(prf->prfctx, exchange->message_id,
1943 	    ISAKMP_HDR_MESSAGE_ID_LEN);
1944 	LOG_DBG_BUF((LOG_NEGOTIATION, 90, "responder_recv_HASH: NONCE_I_b",
1945 	    exchange->nonce_i, exchange->nonce_i_len));
1946 	prf->Update(prf->prfctx, exchange->nonce_i, exchange->nonce_i_len);
1947 	LOG_DBG_BUF((LOG_NEGOTIATION, 90, "responder_recv_HASH: NONCE_R_b",
1948 	    exchange->nonce_r, exchange->nonce_r_len));
1949 	prf->Update(prf->prfctx, exchange->nonce_r, exchange->nonce_r_len);
1950 	prf->Final(my_hash, prf->prfctx);
1951 	prf_free(prf);
1952 	LOG_DBG_BUF((LOG_NEGOTIATION, 90,
1953 	    "responder_recv_HASH: computed HASH(3)", my_hash,
1954 	    hash_len - ISAKMP_GEN_SZ));
1955 	if (memcmp(hash + ISAKMP_GEN_SZ, my_hash, hash_len - ISAKMP_GEN_SZ)
1956 	    != 0) {
1957 		message_drop(msg, ISAKMP_NOTIFY_INVALID_HASH_INFORMATION, 0,
1958 		    1, 0);
1959 		goto cleanup;
1960 	}
1961 	free(my_hash);
1962 
1963 	/* Mark message as authenticated. */
1964 	msg->flags |= MSG_AUTHENTICATED;
1965 
1966 	post_quick_mode(msg);
1967 
1968 	return 0;
1969 
1970 cleanup:
1971 	free(my_hash);
1972 	return -1;
1973 }
1974