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