xref: /openbsd/sbin/isakmpd/ike_phase_1.c (revision fc61954a)
1 /* $OpenBSD: ike_phase_1.c,v 1.76 2015/12/10 17:27:00 mmcc Exp $	 */
2 /* $EOM: ike_phase_1.c,v 1.31 2000/12/11 23:47:56 niklas Exp $	 */
3 
4 /*
5  * Copyright (c) 1999, 2000 Niklas Hallqvist.  All rights reserved.
6  * Copyright (c) 1999, 2000 Angelos D. Keromytis.  All rights reserved.
7  * Copyright (c) 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 <sys/types.h>
35 #include <netinet/in.h>
36 #include <arpa/inet.h>
37 #include <stdlib.h>
38 #include <string.h>
39 
40 #include "attribute.h"
41 #include "conf.h"
42 #include "constants.h"
43 #include "crypto.h"
44 #include "dh.h"
45 #include "doi.h"
46 #include "dpd.h"
47 #include "exchange.h"
48 #include "hash.h"
49 #include "ike_auth.h"
50 #include "ike_phase_1.h"
51 #include "ipsec.h"
52 #include "ipsec_doi.h"
53 #include "isakmp.h"
54 #include "log.h"
55 #include "message.h"
56 #include "nat_traversal.h"
57 #include "prf.h"
58 #include "sa.h"
59 #include "transport.h"
60 #include "util.h"
61 #include "vendor.h"
62 
63 static int      attribute_unacceptable(u_int16_t, u_int8_t *, u_int16_t,
64 		    void *);
65 static int	ike_phase_1_validate_prop(struct exchange *, struct sa *,
66 		    struct sa *);
67 
68 /* Offer a set of transforms to the responder in the MSG message.  */
69 int
70 ike_phase_1_initiator_send_SA(struct message *msg)
71 {
72 	struct exchange *exchange = msg->exchange;
73 	struct ipsec_exch *ie = exchange->data;
74 	u_int8_t       *proposal = 0, *sa_buf = 0, *saved_nextp, *attr;
75 	u_int8_t      **transform = 0;
76 	size_t          transforms_len = 0, proposal_len, sa_len;
77 	size_t         *transform_len = 0;
78 	struct conf_list *conf, *life_conf;
79 	struct conf_list_node *xf, *life;
80 	int             value, update_nextp;
81 	size_t          i;
82 	struct payload *p;
83 	struct proto   *proto;
84 	struct proto_attr *pa;
85 	int             group_desc = -1, new_group_desc;
86 
87 	/* Get the list of transforms.  */
88 	conf = conf_get_list(exchange->policy, "Transforms");
89 	if (!conf)
90 		return -1;
91 
92 	transform = calloc(conf->cnt, sizeof *transform);
93 	if (!transform) {
94 		log_error("ike_phase_1_initiator_send_SA: calloc (%lu, %lu) "
95 		    "failed", (u_long)conf->cnt, (u_long)sizeof *transform);
96 		goto bail_out;
97 	}
98 	transform_len = calloc(conf->cnt, sizeof *transform_len);
99 	if (!transform_len) {
100 		log_error("ike_phase_1_initiator_send_SA: calloc (%lu, %lu) "
101 		    "failed", (u_long)conf->cnt,
102 		    (u_long)sizeof *transform_len);
103 		goto bail_out;
104 	}
105 	for (xf = TAILQ_FIRST(&conf->fields), i = 0; i < conf->cnt;
106 	    i++, xf = TAILQ_NEXT(xf, link)) {
107 		/* XXX The sizing needs to be dynamic.  */
108 		transform[i] = malloc(ISAKMP_TRANSFORM_SA_ATTRS_OFF +
109 		    16 * ISAKMP_ATTR_VALUE_OFF);
110 		if (!transform[i]) {
111 			log_error("ike_phase_1_initiator_send_SA: malloc (%d) "
112 			    "failed", ISAKMP_TRANSFORM_SA_ATTRS_OFF +
113 			    16 * ISAKMP_ATTR_VALUE_OFF);
114 			goto bail_out;
115 		}
116 		SET_ISAKMP_TRANSFORM_NO(transform[i], i);
117 		SET_ISAKMP_TRANSFORM_ID(transform[i], IPSEC_TRANSFORM_KEY_IKE);
118 		SET_ISAKMP_TRANSFORM_RESERVED(transform[i], 0);
119 
120 		attr = transform[i] + ISAKMP_TRANSFORM_SA_ATTRS_OFF;
121 
122 		if (attribute_set_constant(xf->field, "ENCRYPTION_ALGORITHM",
123 		    ike_encrypt_cst, IKE_ATTR_ENCRYPTION_ALGORITHM, &attr))
124 			goto bail_out;
125 
126 		if (attribute_set_constant(xf->field, "HASH_ALGORITHM",
127 		    ike_hash_cst, IKE_ATTR_HASH_ALGORITHM, &attr))
128 			goto bail_out;
129 
130 		if (attribute_set_constant(xf->field, "AUTHENTICATION_METHOD",
131 		    ike_auth_cst, IKE_ATTR_AUTHENTICATION_METHOD, &attr))
132 			goto bail_out;
133 
134 		if (attribute_set_constant(xf->field, "GROUP_DESCRIPTION",
135 		    ike_group_desc_cst, IKE_ATTR_GROUP_DESCRIPTION, &attr)) {
136 			/*
137 			 * If no group description exists, try looking for
138 			 * a user-defined one.
139 			 */
140 			if (attribute_set_constant(xf->field, "GROUP_TYPE",
141 			    ike_group_cst, IKE_ATTR_GROUP_TYPE, &attr))
142 				goto bail_out;
143 
144 #if 0
145 			if (attribute_set_bignum(xf->field, "GROUP_PRIME",
146 			    IKE_ATTR_GROUP_PRIME, &attr))
147 				goto bail_out;
148 
149 			if (attribute_set_bignum(xf->field,
150 			    "GROUP_GENERATOR_2", IKE_ATTR_GROUP_GENERATOR_2,
151 			    &attr))
152 				goto bail_out;
153 
154 			if (attribute_set_bignum(xf->field,
155 			    "GROUP_GENERATOR_2", IKE_ATTR_GROUP_GENERATOR_2,
156 			    &attr))
157 				goto bail_out;
158 
159 			if (attribute_set_bignum(xf->field, "GROUP_CURVE_A",
160 			    IKE_ATTR_GROUP_CURVE_A, &attr))
161 				goto bail_out;
162 
163 			if (attribute_set_bignum(xf->field, "GROUP_CURVE_B",
164 			    IKE_ATTR_GROUP_CURVE_B, &attr))
165 				goto bail_out;
166 #endif
167 		}
168 		/*
169 		 * Life durations are special, we should be able to specify
170 		 * several, one per type.
171 		 */
172 		life_conf = conf_get_list(xf->field, "Life");
173 		if (life_conf) {
174 			for (life = TAILQ_FIRST(&life_conf->fields); life;
175 			    life = TAILQ_NEXT(life, link)) {
176 				attribute_set_constant(life->field,
177 				    "LIFE_TYPE", ike_duration_cst,
178 				    IKE_ATTR_LIFE_TYPE, &attr);
179 
180 				/*
181 				 * XXX Deals with 16 and 32 bit lifetimes
182 				 * only
183 				 */
184 				value = conf_get_num(life->field,
185 				    "LIFE_DURATION", 0);
186 				if (value) {
187 					if (value <= 0xffff)
188 						attr = attribute_set_basic(
189 						    attr,
190 						    IKE_ATTR_LIFE_DURATION,
191 						    value);
192 					else {
193 						value = htonl(value);
194 						attr = attribute_set_var(attr,
195 						    IKE_ATTR_LIFE_DURATION,
196 						    (u_int8_t *)&value,
197 						    sizeof value);
198 					}
199 				}
200 			}
201 			conf_free_list(life_conf);
202 		}
203 		attribute_set_constant(xf->field, "PRF", ike_prf_cst,
204 		    IKE_ATTR_PRF, &attr);
205 
206 		value = conf_get_num(xf->field, "KEY_LENGTH", 0);
207 		if (value)
208 			attr = attribute_set_basic(attr, IKE_ATTR_KEY_LENGTH,
209 			    value);
210 
211 		value = conf_get_num(xf->field, "FIELD_SIZE", 0);
212 		if (value)
213 			attr = attribute_set_basic(attr, IKE_ATTR_FIELD_SIZE,
214 			    value);
215 
216 		value = conf_get_num(xf->field, "GROUP_ORDER", 0);
217 		if (value)
218 			attr = attribute_set_basic(attr, IKE_ATTR_GROUP_ORDER,
219 			    value);
220 
221 		/* Record the real transform size.  */
222 		transforms_len += transform_len[i] = attr - transform[i];
223 
224 		/* XXX I don't like exchange-specific stuff in here.  */
225 		if (exchange->type == ISAKMP_EXCH_AGGRESSIVE) {
226 			/*
227 			 * Make sure that if a group description is specified,
228 			 * it is specified for all transforms equally.
229 			 */
230 			attr = (u_int8_t *)conf_get_str(xf->field,
231 			    "GROUP_DESCRIPTION");
232 			new_group_desc =
233 			    attr ? constant_value(ike_group_desc_cst,
234 				(char *)attr) : 0;
235 			if (group_desc == -1)
236 				group_desc = new_group_desc;
237 			else if (group_desc != new_group_desc) {
238 				log_print("ike_phase_1_initiator_send_SA: "
239 				    "differing group descriptions in a "
240 				    "proposal");
241 				goto bail_out;
242 			}
243 		}
244 		/*
245 		 * We need to check that we actually support our
246 		 * configuration.
247 		 */
248 		if (attribute_map(transform[i] + ISAKMP_TRANSFORM_SA_ATTRS_OFF,
249 		    transform_len[i] - ISAKMP_TRANSFORM_SA_ATTRS_OFF,
250 		    exchange->doi->is_attribute_incompatible, msg)) {
251 			log_print("ike_phase_1_initiator_send_SA: "
252 			    "section [%s] has unsupported attribute(s)",
253 			    xf->field);
254 			goto bail_out;
255 		}
256 	}
257 
258 	/* XXX I don't like exchange-specific stuff in here.  */
259 	if (exchange->type == ISAKMP_EXCH_AGGRESSIVE)
260 		ie->group = group_get(group_desc);
261 
262 	proposal_len = ISAKMP_PROP_SPI_OFF;
263 	proposal = malloc(proposal_len);
264 	if (!proposal) {
265 		log_error("ike_phase_1_initiator_send_SA: malloc (%lu) failed",
266 		    (unsigned long)proposal_len);
267 		goto bail_out;
268 	}
269 	SET_ISAKMP_PROP_NO(proposal, 1);
270 	SET_ISAKMP_PROP_PROTO(proposal, ISAKMP_PROTO_ISAKMP);
271 	SET_ISAKMP_PROP_SPI_SZ(proposal, 0);
272 	SET_ISAKMP_PROP_NTRANSFORMS(proposal, conf->cnt);
273 
274 	/* XXX I would like to see this factored out.  */
275 	proto = calloc(1, sizeof *proto);
276 	if (!proto) {
277 		log_error("ike_phase_1_initiator_send_SA: "
278 		    "calloc (1, %lu) failed", (unsigned long)sizeof *proto);
279 		goto bail_out;
280 	}
281 	proto->no = 1;
282 	proto->proto = ISAKMP_PROTO_ISAKMP;
283 	proto->sa = TAILQ_FIRST(&exchange->sa_list);
284 	proto->xf_cnt = conf->cnt;
285 	TAILQ_INIT(&proto->xfs);
286 	for (i = 0; i < proto->xf_cnt; i++) {
287 		pa = calloc(1, sizeof *pa);
288 		if (!pa)
289 			goto bail_out;
290 		pa->len = transform_len[i];
291 		pa->attrs = malloc(pa->len);
292 		if (!pa->attrs) {
293 			free(pa);
294 			goto bail_out;
295 		}
296 		memcpy(pa->attrs, transform[i], pa->len);
297 		TAILQ_INSERT_TAIL(&proto->xfs, pa, next);
298 	}
299 	TAILQ_INSERT_TAIL(&TAILQ_FIRST(&exchange->sa_list)->protos, proto,
300 	    link);
301 
302 	sa_len = ISAKMP_SA_SIT_OFF + IPSEC_SIT_SIT_LEN;
303 	sa_buf = malloc(sa_len);
304 	if (!sa_buf) {
305 		log_error("ike_phase_1_initiator_send_SA: malloc (%lu) failed",
306 		    (unsigned long)sa_len);
307 		goto bail_out;
308 	}
309 	SET_ISAKMP_SA_DOI(sa_buf, IPSEC_DOI_IPSEC);
310 	SET_IPSEC_SIT_SIT(sa_buf + ISAKMP_SA_SIT_OFF, IPSEC_SIT_IDENTITY_ONLY);
311 
312 	/*
313 	 * Add the payloads.  As this is a SA, we need to recompute the
314 	 * lengths of the payloads containing others.
315 	 */
316 	if (message_add_payload(msg, ISAKMP_PAYLOAD_SA, sa_buf, sa_len, 1))
317 		goto bail_out;
318 	SET_ISAKMP_GEN_LENGTH(sa_buf,
319 	    sa_len + proposal_len + transforms_len);
320 	sa_buf = 0;
321 
322 	saved_nextp = msg->nextp;
323 	if (message_add_payload(msg, ISAKMP_PAYLOAD_PROPOSAL, proposal,
324 	    proposal_len, 0))
325 		goto bail_out;
326 	SET_ISAKMP_GEN_LENGTH(proposal, proposal_len + transforms_len);
327 	proposal = 0;
328 
329 	update_nextp = 0;
330 	for (i = 0; i < conf->cnt; i++) {
331 		if (message_add_payload(msg, ISAKMP_PAYLOAD_TRANSFORM,
332 		    transform[i], transform_len[i], update_nextp))
333 			goto bail_out;
334 		update_nextp = 1;
335 		transform[i] = 0;
336 	}
337 	msg->nextp = saved_nextp;
338 
339 	/* Save SA payload body in ie->sa_i_b, length ie->sa_i_b_len.  */
340 	ie->sa_i_b_len = sa_len + proposal_len + transforms_len -
341 	    ISAKMP_GEN_SZ;
342 	ie->sa_i_b = malloc(ie->sa_i_b_len);
343 	if (!ie->sa_i_b) {
344 		log_error("ike_phase_1_initiator_send_SA: malloc (%lu) failed",
345 		    (unsigned long)ie->sa_i_b_len);
346 		goto bail_out;
347 	}
348 	memcpy(ie->sa_i_b,
349 	    payload_first(msg, ISAKMP_PAYLOAD_SA)->p + ISAKMP_GEN_SZ,
350 	    sa_len - ISAKMP_GEN_SZ);
351 	memcpy(ie->sa_i_b + sa_len - ISAKMP_GEN_SZ,
352 	    payload_first(msg, ISAKMP_PAYLOAD_PROPOSAL)->p, proposal_len);
353 	transforms_len = 0;
354 	for (i = 0, p = TAILQ_FIRST(&msg->payload[ISAKMP_PAYLOAD_TRANSFORM]);
355 	    i < conf->cnt; i++, p = TAILQ_NEXT(p, link)) {
356 		memcpy(ie->sa_i_b + sa_len + proposal_len + transforms_len -
357 		    ISAKMP_GEN_SZ, p->p, transform_len[i]);
358 		transforms_len += transform_len[i];
359 	}
360 
361 	/* Advertise OpenBSD isakmpd. */
362 	if (add_vendor_openbsd(msg))
363 		goto bail_out;
364 
365 	/* Advertise NAT-T capability.  */
366 	if (nat_t_add_vendor_payloads(msg))
367 		goto bail_out;
368 
369 	/* Advertise DPD capability.  */
370 	if (dpd_add_vendor_payload(msg))
371 		goto bail_out;
372 
373 	conf_free_list(conf);
374 	free(transform);
375 	free(transform_len);
376 	return 0;
377 
378 bail_out:
379 	free(sa_buf);
380 	free(proposal);
381 	if (transform) {
382 		for (i = 0; i < conf->cnt; i++)
383 			free(transform[i]);
384 		free(transform);
385 	}
386 	free(transform_len);
387 	conf_free_list(conf);
388 	return -1;
389 }
390 
391 /* Figure out what transform the responder chose.  */
392 int
393 ike_phase_1_initiator_recv_SA(struct message *msg)
394 {
395 	struct exchange *exchange = msg->exchange;
396 	struct sa      *sa = TAILQ_FIRST(&exchange->sa_list);
397 	struct ipsec_exch *ie = exchange->data;
398 	struct ipsec_sa *isa = sa->data;
399 	struct payload *sa_p = payload_first(msg, ISAKMP_PAYLOAD_SA);
400 	struct payload *prop = payload_first(msg, ISAKMP_PAYLOAD_PROPOSAL);
401 	struct payload *xf = payload_first(msg, ISAKMP_PAYLOAD_TRANSFORM);
402 
403 	/*
404 	 * IKE requires that only one SA with only one proposal exists and
405 	 * since we are getting an answer on our transform offer, only one
406 	 * transform.
407 	 */
408 	if (TAILQ_NEXT(sa_p, link) || TAILQ_NEXT(prop, link) ||
409 	    TAILQ_NEXT(xf, link)) {
410 		log_print("ike_phase_1_initiator_recv_SA: "
411 		    "multiple SA, proposal or transform payloads in phase 1");
412 		/* XXX Is there a better notification type?  */
413 		message_drop(msg, ISAKMP_NOTIFY_PAYLOAD_MALFORMED, 0, 1, 0);
414 		return -1;
415 	}
416 	/* Check that the chosen transform matches an offer.  */
417 	if (message_negotiate_sa(msg, ike_phase_1_validate_prop) ||
418 	    !TAILQ_FIRST(&sa->protos))
419 		return -1;
420 
421 	ipsec_decode_transform(msg, sa, TAILQ_FIRST(&sa->protos), xf->p);
422 
423 	/* XXX I don't like exchange-specific stuff in here.  */
424 	if (exchange->type != ISAKMP_EXCH_AGGRESSIVE)
425 		ie->group = group_get(isa->group_desc);
426 
427 	/* Mark the SA as handled.  */
428 	sa_p->flags |= PL_MARK;
429 
430 	return 0;
431 }
432 
433 /* Send our public DH value and a nonce to the responder.  */
434 int
435 ike_phase_1_initiator_send_KE_NONCE(struct message *msg)
436 {
437 	struct ipsec_exch *ie = msg->exchange->data;
438 
439 	ie->g_x_len = dh_getlen(ie->group);
440 
441 	/* XXX I want a better way to specify the nonce's size.  */
442 	return ike_phase_1_send_KE_NONCE(msg, 16);
443 }
444 
445 /* Accept responder's public DH value and nonce.  */
446 int
447 ike_phase_1_initiator_recv_KE_NONCE(struct message *msg)
448 {
449 	if (ike_phase_1_recv_KE_NONCE(msg))
450 		return -1;
451 
452 	return ike_phase_1_post_exchange_KE_NONCE(msg);
453 }
454 
455 /*
456  * Accept a set of transforms offered by the initiator and chose one we can
457  * handle.
458  */
459 int
460 ike_phase_1_responder_recv_SA(struct message *msg)
461 {
462 	struct exchange *exchange = msg->exchange;
463 	struct sa      *sa = TAILQ_FIRST(&exchange->sa_list);
464 	struct ipsec_sa *isa = sa->data;
465 	struct payload *sa_p = payload_first(msg, ISAKMP_PAYLOAD_SA);
466 	struct payload *prop = payload_first(msg, ISAKMP_PAYLOAD_PROPOSAL);
467 	struct ipsec_exch *ie = exchange->data;
468 
469 	/* Mark the SA as handled.  */
470 	sa_p->flags |= PL_MARK;
471 
472 	/* IKE requires that only one SA with only one proposal exists.  */
473 	if (TAILQ_NEXT(sa_p, link) || TAILQ_NEXT(prop, link)) {
474 		log_print("ike_phase_1_responder_recv_SA: "
475 		    "multiple SA or proposal payloads in phase 1");
476 		/* XXX Is there a better notification type?  */
477 		message_drop(msg, ISAKMP_NOTIFY_PAYLOAD_MALFORMED, 0, 1, 0);
478 		return -1;
479 	}
480 	/* Chose a transform from the SA.  */
481 	if (message_negotiate_sa(msg, ike_phase_1_validate_prop) ||
482 	    !TAILQ_FIRST(&sa->protos))
483 		return -1;
484 
485 	/* XXX Move into message_negotiate_sa?  */
486 	ipsec_decode_transform(msg, sa, TAILQ_FIRST(&sa->protos),
487 	    TAILQ_FIRST(&sa->protos)->chosen->p);
488 
489 	ie->group = group_get(isa->group_desc);
490 
491 	/*
492 	 * Check that the mandatory attributes: encryption, hash,
493 	 * authentication method and Diffie-Hellman group description, has
494 	 * been supplied.
495 	 */
496 	if (!exchange->crypto || !ie->hash || !ie->ike_auth || !ie->group) {
497 		message_drop(msg, ISAKMP_NOTIFY_PAYLOAD_MALFORMED, 0, 1, 0);
498 		return -1;
499 	}
500 	/* Save the body for later hash computation.  */
501 	ie->sa_i_b_len = GET_ISAKMP_GEN_LENGTH(sa_p->p) - ISAKMP_GEN_SZ;
502 	ie->sa_i_b = malloc(ie->sa_i_b_len);
503 	if (!ie->sa_i_b) {
504 		/* XXX How to notify peer?  */
505 		log_error("ike_phase_1_responder_recv_SA: malloc (%lu) failed",
506 		    (unsigned long)ie->sa_i_b_len);
507 		return -1;
508 	}
509 	memcpy(ie->sa_i_b, sa_p->p + ISAKMP_GEN_SZ, ie->sa_i_b_len);
510 	return 0;
511 }
512 
513 /* Reply with the transform we chose.  */
514 int
515 ike_phase_1_responder_send_SA(struct message *msg)
516 {
517 	/* Add the SA payload with the transform that was chosen.  */
518 	if (message_add_sa_payload(msg))
519 		return -1;
520 
521 	/* Advertise OpenBSD isakmpd. */
522 	if (add_vendor_openbsd(msg))
523 		return -1;
524 
525 	/* Advertise NAT-T capability.  */
526 	if (nat_t_add_vendor_payloads(msg))
527 		return -1;
528 
529 	/* Advertise DPD capability.  */
530 	if (dpd_add_vendor_payload(msg))
531 		return -1;
532 	return 0;
533 }
534 
535 /* Send our public DH value and a nonce to the peer.  */
536 int
537 ike_phase_1_send_KE_NONCE(struct message *msg, size_t nonce_sz)
538 {
539 	/* Public DH key.  */
540 	if (ipsec_gen_g_x(msg)) {
541 		/* XXX How to log and notify peer?  */
542 		return -1;
543 	}
544 	/* Generate a nonce, and add it to the message.  */
545 	if (exchange_gen_nonce(msg, nonce_sz)) {
546 		/* XXX Log?  */
547 		return -1;
548 	}
549 	/* Are there any CERTREQs to send? */
550 	if (exchange_add_certreqs(msg)) {
551 		/* XXX Log? */
552 		return -1;
553 	}
554 	/* Try to add certificates which are acceptable for the CERTREQs */
555 	if (exchange_add_certs(msg)) {
556 		/* XXX Log? */
557 		return -1;
558 	}
559 	/* If this exchange uses NAT-Traversal, add NAT-D payloads now.  */
560 	if (msg->exchange->flags & EXCHANGE_FLAG_NAT_T_CAP_PEER)
561 		if (nat_t_exchange_add_nat_d(msg)) {
562 			/* XXX Log? */
563 			return -1;
564 		}
565 	return 0;
566 }
567 
568 /* Receive our peer's public DH value and nonce.  */
569 int
570 ike_phase_1_recv_KE_NONCE(struct message *msg)
571 {
572 	/* Copy out the initiator's DH public value.  */
573 	if (ipsec_save_g_x(msg)) {
574 		/* XXX How to log and notify peer?  */
575 		return -1;
576 	}
577 	/* Copy out the initiator's nonce.  */
578 	if (exchange_save_nonce(msg)) {
579 		/* XXX How to log and notify peer?  */
580 		return -1;
581 	}
582 	/* Copy out the initiator's cert requests.  */
583 	if (exchange_save_certreq(msg)) {
584 		/* XXX How to log and notify peer?  */
585 		return -1;
586 	}
587 	/* MainMode: Check for NAT-D payloads and contents.  */
588 	if (msg->exchange->type == ISAKMP_EXCH_ID_PROT &&
589 	    msg->exchange->flags & EXCHANGE_FLAG_NAT_T_CAP_PEER)
590 		(void)nat_t_exchange_check_nat_d(msg);
591 	return 0;
592 }
593 
594 /*
595  * Compute DH values and key material.  This is done in a post-send function
596  * as that means we can do parallel work in both the initiator and responder
597  * thus speeding up exchanges.
598  */
599 int
600 ike_phase_1_post_exchange_KE_NONCE(struct message *msg)
601 {
602 	struct exchange *exchange = msg->exchange;
603 	struct ipsec_exch *ie = exchange->data;
604 	struct prf     *prf;
605 	struct hash    *hash = ie->hash;
606 	enum cryptoerr  err;
607 
608 	/* Compute Diffie-Hellman shared value.  */
609 	ie->g_xy = malloc(ie->g_x_len);
610 	if (!ie->g_xy) {
611 		/* XXX How to notify peer?  */
612 		log_error("ike_phase_1_post_exchange_KE_NONCE: "
613 		    "malloc (%lu) failed", (unsigned long)ie->g_x_len);
614 		return -1;
615 	}
616 	if (dh_create_shared(ie->group, ie->g_xy,
617 	    exchange->initiator ? ie->g_xr : ie->g_xi)) {
618 		log_print("ike_phase_1_post_exchange_KE_NONCE: "
619 		    "dh_create_shared failed");
620 		return -1;
621 	}
622 	LOG_DBG_BUF((LOG_NEGOTIATION, 80,
623 	    "ike_phase_1_post_exchange_KE_NONCE: g^xy", ie->g_xy,
624 	    ie->g_x_len));
625 
626 	/* Compute the SKEYID depending on the authentication method.  */
627 	ie->skeyid = ie->ike_auth->gen_skeyid(exchange, &ie->skeyid_len);
628 	if (!ie->skeyid) {
629 		/* XXX Log and teardown?  */
630 		return -1;
631 	}
632 	LOG_DBG_BUF((LOG_NEGOTIATION, 80,
633 	    "ike_phase_1_post_exchange_KE_NONCE: SKEYID", ie->skeyid,
634 	    ie->skeyid_len));
635 
636 	/* SKEYID_d.  */
637 	ie->skeyid_d = malloc(ie->skeyid_len);
638 	if (!ie->skeyid_d) {
639 		/* XXX How to notify peer?  */
640 		log_error("ike_phase_1_post_exchange_KE_NONCE: "
641 		    "malloc (%lu) failed", (unsigned long)ie->skeyid_len);
642 		return -1;
643 	}
644 	prf = prf_alloc(ie->prf_type, hash->type, ie->skeyid, ie->skeyid_len);
645 	if (!prf) {
646 		/* XXX Log and teardown?  */
647 		return -1;
648 	}
649 	prf->Init(prf->prfctx);
650 	prf->Update(prf->prfctx, ie->g_xy, ie->g_x_len);
651 	prf->Update(prf->prfctx, exchange->cookies, ISAKMP_HDR_COOKIES_LEN);
652 	prf->Update(prf->prfctx, (unsigned char *)"\0", 1);
653 	prf->Final(ie->skeyid_d, prf->prfctx);
654 	LOG_DBG_BUF((LOG_NEGOTIATION, 80,
655 	    "ike_phase_1_post_exchange_KE_NONCE: SKEYID_d", ie->skeyid_d,
656 	    ie->skeyid_len));
657 
658 	/* SKEYID_a.  */
659 	ie->skeyid_a = malloc(ie->skeyid_len);
660 	if (!ie->skeyid_a) {
661 		log_error("ike_phase_1_post_exchange_KE_NONCE: "
662 		    "malloc (%lu) failed", (unsigned long)ie->skeyid_len);
663 		prf_free(prf);
664 		return -1;
665 	}
666 	prf->Init(prf->prfctx);
667 	prf->Update(prf->prfctx, ie->skeyid_d, ie->skeyid_len);
668 	prf->Update(prf->prfctx, ie->g_xy, ie->g_x_len);
669 	prf->Update(prf->prfctx, exchange->cookies, ISAKMP_HDR_COOKIES_LEN);
670 	prf->Update(prf->prfctx, (unsigned char *)"\1", 1);
671 	prf->Final(ie->skeyid_a, prf->prfctx);
672 	LOG_DBG_BUF((LOG_NEGOTIATION, 80,
673 	    "ike_phase_1_post_exchange_KE_NONCE: SKEYID_a", ie->skeyid_a,
674 	    ie->skeyid_len));
675 
676 	/* SKEYID_e.  */
677 	ie->skeyid_e = malloc(ie->skeyid_len);
678 	if (!ie->skeyid_e) {
679 		/* XXX How to notify peer?  */
680 		log_error("ike_phase_1_post_exchange_KE_NONCE: "
681 		    "malloc (%lu) failed", (unsigned long)ie->skeyid_len);
682 		prf_free(prf);
683 		return -1;
684 	}
685 	prf->Init(prf->prfctx);
686 	prf->Update(prf->prfctx, ie->skeyid_a, ie->skeyid_len);
687 	prf->Update(prf->prfctx, ie->g_xy, ie->g_x_len);
688 	prf->Update(prf->prfctx, exchange->cookies, ISAKMP_HDR_COOKIES_LEN);
689 	prf->Update(prf->prfctx, (unsigned char *)"\2", 1);
690 	prf->Final(ie->skeyid_e, prf->prfctx);
691 	prf_free(prf);
692 	LOG_DBG_BUF((LOG_NEGOTIATION, 80,
693 	    "ike_phase_1_post_exchange_KE_NONCE: SKEYID_e", ie->skeyid_e,
694 	    ie->skeyid_len));
695 
696 	/* Key length determination.  */
697 	if (!exchange->key_length)
698 		exchange->key_length = exchange->crypto->keymax;
699 
700 	/* Derive a longer key from skeyid_e */
701 	if (ie->skeyid_len < exchange->key_length) {
702 		u_int16_t       len, keylen;
703 		u_int8_t       *key, *p;
704 
705 		prf = prf_alloc(ie->prf_type, hash->type, ie->skeyid_e,
706 		    ie->skeyid_len);
707 		if (!prf) {
708 			/* XXX - notify peer */
709 			return -1;
710 		}
711 		/* Make keylen a multiple of prf->blocksize */
712 		keylen = exchange->key_length;
713 		if (keylen % prf->blocksize)
714 			keylen += prf->blocksize - (keylen % prf->blocksize);
715 
716 		key = malloc(keylen);
717 		if (!key) {
718 			/* XXX - Notify peer.  */
719 			prf_free(prf);
720 			log_error("ike_phase_1_post_exchange_KE_NONCE: "
721 			    "malloc (%d) failed", keylen);
722 			return -1;
723 		}
724 		prf->Init(prf->prfctx);
725 		prf->Update(prf->prfctx, (unsigned char *)"\0", 1);
726 		prf->Final(key, prf->prfctx);
727 
728 		for (len = prf->blocksize, p = key; len < exchange->key_length;
729 		    len += prf->blocksize, p += prf->blocksize) {
730 			prf->Init(prf->prfctx);
731 			prf->Update(prf->prfctx, p, prf->blocksize);
732 			prf->Final(p + prf->blocksize, prf->prfctx);
733 		}
734 		prf_free(prf);
735 
736 		/* Setup our keystate using the derived encryption key.  */
737 		exchange->keystate = crypto_init(exchange->crypto, key,
738 		    exchange->key_length, &err);
739 
740 		free(key);
741 	} else
742 		/* Setup our keystate using the raw skeyid_e.  */
743 		exchange->keystate = crypto_init(exchange->crypto,
744 		    ie->skeyid_e, exchange->key_length, &err);
745 
746 	/* Special handling for DES weak keys.  */
747 	if (!exchange->keystate && err == EWEAKKEY &&
748 	    (exchange->key_length << 1) <= ie->skeyid_len) {
749 		log_print("ike_phase_1_post_exchange_KE_NONCE: "
750 		    "weak key, trying subseq. skeyid_e");
751 		exchange->keystate = crypto_init(exchange->crypto,
752 		    ie->skeyid_e + exchange->key_length,
753 		    exchange->key_length, &err);
754 	}
755 	if (!exchange->keystate) {
756 		log_print("ike_phase_1_post_exchange_KE_NONCE: "
757 		    "exchange->crypto->init () failed: %d", err);
758 
759 		/*
760 		 * XXX We really need to know if problems are of transient
761 		 * nature or fatal (like failed assertions etc.)
762 		 */
763 		return -1;
764 	}
765 	/* Setup IV.  XXX Only for CBC transforms, no?  */
766 	hash->Init(hash->ctx);
767 	hash->Update(hash->ctx, ie->g_xi, ie->g_x_len);
768 	hash->Update(hash->ctx, ie->g_xr, ie->g_x_len);
769 	hash->Final(hash->digest, hash->ctx);
770 	crypto_init_iv(exchange->keystate, hash->digest,
771 	    exchange->crypto->blocksize);
772 	return 0;
773 }
774 
775 int
776 ike_phase_1_responder_send_ID_AUTH(struct message *msg)
777 {
778 	if (ike_phase_1_send_ID(msg))
779 		return -1;
780 
781 	return ike_phase_1_send_AUTH(msg);
782 }
783 
784 int
785 ike_phase_1_send_ID(struct message *msg)
786 {
787 	struct exchange *exchange = msg->exchange;
788 	u_int8_t       *buf;
789 	char            header[80];
790 	ssize_t         sz;
791 	struct sockaddr *src;
792 	int             initiator = exchange->initiator;
793 	u_int8_t      **id;
794 	size_t         *id_len;
795 	char           *my_id = 0, *data;
796 	u_int8_t        id_type;
797 	sa_family_t	af = 0;
798 
799 	/* Choose the right fields to fill-in.  */
800 	id = initiator ? &exchange->id_i : &exchange->id_r;
801 	id_len = initiator ? &exchange->id_i_len : &exchange->id_r_len;
802 
803 	if (exchange->name)
804 		my_id = conf_get_str(exchange->name, "ID");
805 
806 	if (!my_id)
807 		my_id = conf_get_str("General", "Default-phase-1-ID");
808 
809 	msg->transport->vtbl->get_src(msg->transport, &src);
810 	sz = my_id ? ipsec_id_size(my_id, &id_type) : sockaddr_addrlen(src);
811 	if (sz == -1)
812 		return -1;
813 
814 	sz += ISAKMP_ID_DATA_OFF;
815 	buf = malloc(sz);
816 	if (!buf) {
817 		log_error("ike_phase_1_send_ID: malloc (%lu) failed",
818 			  (unsigned long)sz);
819 		return -1;
820 	}
821 	SET_IPSEC_ID_PROTO(buf + ISAKMP_ID_DOI_DATA_OFF, 0);
822 	SET_IPSEC_ID_PORT(buf + ISAKMP_ID_DOI_DATA_OFF, 0);
823 	if (my_id) {
824 		SET_ISAKMP_ID_TYPE(buf, id_type);
825 		switch (id_type) {
826 		case IPSEC_ID_IPV4_ADDR:
827 		case IPSEC_ID_IPV4_ADDR_SUBNET:
828 			af = AF_INET;
829 			break;
830 		case IPSEC_ID_IPV6_ADDR:
831 		case IPSEC_ID_IPV6_ADDR_SUBNET:
832 			af = AF_INET6;
833 			break;
834 		}
835 		switch (id_type) {
836 		case IPSEC_ID_IPV4_ADDR:
837 		case IPSEC_ID_IPV6_ADDR:
838 			data = conf_get_str(my_id, "Address");
839 			if (!data) {
840 				log_print("ike_phase_1_send_ID: section %s "
841 				    "has no \"Address\" tag", my_id);
842 				free(buf);
843 				return -1;
844 			}
845 			if (text2sockaddr(data, NULL, &src, af, 0)) {
846 				log_error("ike_phase_1_send_ID: "
847 				    "text2sockaddr() failed");
848 				free(buf);
849 				return -1;
850 			}
851 			memcpy(buf + ISAKMP_ID_DATA_OFF,
852 			    sockaddr_addrdata(src), sockaddr_addrlen(src));
853 			free(src);
854 			break;
855 
856 		case IPSEC_ID_IPV4_ADDR_SUBNET:
857 		case IPSEC_ID_IPV6_ADDR_SUBNET:
858 			/* Network */
859 			data = conf_get_str(my_id, "Network");
860 			if (!data) {
861 				log_print("ike_phase_1_send_ID: section %s "
862 				    "has no \"Network\" tag", my_id);
863 				free(buf);
864 				return -1;
865 			}
866 			if (text2sockaddr(data, NULL, &src, af, 0)) {
867 				log_error("ike_phase_1_send_ID: "
868 				    "text2sockaddr() failed");
869 				free(buf);
870 				return -1;
871 			}
872 			memcpy(buf + ISAKMP_ID_DATA_OFF,
873 			    sockaddr_addrdata(src), sockaddr_addrlen(src));
874 			free(src);
875 			/* Netmask */
876 			data = conf_get_str(my_id, "Netmask");
877 			if (!data) {
878 				log_print("ike_phase_1_send_ID: section %s "
879 				    "has no \"Netmask\" tag", my_id);
880 				free(buf);
881 				return -1;
882 			}
883 			if (text2sockaddr(data, NULL, &src, af, 1)) {
884 				log_error("ike_phase_1_send_ID: "
885 				    "text2sockaddr() failed");
886 				free(buf);
887 				return -1;
888 			}
889 			memcpy(buf + ISAKMP_ID_DATA_OFF +
890 			    sockaddr_addrlen(src), sockaddr_addrdata(src),
891 			    sockaddr_addrlen(src));
892 			free(src);
893 			break;
894 
895 		case IPSEC_ID_FQDN:
896 		case IPSEC_ID_USER_FQDN:
897 		case IPSEC_ID_KEY_ID:
898 			data = conf_get_str(my_id, "Name");
899 			if (!data) {
900 				log_print("ike_phase_1_send_ID: section %s "
901 				    "has no \"Name\" tag", my_id);
902 				free(buf);
903 				return -1;
904 			}
905 			memcpy(buf + ISAKMP_ID_DATA_OFF, data,
906 			    sz - ISAKMP_ID_DATA_OFF);
907 			break;
908 
909 		default:
910 			log_print("ike_phase_1_send_ID: "
911 			    "unsupported ID type %d", id_type);
912 			free(buf);
913 			return -1;
914 		}
915 	} else {
916 		switch (src->sa_family) {
917 		case AF_INET:
918 			SET_ISAKMP_ID_TYPE(buf, IPSEC_ID_IPV4_ADDR);
919 			break;
920 		case AF_INET6:
921 			SET_ISAKMP_ID_TYPE(buf, IPSEC_ID_IPV6_ADDR);
922 			break;
923 		}
924 		/* Already in network byteorder.  */
925 		memcpy(buf + ISAKMP_ID_DATA_OFF, sockaddr_addrdata(src),
926 		    sockaddr_addrlen(src));
927 	}
928 
929 	if (message_add_payload(msg, ISAKMP_PAYLOAD_ID, buf, sz, 1)) {
930 		free(buf);
931 		return -1;
932 	}
933 	*id_len = sz - ISAKMP_GEN_SZ;
934 	*id = malloc(*id_len);
935 	if (!*id) {
936 		log_error("ike_phase_1_send_ID: malloc (%lu) failed",
937 		    (unsigned long)*id_len);
938 		return -1;
939 	}
940 	memcpy(*id, buf + ISAKMP_GEN_SZ, *id_len);
941 	snprintf(header, sizeof header, "ike_phase_1_send_ID: %s",
942 	    constant_name(ipsec_id_cst, GET_ISAKMP_ID_TYPE(buf)));
943 	LOG_DBG_BUF((LOG_NEGOTIATION, 40, header, buf + ISAKMP_ID_DATA_OFF,
944 	    sz - ISAKMP_ID_DATA_OFF));
945 	return 0;
946 }
947 
948 int
949 ike_phase_1_send_AUTH(struct message *msg)
950 {
951 	struct exchange *exchange = msg->exchange;
952 	struct ipsec_exch *ie = exchange->data;
953 
954 	if (ie->ike_auth->encode_hash(msg)) {
955 		/* XXX Log? */
956 		return -1;
957 	}
958 	/*
959 	 * XXX Many people say the COMMIT flag is just junk, especially in
960 	 * Phase 1.
961 	 */
962 #ifdef notyet
963 	if ((exchange->flags & EXCHANGE_FLAG_COMMITTED) == 0)
964 		exchange->flags |= EXCHANGE_FLAG_I_COMMITTED;
965 #endif
966 
967 	return 0;
968 }
969 
970 /* Receive ID and HASH and check that the exchange has been consistent.  */
971 int
972 ike_phase_1_recv_ID_AUTH(struct message *msg)
973 {
974 	if (ike_phase_1_recv_ID(msg))
975 		return -1;
976 
977 	return ike_phase_1_recv_AUTH(msg);
978 }
979 
980 /* Receive ID.  */
981 int
982 ike_phase_1_recv_ID(struct message *msg)
983 {
984 	struct exchange *exchange = msg->exchange;
985 	struct payload *payload;
986 	char            header[80], *rs = 0, *rid = 0, *p;
987 	int             initiator = exchange->initiator;
988 	u_int8_t      **id, id_type;
989 	size_t         *id_len;
990 	ssize_t         sz;
991 	struct sockaddr *sa;
992 	sa_family_t	af = 0;
993 
994 	payload = payload_first(msg, ISAKMP_PAYLOAD_ID);
995 
996 	if (exchange->name)
997 		rs = conf_get_str(exchange->name, "Remote-ID");
998 
999 	if (rs) {
1000 		sz = ipsec_id_size(rs, &id_type);
1001 		if (sz == -1) {
1002 			log_print("ike_phase_1_recv_ID: could not handle "
1003 			    "specified Remote-ID [%s]", rs);
1004 			return -1;
1005 		}
1006 		rid = malloc(sz);
1007 		if (!rid) {
1008 			log_error("ike_phase_1_recv_ID: malloc (%lu) failed",
1009 			    (unsigned long)sz);
1010 			return -1;
1011 		}
1012 		switch (id_type) {
1013 		case IPSEC_ID_IPV4_ADDR:
1014 			af = AF_INET;
1015 			break;
1016 		case IPSEC_ID_IPV6_ADDR:
1017 			af = AF_INET6;
1018 			break;
1019 		}
1020 		switch (id_type) {
1021 		case IPSEC_ID_IPV4_ADDR:
1022 		case IPSEC_ID_IPV6_ADDR:
1023 			p = conf_get_str(rs, "Address");
1024 			if (!p) {
1025 				log_print("ike_phase_1_recv_ID: failed to get "
1026 				    "Address in Remote-ID section [%s]", rs);
1027 				free(rid);
1028 				return -1;
1029 			}
1030 			if (text2sockaddr(p, 0, &sa, af, 0) == -1) {
1031 				log_print("ike_phase_1_recv_ID: "
1032 				    "failed to parse address %s", p);
1033 				free(rid);
1034 				return -1;
1035 			}
1036 			if ((id_type == IPSEC_ID_IPV4_ADDR &&
1037 			    sa->sa_family != AF_INET) ||
1038 			    (id_type == IPSEC_ID_IPV6_ADDR &&
1039 			    sa->sa_family != AF_INET6)) {
1040 				log_print("ike_phase_1_recv_ID: "
1041 				    "address %s not of expected family", p);
1042 				free(rid);
1043 				free(sa);
1044 				return -1;
1045 			}
1046 			memcpy(rid, sockaddr_addrdata(sa),
1047 			    sockaddr_addrlen(sa));
1048 			free(sa);
1049 			break;
1050 
1051 		case IPSEC_ID_FQDN:
1052 		case IPSEC_ID_USER_FQDN:
1053 		case IPSEC_ID_KEY_ID:
1054 			p = conf_get_str(rs, "Name");
1055 			if (!p) {
1056 				log_print("ike_phase_1_recv_ID: failed to "
1057 				    "get Name in Remote-ID section [%s]", rs);
1058 				free(rid);
1059 				return -1;
1060 			}
1061 			memcpy(rid, p, sz);
1062 			break;
1063 
1064 		default:
1065 			log_print("ike_phase_1_recv_ID: "
1066 			    "unsupported ID type %d", id_type);
1067 			free(rid);
1068 			return -1;
1069 		}
1070 
1071 		/* Compare expected/desired and received remote ID */
1072 		if (memcmp(rid, payload->p + ISAKMP_ID_DATA_OFF, sz) != 0) {
1073 			free(rid);
1074 			log_print("ike_phase_1_recv_ID: "
1075 			    "received remote ID other than expected %s", p);
1076 			return -1;
1077 		}
1078 		free(rid);
1079 	}
1080 	/* Choose the right fields to fill in */
1081 	id = initiator ? &exchange->id_r : &exchange->id_i;
1082 	id_len = initiator ? &exchange->id_r_len : &exchange->id_i_len;
1083 
1084 	*id_len = GET_ISAKMP_GEN_LENGTH(payload->p) - ISAKMP_GEN_SZ;
1085 	*id = malloc(*id_len);
1086 	if (!*id) {
1087 		log_error("ike_phase_1_recv_ID: malloc (%lu) failed",
1088 		    (unsigned long)*id_len);
1089 		return -1;
1090 	}
1091 	memcpy(*id, payload->p + ISAKMP_GEN_SZ, *id_len);
1092 	snprintf(header, sizeof header, "ike_phase_1_recv_ID: %s",
1093 	    constant_name(ipsec_id_cst, GET_ISAKMP_ID_TYPE(payload->p)));
1094 	LOG_DBG_BUF((LOG_NEGOTIATION, 40, header,
1095 	    payload->p + ISAKMP_ID_DATA_OFF,
1096 	    *id_len + ISAKMP_GEN_SZ - ISAKMP_ID_DATA_OFF));
1097 	payload->flags |= PL_MARK;
1098 	return 0;
1099 }
1100 
1101 /* Receive HASH and check that the exchange has been consistent.  */
1102 int
1103 ike_phase_1_recv_AUTH(struct message *msg)
1104 {
1105 	struct exchange *exchange = msg->exchange;
1106 	struct ipsec_exch *ie = exchange->data;
1107 	struct prf     *prf;
1108 	struct hash    *hash = ie->hash;
1109 	char            header[80];
1110 	size_t          hashsize = hash->hashsize;
1111 	int             initiator = exchange->initiator;
1112 	u_int8_t      **hash_p, *id;
1113 	size_t          id_len;
1114 
1115 	/* Choose the right fields to fill in */
1116 	hash_p = initiator ? &ie->hash_r : &ie->hash_i;
1117 	id = initiator ? exchange->id_r : exchange->id_i;
1118 	id_len = initiator ? exchange->id_r_len : exchange->id_i_len;
1119 
1120 	/* The decoded hash will be in ie->hash_r or ie->hash_i */
1121 	if (ie->ike_auth->decode_hash(msg)) {
1122 		message_drop(msg, ISAKMP_NOTIFY_INVALID_ID_INFORMATION, 0, 1,
1123 		    0);
1124 		return -1;
1125 	}
1126 	/* Allocate the prf and start calculating his HASH.  */
1127 	prf = prf_alloc(ie->prf_type, hash->type, ie->skeyid, ie->skeyid_len);
1128 	if (!prf) {
1129 		/* XXX Log?  */
1130 		return -1;
1131 	}
1132 	prf->Init(prf->prfctx);
1133 	prf->Update(prf->prfctx, initiator ? ie->g_xr : ie->g_xi, ie->g_x_len);
1134 	prf->Update(prf->prfctx, initiator ? ie->g_xi : ie->g_xr, ie->g_x_len);
1135 	prf->Update(prf->prfctx, exchange->cookies +
1136 	    (initiator ? ISAKMP_HDR_RCOOKIE_OFF : ISAKMP_HDR_ICOOKIE_OFF),
1137 	    ISAKMP_HDR_ICOOKIE_LEN);
1138 	prf->Update(prf->prfctx, exchange->cookies +
1139 	    (initiator ? ISAKMP_HDR_ICOOKIE_OFF : ISAKMP_HDR_RCOOKIE_OFF),
1140 	    ISAKMP_HDR_ICOOKIE_LEN);
1141 	prf->Update(prf->prfctx, ie->sa_i_b, ie->sa_i_b_len);
1142 	prf->Update(prf->prfctx, id, id_len);
1143 	prf->Final(hash->digest, prf->prfctx);
1144 	prf_free(prf);
1145 	snprintf(header, sizeof header, "ike_phase_1_recv_AUTH: "
1146 	    "computed HASH_%c", initiator ? 'R' : 'I');
1147 	LOG_DBG_BUF((LOG_NEGOTIATION, 80, header, hash->digest, hashsize));
1148 
1149 	/* Check that the hash we got matches the one we computed.  */
1150 	if (memcmp(*hash_p, hash->digest, hashsize) != 0) {
1151 		/* XXX Log?  */
1152 		return -1;
1153 	}
1154 
1155 	/* Mark message as authenticated. */
1156 	msg->flags |= MSG_AUTHENTICATED;
1157 
1158 	return 0;
1159 }
1160 
1161 struct attr_node {
1162 	LIST_ENTRY(attr_node) link;
1163 	u_int16_t       type;
1164 };
1165 
1166 struct validation_state {
1167 	struct conf_list_node *xf;
1168 	LIST_HEAD(attr_head, attr_node) attrs;
1169 	char           *life;
1170 };
1171 
1172 /* Validate a proposal inside SA according to EXCHANGE's policy.  */
1173 static int
1174 ike_phase_1_validate_prop(struct exchange *exchange, struct sa *sa,
1175     struct sa *isakmp_sa)
1176 {
1177 	struct conf_list *conf, *tags;
1178 	struct conf_list_node *xf, *tag;
1179 	struct proto   *proto;
1180 	struct validation_state vs;
1181 	struct attr_node *node, *next_node;
1182 
1183 	/* Get the list of transforms.  */
1184 	conf = conf_get_list(exchange->policy, "Transforms");
1185 	if (!conf)
1186 		return 0;
1187 
1188 	for (xf = TAILQ_FIRST(&conf->fields); xf; xf = TAILQ_NEXT(xf, link)) {
1189 		for (proto = TAILQ_FIRST(&sa->protos); proto;
1190 		    proto = TAILQ_NEXT(proto, link)) {
1191 			/* Mark all attributes in our policy as unseen.  */
1192 			LIST_INIT(&vs.attrs);
1193 			vs.xf = xf;
1194 			vs.life = 0;
1195 			if (attribute_map(proto->chosen->p +
1196 			    ISAKMP_TRANSFORM_SA_ATTRS_OFF,
1197 			    GET_ISAKMP_GEN_LENGTH(proto->chosen->p) -
1198 			    ISAKMP_TRANSFORM_SA_ATTRS_OFF,
1199 			    attribute_unacceptable, &vs))
1200 				goto try_next;
1201 
1202 			/* Sweep over unseen tags in this section.  */
1203 			tags = conf_get_tag_list(xf->field);
1204 			if (tags) {
1205 				for (tag = TAILQ_FIRST(&tags->fields); tag;
1206 				    tag = TAILQ_NEXT(tag, link))
1207 					/*
1208 					 * XXX Should we care about attributes
1209 					 * we have, they do not provide?
1210 					 */
1211 					for (node = LIST_FIRST(&vs.attrs);
1212 					    node; node = next_node) {
1213 						next_node =
1214 						    LIST_NEXT(node, link);
1215 						if (node->type ==
1216 						    constant_value(ike_attr_cst,
1217 						    tag->field)) {
1218 							LIST_REMOVE(node, link);
1219 							free(node);
1220 						}
1221 					}
1222 				conf_free_list(tags);
1223 			}
1224 			/* Are there leftover tags in this section?  */
1225 			node = LIST_FIRST(&vs.attrs);
1226 			if (node)
1227 				goto try_next;
1228 		}
1229 
1230 		/* All protocols were OK, we succeeded.  */
1231 		LOG_DBG((LOG_NEGOTIATION, 20, "ike_phase_1_validate_prop: "
1232 		    "success"));
1233 		conf_free_list(conf);
1234 		free(vs.life);
1235 		return 1;
1236 
1237 try_next:
1238 		/* Are there leftover tags in this section?  */
1239 		node = LIST_FIRST(&vs.attrs);
1240 		while (node) {
1241 			LIST_REMOVE(node, link);
1242 			free(node);
1243 			node = LIST_FIRST(&vs.attrs);
1244 		}
1245 		free(vs.life);
1246 	}
1247 
1248 	LOG_DBG((LOG_NEGOTIATION, 20, "ike_phase_1_validate_prop: failure"));
1249 	conf_free_list(conf);
1250 	return 0;
1251 }
1252 
1253 /*
1254  * Look at the attribute of type TYPE, located at VALUE for LEN bytes forward.
1255  * The VVS argument holds a validation state kept across invocations.
1256  * If the attribute is unacceptable to use, return non-zero, otherwise zero.
1257  */
1258 static int
1259 attribute_unacceptable(u_int16_t type, u_int8_t *value, u_int16_t len,
1260     void *vvs)
1261 {
1262 	struct validation_state *vs = vvs;
1263 	struct conf_list *life_conf;
1264 	struct conf_list_node *xf = vs->xf, *life;
1265 	char           *tag = constant_lookup(ike_attr_cst, type);
1266 	char           *str;
1267 	struct constant_map *map;
1268 	struct attr_node *node;
1269 	int             rv, dur = 0;
1270 
1271 	if (!tag) {
1272 		log_print("attribute_unacceptable: "
1273 		    "attribute type %d not known", type);
1274 		return 1;
1275 	}
1276 	switch (type) {
1277 	case IKE_ATTR_ENCRYPTION_ALGORITHM:
1278 	case IKE_ATTR_HASH_ALGORITHM:
1279 	case IKE_ATTR_AUTHENTICATION_METHOD:
1280 	case IKE_ATTR_GROUP_DESCRIPTION:
1281 	case IKE_ATTR_GROUP_TYPE:
1282 	case IKE_ATTR_PRF:
1283 		str = conf_get_str(xf->field, tag);
1284 		if (!str) {
1285 			/* This attribute does not exist in this policy.  */
1286 			log_print("attribute_unacceptable: "
1287 			    "attr %s does not exist in %s", tag, xf->field);
1288 			return 1;
1289 		}
1290 		map = constant_link_lookup(ike_attr_cst, type);
1291 		if (!map)
1292 			return 1;
1293 
1294 		if ((constant_value(map, str) == decode_16(value)) ||
1295 		    (!strcmp(str, "ANY"))) {
1296 			/* Mark this attribute as seen.  */
1297 			node = malloc(sizeof *node);
1298 			if (!node) {
1299 				log_error("attribute_unacceptable: "
1300 				    "malloc (%lu) failed",
1301 				    (unsigned long)sizeof *node);
1302 				return 1;
1303 			}
1304 			node->type = type;
1305 			LIST_INSERT_HEAD(&vs->attrs, node, link);
1306 			return 0;
1307 		}
1308 		log_print("attribute_unacceptable: %s: got %s, expected %s",
1309 		    tag, constant_name(map, decode_16(value)), str);
1310 		return 1;
1311 
1312 	case IKE_ATTR_GROUP_PRIME:
1313 	case IKE_ATTR_GROUP_GENERATOR_1:
1314 	case IKE_ATTR_GROUP_GENERATOR_2:
1315 	case IKE_ATTR_GROUP_CURVE_A:
1316 	case IKE_ATTR_GROUP_CURVE_B:
1317 		/* XXX Bignums not handled yet.  */
1318 		log_print("attribute_unacceptable: "
1319 		    "bignum type %d not supported", type);
1320 		return 1;
1321 
1322 	case IKE_ATTR_LIFE_TYPE:
1323 	case IKE_ATTR_LIFE_DURATION:
1324 		life_conf = conf_get_list(xf->field, "Life");
1325 		if (life_conf &&
1326 		    !strcmp(conf_get_str(xf->field, "Life"), "ANY")) {
1327 			conf_free_list(life_conf);
1328 			return 0;
1329 		}
1330 
1331 		rv = 1;
1332 		if (!life_conf) {
1333 			/* Life attributes given, but not in our policy.  */
1334 			log_print("attribute_unacceptable: "
1335 			    "life attribute received, none in policy");
1336 			return 1;
1337 		}
1338 		/*
1339 		 * Each lifetime type must match, otherwise we turn the
1340 		 * proposal down. In order to do this we need to find the
1341 		 * specific section of our policy's "Life" list and match
1342 		 * its duration.
1343 		 */
1344 		switch (type) {
1345 		case IKE_ATTR_LIFE_TYPE:
1346 			for (life = TAILQ_FIRST(&life_conf->fields); life;
1347 			    life = TAILQ_NEXT(life, link)) {
1348 				str = conf_get_str(life->field, "LIFE_TYPE");
1349 				if (!str) {
1350 					log_print("attribute_unacceptable: "
1351 					    "section [%s] has no LIFE_TYPE",
1352 					    life->field);
1353 					continue;
1354 				}
1355 
1356 				/*
1357 				 * If this is the type we are looking at,
1358 				 * save a pointer to this section in vs->life.
1359 				 */
1360 				if (constant_value(ike_duration_cst, str) ==
1361 				    decode_16(value)) {
1362 					vs->life = strdup(life->field);
1363 					rv = 0;
1364 					goto bail_out;
1365 				}
1366 			}
1367 			log_print("attribute_unacceptable: "
1368 			    "unrecognized LIFE_TYPE %d", decode_16(value));
1369 			vs->life = 0;
1370 			break;
1371 
1372 		case IKE_ATTR_LIFE_DURATION:
1373 			if (!vs->life) {
1374 				log_print("attribute_unacceptable: "
1375 				    "LIFE_DURATION without LIFE_TYPE");
1376 				rv = 1;
1377 				goto bail_out;
1378 			}
1379 			str = conf_get_str(vs->life, "LIFE_DURATION");
1380 			if (str) {
1381 				if (!strcmp(str, "ANY"))
1382 					rv = 0;
1383 				else
1384 					dur = (len == 4) ? decode_32(value) :
1385 					    decode_16(value);
1386 					if ((rv = !conf_match_num(vs->life,
1387 					    "LIFE_DURATION", dur))) {
1388 						log_print(
1389 						    "attribute_unacceptable: "
1390 						    "LIFE_DURATION: got %d, "
1391 						    " expected %s", dur, str);
1392 					}
1393 			} else {
1394 				log_print("attribute_unacceptable: "
1395 				    "section [%s] has no LIFE_DURATION",
1396 				    vs->life);
1397 				rv = 1;
1398 			}
1399 
1400 			free(vs->life);
1401 			vs->life = 0;
1402 			break;
1403 		}
1404 
1405 bail_out:
1406 		conf_free_list(life_conf);
1407 		return rv;
1408 
1409 	case IKE_ATTR_KEY_LENGTH:
1410 	case IKE_ATTR_FIELD_SIZE:
1411 	case IKE_ATTR_GROUP_ORDER:
1412 		if (conf_match_num(xf->field, tag, decode_16(value))) {
1413 			/* Mark this attribute as seen.  */
1414 			node = malloc(sizeof *node);
1415 			if (!node) {
1416 				log_error("attribute_unacceptable: "
1417 				    "malloc (%lu) failed",
1418 				    (unsigned long)sizeof *node);
1419 				return 1;
1420 			}
1421 			node->type = type;
1422 			LIST_INSERT_HEAD(&vs->attrs, node, link);
1423 			return 0;
1424 		}
1425 		return 1;
1426 	default:
1427 		log_print("attribute_unacceptable: unexpected type %d",
1428 		    type);
1429 	}
1430 	return 1;
1431 }
1432