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