xref: /openbsd/sbin/isakmpd/message.c (revision a6445c1d)
1 /* $OpenBSD: message.c,v 1.127 2014/10/09 02:38:56 deraadt Exp $	 */
2 /* $EOM: message.c,v 1.156 2000/10/10 12:36:39 provos Exp $	 */
3 
4 /*
5  * Copyright (c) 1998, 1999, 2000, 2001 Niklas Hallqvist.  All rights reserved.
6  * Copyright (c) 1999 Angelos D. Keromytis.  All rights reserved.
7  * Copyright (c) 1999, 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 <sys/types.h>
35 #include <sys/socket.h>
36 #include <netinet/in.h>
37 #include <arpa/inet.h>
38 #include <stdlib.h>
39 #include <string.h>
40 
41 #include "attribute.h"
42 #include "cert.h"
43 #include "constants.h"
44 #include "crypto.h"
45 #include "doi.h"
46 #include "dpd.h"
47 #include "exchange.h"
48 #include "field.h"
49 #include "hash.h"
50 #include "ipsec.h"
51 #include "ipsec_num.h"
52 #include "isakmp.h"
53 #include "log.h"
54 #include "message.h"
55 #include "nat_traversal.h"
56 #include "prf.h"
57 #include "sa.h"
58 #include "timer.h"
59 #include "transport.h"
60 #include "util.h"
61 #include "vendor.h"
62 #include "virtual.h"
63 
64 /* A local set datatype, coincidentally fd_set suits our purpose fine.  */
65 typedef fd_set  set;
66 #define ISSET FD_ISSET
67 #define SET FD_SET
68 #define ZERO FD_ZERO
69 
70 static int      message_check_duplicate(struct message *);
71 static int      message_encrypt(struct message *);
72 static int	message_index_payload(struct message *, struct payload *,
73 		    u_int8_t ,u_int8_t *);
74 static int	message_parse_transform(struct message *, struct payload *,
75 		    u_int8_t, u_int8_t *);
76 static struct field *message_get_field(u_int8_t);
77 static int	message_validate_payload(struct message *, struct payload *,
78 		    u_int8_t);
79 static u_int16_t message_payload_sz(u_int8_t);
80 static int      message_validate_attribute(struct message *, struct payload *);
81 static int      message_validate_cert(struct message *, struct payload *);
82 static int      message_validate_cert_req(struct message *, struct payload *);
83 static int      message_validate_delete(struct message *, struct payload *);
84 static int      message_validate_hash(struct message *, struct payload *);
85 static int      message_validate_id(struct message *, struct payload *);
86 static int      message_validate_key_exch(struct message *, struct payload *);
87 static int      message_validate_nat_d(struct message *, struct payload *);
88 static int      message_validate_nat_oa(struct message *, struct payload *);
89 static int      message_validate_nonce(struct message *, struct payload *);
90 static int      message_validate_notify(struct message *, struct payload *);
91 static int      message_validate_proposal(struct message *, struct payload *);
92 static int      message_validate_sa(struct message *, struct payload *);
93 static int      message_validate_sig(struct message *, struct payload *);
94 static int      message_validate_transform(struct message *, struct payload *);
95 static int      message_validate_vendor(struct message *, struct payload *);
96 
97 static void     message_packet_log(struct message *);
98 
99 /*
100  * Fields used for checking monotonic increasing of proposal and transform
101  * numbers.
102  */
103 static u_int8_t *last_sa = 0;
104 static u_int32_t last_prop_no;
105 static u_int8_t *last_prop = 0;
106 static u_int32_t last_xf_no;
107 
108 /*
109  * Allocate a message structure bound to transport T, and with a first
110  * segment buffer sized SZ, copied from BUF if given.
111  */
112 struct message *
113 message_alloc(struct transport *t, u_int8_t *buf, size_t sz)
114 {
115 	struct message *msg;
116 	int             i;
117 
118 	/*
119 	 * We use calloc(3) because it zeroes the structure which we rely on in
120 	 * message_free when determining what sub-allocations to free.
121 	 */
122 	msg = (struct message *)calloc(1, sizeof *msg);
123 	if (!msg)
124 		return 0;
125 	msg->iov = calloc(1, sizeof *msg->iov);
126 	if (!msg->iov) {
127 		message_free(msg);
128 		return 0;
129 	}
130 	msg->iov[0].iov_len = sz;
131 	msg->iov[0].iov_base = malloc(sz);
132 	if (!msg->iov[0].iov_base) {
133 		message_free(msg);
134 		return 0;
135 	}
136 	msg->iovlen = 1;
137 	if (buf)
138 		memcpy(msg->iov[0].iov_base, buf, sz);
139 	msg->nextp = (u_int8_t *)msg->iov[0].iov_base +
140 	    ISAKMP_HDR_NEXT_PAYLOAD_OFF;
141 	msg->transport = t;
142 	transport_reference(t);
143 	msg->payload = (struct payload_head *)calloc(ISAKMP_PAYLOAD_MAX,
144 	    sizeof *msg->payload);
145 	if (!msg->payload) {
146 		message_free(msg);
147 		return 0;
148 	}
149 	for (i = 0; i < ISAKMP_PAYLOAD_MAX; i++)
150 		TAILQ_INIT(&msg->payload[i]);
151 	TAILQ_INIT(&msg->post_send);
152 	LOG_DBG((LOG_MESSAGE, 90, "message_alloc: allocated %p", msg));
153 	return msg;
154 }
155 
156 /*
157  * Allocate a message suitable for a reply to MSG.  Just allocate an empty
158  * ISAKMP header as the first segment.
159  */
160 struct message *
161 message_alloc_reply(struct message *msg)
162 {
163 	struct message *reply;
164 
165 	reply = message_alloc(msg->transport, 0, ISAKMP_HDR_SZ);
166 	reply->exchange = msg->exchange;
167 	reply->isakmp_sa = msg->isakmp_sa;
168 	reply->flags = msg->flags;
169 	if (msg->isakmp_sa)
170 		sa_reference(msg->isakmp_sa);
171 	return reply;
172 }
173 
174 /* Free up all resources used by the MSG message.  */
175 void
176 message_free(struct message *msg)
177 {
178 	u_int32_t       i;
179 	struct payload *payload;
180 	struct post_send *node;
181 
182 	LOG_DBG((LOG_MESSAGE, 20, "message_free: freeing %p", msg));
183 	if (!msg)
184 		return;
185 	if (msg->iov) {
186 		if (msg->orig && msg->orig != (u_int8_t *)msg->iov[0].iov_base)
187 			free(msg->orig);
188 		for (i = 0; i < msg->iovlen; i++)
189 			free(msg->iov[i].iov_base);
190 		free(msg->iov);
191 	}
192 	if (msg->retrans)
193 		timer_remove_event(msg->retrans);
194 	if (msg->payload) {
195 		for (i = 0; i < ISAKMP_PAYLOAD_MAX; i++)
196 			while ((payload = TAILQ_FIRST(&msg->payload[i]))) {
197 				TAILQ_REMOVE(&msg->payload[i], payload, link);
198 				free(payload);
199 			}
200 		free(msg->payload);
201 	}
202 	while ((node = TAILQ_FIRST(&msg->post_send)))
203 		TAILQ_REMOVE(&msg->post_send, node, link);
204 	if (msg->transport) {
205 		/* If we are on the send queue, remove us from there.  */
206 		if (msg->flags & MSG_IN_TRANSIT)
207 			TAILQ_REMOVE(msg->transport->vtbl->get_queue(msg),
208 			    msg, link);
209 
210 		transport_release(msg->transport);
211 	}
212 
213 	if (msg->isakmp_sa)
214 		sa_release(msg->isakmp_sa);
215 
216 	free(msg);
217 }
218 
219 /*
220  * Generic ISAKMP parser.
221  * MSG is the ISAKMP message to be parsed.  NEXT is the type of the first
222  * payload to be parsed, and it's pointed to by BUF.  ACCEPTED_PAYLOADS
223  * tells what payloads are accepted and FUNC is a pointer to a function
224  * to be called for each payload found, which is also responsible for
225  * freeing the passed ISAKMP message in the failure case.
226  * Returns the total length of the parsed payloads.
227  */
228 static int
229 message_parse_payloads(struct message *msg, struct payload *p, u_int8_t next,
230     u_int8_t *buf, set *accepted_payloads, int (*func)(struct message *,
231     struct payload *, u_int8_t, u_int8_t *))
232 {
233 	u_int8_t        payload;
234 	u_int16_t       len;
235 	int             sz = 0;
236 
237 	do {
238 		LOG_DBG((LOG_MESSAGE, 50,
239 			 "message_parse_payloads: offset %ld payload %s",
240 			 (long)(buf - (u_int8_t *) msg->iov[0].iov_base),
241 			 constant_name(isakmp_payload_cst, next)));
242 
243 		/* Does this payload's header fit?  */
244 		if (buf + ISAKMP_GEN_SZ > (u_int8_t *)msg->iov[0].iov_base +
245 		    msg->iov[0].iov_len) {
246 			log_print("message_parse_payloads: short message");
247 			message_drop(msg,
248 			    ISAKMP_NOTIFY_UNEQUAL_PAYLOAD_LENGTHS, 0, 1, 1);
249 			return -1;
250 		}
251 		/* Ponder on the payload that is at BUF...  */
252 		payload = next;
253 
254 		/* Look at the next payload's type.  */
255 		next = GET_ISAKMP_GEN_NEXT_PAYLOAD(buf);
256 		if (next >= ISAKMP_PAYLOAD_RESERVED_MIN &&
257 		    next <= ISAKMP_PAYLOAD_RESERVED_MAX) {
258 			log_print("message_parse_payloads: invalid next "
259 			    "payload type %s in payload of type %d",
260 			    constant_name(isakmp_payload_cst, next), payload);
261 			message_drop(msg, ISAKMP_NOTIFY_INVALID_PAYLOAD_TYPE,
262 			    0, 1, 1);
263 			return -1;
264 		}
265 		/* Reserved fields in ISAKMP messages should be zero.  */
266 		if (GET_ISAKMP_GEN_RESERVED(buf) != 0) {
267 			log_print("message_parse_payloads: reserved field "
268 			    "non-zero: %x", GET_ISAKMP_GEN_RESERVED(buf));
269 			message_drop(msg, ISAKMP_NOTIFY_PAYLOAD_MALFORMED,
270 			    0, 1, 1);
271 			return -1;
272 		}
273 		/*
274 		 * Decode and validate the payload length field.
275 		 */
276 		len = GET_ISAKMP_GEN_LENGTH(buf);
277 
278 		if (message_payload_sz(payload) == 0) {
279 			log_print("message_parse_payloads: unknown minimum "
280 			    "payload size for payload type %s",
281 			    constant_name(isakmp_payload_cst, payload));
282 			message_drop(msg, ISAKMP_NOTIFY_PAYLOAD_MALFORMED,
283 			    0, 1, 1);
284 			return -1;
285 		}
286 		if (len < message_payload_sz(payload)) {
287 			log_print("message_parse_payloads: payload too "
288 			    "short: %u", len);
289 			message_drop(msg, ISAKMP_NOTIFY_PAYLOAD_MALFORMED,
290 			    0, 1, 1);
291 			return -1;
292 		}
293 		if (buf + len > (u_int8_t *)msg->iov[0].iov_base +
294 		    msg->iov[0].iov_len) {
295 			log_print("message_parse_payloads: payload too "
296 			    "long: %u", len);
297 			message_drop(msg, ISAKMP_NOTIFY_PAYLOAD_MALFORMED,
298 			    0, 1, 1);
299 			return -1;
300 		}
301 		/* Ignore most private payloads.  */
302 		if (next >= ISAKMP_PAYLOAD_PRIVATE_MIN &&
303 		    next != ISAKMP_PAYLOAD_NAT_D_DRAFT &&
304 		    next != ISAKMP_PAYLOAD_NAT_OA_DRAFT) {
305 			LOG_DBG((LOG_MESSAGE, 30, "message_parse_payloads: "
306 			    "private next payload type %s in payload of "
307 			    "type %d ignored",
308 			    constant_name(isakmp_payload_cst, next), payload));
309 			goto next_payload;
310 		}
311 		/*
312 		 * Check if the current payload is one of the accepted ones at
313 		 * this stage.
314 		 */
315 		if (!ISSET(payload, accepted_payloads)) {
316 			log_print("message_parse_payloads: payload type %s "
317 			    "unexpected", constant_name(isakmp_payload_cst,
318 				payload));
319 			message_drop(msg, ISAKMP_NOTIFY_INVALID_PAYLOAD_TYPE,
320 			    0, 1, 1);
321 			return -1;
322 		}
323 		/* Call the payload handler specified by the caller.  */
324 		if (func(msg, p, payload, buf))
325 			return -1;
326 
327 next_payload:
328 		/* Advance to next payload.  */
329 		buf += len;
330 		sz += len;
331 	} while (next != ISAKMP_PAYLOAD_NONE);
332 	return sz;
333 }
334 
335 /*
336  * Parse a proposal payload found in message MSG.  PAYLOAD is always
337  * ISAKMP_PAYLOAD_PROPOSAL and ignored in here.  It's needed as the API for
338  * message_parse_payloads requires it.  BUF points to the proposal's
339  * generic payload header.
340  */
341 static int
342 message_parse_proposal(struct message *msg, struct payload *p,
343     u_int8_t payload, u_int8_t *buf)
344 {
345 	set	payload_set;
346 
347 	/* Put the proposal into the proposal bucket.  */
348 	if (message_index_payload(msg, p, payload, buf) == -1)
349 		return -1;
350 
351 	ZERO(&payload_set);
352 	SET(ISAKMP_PAYLOAD_TRANSFORM, &payload_set);
353 	if (message_parse_payloads(msg,
354 	    TAILQ_LAST(&msg->payload[ISAKMP_PAYLOAD_PROPOSAL], payload_head),
355 	    ISAKMP_PAYLOAD_TRANSFORM, buf + ISAKMP_PROP_SPI_OFF +
356 	    GET_ISAKMP_PROP_SPI_SZ(buf), &payload_set, message_parse_transform)
357 	    == -1)
358 		return -1;
359 
360 	return 0;
361 }
362 
363 static int
364 message_parse_transform(struct message *msg, struct payload *p,
365     u_int8_t payload, u_int8_t *buf)
366 {
367 	/* Put the transform into the transform bucket.  */
368 	if (message_index_payload(msg, p, payload, buf) == -1)
369 		return -1;
370 
371 	LOG_DBG((LOG_MESSAGE, 50, "Transform %d's attributes",
372 	    GET_ISAKMP_TRANSFORM_NO(buf)));
373 	attribute_map(buf + ISAKMP_TRANSFORM_SA_ATTRS_OFF,
374 	    GET_ISAKMP_GEN_LENGTH(buf) - ISAKMP_TRANSFORM_SA_ATTRS_OFF,
375 	    msg->exchange->doi->debug_attribute, msg);
376 
377 	return 0;
378 }
379 
380 static struct field *
381 message_get_field(u_int8_t payload)
382 {
383 	switch (payload) {
384 	case ISAKMP_PAYLOAD_SA:
385 		return isakmp_sa_fld;
386 	case ISAKMP_PAYLOAD_PROPOSAL:
387 		return isakmp_prop_fld;
388 	case ISAKMP_PAYLOAD_TRANSFORM:
389 		return isakmp_transform_fld;
390 	case ISAKMP_PAYLOAD_KEY_EXCH:
391 		return isakmp_ke_fld;
392 	case ISAKMP_PAYLOAD_ID:
393 		return isakmp_id_fld;
394 	case ISAKMP_PAYLOAD_CERT:
395 		return isakmp_cert_fld;
396 	case ISAKMP_PAYLOAD_CERT_REQ:
397 		return isakmp_certreq_fld;
398 	case ISAKMP_PAYLOAD_HASH:
399 		return isakmp_hash_fld;
400 	case ISAKMP_PAYLOAD_SIG:
401 		return isakmp_sig_fld;
402 	case ISAKMP_PAYLOAD_NONCE:
403 		return isakmp_nonce_fld;
404 	case ISAKMP_PAYLOAD_NOTIFY:
405 		return isakmp_notify_fld;
406 	case ISAKMP_PAYLOAD_DELETE:
407 		return isakmp_delete_fld;
408 	case ISAKMP_PAYLOAD_VENDOR:
409 		return isakmp_vendor_fld;
410 	case ISAKMP_PAYLOAD_ATTRIBUTE:
411 		return isakmp_attribute_fld;
412 	case ISAKMP_PAYLOAD_NAT_D:
413 	case ISAKMP_PAYLOAD_NAT_D_DRAFT:
414 		return isakmp_nat_d_fld;
415 	case ISAKMP_PAYLOAD_NAT_OA:
416 	case ISAKMP_PAYLOAD_NAT_OA_DRAFT:
417 		return isakmp_nat_oa_fld;
418 	/* Not yet supported and any other unknown payloads. */
419 	case ISAKMP_PAYLOAD_SAK:
420 	case ISAKMP_PAYLOAD_SAT:
421 	case ISAKMP_PAYLOAD_KD:
422 	case ISAKMP_PAYLOAD_SEQ:
423 	case ISAKMP_PAYLOAD_POP:
424 	default:
425 		break;
426 	}
427 	return NULL;
428 }
429 
430 static int
431 message_validate_payload(struct message *m, struct payload *p, u_int8_t payload)
432 {
433 	switch (payload) {
434 	case ISAKMP_PAYLOAD_SA:
435 		return message_validate_sa(m, p);
436 	case ISAKMP_PAYLOAD_PROPOSAL:
437 		return message_validate_proposal(m, p);
438 	case ISAKMP_PAYLOAD_TRANSFORM:
439 		return message_validate_transform(m, p);
440 	case ISAKMP_PAYLOAD_KEY_EXCH:
441 		return message_validate_key_exch(m, p);
442 	case ISAKMP_PAYLOAD_ID:
443 		return message_validate_id(m, p);
444 	case ISAKMP_PAYLOAD_CERT:
445 		return message_validate_cert(m, p);
446 	case ISAKMP_PAYLOAD_CERT_REQ:
447 		return message_validate_cert_req(m, p);
448 	case ISAKMP_PAYLOAD_HASH:
449 		return message_validate_hash(m, p);
450 	case ISAKMP_PAYLOAD_SIG:
451 		return message_validate_sig(m, p);
452 	case ISAKMP_PAYLOAD_NONCE:
453 		return message_validate_nonce(m, p);
454 	case ISAKMP_PAYLOAD_NOTIFY:
455 		return message_validate_notify(m, p);
456 	case ISAKMP_PAYLOAD_DELETE:
457 		return message_validate_delete(m, p);
458 	case ISAKMP_PAYLOAD_VENDOR:
459 		return message_validate_vendor(m, p);
460 	case ISAKMP_PAYLOAD_ATTRIBUTE:
461 		return message_validate_attribute(m, p);
462 	case ISAKMP_PAYLOAD_NAT_D:
463 	case ISAKMP_PAYLOAD_NAT_D_DRAFT:
464 		return message_validate_nat_d(m, p);
465 	case ISAKMP_PAYLOAD_NAT_OA:
466 	case ISAKMP_PAYLOAD_NAT_OA_DRAFT:
467 		return message_validate_nat_oa(m, p);
468 	/* Not yet supported and any other unknown payloads. */
469 	case ISAKMP_PAYLOAD_SAK:
470 	case ISAKMP_PAYLOAD_SAT:
471 	case ISAKMP_PAYLOAD_KD:
472 	case ISAKMP_PAYLOAD_SEQ:
473 	case ISAKMP_PAYLOAD_POP:
474 	default:
475 		break;
476 	}
477 	message_drop(m, ISAKMP_NOTIFY_INVALID_PAYLOAD_TYPE, 0, 1, 1);
478 	return -1;
479 }
480 
481 /* Check payloads for their required minimum size. */
482 static u_int16_t
483 message_payload_sz(u_int8_t payload)
484 {
485 	switch (payload) {
486 	case ISAKMP_PAYLOAD_SA:
487 		return ISAKMP_SA_SZ;
488 	case ISAKMP_PAYLOAD_PROPOSAL:
489 		return ISAKMP_PROP_SZ;
490 	case ISAKMP_PAYLOAD_TRANSFORM:
491 		return ISAKMP_TRANSFORM_SZ;
492 	case ISAKMP_PAYLOAD_KEY_EXCH:
493 		return ISAKMP_KE_SZ;
494 	case ISAKMP_PAYLOAD_ID:
495 		return ISAKMP_ID_SZ;
496 	case ISAKMP_PAYLOAD_CERT:
497 		return ISAKMP_CERT_SZ;
498 	case ISAKMP_PAYLOAD_CERT_REQ:
499 		return ISAKMP_CERTREQ_SZ;
500 	case ISAKMP_PAYLOAD_HASH:
501 		return ISAKMP_HASH_SZ;
502 	case ISAKMP_PAYLOAD_SIG:
503 		return ISAKMP_SIG_SZ;
504 	case ISAKMP_PAYLOAD_NONCE:
505 		return ISAKMP_NONCE_SZ;
506 	case ISAKMP_PAYLOAD_NOTIFY:
507 		return ISAKMP_NOTIFY_SZ;
508 	case ISAKMP_PAYLOAD_DELETE:
509 		return ISAKMP_DELETE_SZ;
510 	case ISAKMP_PAYLOAD_VENDOR:
511 		return ISAKMP_VENDOR_SZ;
512 	case ISAKMP_PAYLOAD_ATTRIBUTE:
513 		return ISAKMP_ATTRIBUTE_SZ;
514 	case ISAKMP_PAYLOAD_NAT_D:
515 	case ISAKMP_PAYLOAD_NAT_D_DRAFT:
516 		return ISAKMP_NAT_D_SZ;
517 	case ISAKMP_PAYLOAD_NAT_OA:
518 	case ISAKMP_PAYLOAD_NAT_OA_DRAFT:
519 		return ISAKMP_NAT_OA_SZ;
520 	/* Not yet supported and any other unknown payloads. */
521 	case ISAKMP_PAYLOAD_SAK:
522 	case ISAKMP_PAYLOAD_SAT:
523 	case ISAKMP_PAYLOAD_KD:
524 	case ISAKMP_PAYLOAD_SEQ:
525 	case ISAKMP_PAYLOAD_POP:
526 	default:
527 		return 0;
528 	}
529 }
530 
531 /* Validate the attribute payload P in message MSG.  */
532 static int
533 message_validate_attribute(struct message *msg, struct payload *p)
534 {
535 	/* If we don't have an exchange yet, create one.  */
536 	if (!msg->exchange) {
537 		if (zero_test((u_int8_t *) msg->iov[0].iov_base +
538 		    ISAKMP_HDR_MESSAGE_ID_OFF, ISAKMP_HDR_MESSAGE_ID_LEN))
539 			msg->exchange = exchange_setup_p1(msg,
540 			    IPSEC_DOI_IPSEC);
541 		else
542 			msg->exchange = exchange_setup_p2(msg,
543 			    IPSEC_DOI_IPSEC);
544 		if (!msg->exchange) {
545 			log_print("message_validate_attribute: can not "
546 			    "create exchange");
547 			message_free(msg);
548 			return -1;
549 		}
550 	}
551 	return 0;
552 }
553 
554 /* Validate the certificate payload P in message MSG.  */
555 static int
556 message_validate_cert(struct message *msg, struct payload *p)
557 {
558 	if (GET_ISAKMP_CERT_ENCODING(p->p) >= ISAKMP_CERTENC_RESERVED_MIN) {
559 		message_drop(msg, ISAKMP_NOTIFY_INVALID_CERT_ENCODING, 0, 1,
560 		    1);
561 		return -1;
562 	}
563 	return 0;
564 }
565 
566 /* Validate the certificate request payload P in message MSG.  */
567 static int
568 message_validate_cert_req(struct message *msg, struct payload *p)
569 {
570 	struct cert_handler *cert;
571 	size_t	len =
572 	    GET_ISAKMP_GEN_LENGTH(p->p) - ISAKMP_CERTREQ_AUTHORITY_OFF;
573 
574 	if (GET_ISAKMP_CERTREQ_TYPE(p->p) >= ISAKMP_CERTENC_RESERVED_MIN) {
575 		message_drop(msg, ISAKMP_NOTIFY_INVALID_CERT_ENCODING, 0, 1,
576 		    1);
577 		return -1;
578 	}
579 	/*
580 	 * Check the certificate types we support and if an acceptable
581 	 * authority is included in the payload check if it can be decoded
582 	 */
583 	cert = cert_get(GET_ISAKMP_CERTREQ_TYPE(p->p));
584 	if (!cert || (len && !cert->certreq_validate(p->p +
585 	    ISAKMP_CERTREQ_AUTHORITY_OFF, len))) {
586 		message_drop(msg, ISAKMP_NOTIFY_CERT_TYPE_UNSUPPORTED, 0, 1,
587 		    1);
588 		return -1;
589 	}
590 	return 0;
591 }
592 
593 /*
594  * Validate the delete payload P in message MSG.  As a side-effect, create
595  * an exchange if we do not have one already.
596  */
597 static int
598 message_validate_delete(struct message *msg, struct payload *p)
599 {
600 	u_int8_t        proto = GET_ISAKMP_DELETE_PROTO(p->p);
601 	struct doi     *doi;
602 	struct sa      *sa, *isakmp_sa;
603 	struct sockaddr *dst, *dst_isa;
604 	u_int32_t       nspis = GET_ISAKMP_DELETE_NSPIS(p->p);
605 	u_int8_t       *spis = (u_int8_t *)p->p + ISAKMP_DELETE_SPI_OFF;
606 	u_int32_t       i;
607 	char           *addr;
608 
609 	/* Only accept authenticated DELETEs. */
610 	if ((msg->flags & MSG_AUTHENTICATED) == 0) {
611 		log_print("message_validate_delete: "
612 		    "got unauthenticated DELETE");
613 		message_free(msg);
614 		return -1;
615 	}
616 
617 	doi = doi_lookup(GET_ISAKMP_DELETE_DOI(p->p));
618 	if (!doi) {
619 		log_print("message_validate_delete: DOI not supported");
620 		message_free(msg);
621 		return -1;
622 	}
623 	/* If we don't have an exchange yet, create one.  */
624 	if (!msg->exchange) {
625 		if (zero_test((u_int8_t *) msg->iov[0].iov_base
626 		    + ISAKMP_HDR_MESSAGE_ID_OFF, ISAKMP_HDR_MESSAGE_ID_LEN))
627 			msg->exchange = exchange_setup_p1(msg, doi->id);
628 		else
629 			msg->exchange = exchange_setup_p2(msg, doi->id);
630 		if (!msg->exchange) {
631 			log_print("message_validate_delete: can not create "
632 			    "exchange");
633 			message_free(msg);
634 			return -1;
635 		}
636 	}
637 	/* Only accept DELETE as part of an INFORMATIONAL exchange. */
638 	if (msg->exchange->type != ISAKMP_EXCH_INFO) {
639 		log_print("message_validate_delete: delete in exchange other "
640 		    "than INFO: %s", constant_name(isakmp_exch_cst,
641 		    msg->exchange->type));
642 		message_free(msg);
643 		return -1;
644 	}
645 	if (proto != ISAKMP_PROTO_ISAKMP && doi->validate_proto(proto)) {
646 		log_print("message_validate_delete: protocol not supported");
647 		message_free(msg);
648 		return -1;
649 	}
650 	/* Validate the SPIs.  */
651 	for (i = 0; i < nspis; i++) {
652 		/* Get ISAKMP SA protecting this message. */
653 		isakmp_sa = msg->isakmp_sa;
654 		if (!isakmp_sa) {
655 			/* XXX should not happen? */
656 			log_print("message_validate_delete: invalid spi (no "
657 			    "valid ISAKMP SA found)");
658 			message_free(msg);
659 			return -1;
660 		}
661 		isakmp_sa->transport->vtbl->get_dst(isakmp_sa->transport,
662 		    &dst_isa);
663 
664 		/* Get SA to be deleted. */
665 		msg->transport->vtbl->get_dst(msg->transport, &dst);
666 		if (proto == ISAKMP_PROTO_ISAKMP)
667 			sa = sa_lookup_isakmp_sa(dst, spis + i
668 			    * ISAKMP_HDR_COOKIES_LEN);
669 		else
670 			sa = ipsec_sa_lookup(dst, ((u_int32_t *) spis)[i],
671 			    proto);
672 		if (!sa) {
673 			LOG_DBG((LOG_MESSAGE, 50, "message_validate_delete: "
674 			    "invalid spi (no valid SA found)"));
675 			message_free(msg);
676 			return -1;
677 		}
678 		sa->transport->vtbl->get_dst(sa->transport, &dst);
679 
680 		/* Destination addresses must match. */
681 		if (dst->sa_family != dst_isa->sa_family ||
682 		    memcmp(sockaddr_addrdata(dst_isa), sockaddr_addrdata(dst),
683 		    sockaddr_addrlen(dst))) {
684 			sockaddr2text(dst_isa, &addr, 0);
685 
686 			log_print("message_validate_delete: invalid spi "
687 			    "(illegal delete request from %s)", addr);
688 			free(addr);
689 			message_free(msg);
690 			return -1;
691 		}
692 	}
693 
694 	return 0;
695 }
696 
697 /*
698  * Validate the hash payload P in message MSG.
699  */
700 static int
701 message_validate_hash(struct message *msg, struct payload *p)
702 {
703 	struct sa      *isakmp_sa = msg->isakmp_sa;
704 	struct ipsec_sa *isa;
705 	struct hash    *hash;
706 	struct payload *hashp = payload_first(msg, ISAKMP_PAYLOAD_HASH);
707 	struct prf     *prf;
708 	u_int8_t       *rest;
709 	u_int8_t        message_id[ISAKMP_HDR_MESSAGE_ID_LEN];
710 	size_t          rest_len;
711 
712 	/* active exchanges other than INFORMATIONAL validates hash payload. */
713 	if (msg->exchange && (msg->exchange->type != ISAKMP_EXCH_INFO))
714 		return 0;
715 
716 	if (isakmp_sa == NULL)
717 		goto invalid;
718 
719 	isa = isakmp_sa->data;
720 	hash = hash_get(isa->hash);
721 	if (hash == NULL)
722 		goto invalid;
723 
724 	/* If no SKEYID_a, we can not do anything (should not happen).  */
725 	if (!isa->skeyid_a)
726 		goto invalid;
727 
728 	/* Allocate the prf and start calculating our HASH(1). */
729 	LOG_DBG_BUF((LOG_MISC, 90, "message_validate_hash: SKEYID_a",
730 	    isa->skeyid_a, isa->skeyid_len));
731 	prf = prf_alloc(isa->prf_type, hash->type, isa->skeyid_a,
732 	    isa->skeyid_len);
733 	if (!prf) {
734 		message_free(msg);
735 		return -1;
736 	}
737 	/* This is not an active exchange. */
738 	GET_ISAKMP_HDR_MESSAGE_ID(msg->iov[0].iov_base, message_id);
739 
740 	prf->Init(prf->prfctx);
741 	LOG_DBG_BUF((LOG_MISC, 90, "message_validate_hash: message_id",
742 	    message_id, ISAKMP_HDR_MESSAGE_ID_LEN));
743 	prf->Update(prf->prfctx, message_id, ISAKMP_HDR_MESSAGE_ID_LEN);
744 	rest = hashp->p + GET_ISAKMP_GEN_LENGTH(hashp->p);
745 	rest_len = (GET_ISAKMP_HDR_LENGTH(msg->iov[0].iov_base) - (rest -
746 	    (u_int8_t *)msg->iov[0].iov_base));
747 	LOG_DBG_BUF((LOG_MISC, 90,
748 	    "message_validate_hash: payloads after HASH(1)", rest, rest_len));
749 	prf->Update(prf->prfctx, rest, rest_len);
750 	prf->Final(hash->digest, prf->prfctx);
751 	prf_free(prf);
752 
753 	if (memcmp(hashp->p + ISAKMP_HASH_DATA_OFF, hash->digest,
754 	    hash->hashsize))
755 		goto invalid;
756 
757 	/* Mark the HASH as handled. */
758 	hashp->flags |= PL_MARK;
759 
760 	/* Mark message as authenticated. */
761 	msg->flags |= MSG_AUTHENTICATED;
762 
763 	return 0;
764 
765   invalid:
766 	log_print("message_validate_hash: invalid hash information");
767 	message_drop(msg, ISAKMP_NOTIFY_INVALID_HASH_INFORMATION, 0, 1, 1);
768 	return -1;
769 }
770 
771 /* Validate the identification payload P in message MSG.  */
772 static int
773 message_validate_id(struct message *msg, struct payload *p)
774 {
775 	struct exchange *exchange = msg->exchange;
776 	size_t          len = GET_ISAKMP_GEN_LENGTH(p->p);
777 
778 	if (!exchange) {
779 		/* We should have an exchange at this point.  */
780 		log_print("message_validate_id: payload out of sequence");
781 		message_drop(msg, ISAKMP_NOTIFY_PAYLOAD_MALFORMED, 0, 1, 1);
782 		return -1;
783 	}
784 	if (exchange->doi &&
785 	    exchange->doi->validate_id_information(GET_ISAKMP_ID_TYPE(p->p),
786 	    p->p + ISAKMP_ID_DOI_DATA_OFF, p->p + ISAKMP_ID_DATA_OFF,
787 	    len - ISAKMP_ID_DATA_OFF, exchange)) {
788 		message_drop(msg, ISAKMP_NOTIFY_INVALID_ID_INFORMATION, 0, 1,
789 		    1);
790 		return -1;
791 	}
792 	return 0;
793 }
794 
795 /* Validate the key exchange payload P in message MSG.  */
796 static int
797 message_validate_key_exch(struct message *msg, struct payload *p)
798 {
799 	struct exchange *exchange = msg->exchange;
800 	size_t          len = GET_ISAKMP_GEN_LENGTH(p->p);
801 
802 	if (!exchange) {
803 		/* We should have an exchange at this point.  */
804 		log_print("message_validate_key_exch: "
805 		    "payload out of sequence");
806 		message_drop(msg, ISAKMP_NOTIFY_PAYLOAD_MALFORMED, 0, 1, 1);
807 		return -1;
808 	}
809 	if (exchange->doi && exchange->doi->validate_key_information(p->p +
810 	    ISAKMP_KE_DATA_OFF, len - ISAKMP_KE_DATA_OFF)) {
811 		message_drop(msg, ISAKMP_NOTIFY_INVALID_KEY_INFORMATION,
812 		    0, 1, 1);
813 		return -1;
814 	}
815 	return 0;
816 }
817 
818 /* Validate the NAT-D payload P in message MSG.  */
819 static int
820 message_validate_nat_d(struct message *msg, struct payload *p)
821 {
822 	struct exchange	*exchange = msg->exchange;
823 
824 	if (!exchange) {
825 		/* We should have an exchange at this point.  */
826 		log_print("message_validate_nat_d: payload out of sequence");
827 		message_drop(msg, ISAKMP_NOTIFY_PAYLOAD_MALFORMED, 0, 1, 1);
828 		return -1;
829 	}
830 
831 	if (exchange->phase != 1) {
832 		log_print("message_validate_nat_d: "
833 		    "NAT-D payload must be in phase 1");
834 		message_drop(msg, ISAKMP_NOTIFY_PAYLOAD_MALFORMED, 0, 1, 1);
835 		return -1;
836 	}
837 
838 	/* Mark as handled.  */
839 	p->flags |= PL_MARK;
840 
841 	return 0;
842 }
843 
844 /* Validate the NAT-OA payload P in message MSG.  */
845 static int
846 message_validate_nat_oa(struct message *msg, struct payload *p)
847 {
848 	struct exchange	*exchange = msg->exchange;
849 
850 	if (!exchange) {
851 		/* We should have an exchange at this point.  */
852 		log_print("message_validate_nat_d: payload out of sequence");
853 		message_drop(msg, ISAKMP_NOTIFY_PAYLOAD_MALFORMED, 0, 1, 1);
854 		return -1;
855 	}
856 
857 #ifdef notyet /* XXX Probably never, due to patent issues.  */
858 	/* Mark as handled.  */
859 	p->flags |= PL_MARK;
860 #endif
861 
862 	return 0;
863 }
864 
865 /* Validate the nonce payload P in message MSG.  */
866 static int
867 message_validate_nonce(struct message *msg, struct payload *p)
868 {
869 	if (!msg->exchange) {
870 		/* We should have an exchange at this point.  */
871 		log_print("message_validate_nonce: payload out of sequence");
872 		message_drop(msg, ISAKMP_NOTIFY_PAYLOAD_MALFORMED, 0, 1, 1);
873 		return -1;
874 	}
875 	/* Nonces require no specific validation.  */
876 	return 0;
877 }
878 
879 /*
880  * Validate the notify payload P in message MSG.  As a side-effect, create
881  * an exchange if we do not have one already.
882  */
883 static int
884 message_validate_notify(struct message *msg, struct payload *p)
885 {
886 	u_int8_t        proto = GET_ISAKMP_NOTIFY_PROTO(p->p);
887 	u_int16_t       type = GET_ISAKMP_NOTIFY_MSG_TYPE(p->p);
888 	struct doi     *doi;
889 
890 	doi = doi_lookup(GET_ISAKMP_NOTIFY_DOI(p->p));
891 	if (!doi) {
892 		log_print("message_validate_notify: DOI not supported");
893 		message_free(msg);
894 		return -1;
895 	}
896 	/* If we don't have an exchange yet, create one.  */
897 	if (!msg->exchange) {
898 		if (zero_test((u_int8_t *) msg->iov[0].iov_base +
899 		    ISAKMP_HDR_MESSAGE_ID_OFF, ISAKMP_HDR_MESSAGE_ID_LEN))
900 			msg->exchange = exchange_setup_p1(msg, doi->id);
901 		else
902 			msg->exchange = exchange_setup_p2(msg, doi->id);
903 		if (!msg->exchange) {
904 			log_print("message_validate_notify: can not create "
905 			    "exchange");
906 			message_free(msg);
907 			return -1;
908 		}
909 	}
910 	if (proto != ISAKMP_PROTO_ISAKMP && doi->validate_proto(proto)) {
911 		log_print("message_validate_notify: protocol not supported");
912 		message_free(msg);
913 		return -1;
914 	}
915 
916 	/* Validate the SPI. XXX Just ISAKMP for now.  */
917 	if (proto == ISAKMP_PROTO_ISAKMP &&
918 	    GET_ISAKMP_NOTIFY_SPI_SZ(p->p) == ISAKMP_HDR_COOKIES_LEN &&
919 	    msg->isakmp_sa &&
920 	    memcmp(p->p + ISAKMP_NOTIFY_SPI_OFF, msg->isakmp_sa->cookies,
921 		ISAKMP_HDR_COOKIES_LEN) != 0) {
922 		log_print("message_validate_notify: bad cookies");
923 		message_drop(msg, ISAKMP_NOTIFY_INVALID_SPI, 0, 1, 1);
924 		return -1;
925 	}
926 
927 	if (type < ISAKMP_NOTIFY_INVALID_PAYLOAD_TYPE ||
928 	    (type >= ISAKMP_NOTIFY_RESERVED_MIN &&
929 	    type < ISAKMP_NOTIFY_PRIVATE_MIN) ||
930 	    (type >= ISAKMP_NOTIFY_STATUS_RESERVED1_MIN &&
931 	    type <= ISAKMP_NOTIFY_STATUS_RESERVED1_MAX) ||
932 	    (type >= ISAKMP_NOTIFY_STATUS_DOI_MIN &&
933 	    type <= ISAKMP_NOTIFY_STATUS_DOI_MAX &&
934 	    doi->validate_notification(type)) ||
935 	    type >= ISAKMP_NOTIFY_STATUS_RESERVED2_MIN) {
936 		log_print("message_validate_notify: "
937 		    "message type not supported");
938 		message_free(msg);
939 		return -1;
940 	}
941 
942 	return 0;
943 }
944 
945 /* Validate the proposal payload P in message MSG.  */
946 static int
947 message_validate_proposal(struct message *msg, struct payload *p)
948 {
949 	u_int8_t        proto = GET_ISAKMP_PROP_PROTO(p->p);
950 	u_int8_t       *sa = p->context->p;
951 
952 	if (!msg->exchange) {
953 		/* We should have an exchange at this point.  */
954 		log_print("message_validate_proposal: "
955 		    "payload out of sequence");
956 		message_drop(msg, ISAKMP_NOTIFY_PAYLOAD_MALFORMED, 0, 1, 1);
957 		return -1;
958 	}
959 	if (proto != ISAKMP_PROTO_ISAKMP &&
960 	    msg->exchange->doi->validate_proto(proto)) {
961 		message_drop(msg, ISAKMP_NOTIFY_INVALID_PROTOCOL_ID, 0, 1, 1);
962 		return -1;
963 	}
964 	/* Check that we get monotonically increasing proposal IDs per SA.  */
965 	if (sa != last_sa)
966 		last_sa = sa;
967 	else if (GET_ISAKMP_PROP_NO(p->p) < last_prop_no) {
968 		message_drop(msg, ISAKMP_NOTIFY_BAD_PROPOSAL_SYNTAX, 0, 1, 1);
969 		return -1;
970 	}
971 	last_prop_no = GET_ISAKMP_PROP_NO(p->p);
972 
973 	/* XXX Validate the SPI, and other syntactic things.  */
974 
975 	return 0;
976 }
977 
978 /*
979  * Validate the SA payload P in message MSG.
980  * Aside from normal validation, note what DOI is in use for other
981  * validation routines to look at.  Also index the proposal payloads
982  * on the fly.
983  * XXX This assumes PAYLOAD_SA is always the first payload
984  * to be validated, which is true for IKE, except for quick mode where
985  * a PAYLOAD_HASH comes first, but in that specific case it does not matter.
986  * XXX Make sure the above comment is relevant, isn't SA always checked
987  * first due to the IANA assigned payload number?
988  */
989 static int
990 message_validate_sa(struct message *msg, struct payload *p)
991 {
992 	set             payload_set;
993 	size_t          len;
994 	u_int32_t       doi_id;
995 	struct exchange *exchange = msg->exchange;
996 	u_int8_t       *pkt = msg->iov[0].iov_base;
997 
998 	doi_id = GET_ISAKMP_SA_DOI(p->p);
999 	if (!doi_lookup(doi_id)) {
1000 		log_print("message_validate_sa: DOI not supported");
1001 		message_drop(msg, ISAKMP_NOTIFY_DOI_NOT_SUPPORTED, 0, 1, 1);
1002 		return -1;
1003 	}
1004 	/*
1005 	 * It's time to figure out what SA this message is about.  If it is
1006 	 * already set, then we are creating a new phase 1 SA.  Otherwise,
1007 	 * lookup the SA using the cookies and the message ID.  If we cannot
1008 	 * find it, and the phase 1 SA is ready, setup a phase 2 SA.
1009 	 */
1010 	if (!exchange) {
1011 		if (zero_test(pkt + ISAKMP_HDR_RCOOKIE_OFF,
1012 		    ISAKMP_HDR_RCOOKIE_LEN))
1013 			exchange = exchange_setup_p1(msg, doi_id);
1014 		else if (msg->isakmp_sa->flags & SA_FLAG_READY)
1015 			exchange = exchange_setup_p2(msg, doi_id);
1016 		else {
1017 			/* XXX What to do here?  */
1018 			message_free(msg);
1019 			return -1;
1020 		}
1021 		if (!exchange) {
1022 			/* XXX Log?  */
1023 			message_free(msg);
1024 			return -1;
1025 		}
1026 	}
1027 	msg->exchange = exchange;
1028 
1029 	/*
1030 	 * Create a struct sa for each SA payload handed to us unless we are
1031 	 * the initiator where we only will count them.
1032 	 */
1033 	if (exchange->initiator) {
1034 		/* XXX Count SA payloads.  */
1035 	} else if (sa_create(exchange, msg->transport)) {
1036 		/* XXX Remove exchange if we just created it?   */
1037 		message_free(msg);
1038 		return -1;
1039 	}
1040 	if (exchange->phase == 1) {
1041 		msg->isakmp_sa = TAILQ_FIRST(&exchange->sa_list);
1042 		if (msg->isakmp_sa)
1043 			sa_reference(msg->isakmp_sa);
1044 	}
1045 	/*
1046 	 * Let the DOI validate the situation, at the same time it tells us
1047 	 * what the length of the situation field is.
1048 	 */
1049 	if (exchange->doi->validate_situation(p->p + ISAKMP_SA_SIT_OFF, &len,
1050 	    GET_ISAKMP_GEN_LENGTH(p->p) - ISAKMP_SA_SIT_OFF)) {
1051 		log_print("message_validate_sa: situation not supported");
1052 		message_drop(msg, ISAKMP_NOTIFY_SITUATION_NOT_SUPPORTED,
1053 		    0, 1, 1);
1054 		return -1;
1055 	}
1056 	/*
1057 	 * Reset the fields we base our proposal & transform number checks
1058 	 * on.
1059 	 */
1060 	last_sa = last_prop = 0;
1061 	last_prop_no = last_xf_no = 0;
1062 
1063 	/* Go through the PROPOSAL payloads.  */
1064 	ZERO(&payload_set);
1065 	SET(ISAKMP_PAYLOAD_PROPOSAL, &payload_set);
1066 	if (message_parse_payloads(msg, p, ISAKMP_PAYLOAD_PROPOSAL,
1067 	    p->p + ISAKMP_SA_SIT_OFF + len, &payload_set,
1068 	    message_parse_proposal) == -1)
1069 		return -1;
1070 
1071 	return 0;
1072 }
1073 
1074 /* Validate the signature payload P in message MSG.  */
1075 static int
1076 message_validate_sig(struct message *msg, struct payload *p)
1077 {
1078 	if (!msg->exchange) {
1079 		/* We should have an exchange at this point.  */
1080 		log_print("message_validate_sig: payload out of sequence");
1081 		message_drop(msg, ISAKMP_NOTIFY_PAYLOAD_MALFORMED, 0, 1, 1);
1082 		return -1;
1083 	}
1084 	/* XXX Not implemented yet.  */
1085 	return 0;
1086 }
1087 
1088 /* Validate the transform payload P in message MSG.  */
1089 static int
1090 message_validate_transform(struct message *msg, struct payload *p)
1091 {
1092 	u_int8_t        proto = GET_ISAKMP_PROP_PROTO(p->context->p);
1093 	u_int8_t       *prop = p->context->p;
1094 
1095 	if (!msg->exchange) {
1096 		/* We should have an exchange at this point.  */
1097 		log_print("message_validate_transform: "
1098 		    "payload out of sequence");
1099 		message_drop(msg, ISAKMP_NOTIFY_PAYLOAD_MALFORMED, 0, 1, 1);
1100 		return -1;
1101 	}
1102 	if (msg->exchange->doi
1103 	    ->validate_transform_id(proto, GET_ISAKMP_TRANSFORM_ID(p->p))) {
1104 		message_drop(msg, ISAKMP_NOTIFY_INVALID_TRANSFORM_ID, 0, 1, 1);
1105 		return -1;
1106 	}
1107 	/* Check that the reserved field is zero.  */
1108 	if (!zero_test(p->p + ISAKMP_TRANSFORM_RESERVED_OFF,
1109 	    ISAKMP_TRANSFORM_RESERVED_LEN)) {
1110 		message_drop(msg, ISAKMP_NOTIFY_PAYLOAD_MALFORMED, 0, 1, 1);
1111 		return -1;
1112 	}
1113 	/*
1114 	 * Check that we get monotonically increasing transform numbers per
1115 	 * proposal.
1116 	 */
1117 	if (prop != last_prop)
1118 		last_prop = prop;
1119 	else if (GET_ISAKMP_TRANSFORM_NO(p->p) <= last_xf_no) {
1120 		message_drop(msg, ISAKMP_NOTIFY_BAD_PROPOSAL_SYNTAX, 0, 1, 1);
1121 		return -1;
1122 	}
1123 	last_xf_no = GET_ISAKMP_TRANSFORM_NO(p->p);
1124 
1125 	/* Validate the attributes.  */
1126 	if (attribute_map(p->p + ISAKMP_TRANSFORM_SA_ATTRS_OFF,
1127 	    GET_ISAKMP_GEN_LENGTH(p->p) - ISAKMP_TRANSFORM_SA_ATTRS_OFF,
1128 	    msg->exchange->doi->validate_attribute, msg)) {
1129 		message_drop(msg, ISAKMP_NOTIFY_ATTRIBUTES_NOT_SUPPORTED,
1130 		    0, 1, 1);
1131 		return -1;
1132 	}
1133 	return 0;
1134 }
1135 
1136 /* Validate the vendor payload P in message MSG.  */
1137 static int
1138 message_validate_vendor(struct message *msg, struct payload *p)
1139 {
1140 	if (!msg->exchange) {
1141 		/* We should have an exchange at this point.  */
1142 		log_print("message_validate_vendor: payload out of sequence");
1143 		message_drop(msg, ISAKMP_NOTIFY_PAYLOAD_MALFORMED, 0, 1, 1);
1144 		return -1;
1145 	}
1146 	/* Vendor IDs are only allowed in phase 1.  */
1147 	if (msg->exchange->phase != 1) {
1148 		message_drop(msg, ISAKMP_NOTIFY_INVALID_PAYLOAD_TYPE, 0, 1, 1);
1149 		return -1;
1150 	}
1151 	check_vendor_openbsd(msg, p);
1152 	dpd_check_vendor_payload(msg, p);
1153 	nat_t_check_vendor_payload(msg, p);
1154 	if (!(p->flags & PL_MARK))
1155 		LOG_DBG((LOG_MESSAGE, 40, "message_validate_vendor: "
1156 		    "vendor ID seen"));
1157 	return 0;
1158 }
1159 
1160 /*
1161  * Add an index-record pointing to the payload at BUF in message MSG
1162  * to the PAYLOAD bucket of payloads.  This allows us to quickly reference
1163  * payloads by type.  Also stash the parent payload P link into the new
1164  * node so we can go from transforms -> payloads -> SAs.
1165  */
1166 static int
1167 message_index_payload(struct message *msg, struct payload *p, u_int8_t payload,
1168     u_int8_t *buf)
1169 {
1170 	struct payload *payload_node;
1171 
1172 	/* Put the payload pointer into the right bucket.  */
1173 	payload_node = malloc(sizeof *payload_node);
1174 	if (!payload_node) {
1175 		message_free(msg);
1176 		return -1;
1177 	}
1178 	payload_node->p = buf;
1179 	payload_node->context = p;
1180 	payload_node->flags = 0;
1181 	TAILQ_INSERT_TAIL(&msg->payload[payload], payload_node, link);
1182 	return 0;
1183 }
1184 
1185 /*
1186  * Group each payload found in MSG by type for easy reference later.
1187  * While doing this, validate the generic parts of the message structure too.
1188  * NEXT is the 1st payload's type.  This routine will also register the
1189  * computed message length (i.e. without padding) in msg->iov[0].iov_len.
1190  */
1191 static int
1192 message_sort_payloads(struct message *msg, u_int8_t next)
1193 {
1194 	set	payload_set;
1195 	int	i, sz;
1196 
1197 	ZERO(&payload_set);
1198 	for (i = ISAKMP_PAYLOAD_SA; i < ISAKMP_PAYLOAD_MAX; i++)
1199 		if (i != ISAKMP_PAYLOAD_PROPOSAL && i !=
1200 		    ISAKMP_PAYLOAD_TRANSFORM)
1201 			SET(i, &payload_set);
1202 	sz = message_parse_payloads(msg, 0, next,
1203 	    (u_int8_t *)msg->iov[0].iov_base + ISAKMP_HDR_SZ, &payload_set,
1204 	    message_index_payload);
1205 	if (sz == -1)
1206 		return -1;
1207 	msg->iov[0].iov_len = ISAKMP_HDR_SZ + sz;
1208 	SET_ISAKMP_HDR_LENGTH(msg->iov[0].iov_base, ISAKMP_HDR_SZ + sz);
1209 	return 0;
1210 }
1211 
1212 /* Run all the generic payload tests that the drafts specify.  */
1213 static int
1214 message_validate_payloads(struct message *msg)
1215 {
1216 	int             i;
1217 	struct payload *p;
1218 	struct field   *f;
1219 
1220 	for (i = ISAKMP_PAYLOAD_SA; i < ISAKMP_PAYLOAD_MAX; i++)
1221 		TAILQ_FOREACH(p, &msg->payload[i], link) {
1222 			LOG_DBG((LOG_MESSAGE, 60, "message_validate_payloads: "
1223 			    "payload %s at %p of message %p",
1224 			    constant_name(isakmp_payload_cst, i), p->p, msg));
1225 			if ((f = message_get_field(i)) != NULL)
1226 				field_dump_payload(f, p->p);
1227 			if (message_validate_payload(msg, p, i))
1228 				return -1;
1229 		}
1230 	return 0;
1231 }
1232 
1233 /*
1234  * All incoming messages go through here.  We do generic validity checks
1235  * and try to find or establish SAs.  Last but not least we try to find
1236  * the exchange this message, MSG, is part of, and feed it there.
1237  */
1238 int
1239 message_recv(struct message *msg)
1240 {
1241 	u_int8_t       *buf = msg->iov[0].iov_base;
1242 	size_t          sz = msg->iov[0].iov_len;
1243 	u_int8_t        exch_type;
1244 	int             setup_isakmp_sa, msgid_is_zero;
1245 	u_int8_t        flags;
1246 	struct keystate *ks = 0;
1247 	struct proto    tmp_proto;
1248 	struct sa       tmp_sa;
1249 	struct transport *t;
1250 
1251 	/* Messages shorter than an ISAKMP header are bad.  */
1252 	if (sz < ISAKMP_HDR_SZ || sz != GET_ISAKMP_HDR_LENGTH(buf)) {
1253 		log_print("message_recv: bad message length");
1254 		message_drop(msg, 0, 0, 1, 1);
1255 		return -1;
1256 	}
1257 	/* Possibly dump a raw hex image of the message to the log channel.  */
1258 	message_dump_raw("message_recv", msg, LOG_MESSAGE);
1259 
1260 	/*
1261 	 * If the responder cookie is zero, this is a request to setup an
1262 	 * ISAKMP SA.  Otherwise the cookies should refer to an existing
1263 	 * ISAKMP SA.
1264 	 *
1265 	 * XXX This is getting ugly, please reread later to see if it can be
1266 	 * made nicer.
1267 	 */
1268 	setup_isakmp_sa = zero_test(buf + ISAKMP_HDR_RCOOKIE_OFF,
1269 	    ISAKMP_HDR_RCOOKIE_LEN);
1270 	if (setup_isakmp_sa) {
1271 		/*
1272 		 * This might be a retransmission of a former ISAKMP SA setup
1273 		 * message.  If so, just drop it.
1274 		 * XXX Must we really look in both the SA and exchange pools?
1275 		 */
1276 		if (exchange_lookup_from_icookie(buf + ISAKMP_HDR_ICOOKIE_OFF) ||
1277 		    sa_lookup_from_icookie(buf + ISAKMP_HDR_ICOOKIE_OFF)) {
1278 			/*
1279 			 * XXX Later we should differentiate between
1280 			 * retransmissions and potential replay attacks.
1281 			 */
1282 			LOG_DBG((LOG_MESSAGE, 90,
1283 			    "message_recv: dropping setup for existing SA"));
1284 			message_free(msg);
1285 			return -1;
1286 		}
1287 	} else {
1288 		msg->isakmp_sa = sa_lookup_by_header(buf, 0);
1289 		if (msg->isakmp_sa)
1290 			sa_reference(msg->isakmp_sa);
1291 
1292 		/*
1293 		 * If we cannot find an ISAKMP SA out of the cookies, this is
1294 		 * either a responder's first reply, and we need to upgrade
1295 		 * our exchange, or it's just plain invalid cookies.
1296 		 */
1297 		if (!msg->isakmp_sa) {
1298 			msg->exchange = exchange_lookup_from_icookie(buf +
1299 			    ISAKMP_HDR_ICOOKIE_OFF);
1300 			if (msg->exchange && msg->exchange->phase == 1 &&
1301 			    zero_test(msg->exchange->cookies +
1302 			    ISAKMP_HDR_RCOOKIE_OFF, ISAKMP_HDR_RCOOKIE_LEN))
1303 				exchange_upgrade_p1(msg);
1304 			else {
1305 				log_print("message_recv: invalid cookie(s) "
1306 				    "%08x%08x %08x%08x",
1307 				    decode_32(buf + ISAKMP_HDR_ICOOKIE_OFF),
1308 				decode_32(buf + ISAKMP_HDR_ICOOKIE_OFF + 4),
1309 				    decode_32(buf + ISAKMP_HDR_RCOOKIE_OFF),
1310 				decode_32(buf + ISAKMP_HDR_RCOOKIE_OFF + 4));
1311 				tmp_proto.sa = &tmp_sa;
1312 				tmp_sa.doi = doi_lookup(ISAKMP_DOI_ISAKMP);
1313 				tmp_proto.proto = ISAKMP_PROTO_ISAKMP;
1314 				tmp_proto.spi_sz[1] = ISAKMP_HDR_COOKIES_LEN;
1315 				tmp_proto.spi[1] =
1316 				    buf + ISAKMP_HDR_COOKIES_OFF;
1317 				message_drop(msg, ISAKMP_NOTIFY_INVALID_COOKIE,
1318 				    &tmp_proto, 1, 1);
1319 				return -1;
1320 			}
1321 #if 0
1322 			msg->isakmp_sa = sa_lookup_from_icookie(buf +
1323 			    ISAKMP_HDR_ICOOKIE_OFF);
1324 			if (msg->isakmp_sa)
1325 				sa_isakmp_upgrade(msg);
1326 #endif
1327 		}
1328 		msg->exchange = exchange_lookup(buf, 1);
1329 	}
1330 
1331 	if (message_check_duplicate(msg))
1332 		return -1;
1333 
1334 	if (GET_ISAKMP_HDR_NEXT_PAYLOAD(buf) >= ISAKMP_PAYLOAD_RESERVED_MIN) {
1335 		log_print("message_recv: invalid payload type %d in ISAKMP "
1336 		    "header (check passphrases, if applicable and in Phase 1)",
1337 		    GET_ISAKMP_HDR_NEXT_PAYLOAD(buf));
1338 		message_drop(msg, ISAKMP_NOTIFY_INVALID_PAYLOAD_TYPE, 0, 1, 1);
1339 		return -1;
1340 	}
1341 	/* Validate that the message is of version 1.0.  */
1342 	if (ISAKMP_VERSION_MAJOR(GET_ISAKMP_HDR_VERSION(buf)) != 1) {
1343 		log_print("message_recv: invalid version major %d",
1344 		    ISAKMP_VERSION_MAJOR(GET_ISAKMP_HDR_VERSION(buf)));
1345 		message_drop(msg, ISAKMP_NOTIFY_INVALID_MAJOR_VERSION, 0, 1,
1346 		    1);
1347 		return -1;
1348 	}
1349 	if (ISAKMP_VERSION_MINOR(GET_ISAKMP_HDR_VERSION(buf)) != 0) {
1350 		log_print("message_recv: invalid version minor %d",
1351 		    ISAKMP_VERSION_MINOR(GET_ISAKMP_HDR_VERSION(buf)));
1352 		message_drop(msg, ISAKMP_NOTIFY_INVALID_MINOR_VERSION, 0, 1,
1353 		    1);
1354 		return -1;
1355 	}
1356 	/*
1357 	 * Validate the exchange type.  If it's a DOI-specified exchange wait
1358 	 * until after all payloads have been seen for the validation as the
1359 	 * SA payload might not yet have been parsed, thus the DOI might be
1360 	 * unknown.
1361 	 */
1362 	exch_type = GET_ISAKMP_HDR_EXCH_TYPE(buf);
1363 	if (exch_type == ISAKMP_EXCH_NONE ||
1364 	    (exch_type >= ISAKMP_EXCH_FUTURE_MIN &&
1365 	    exch_type <= ISAKMP_EXCH_FUTURE_MAX) ||
1366 	    (setup_isakmp_sa && exch_type >= ISAKMP_EXCH_DOI_MIN)) {
1367 		log_print("message_recv: invalid exchange type %s",
1368 		    constant_name(isakmp_exch_cst, exch_type));
1369 		message_drop(msg, ISAKMP_NOTIFY_INVALID_EXCHANGE_TYPE, 0, 1,
1370 		    1);
1371 		return -1;
1372 	}
1373 	/*
1374 	 * Check for unrecognized flags, or the encryption flag when we don't
1375 	 * have an ISAKMP SA to decrypt with.
1376 	 */
1377 	flags = GET_ISAKMP_HDR_FLAGS(buf);
1378 	if (flags & ~(ISAKMP_FLAGS_ENC | ISAKMP_FLAGS_COMMIT |
1379 	    ISAKMP_FLAGS_AUTH_ONLY)) {
1380 		log_print("message_recv: invalid flags 0x%x",
1381 		    GET_ISAKMP_HDR_FLAGS(buf));
1382 		message_drop(msg, ISAKMP_NOTIFY_INVALID_FLAGS, 0, 1, 1);
1383 		return -1;
1384 	}
1385 	/*
1386 	 * If we are about to setup an ISAKMP SA, the message ID must be
1387 	 * zero.
1388 	 */
1389 	msgid_is_zero = zero_test(buf + ISAKMP_HDR_MESSAGE_ID_OFF,
1390 	    ISAKMP_HDR_MESSAGE_ID_LEN);
1391 	if (setup_isakmp_sa && !msgid_is_zero) {
1392 		log_print("message_recv: invalid message id");
1393 		message_drop(msg, ISAKMP_NOTIFY_INVALID_MESSAGE_ID, 0, 1, 1);
1394 		return -1;
1395 	}
1396 	if (!setup_isakmp_sa && msgid_is_zero) {
1397 		/*
1398 		 * XXX Very likely redundant, look at the  else clause of the
1399 		 * if (setup_isakmp_sa) statement above.
1400 		 */
1401 		msg->exchange = exchange_lookup(buf, 0);
1402 		if (!msg->exchange) {
1403 			log_print("message_recv: phase 1 message after "
1404 			    "ISAKMP SA is ready");
1405 			message_free(msg);
1406 			return -1;
1407 		} else if (msg->exchange->last_sent) {
1408 			LOG_DBG((LOG_MESSAGE, 80, "message_recv: resending "
1409 			    "last message from phase 1"));
1410 			message_send(msg->exchange->last_sent);
1411 		}
1412 	}
1413 	if (flags & ISAKMP_FLAGS_ENC) {
1414 		if (!msg->isakmp_sa) {
1415 			LOG_DBG((LOG_MISC, 10, "message_recv: no isakmp_sa "
1416 			    "for encrypted message"));
1417 			message_free(msg);
1418 			return -1;
1419 		}
1420 		/* Decrypt rest of message using a DOI-specified IV.  */
1421 		ks = msg->isakmp_sa->doi->get_keystate(msg);
1422 		if (!ks) {
1423 			message_free(msg);
1424 			return -1;
1425 		}
1426 		msg->orig = malloc(sz);
1427 		if (!msg->orig) {
1428 			message_free(msg);
1429 			free(ks);
1430 			return -1;
1431 		}
1432 		memcpy(msg->orig, buf, sz);
1433 		crypto_decrypt(ks, buf + ISAKMP_HDR_SZ, sz - ISAKMP_HDR_SZ);
1434 	} else
1435 		msg->orig = buf;
1436 	msg->orig_sz = sz;
1437 
1438 	/* IKE packet capture */
1439 	message_packet_log(msg);
1440 
1441 	/*
1442 	 * Check the overall payload structure at the same time as indexing
1443 	 * them by type.
1444 	 */
1445 	if (GET_ISAKMP_HDR_NEXT_PAYLOAD(buf) != ISAKMP_PAYLOAD_NONE &&
1446 	    message_sort_payloads(msg, GET_ISAKMP_HDR_NEXT_PAYLOAD(buf))) {
1447 		free(ks);
1448 		return -1;
1449 	}
1450 	/*
1451 	 * Run generic payload tests now.  If anything fails these checks, the
1452 	 * message needs either to be retained for later duplicate checks or
1453 	 * freed entirely.
1454 	 * XXX Should SAs and even transports be cleaned up then too?
1455 	 */
1456 	if (message_validate_payloads(msg)) {
1457 		free(ks);
1458 		return -1;
1459 	}
1460 	/*
1461 	 * If we have not found an exchange by now something is definitely
1462 	 * wrong.
1463 	 */
1464 	if (!msg->exchange) {
1465 		log_print("message_recv: no exchange");
1466 		message_drop(msg, ISAKMP_NOTIFY_PAYLOAD_MALFORMED, 0, 1, 1);
1467 		free(ks);
1468 		return -1;
1469 	}
1470 	/*
1471 	 * NAT-T may have switched ports for us. We need to replace the
1472 	 * old ISAKMP SA transport here with one that contains the proper
1473 	 * (i.e translated) ports.
1474 	 */
1475 	if (msg->isakmp_sa && msg->exchange->phase == 1) {
1476 		t = msg->isakmp_sa->transport;
1477 		msg->isakmp_sa->transport = msg->transport;
1478 		transport_reference(msg->transport);
1479 		transport_release(t);
1480 	}
1481 
1482 	/*
1483 	 * Now we can validate DOI-specific exchange types.  If we have no SA
1484 	 * DOI-specific exchange types are definitely wrong.
1485 	 */
1486 	if (exch_type >= ISAKMP_EXCH_DOI_MIN &&
1487 	    msg->exchange->doi->validate_exchange(exch_type)) {
1488 		log_print("message_recv: invalid DOI exchange type %d",
1489 		    exch_type);
1490 		message_drop(msg, ISAKMP_NOTIFY_INVALID_EXCHANGE_TYPE, 0, 1,
1491 		    1);
1492 		free(ks);
1493 		return -1;
1494 	}
1495 	/* Make sure the IV we used gets saved in the proper SA.  */
1496 	if (ks) {
1497 		if (!msg->exchange->keystate) {
1498 			msg->exchange->keystate = ks;
1499 			msg->exchange->crypto = ks->xf;
1500 		} else
1501 			free(ks);
1502 	}
1503 	/* Handle the flags.  */
1504 	if (flags & ISAKMP_FLAGS_ENC)
1505 		msg->exchange->flags |= EXCHANGE_FLAG_ENCRYPT;
1506 	if ((msg->exchange->flags & EXCHANGE_FLAG_COMMITTED) == 0 &&
1507 	    (flags & ISAKMP_FLAGS_COMMIT))
1508 		msg->exchange->flags |= EXCHANGE_FLAG_HE_COMMITTED;
1509 
1510 	/*
1511 	 * Except for the 3rd Aggressive Mode message, require encryption
1512 	 * as soon as we have the keystate for it.
1513 	 */
1514 	if ((flags & ISAKMP_FLAGS_ENC) == 0 &&
1515 	    (msg->exchange->phase == 2 ||
1516 		(msg->exchange->keystate &&
1517 		    msg->exchange->type != ISAKMP_EXCH_AGGRESSIVE))) {
1518 		log_print("message_recv: cleartext phase %d message",
1519 		    msg->exchange->phase);
1520 		message_drop(msg, ISAKMP_NOTIFY_INVALID_FLAGS, 0, 1, 1);
1521 		return -1;
1522 	}
1523 
1524 	/* OK let the exchange logic do the rest.  */
1525 	exchange_run(msg);
1526 
1527 	return 0;
1528 }
1529 
1530 void
1531 message_send_expire(struct message *msg)
1532 {
1533 	msg->retrans = 0;
1534 
1535 	message_send(msg);
1536 }
1537 
1538 /* Queue up message MSG for transmittal.  */
1539 void
1540 message_send(struct message *msg)
1541 {
1542 	struct exchange *exchange = msg->exchange;
1543 	struct message *m;
1544 	struct msg_head *q;
1545 
1546 	/* Remove retransmissions on this message  */
1547 	if (msg->retrans) {
1548 		timer_remove_event(msg->retrans);
1549 		msg->retrans = 0;
1550 	}
1551 	/* IKE packet capture */
1552 	message_packet_log(msg);
1553 
1554 	/*
1555 	 * If the ISAKMP SA has set up encryption, encrypt the message.
1556 	 * However, in a retransmit, it is already encrypted.
1557 	 */
1558 	if ((msg->flags & MSG_ENCRYPTED) == 0 &&
1559 	    exchange->flags & EXCHANGE_FLAG_ENCRYPT) {
1560 		if (!exchange->keystate) {
1561 			exchange->keystate = exchange->doi->get_keystate(msg);
1562 			if (!exchange->keystate)
1563 				return;
1564 			exchange->crypto = exchange->keystate->xf;
1565 			exchange->flags |= EXCHANGE_FLAG_ENCRYPT;
1566 		}
1567 		if (message_encrypt(msg)) {
1568 			/* XXX Log.  */
1569 			return;
1570 		}
1571 	}
1572 	/* Keep the COMMIT bit on.  */
1573 	if (exchange->flags & EXCHANGE_FLAG_COMMITTED)
1574 		SET_ISAKMP_HDR_FLAGS(msg->iov[0].iov_base,
1575 		    GET_ISAKMP_HDR_FLAGS(msg->iov[0].iov_base)
1576 		    | ISAKMP_FLAGS_COMMIT);
1577 
1578 	message_dump_raw("message_send", msg, LOG_MESSAGE);
1579 	msg->flags |= MSG_IN_TRANSIT;
1580 	exchange->in_transit = msg;
1581 
1582 	/*
1583 	 * If we get a retransmission of a message before our response
1584 	 * has left the queue, don't queue it again, as it will result
1585 	 * in a circular list.
1586 	 */
1587 	q = msg->transport->vtbl->get_queue(msg);
1588 	for (m = TAILQ_FIRST(q); m; m = TAILQ_NEXT(m, link))
1589 		if (m == msg) {
1590 			LOG_DBG((LOG_MESSAGE, 60,
1591 			    "message_send: msg %p already on sendq %p", m, q));
1592 			return;
1593 		}
1594 	TAILQ_INSERT_TAIL(q, msg, link);
1595 }
1596 
1597 /*
1598  * Setup the ISAKMP message header for message MSG.  EXCHANGE is the exchange
1599  * type, FLAGS are the ISAKMP header flags and MSG_ID is message ID
1600  * identifying the exchange.
1601  */
1602 void
1603 message_setup_header(struct message *msg, u_int8_t exchange, u_int8_t flags,
1604     u_int8_t *msg_id)
1605 {
1606 	u_int8_t	*buf = msg->iov[0].iov_base;
1607 
1608 	SET_ISAKMP_HDR_ICOOKIE(buf, msg->exchange->cookies);
1609 	SET_ISAKMP_HDR_RCOOKIE(buf, msg->exchange->cookies +
1610 	    ISAKMP_HDR_ICOOKIE_LEN);
1611 	SET_ISAKMP_HDR_NEXT_PAYLOAD(buf, ISAKMP_PAYLOAD_NONE);
1612 	SET_ISAKMP_HDR_VERSION(buf, ISAKMP_VERSION_MAKE(1, 0));
1613 	SET_ISAKMP_HDR_EXCH_TYPE(buf, exchange);
1614 	SET_ISAKMP_HDR_FLAGS(buf, flags);
1615 	SET_ISAKMP_HDR_MESSAGE_ID(buf, msg_id);
1616 	SET_ISAKMP_HDR_LENGTH(buf, msg->iov[0].iov_len);
1617 }
1618 
1619 /*
1620  * Add the payload of type PAYLOAD in BUF sized SZ to the MSG message.
1621  * The caller thereby is released from the responsibility of freeing BUF,
1622  * unless we return a failure of course.  If LINK is set the former
1623  * payload's "next payload" field to PAYLOAD.
1624  *
1625  * XXX We might want to resize the iov array several slots at a time.
1626  */
1627 int
1628 message_add_payload(struct message *msg, u_int8_t payload, u_int8_t *buf,
1629     size_t sz, int link)
1630 {
1631 	struct iovec   *new_iov;
1632 	struct payload *payload_node;
1633 
1634 	payload_node = calloc(1, sizeof *payload_node);
1635 	if (!payload_node) {
1636 		log_error("message_add_payload: calloc (1, %lu) failed",
1637 		    (unsigned long)sizeof *payload_node);
1638 		return -1;
1639 	}
1640 	new_iov = reallocarray(msg->iov, msg->iovlen + 1,
1641 	    sizeof *msg->iov);
1642 	if (!new_iov) {
1643 		log_error("message_add_payload: realloc (%p, %lu) failed",
1644 		    msg->iov, (msg->iovlen + 1) *
1645 		    (unsigned long)sizeof *msg->iov);
1646 		free(payload_node);
1647 		return -1;
1648 	}
1649 	msg->iov = new_iov;
1650 	new_iov[msg->iovlen].iov_base = buf;
1651 	new_iov[msg->iovlen].iov_len = sz;
1652 	msg->iovlen++;
1653 	if (link)
1654 		*msg->nextp = payload;
1655 	msg->nextp = buf + ISAKMP_GEN_NEXT_PAYLOAD_OFF;
1656 	*msg->nextp = ISAKMP_PAYLOAD_NONE;
1657 	SET_ISAKMP_GEN_RESERVED(buf, 0);
1658 	SET_ISAKMP_GEN_LENGTH(buf, sz);
1659 	SET_ISAKMP_HDR_LENGTH(msg->iov[0].iov_base,
1660 	    GET_ISAKMP_HDR_LENGTH(msg->iov[0].iov_base) + sz);
1661 
1662 	/*
1663 	 * For the sake of exchange_validate we index the payloads even in
1664 	 * outgoing messages, however context and flags are uninteresting in
1665 	 * this situation.
1666 	 */
1667 	payload_node->p = buf;
1668 	TAILQ_INSERT_TAIL(&msg->payload[payload], payload_node, link);
1669 	return 0;
1670 }
1671 
1672 /* XXX Move up when ready.  */
1673 struct info_args {
1674 	char            discr;
1675 	u_int32_t       doi;
1676 	u_int8_t        proto;
1677 	u_int16_t       spi_sz;
1678 	union {
1679 		struct {
1680 			u_int16_t       msg_type;
1681 			u_int8_t       *spi;
1682 		} n;
1683 		struct {
1684 			u_int16_t       nspis;
1685 			u_int8_t       *spis;
1686 		} d;
1687 		struct {
1688 			u_int16_t	msg_type;
1689 			u_int8_t	*spi;
1690 			u_int32_t	seq;
1691 		} dpd;
1692 	} u;
1693 };
1694 
1695 /*
1696  * As a reaction to the incoming message MSG create an informational exchange
1697  * protected by ISAKMP_SA and send a notify payload of type NOTIFY, with
1698  * fields initialized from SA.  INCOMING is true if the SPI field should be
1699  * filled with the incoming SPI and false if it is to be filled with the
1700  * outgoing one.
1701  *
1702  * XXX Should we handle sending multiple notify payloads?  The draft allows
1703  * it, but do we need it?  Furthermore, should we not return a success
1704  * status value?
1705  */
1706 void
1707 message_send_notification(struct message *msg, struct sa *isakmp_sa,
1708     u_int16_t notify, struct proto *proto, int incoming)
1709 {
1710 	struct info_args args;
1711 	struct sa      *doi_sa = proto ? proto->sa : isakmp_sa;
1712 
1713 	args.discr = 'N';
1714 	args.doi = doi_sa ? doi_sa->doi->id : ISAKMP_DOI_ISAKMP;
1715 	args.proto = proto ? proto->proto : ISAKMP_PROTO_ISAKMP;
1716 	args.spi_sz = proto ? proto->spi_sz[incoming] : 0;
1717 	args.u.n.msg_type = notify;
1718 	args.u.n.spi = proto ? proto->spi[incoming] : 0;
1719 	if (isakmp_sa && (isakmp_sa->flags & SA_FLAG_READY))
1720 		exchange_establish_p2(isakmp_sa, ISAKMP_EXCH_INFO, 0, &args,
1721 		    0, 0);
1722 	else
1723 		exchange_establish_p1(msg->transport, ISAKMP_EXCH_INFO,
1724 		    msg->exchange ? msg->exchange->doi->id : ISAKMP_DOI_ISAKMP,
1725 		    0, &args, 0, 0, 0);
1726 }
1727 
1728 /* Send a DELETE inside an informational exchange for each protocol in SA.  */
1729 void
1730 message_send_delete(struct sa *sa)
1731 {
1732 	struct info_args args;
1733 	struct proto   *proto;
1734 	struct sa      *isakmp_sa;
1735 	struct sockaddr *dst;
1736 
1737 	if (!sa->transport)
1738 		return;
1739 
1740 	sa->transport->vtbl->get_dst(sa->transport, &dst);
1741 	isakmp_sa = sa_isakmp_lookup_by_peer(dst, SA_LEN(dst));
1742 	if (!isakmp_sa) {
1743 		/*
1744 		 * XXX We ought to setup an ISAKMP SA with our peer here and
1745 		 * send the DELETE over that one.
1746 		 */
1747 		return;
1748 	}
1749 	args.discr = 'D';
1750 	args.doi = sa->doi->id;
1751 	args.u.d.nspis = 1;
1752 	for (proto = TAILQ_FIRST(&sa->protos); proto;
1753 	    proto = TAILQ_NEXT(proto, link)) {
1754 		switch (proto->proto) {
1755 		case ISAKMP_PROTO_ISAKMP:
1756 			args.spi_sz = ISAKMP_HDR_COOKIES_LEN;
1757 			args.u.d.spis = sa->cookies;
1758 			break;
1759 
1760 		case IPSEC_PROTO_IPSEC_AH:
1761 		case IPSEC_PROTO_IPSEC_ESP:
1762 		case IPSEC_PROTO_IPCOMP:
1763 			args.spi_sz = proto->spi_sz[1];
1764 			args.u.d.spis = proto->spi[1];
1765 			break;
1766 		default:
1767 			log_print("message_send_delete: cannot delete unknown "
1768 			    "protocol %d", proto->proto);
1769 			continue;
1770 		}
1771 
1772 		args.proto = proto->proto;
1773 		exchange_establish_p2(isakmp_sa, ISAKMP_EXCH_INFO, 0, &args,
1774 		    0, 0);
1775 	}
1776 }
1777 
1778 void
1779 message_send_dpd_notify(struct sa* isakmp_sa, u_int16_t notify, u_int32_t seq)
1780 {
1781 	struct info_args args;
1782 
1783 	args.discr = 'P';
1784 	args.doi = IPSEC_DOI_IPSEC;
1785 	args.proto = ISAKMP_PROTO_ISAKMP;
1786 	args.spi_sz = ISAKMP_HDR_COOKIES_LEN;
1787 	args.u.dpd.msg_type = notify;
1788 	args.u.dpd.spi = isakmp_sa->cookies;
1789 	args.u.dpd.seq = htonl(seq);
1790 
1791 	exchange_establish_p2(isakmp_sa, ISAKMP_EXCH_INFO, 0, &args, 0, 0);
1792 }
1793 
1794 /* Build the informational message into MSG.  */
1795 int
1796 message_send_info(struct message *msg)
1797 {
1798 	u_int8_t       *buf;
1799 	size_t          sz = 0;
1800 	struct info_args *args = msg->extra;
1801 	u_int8_t	payload;
1802 
1803 	/* Let the DOI get the first hand on the message.  */
1804 	if (msg->exchange->doi->informational_pre_hook)
1805 		if (msg->exchange->doi->informational_pre_hook(msg))
1806 			return -1;
1807 
1808 	switch (args->discr) {
1809 	case 'P':
1810 		sz = sizeof args->u.dpd.seq;
1811 		/* FALLTHROUGH */
1812 	case 'N':
1813 		sz += ISAKMP_NOTIFY_SPI_OFF + args->spi_sz;
1814 		break;
1815 	case 'D':
1816 	default:	/* Silence gcc */
1817 		sz = ISAKMP_DELETE_SPI_OFF + args->u.d.nspis * args->spi_sz;
1818 		break;
1819 	}
1820 
1821 	buf = calloc(1, sz);
1822 	if (!buf) {
1823 		log_error("message_send_info: calloc (1, %lu) failed",
1824 		    (unsigned long)sz);
1825 		message_free(msg);
1826 		return -1;
1827 	}
1828 	switch (args->discr) {
1829 	case 'P':
1830 		memcpy(buf + ISAKMP_NOTIFY_SPI_OFF + args->spi_sz,
1831 		    &args->u.dpd.seq, sizeof args->u.dpd.seq);
1832 		/* FALLTHROUGH */
1833 	case 'N':
1834 		/* Build the NOTIFY payload.  */
1835 		payload = ISAKMP_PAYLOAD_NOTIFY;
1836 		SET_ISAKMP_NOTIFY_DOI(buf, args->doi);
1837 		SET_ISAKMP_NOTIFY_PROTO(buf, args->proto);
1838 		SET_ISAKMP_NOTIFY_SPI_SZ(buf, args->spi_sz);
1839 		SET_ISAKMP_NOTIFY_MSG_TYPE(buf, args->u.n.msg_type);
1840 		memcpy(buf + ISAKMP_NOTIFY_SPI_OFF, args->u.n.spi,
1841 		    args->spi_sz);
1842 		break;
1843 
1844 	case 'D':
1845 	default:		/* Silence GCC.  */
1846 		/* Build the DELETE payload.  */
1847 		payload = ISAKMP_PAYLOAD_DELETE;
1848 		SET_ISAKMP_DELETE_DOI(buf, args->doi);
1849 		SET_ISAKMP_DELETE_PROTO(buf, args->proto);
1850 		SET_ISAKMP_DELETE_SPI_SZ(buf, args->spi_sz);
1851 		SET_ISAKMP_DELETE_NSPIS(buf, args->u.d.nspis);
1852 		memcpy(buf + ISAKMP_DELETE_SPI_OFF, args->u.d.spis,
1853 		    args->u.d.nspis * args->spi_sz);
1854 		msg->flags |= MSG_PRIORITIZED;
1855 		break;
1856 	}
1857 
1858 	if (message_add_payload(msg, payload, buf, sz, 1)) {
1859 		free(buf);
1860 		message_free(msg);
1861 		return -1;
1862 	}
1863 	/* Let the DOI get the last hand on the message.  */
1864 	if (msg->exchange->doi->informational_post_hook)
1865 		if (msg->exchange->doi->informational_post_hook(msg)) {
1866 			message_free(msg);
1867 			return -1;
1868 		}
1869 	return 0;
1870 }
1871 
1872 /*
1873  * Drop the MSG message due to reason given in NOTIFY.  If NOTIFY is set
1874  * send out a notification to the originator.  Fill this notification with
1875  * values from PROTO.  INCOMING decides which SPI to include.  If CLEAN is
1876  * set, free the message when ready with it.
1877  */
1878 void
1879 message_drop(struct message *msg, int notify, struct proto *proto,
1880     int incoming, int clean)
1881 {
1882 	struct transport *t = msg->transport;
1883 	struct sockaddr *dst;
1884 	char           *address;
1885 	short           port = 0;
1886 
1887 	t->vtbl->get_dst(t, &dst);
1888 	if (sockaddr2text(dst, &address, 0)) {
1889 		log_error("message_drop: sockaddr2text () failed");
1890 		address = 0;
1891 	}
1892 	switch (dst->sa_family) {
1893 	case AF_INET:
1894 		port = ((struct sockaddr_in *)dst)->sin_port;
1895 		break;
1896 	case AF_INET6:
1897 		port = ((struct sockaddr_in6 *)dst)->sin6_port;
1898 		break;
1899 	default:
1900 		log_print("message_drop: unknown protocol family %d",
1901 		    dst->sa_family);
1902 	}
1903 
1904 	log_print("dropped message from %s port %d due to notification type "
1905 	    "%s", address ? address : "<unknown>", htons(port),
1906 	    constant_name(isakmp_notify_cst, notify));
1907 
1908 	free(address);
1909 
1910 	/* If specified, return a notification.  */
1911 	if (notify)
1912 		message_send_notification(msg, msg->isakmp_sa, notify, proto,
1913 		    incoming);
1914 	if (clean)
1915 		message_free(msg);
1916 }
1917 
1918 /*
1919  * If the user demands debug printouts, printout MSG with as much detail
1920  * as we can without resorting to per-payload handling.
1921  */
1922 void
1923 message_dump_raw(char *header, struct message *msg, int class)
1924 {
1925 	u_int32_t	i, j, k = 0;
1926 	char            buf[80], *p = buf;
1927 
1928 	LOG_DBG((class, 70, "%s: message %p", header, msg));
1929 	field_dump_payload(isakmp_hdr_fld, msg->iov[0].iov_base);
1930 	for (i = 0; i < msg->iovlen; i++)
1931 		for (j = 0; j < msg->iov[i].iov_len; j++) {
1932 			snprintf(p, sizeof buf - (int) (p - buf), "%02x",
1933 			    ((u_int8_t *) msg->iov[i].iov_base)[j]);
1934 			p += strlen(p);
1935 			if (++k % 32 == 0) {
1936 				*p = '\0';
1937 				LOG_DBG((class, 70, "%s: %s", header, buf));
1938 				p = buf;
1939 			} else if (k % 4 == 0)
1940 				*p++ = ' ';
1941 		}
1942 	*p = '\0';
1943 	if (p != buf)
1944 		LOG_DBG((class, 70, "%s: %s", header, buf));
1945 }
1946 
1947 static void
1948 message_packet_log(struct message *msg)
1949 {
1950 	struct sockaddr *src, *dst;
1951 	struct transport *t = msg->transport;
1952 
1953 	/* Don't log retransmissions. Redundant for incoming packets... */
1954 	if (msg->xmits > 0)
1955 		return;
1956 
1957 	if (msg->exchange && msg->exchange->flags & EXCHANGE_FLAG_NAT_T_ENABLE)
1958 		t = ((struct virtual_transport *)msg->transport)->encap;
1959 
1960 	/* Figure out direction. */
1961 	if (msg->exchange &&
1962 	    msg->exchange->initiator ^ (msg->exchange->step % 2)) {
1963 		t->vtbl->get_src(t, &src);
1964 		t->vtbl->get_dst(t, &dst);
1965 	} else {
1966 		t->vtbl->get_src(t, &dst);
1967 		t->vtbl->get_dst(t, &src);
1968 	}
1969 
1970 	log_packet_iov(src, dst, msg->iov, msg->iovlen);
1971 }
1972 
1973 /*
1974  * Encrypt an outgoing message MSG.  As outgoing messages are represented
1975  * with an iovec with one segment per payload, we need to coalesce them
1976  * into just une buffer containing all payloads and some padding before
1977  * we encrypt.
1978  */
1979 static int
1980 message_encrypt(struct message *msg)
1981 {
1982 	struct exchange *exchange = msg->exchange;
1983 	size_t          i, sz = 0;
1984 	u_int8_t       *buf;
1985 
1986 	/* If no payloads, nothing to do.  */
1987 	if (msg->iovlen == 1)
1988 		return 0;
1989 
1990 	/*
1991 	 * For encryption we need to put all payloads together in a single
1992 	 * buffer.  This buffer should be padded to the current crypto
1993 	 * transform's blocksize.
1994 	 */
1995 	for (i = 1; i < msg->iovlen; i++)
1996 		sz += msg->iov[i].iov_len;
1997 	sz = ((sz + exchange->crypto->blocksize - 1) /
1998 	    exchange->crypto->blocksize) * exchange->crypto->blocksize;
1999 	buf = realloc(msg->iov[1].iov_base, sz);
2000 	if (!buf) {
2001 		log_error("message_encrypt: realloc (%p, %lu) failed",
2002 		    msg->iov[1].iov_base, (unsigned long) sz);
2003 		return -1;
2004 	}
2005 	msg->iov[1].iov_base = buf;
2006 	for (i = 2; i < msg->iovlen; i++) {
2007 		memcpy(buf + msg->iov[1].iov_len, msg->iov[i].iov_base,
2008 		    msg->iov[i].iov_len);
2009 		msg->iov[1].iov_len += msg->iov[i].iov_len;
2010 		free(msg->iov[i].iov_base);
2011 	}
2012 
2013 	/* Pad with zeroes.  */
2014 	memset(buf + msg->iov[1].iov_len, '\0', sz - msg->iov[1].iov_len);
2015 	msg->iov[1].iov_len = sz;
2016 	msg->iovlen = 2;
2017 
2018 	SET_ISAKMP_HDR_FLAGS(msg->iov[0].iov_base,
2019 	    GET_ISAKMP_HDR_FLAGS(msg->iov[0].iov_base) | ISAKMP_FLAGS_ENC);
2020 	SET_ISAKMP_HDR_LENGTH(msg->iov[0].iov_base, ISAKMP_HDR_SZ + sz);
2021 	crypto_encrypt(exchange->keystate, buf, msg->iov[1].iov_len);
2022 	msg->flags |= MSG_ENCRYPTED;
2023 
2024 	/* Update the IV so we can decrypt the next incoming message.  */
2025 	crypto_update_iv(exchange->keystate);
2026 
2027 	return 0;
2028 }
2029 
2030 /*
2031  * Check whether the message MSG is a duplicate of the last one negotiating
2032  * this specific SA.
2033  */
2034 static int
2035 message_check_duplicate(struct message *msg)
2036 {
2037 	struct exchange *exchange = msg->exchange;
2038 	size_t          sz = msg->iov[0].iov_len;
2039 	u_int8_t       *pkt = msg->iov[0].iov_base;
2040 
2041 	/* If no SA has been found, we cannot test, thus it's good.  */
2042 	if (!exchange)
2043 		return 0;
2044 
2045 	LOG_DBG((LOG_MESSAGE, 90, "message_check_duplicate: last_received %p",
2046 	    exchange->last_received));
2047 	if (exchange->last_received) {
2048 		LOG_DBG_BUF((LOG_MESSAGE, 95,
2049 		    "message_check_duplicate: last_received",
2050 		    exchange->last_received->orig,
2051 		    exchange->last_received->orig_sz));
2052 		/* Is it a duplicate, lose the new one.  */
2053 		if (sz == exchange->last_received->orig_sz &&
2054 		    memcmp(pkt, exchange->last_received->orig, sz) == 0) {
2055 			LOG_DBG((LOG_MESSAGE, 80,
2056 			    "message_check_duplicate: dropping dup"));
2057 
2058 			/*
2059 			 * Retransmit if the previous sent message was the last
2060 			 * of an exchange, otherwise just wait for the
2061 			 * ordinary retransmission.
2062 			 */
2063 			if (exchange->last_sent && (exchange->last_sent->flags
2064 			    & MSG_LAST))
2065 				message_send(exchange->last_sent);
2066 			message_free(msg);
2067 			return -1;
2068 		}
2069 	}
2070 	/*
2071 	 * As this new message is an indication that state is moving forward
2072 	 * at the peer, remove the retransmit timer on our last message.
2073 	 */
2074 	if (exchange->last_sent) {
2075 		if (exchange->last_sent == exchange->in_transit) {
2076 			struct message *m = exchange->in_transit;
2077 			TAILQ_REMOVE(m->transport->vtbl->get_queue(m), m,
2078 			    link);
2079 			exchange->in_transit = 0;
2080 		}
2081 		message_free(exchange->last_sent);
2082 		exchange->last_sent = 0;
2083 	}
2084 	return 0;
2085 }
2086 
2087 /* Helper to message_negotiate_sa.  */
2088 static __inline struct payload *
2089 step_transform(struct payload *tp, struct payload **propp,
2090     struct payload **sap)
2091 {
2092 	tp = TAILQ_NEXT(tp, link);
2093 	if (tp) {
2094 		*propp = tp->context;
2095 		*sap = (*propp)->context;
2096 	}
2097 	return tp;
2098 }
2099 
2100 /*
2101  * Pick out the first transforms out of MSG (which should contain at least one
2102  * SA payload) we accept as a full protection suite.
2103  */
2104 int
2105 message_negotiate_sa(struct message *msg, int (*validate)(struct exchange *,
2106     struct sa *, struct sa *))
2107 {
2108 	struct payload *tp, *propp, *sap, *next_tp = 0, *next_propp, *next_sap;
2109 	struct payload *saved_tp = 0, *saved_propp = 0, *saved_sap = 0;
2110 	struct sa      *sa;
2111 	struct proto   *proto;
2112 	int             suite_ok_so_far = 0;
2113 	struct exchange *exchange = msg->exchange;
2114 
2115 	/*
2116 	 * This algorithm is a weird bottom-up thing... mostly due to the
2117 	 * payload links pointing upwards.
2118 	 *
2119 	 * The algorithm goes something like this:
2120 	 * Foreach transform
2121 	 *   If transform is compatible
2122 	 *     Remember that this protocol can work
2123 	 *     Skip to last transform of this protocol
2124 	 *   If next transform belongs to a new protocol inside the same suite
2125 	 *     If no transform was found for the current protocol
2126 	 *       Forget all earlier transforms for protocols in this suite
2127 	 *       Skip to last transform of this suite
2128 	 *   If next transform belongs to a new suite
2129 	 *     If the current protocol had an OK transform
2130 	 *       Skip to the last transform of this SA
2131 	 *   If the next transform belongs to a new SA
2132 	 *     If no transforms have been chosen
2133 	 *       Issue a NO_PROPOSAL_CHOSEN notification
2134 	 */
2135 
2136 	sa = TAILQ_FIRST(&exchange->sa_list);
2137 	for (tp = payload_first(msg, ISAKMP_PAYLOAD_TRANSFORM); tp;
2138 	    tp = next_tp) {
2139 		propp = tp->context;
2140 		sap = propp->context;
2141 		sap->flags |= PL_MARK;
2142 		next_tp = step_transform(tp, &next_propp, &next_sap);
2143 
2144 		/* For each transform, see if it is compatible.  */
2145 		if (!attribute_map(tp->p + ISAKMP_TRANSFORM_SA_ATTRS_OFF,
2146 		    GET_ISAKMP_GEN_LENGTH(tp->p) -
2147 		    ISAKMP_TRANSFORM_SA_ATTRS_OFF,
2148 		    exchange->doi->is_attribute_incompatible, msg)) {
2149 			LOG_DBG((LOG_NEGOTIATION, 30, "message_negotiate_sa: "
2150 			    "transform %d proto %d proposal %d ok",
2151 			    GET_ISAKMP_TRANSFORM_NO(tp->p),
2152 			    GET_ISAKMP_PROP_PROTO(propp->p),
2153 			    GET_ISAKMP_PROP_NO(propp->p)));
2154 			if (sa_add_transform(sa, tp, exchange->initiator,
2155 			    &proto))
2156 				goto cleanup;
2157 			suite_ok_so_far = 1;
2158 
2159 			saved_tp = next_tp;
2160 			saved_propp = next_propp;
2161 			saved_sap = next_sap;
2162 			/* Skip to last transform of this protocol proposal. */
2163 			while ((next_tp = step_transform(tp, &next_propp,
2164 			    &next_sap)) && next_propp == propp)
2165 				tp = next_tp;
2166 		}
2167 retry_transform:
2168 		/*
2169 		 * Figure out if we will be looking at a new protocol proposal
2170 		 * inside the current protection suite.
2171 		 */
2172 		if (next_tp && propp != next_propp && sap == next_sap &&
2173 		    (GET_ISAKMP_PROP_NO(propp->p) ==
2174 		    GET_ISAKMP_PROP_NO(next_propp->p))) {
2175 			if (!suite_ok_so_far) {
2176 				LOG_DBG((LOG_NEGOTIATION, 30,
2177 				    "message_negotiate_sa: proto %d proposal "
2178 				    "%d failed",
2179 				    GET_ISAKMP_PROP_PROTO(propp->p),
2180 				    GET_ISAKMP_PROP_NO(propp->p)));
2181 				/*
2182 				 * Remove potentially succeeded choices from
2183 				 * the SA.
2184 				 */
2185 				while ((proto = TAILQ_FIRST(&sa->protos)))
2186 					TAILQ_REMOVE(&sa->protos, proto, link);
2187 
2188 				/*
2189 				 * Skip to the last transform of this
2190 				 * protection suite.
2191 				 */
2192 				while ((next_tp = step_transform(tp,
2193 				    &next_propp, &next_sap)) &&
2194 				    (GET_ISAKMP_PROP_NO(next_propp->p) ==
2195 				    GET_ISAKMP_PROP_NO(propp->p)) &&
2196 				    next_sap == sap)
2197 					tp = next_tp;
2198 			}
2199 			suite_ok_so_far = 0;
2200 		}
2201 		/*
2202 		 * Figure out if we will be looking at a new protection
2203 		 * suite.
2204 		 */
2205 		if (!next_tp ||
2206 		    (propp != next_propp && (GET_ISAKMP_PROP_NO(propp->p) !=
2207 		    GET_ISAKMP_PROP_NO(next_propp->p))) ||
2208 		    sap != next_sap) {
2209 			/*
2210 			 * Check if the suite we just considered was OK, if so
2211 			 * we check it against the accepted ones.
2212 			 */
2213 			if (suite_ok_so_far) {
2214 				if (!validate || validate(exchange, sa,
2215 				    msg->isakmp_sa)) {
2216 					LOG_DBG((LOG_NEGOTIATION, 30,
2217 					    "message_negotiate_sa: proposal "
2218 					    "%d succeeded",
2219 					    GET_ISAKMP_PROP_NO(propp->p)));
2220 
2221 					/*
2222 					 * Skip to the last transform of this
2223 					 * SA.
2224 					 */
2225 					while ((next_tp = step_transform(tp,
2226 					    &next_propp, &next_sap)) &&
2227 					    next_sap == sap)
2228 						tp = next_tp;
2229 				} else {
2230 					/* Backtrack.  */
2231 					LOG_DBG((LOG_NEGOTIATION, 30,
2232 					    "message_negotiate_sa: proposal "
2233 					    "%d failed",
2234 					    GET_ISAKMP_PROP_NO(propp->p)));
2235 					next_tp = saved_tp;
2236 					next_propp = saved_propp;
2237 					next_sap = saved_sap;
2238 					suite_ok_so_far = 0;
2239 
2240 					/*
2241 					 * Remove potentially succeeded
2242 					 * choices from the SA.
2243 					 */
2244 					while ((proto =
2245 					    TAILQ_FIRST(&sa->protos)))
2246 						TAILQ_REMOVE(&sa->protos,
2247 						    proto, link);
2248 					goto retry_transform;
2249 				}
2250 			}
2251 		}
2252 		/* Have we walked all the proposals of an SA?  */
2253 		if (!next_tp || sap != next_sap) {
2254 			if (!suite_ok_so_far) {
2255 				/*
2256 				 * XXX We cannot possibly call this a drop...
2257 				 * seeing we just turn down one of the offers,
2258 				 * can we?  I suggest renaming message_drop to
2259 				 * something else.
2260 				 */
2261 				log_print("message_negotiate_sa: no "
2262 				    "compatible proposal found");
2263 				message_drop(msg,
2264 				    ISAKMP_NOTIFY_NO_PROPOSAL_CHOSEN, 0, 1, 0);
2265 			}
2266 			sa = TAILQ_NEXT(sa, next);
2267 		}
2268 	}
2269 	return 0;
2270 
2271 cleanup:
2272 	/*
2273 	 * Remove potentially succeeded choices from the SA.
2274 	 * XXX Do we leak struct protos and related data here?
2275 	 */
2276 	while ((proto = TAILQ_FIRST(&sa->protos)))
2277 		TAILQ_REMOVE(&sa->protos, proto, link);
2278 	return -1;
2279 }
2280 
2281 /*
2282  * Add SA, proposal and transform payload(s) to MSG out of information
2283  * found in the exchange MSG is part of..
2284  */
2285 int
2286 message_add_sa_payload(struct message *msg)
2287 {
2288 	struct exchange *exchange = msg->exchange;
2289 	u_int8_t       *sa_buf, *saved_nextp_sa, *saved_nextp_prop;
2290 	size_t          sa_len, extra_sa_len;
2291 	int             i, nprotos = 0;
2292 	struct proto   *proto;
2293 	u_int8_t      **transforms = 0, **proposals = 0;
2294 	size_t         *transform_lens = 0, *proposal_lens = 0;
2295 	struct sa      *sa;
2296 	struct doi     *doi = exchange->doi;
2297 	u_int8_t       *spi = 0;
2298 	size_t          spi_sz;
2299 
2300 	/*
2301 	 * Generate SA payloads.
2302 	 */
2303 	for (sa = TAILQ_FIRST(&exchange->sa_list); sa;
2304 	    sa = TAILQ_NEXT(sa, next)) {
2305 		/* Setup a SA payload.  */
2306 		sa_len = ISAKMP_SA_SIT_OFF + doi->situation_size();
2307 		extra_sa_len = 0;
2308 		sa_buf = malloc(sa_len);
2309 		if (!sa_buf) {
2310 			log_error("message_add_sa_payload: "
2311 			    "malloc (%lu) failed", (unsigned long)sa_len);
2312 			goto cleanup;
2313 		}
2314 		SET_ISAKMP_SA_DOI(sa_buf, doi->id);
2315 		doi->setup_situation(sa_buf);
2316 
2317 		/* Count transforms.  */
2318 		nprotos = 0;
2319 		for (proto = TAILQ_FIRST(&sa->protos); proto;
2320 		    proto = TAILQ_NEXT(proto, link))
2321 			nprotos++;
2322 
2323 		/*
2324 		 * Allocate transient transform and proposal payload/size
2325 		 * vectors.
2326 		 */
2327 		transforms = calloc(nprotos, sizeof *transforms);
2328 		if (!transforms) {
2329 			log_error("message_add_sa_payload: calloc (%d, %lu) "
2330 			    "failed", nprotos,
2331 			    (unsigned long)sizeof *transforms);
2332 			goto cleanup;
2333 		}
2334 		transform_lens = calloc(nprotos, sizeof *transform_lens);
2335 		if (!transform_lens) {
2336 			log_error("message_add_sa_payload: calloc (%d, %lu) "
2337 			    "failed", nprotos,
2338 			    (unsigned long) sizeof *transform_lens);
2339 			goto cleanup;
2340 		}
2341 		proposals = calloc(nprotos, sizeof *proposals);
2342 		if (!proposals) {
2343 			log_error("message_add_sa_payload: calloc (%d, %lu) "
2344 			    "failed", nprotos,
2345 			    (unsigned long)sizeof *proposals);
2346 			goto cleanup;
2347 		}
2348 		proposal_lens = calloc(nprotos, sizeof *proposal_lens);
2349 		if (!proposal_lens) {
2350 			log_error("message_add_sa_payload: calloc (%d, %lu) "
2351 			    "failed", nprotos,
2352 			    (unsigned long)sizeof *proposal_lens);
2353 			goto cleanup;
2354 		}
2355 		/* Pick out the chosen transforms.  */
2356 		for (proto = TAILQ_FIRST(&sa->protos), i = 0; proto;
2357 		    proto = TAILQ_NEXT(proto, link), i++) {
2358 			transform_lens[i] =
2359 			    GET_ISAKMP_GEN_LENGTH(proto->chosen->p);
2360 			transforms[i] = malloc(transform_lens[i]);
2361 			if (!transforms[i]) {
2362 				log_error("message_add_sa_payload: malloc "
2363 				    "(%lu) failed",
2364 				    (unsigned long)transform_lens[i]);
2365 				goto cleanup;
2366 			}
2367 			/* Get incoming SPI from application.  */
2368 			if (doi->get_spi) {
2369 				spi = doi->get_spi(&spi_sz,
2370 				    GET_ISAKMP_PROP_PROTO(proto->chosen->context->p),
2371 				    msg);
2372 				if (spi_sz && !spi)
2373 					goto cleanup;
2374 				proto->spi[1] = spi;
2375 				proto->spi_sz[1] = spi_sz;
2376 			} else
2377 				spi_sz = 0;
2378 
2379 			proposal_lens[i] = ISAKMP_PROP_SPI_OFF + spi_sz;
2380 			proposals[i] = malloc(proposal_lens[i]);
2381 			if (!proposals[i]) {
2382 				log_error("message_add_sa_payload: malloc "
2383 				    "(%lu) failed",
2384 				    (unsigned long)proposal_lens[i]);
2385 				goto cleanup;
2386 			}
2387 			memcpy(transforms[i], proto->chosen->p,
2388 			    transform_lens[i]);
2389 			memcpy(proposals[i], proto->chosen->context->p,
2390 			    ISAKMP_PROP_SPI_OFF);
2391 			SET_ISAKMP_PROP_NTRANSFORMS(proposals[i], 1);
2392 			SET_ISAKMP_PROP_SPI_SZ(proposals[i], spi_sz);
2393 			if (spi_sz)
2394 				memcpy(proposals[i] + ISAKMP_PROP_SPI_OFF, spi,
2395 				    spi_sz);
2396 			extra_sa_len += proposal_lens[i] + transform_lens[i];
2397 		}
2398 
2399 		/*
2400 		 * Add the payloads.  As this is a SA, we need to recompute the
2401 		 * lengths of the payloads containing others.  We also need to
2402 		 * reset these payload's "next payload type" field.
2403 		 */
2404 		if (message_add_payload(msg, ISAKMP_PAYLOAD_SA, sa_buf,
2405 		    sa_len, 1))
2406 			goto cleanup;
2407 		SET_ISAKMP_GEN_LENGTH(sa_buf, sa_len + extra_sa_len);
2408 		sa_buf = 0;
2409 
2410 		saved_nextp_sa = msg->nextp;
2411 		for (proto = TAILQ_FIRST(&sa->protos), i = 0; proto;
2412 		    proto = TAILQ_NEXT(proto, link), i++) {
2413 			if (message_add_payload(msg, ISAKMP_PAYLOAD_PROPOSAL,
2414 			    proposals[i], proposal_lens[i], i > 0))
2415 				goto cleanup;
2416 			SET_ISAKMP_GEN_LENGTH(proposals[i], proposal_lens[i] +
2417 			    transform_lens[i]);
2418 			proposals[i] = 0;
2419 
2420 			saved_nextp_prop = msg->nextp;
2421 			if (message_add_payload(msg, ISAKMP_PAYLOAD_TRANSFORM,
2422 			    transforms[i], transform_lens[i], 0))
2423 				goto cleanup;
2424 			msg->nextp = saved_nextp_prop;
2425 			transforms[i] = 0;
2426 		}
2427 		msg->nextp = saved_nextp_sa;
2428 
2429 		/* Free the temporary allocations made above.  */
2430 		free(transforms);
2431 		free(transform_lens);
2432 		free(proposals);
2433 		free(proposal_lens);
2434 	}
2435 	return 0;
2436 
2437 cleanup:
2438 	free(sa_buf);
2439 	for (i = 0; i < nprotos; i++) {
2440 		free(transforms[i]);
2441 		free(proposals[i]);
2442 	}
2443 	free(transforms);
2444 	free(transform_lens);
2445 	free(proposals);
2446 	free(proposal_lens);
2447 	return -1;
2448 }
2449 
2450 /*
2451  * Return a copy of MSG's constants starting from OFFSET and stash the size
2452  * in SZP.  It is the callers responsibility to free this up.
2453  */
2454 u_int8_t *
2455 message_copy(struct message *msg, size_t offset, size_t *szp)
2456 {
2457 	int             skip = 0;
2458 	size_t          i, sz = 0;
2459 	ssize_t         start = -1;
2460 	u_int8_t       *buf, *p;
2461 
2462 	/* Calculate size of message and where we want to start to copy.  */
2463 	for (i = 1; i < msg->iovlen; i++) {
2464 		sz += msg->iov[i].iov_len;
2465 		if (sz <= offset)
2466 			skip = i;
2467 		else if (start < 0)
2468 			start = offset - (sz - msg->iov[i].iov_len);
2469 	}
2470 
2471 	/* Allocate and copy.  */
2472 	*szp = sz - offset;
2473 	buf = malloc(*szp);
2474 	if (!buf)
2475 		return 0;
2476 	p = buf;
2477 	for (i = skip + 1; i < msg->iovlen; i++) {
2478 		memcpy(p, (u_int8_t *) msg->iov[i].iov_base + start,
2479 		    msg->iov[i].iov_len - start);
2480 		p += msg->iov[i].iov_len - start;
2481 		start = 0;
2482 	}
2483 	return buf;
2484 }
2485 
2486 /* Register a post-send function POST_SEND with message MSG.  */
2487 int
2488 message_register_post_send(struct message *msg,
2489     void (*post_send)(struct message *))
2490 {
2491 	struct post_send *node;
2492 
2493 	node = malloc(sizeof *node);
2494 	if (!node)
2495 		return -1;
2496 	node->func = post_send;
2497 	TAILQ_INSERT_TAIL(&msg->post_send, node, link);
2498 	return 0;
2499 }
2500 
2501 /* Run the post-send functions of message MSG.  */
2502 void
2503 message_post_send(struct message *msg)
2504 {
2505 	struct post_send *node;
2506 
2507 	while ((node = TAILQ_FIRST(&msg->post_send)) != 0) {
2508 		TAILQ_REMOVE(&msg->post_send, node, link);
2509 		node->func(msg);
2510 		free(node);
2511 	}
2512 }
2513 
2514 struct payload *
2515 payload_first(struct message *msg, u_int8_t payload)
2516 {
2517 	return TAILQ_FIRST(&msg->payload[payload]);
2518 }
2519