xref: /openbsd-src/sbin/isakmpd/message.c (revision b2ea75c1b17e1a9a339660e7ed45cd24946b230e)
1 /*	$OpenBSD: message.c,v 1.45 2001/07/01 20:43:39 niklas 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 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     TAILQ_REMOVE (&msg->transport->sendq, msg, link);
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 0x%x payload %s",
247 		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 (msg->iov[0].iov_base + ISAKMP_HDR_MESSAGE_ID_OFF,
378 		     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 (msg->iov[0].iov_base + ISAKMP_HDR_MESSAGE_ID_OFF,
455 		     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->doi
496       && exchange->doi->validate_id_information (GET_ISAKMP_ID_TYPE (p->p),
497 						 p->p + ISAKMP_ID_DOI_DATA_OFF,
498 						 p->p + ISAKMP_ID_DATA_OFF,
499 						 len - ISAKMP_ID_DATA_OFF,
500 						 exchange))
501     {
502       message_drop (msg, ISAKMP_NOTIFY_INVALID_ID_INFORMATION, 0, 1, 1);
503       return -1;
504     }
505   return 0;
506 }
507 
508 /* Validate the key exchange payload P in message MSG.  */
509 static int
510 message_validate_key_exch (struct message *msg, struct payload *p)
511 {
512   struct exchange *exchange = msg->exchange;
513   size_t len = GET_ISAKMP_GEN_LENGTH (p->p);
514 
515   if (exchange->doi
516       && exchange->doi->validate_key_information (p->p + ISAKMP_KE_DATA_OFF,
517 						  len - ISAKMP_KE_DATA_OFF))
518     {
519       message_drop (msg, ISAKMP_NOTIFY_INVALID_KEY_INFORMATION, 0, 1, 1);
520       return -1;
521     }
522   return 0;
523 }
524 
525 /* Validate the nonce payload P in message MSG.  */
526 static int
527 message_validate_nonce (struct message *msg, struct payload *p)
528 {
529   /* Nonces require no specific validation.  */
530   return 0;
531 }
532 
533 /*
534  * Validate the notify payload P in message MSG.  As a side-effect, create
535  * an exchange if we do not have one already.
536  */
537 static int
538 message_validate_notify (struct message *msg, struct payload *p)
539 {
540   u_int8_t proto = GET_ISAKMP_NOTIFY_PROTO (p->p);
541   u_int16_t type = GET_ISAKMP_NOTIFY_MSG_TYPE (p->p);
542   struct doi *doi;
543 
544   doi = doi_lookup (GET_ISAKMP_NOTIFY_DOI (p->p));
545   if (!doi)
546     {
547       log_print ("message_validate_notify: DOI not supported");
548       message_free (msg);
549       return -1;
550     }
551 
552   /* If we don't have an exchange yet, create one.  */
553   if (!msg->exchange)
554     {
555       if (zero_test (msg->iov[0].iov_base + ISAKMP_HDR_MESSAGE_ID_OFF,
556 		     ISAKMP_HDR_MESSAGE_ID_LEN))
557 	msg->exchange = exchange_setup_p1 (msg, doi->id);
558       else
559 	msg->exchange = exchange_setup_p2 (msg, doi->id);
560       if (!msg->exchange)
561 	{
562 	  log_print ("message_validate_notify: can not create exchange");
563 	  message_free (msg);
564 	  return -1;
565 	}
566     }
567 
568   if (proto != ISAKMP_PROTO_ISAKMP && doi->validate_proto (proto))
569     {
570       log_print ("message_validate_notify: protocol not supported");
571       message_free (msg);
572       return -1;
573     }
574 
575   /* XXX Validate the SPI.  */
576 
577   if (type < ISAKMP_NOTIFY_INVALID_PAYLOAD_TYPE
578       || (type >= ISAKMP_NOTIFY_RESERVED_MIN
579 	  && type < ISAKMP_NOTIFY_PRIVATE_MIN)
580       || (type >= ISAKMP_NOTIFY_STATUS_RESERVED1_MIN
581 	  && type <= ISAKMP_NOTIFY_STATUS_RESERVED1_MAX)
582       || (type >= ISAKMP_NOTIFY_STATUS_DOI_MIN
583 	  && type <= ISAKMP_NOTIFY_STATUS_DOI_MAX
584 	  && doi->validate_notification (type))
585       || type >= ISAKMP_NOTIFY_STATUS_RESERVED2_MIN)
586     {
587       log_print ("message_validate_notify: message type not supported");
588       message_free (msg);
589       return -1;
590     }
591   return 0;
592 }
593 
594 /* Validate the proposal payload P in message MSG.  */
595 static int
596 message_validate_proposal (struct message *msg, struct payload *p)
597 {
598   u_int8_t proto = GET_ISAKMP_PROP_PROTO (p->p);
599   u_int8_t *sa = p->context->p;
600 
601   if (proto != ISAKMP_PROTO_ISAKMP
602       && msg->exchange->doi->validate_proto (proto))
603     {
604       message_drop (msg, ISAKMP_NOTIFY_INVALID_PROTOCOL_ID, 0, 1, 1);
605       return -1;
606     }
607 
608   /* Check that we get monotonically increasing proposal IDs per SA.  */
609   if (sa != last_sa)
610     last_sa = sa;
611   else if (GET_ISAKMP_PROP_NO (p->p) < last_prop_no)
612     {
613       message_drop (msg, ISAKMP_NOTIFY_BAD_PROPOSAL_SYNTAX, 0, 1, 1);
614       return -1;
615     }
616   last_prop_no = GET_ISAKMP_PROP_NO (p->p);
617 
618   /* XXX Validate the SPI, and other syntactic things.  */
619 
620   return 0;
621 }
622 
623 /*
624  * Validate the SA payload P in message MSG.
625  * Aside from normal validation, note what DOI is in use for other
626  * validation routines to look at.  Also index the proposal payloads
627  * on the fly.
628  * XXX This assumes PAYLOAD_SA is always the first payload
629  * to be validated, which is true for IKE, except for quick mode where
630  * a PAYLOAD_HASH comes first, but in that specific case it does not matter.
631  * XXX Make sure the above comment is relevant, isn't SA always checked
632  * first due to the IANA assigned payload number?
633  */
634 static int
635 message_validate_sa (struct message *msg, struct payload *p)
636 {
637   set payload_set;
638   size_t len;
639   u_int32_t doi_id;
640   struct exchange *exchange = msg->exchange;
641   u_int8_t *pkt = msg->iov[0].iov_base;
642 
643   doi_id = GET_ISAKMP_SA_DOI (p->p);
644   if (!doi_lookup (doi_id))
645     {
646       log_print ("message_validate_sa: DOI not supported");
647       message_drop (msg, ISAKMP_NOTIFY_DOI_NOT_SUPPORTED, 0, 1, 1);
648       return -1;
649     }
650 
651   /*
652    * It's time to figure out what SA this message is about.  If it is
653    * already set, then we are creating a new phase 1 SA.  Otherwise, lookup
654    * the SA using the cookies and the message ID.  If we cannot find
655    * it, and the phase 1 SA is ready, setup a phase 2 SA.
656    */
657   if (!exchange)
658     {
659       if (zero_test (pkt + ISAKMP_HDR_RCOOKIE_OFF, ISAKMP_HDR_RCOOKIE_LEN))
660 	exchange = exchange_setup_p1 (msg, doi_id);
661       else if (msg->isakmp_sa->flags & SA_FLAG_READY)
662 	exchange = exchange_setup_p2 (msg, doi_id);
663       else
664 	{
665 	  /* XXX What to do here?  */
666 	  message_free (msg);
667 	  return -1;
668 	}
669       if (!exchange)
670 	{
671 	  /* XXX Log?  */
672 	  message_free (msg);
673 	  return -1;
674 	}
675     }
676   msg->exchange = exchange;
677 
678   /*
679    * Create a struct sa for each SA payload handed to us unless we are the
680    * initiator where we only will count them.
681    */
682   if (exchange->initiator)
683     {
684       /* XXX Count SA payloads.  */
685     }
686   else if (sa_create (exchange, msg->transport))
687     {
688       /* XXX Remove exchange if we just created it?   */
689       message_free (msg);
690       return -1;
691     }
692 
693   if (exchange->phase == 1)
694     {
695       msg->isakmp_sa = TAILQ_FIRST (&exchange->sa_list);
696       if (msg->isakmp_sa)
697         sa_reference (msg->isakmp_sa);
698     }
699 
700   /*
701    * Let the DOI validate the situation, at the same time it tells us what
702    * the length of the situation field is.
703    */
704   if (exchange->doi->validate_situation (p->p + ISAKMP_SA_SIT_OFF, &len))
705     {
706       log_print ("message_validate_sa: situation not supported");
707       message_drop (msg, ISAKMP_NOTIFY_SITUATION_NOT_SUPPORTED, 0, 1, 1);
708       return -1;
709     }
710 
711   /* Reset the fields we base our proposal & transform number checks on.  */
712   last_sa = last_prop = 0;
713   last_prop_no = last_xf_no = 0;
714 
715   /* Go through the PROPOSAL payloads.  */
716   ZERO (&payload_set);
717   SET (ISAKMP_PAYLOAD_PROPOSAL, &payload_set);
718   if (message_parse_payloads (msg, p, ISAKMP_PAYLOAD_PROPOSAL,
719 			      p->p + ISAKMP_SA_SIT_OFF + len, &payload_set,
720 			      message_parse_proposal) == -1)
721     return -1;
722 
723   return 0;
724 }
725 
726 /* Validate the signature payload P in message MSG.  */
727 static int
728 message_validate_sig (struct message *msg, struct payload *p)
729 {
730   /* XXX Not implemented yet.  */
731   return 0;
732 }
733 
734 /* Validate the transform payload P in message MSG.  */
735 static int
736 message_validate_transform (struct message *msg, struct payload *p)
737 {
738   u_int8_t proto = GET_ISAKMP_PROP_PROTO (p->context->p);
739   u_int8_t *prop = p->context->p;
740 
741   if (msg->exchange->doi
742       ->validate_transform_id (proto, GET_ISAKMP_TRANSFORM_ID (p->p)))
743     {
744       message_drop (msg, ISAKMP_NOTIFY_INVALID_TRANSFORM_ID, 0, 1, 1);
745       return -1;
746     }
747 
748   /* Check that the reserved field is zero.  */
749   if (!zero_test (p->p + ISAKMP_TRANSFORM_RESERVED_OFF,
750 		  ISAKMP_TRANSFORM_RESERVED_LEN))
751     {
752       message_drop (msg, ISAKMP_NOTIFY_PAYLOAD_MALFORMED, 0, 1, 1);
753       return -1;
754     }
755 
756   /*
757    * Check that we get monotonically increasing transform numbers per proposal.
758    */
759   if (prop != last_prop)
760     last_prop = prop;
761   else if (GET_ISAKMP_TRANSFORM_NO (p->p) <= last_xf_no)
762     {
763       message_drop (msg, ISAKMP_NOTIFY_BAD_PROPOSAL_SYNTAX, 0, 1, 1);
764       return -1;
765     }
766   last_xf_no = GET_ISAKMP_TRANSFORM_NO (p->p);
767 
768   /* Validate the attributes.  */
769   if (attribute_map (p->p + ISAKMP_TRANSFORM_SA_ATTRS_OFF,
770 		     GET_ISAKMP_GEN_LENGTH (p->p)
771 		     - ISAKMP_TRANSFORM_SA_ATTRS_OFF,
772 		     msg->exchange->doi->validate_attribute, msg))
773     {
774       message_drop (msg, ISAKMP_NOTIFY_ATTRIBUTES_NOT_SUPPORTED, 0, 1, 1);
775       return -1;
776     }
777 
778   return 0;
779 }
780 
781 /* Validate the vendor payload P in message MSG.  */
782 static int
783 message_validate_vendor (struct message *msg, struct payload *p)
784 {
785   /* Vendor IDs are only allowed in phase 1.  */
786   if (msg->exchange->phase != 1)
787     {
788       message_drop (msg, ISAKMP_NOTIFY_INVALID_PAYLOAD_TYPE, 0, 1, 1);
789       return -1;
790     }
791 
792   LOG_DBG ((LOG_MESSAGE, 40, "message_validate_vendor: vendor ID seen"));
793   return 0;
794 }
795 
796 /*
797  * Add an index-record pointing to the payload at BUF in message MSG
798  * to the PAYLOAD bucket of payloads.  This allows us to quickly reference
799  * payloads by type.  Also stash the parent payload P link into the new
800  * node so we can go from transforms -> payloads -> SAs.
801  */
802 static int
803 message_index_payload (struct message *msg, struct payload *p,
804 		       u_int8_t payload, u_int8_t *buf)
805 {
806   struct payload *payload_node;
807 
808   /* Put the payload pointer into the right bucket.  */
809   payload_node = malloc (sizeof *payload_node);
810   if (!payload_node)
811     return -1;
812   payload_node->p = buf;
813   payload_node->context = p;
814   payload_node->flags = 0;
815   TAILQ_INSERT_TAIL (&msg->payload[payload], payload_node, link);
816   return 0;
817 }
818 
819 /*
820  * Group each payload found in MSG by type for easy reference later.
821  * While doing this, validate the generic parts of the message structure too.
822  * NEXT is the 1st payload's type.  This routine will also register the
823  * computed message length (i.e. without padding) in msg->iov[0].iov_len.
824  */
825 static int
826 message_sort_payloads (struct message *msg, u_int8_t next)
827 {
828   set payload_set;
829   int i, sz;
830 
831   ZERO (&payload_set);
832   for (i = ISAKMP_PAYLOAD_SA; i < ISAKMP_PAYLOAD_RESERVED_MIN; i++)
833     if (i != ISAKMP_PAYLOAD_PROPOSAL && i != ISAKMP_PAYLOAD_TRANSFORM)
834       SET (i, &payload_set);
835   sz = message_parse_payloads (msg, 0, next,
836 			       msg->iov[0].iov_base + ISAKMP_HDR_SZ,
837 			       &payload_set, message_index_payload);
838   if (sz == -1)
839     return -1;
840   msg->iov[0].iov_len = ISAKMP_HDR_SZ + sz;
841   SET_ISAKMP_HDR_LENGTH (msg->iov[0].iov_base, ISAKMP_HDR_SZ + sz);
842   return 0;
843 }
844 
845 /* Run all the generic payload tests that the drafts specify.  */
846 static int
847 message_validate_payloads (struct message *msg)
848 {
849   int i;
850   struct payload *p;
851 
852   for (i = ISAKMP_PAYLOAD_SA; i < ISAKMP_PAYLOAD_RESERVED_MIN; i++)
853     for (p = TAILQ_FIRST (&msg->payload[i]); p; p = TAILQ_NEXT (p, link))
854       {
855 	LOG_DBG ((LOG_MESSAGE, 60,
856 		  "message_validate_payloads: "
857 		  "payload %s at %p of message %p",
858 		  constant_name (isakmp_payload_cst, i), p->p, msg));
859 	field_dump_payload (fields[i - ISAKMP_PAYLOAD_SA], p->p);
860 	if (message_validate_payload[i - ISAKMP_PAYLOAD_SA] (msg, p))
861 	  return -1;
862       }
863   return 0;
864 }
865 
866 /*
867  * All incoming messages go through here.  We do generic validity checks
868  * and try to find or establish SAs.  Last but not least we try to find
869  * the exchange this message, MSG, is part of, and feed it there.
870  */
871 int
872 message_recv (struct message *msg)
873 {
874   u_int8_t *buf = msg->iov[0].iov_base;
875   size_t sz = msg->iov[0].iov_len;
876   u_int8_t exch_type;
877   int setup_isakmp_sa, msgid_is_zero;
878   u_int8_t flags;
879   struct keystate *ks = 0;
880   struct proto tmp_proto;
881   struct sa tmp_sa;
882 
883   /* Possibly dump a raw hex image of the message to the log channel.  */
884   message_dump_raw ("message_recv", msg, LOG_MESSAGE);
885 
886   /* Messages shorter than an ISAKMP header are bad.  */
887   if (sz < ISAKMP_HDR_SZ || sz != GET_ISAKMP_HDR_LENGTH (buf))
888     {
889       log_print ("message_recv: bad message length");
890       message_drop (msg, ISAKMP_NOTIFY_UNEQUAL_PAYLOAD_LENGTHS, 0, 1, 1);
891       return -1;
892     }
893 
894   /*
895    * If the responder cookie is zero, this is a request to setup an ISAKMP SA.
896    * Otherwise the cookies should refer to an existing ISAKMP SA.
897    *
898    * XXX This is getting ugly, please reread later to see if it can be made
899    * nicer.
900    */
901   setup_isakmp_sa = zero_test (buf + ISAKMP_HDR_RCOOKIE_OFF,
902 			       ISAKMP_HDR_RCOOKIE_LEN);
903   if (setup_isakmp_sa)
904     {
905       /*
906        * This might be a retransmission of a former ISAKMP SA setup message.
907        * If so, just drop it.
908        * XXX Must we really look in both the SA and exchange pools?
909        */
910       if (exchange_lookup_from_icookie (buf + ISAKMP_HDR_ICOOKIE_OFF)
911 	  || sa_lookup_from_icookie (buf + ISAKMP_HDR_ICOOKIE_OFF))
912 	{
913 	  /*
914 	   * XXX Later we should differentiate between retransmissions and
915 	   * potential replay attacks.
916 	   */
917 	  LOG_DBG ((LOG_MESSAGE, 90,
918 		    "message_recv: dropping setup for existing SA"));
919 	  message_free (msg);
920 	  return -1;
921 	}
922     }
923   else
924     {
925       msg->isakmp_sa = sa_lookup_by_header (buf, 0);
926       if (msg->isakmp_sa)
927         sa_reference (msg->isakmp_sa);
928 
929       /*
930        * If we cannot find an ISAKMP SA out of the cookies, this is either
931        * a responder's first reply, and we need to upgrade our exchange,
932        * or it's just plain invalid cookies.
933        */
934       if (!msg->isakmp_sa)
935 	{
936 	  msg->exchange
937 	    = exchange_lookup_from_icookie (buf + ISAKMP_HDR_ICOOKIE_OFF);
938 	  if (msg->exchange && msg->exchange->phase == 1
939 	      && zero_test (msg->exchange->cookies + ISAKMP_HDR_RCOOKIE_OFF,
940 			    ISAKMP_HDR_RCOOKIE_LEN))
941 	    exchange_upgrade_p1 (msg);
942 	  else
943 	    {
944 	      log_print ("message_recv: invalid cookie(s) %08x%08x %08x%08x",
945 			 decode_32 (buf + ISAKMP_HDR_ICOOKIE_OFF),
946 			 decode_32 (buf + ISAKMP_HDR_ICOOKIE_OFF + 4),
947 			 decode_32 (buf + ISAKMP_HDR_RCOOKIE_OFF),
948 			 decode_32 (buf + ISAKMP_HDR_RCOOKIE_OFF + 4));
949 	      tmp_proto.sa = &tmp_sa;
950 	      tmp_sa.doi = doi_lookup (ISAKMP_DOI_ISAKMP);
951 	      tmp_proto.proto = ISAKMP_PROTO_ISAKMP;
952 	      tmp_proto.spi_sz[1] = ISAKMP_HDR_COOKIES_LEN;
953 	      tmp_proto.spi[1] = buf + ISAKMP_HDR_COOKIES_OFF;
954 	      message_drop (msg, ISAKMP_NOTIFY_INVALID_COOKIE, &tmp_proto, 1,
955 			    1);
956 	      return -1;
957 	    }
958 #if 0
959 	  msg->isakmp_sa
960 	    = sa_lookup_from_icookie (buf + ISAKMP_HDR_ICOOKIE_OFF);
961 	  if (msg->isakmp_sa)
962 	    sa_isakmp_upgrade (msg);
963 #endif
964 	}
965       msg->exchange = exchange_lookup (buf, 1);
966     }
967 
968   if (message_check_duplicate (msg))
969     return -1;
970 
971   if (GET_ISAKMP_HDR_NEXT_PAYLOAD (buf) >= ISAKMP_PAYLOAD_RESERVED_MIN)
972     {
973       log_print ("message_recv: "
974 		 "invalid payload type %d in ISAKMP header "
975 		 "(check passphrases, if applicable and in Phase 1)",
976 		 GET_ISAKMP_HDR_NEXT_PAYLOAD (buf));
977       message_drop (msg, ISAKMP_NOTIFY_INVALID_PAYLOAD_TYPE, 0, 1, 1);
978       return -1;
979     }
980 
981   /* Validate that the message is of version 1.0.  */
982   if (ISAKMP_VERSION_MAJOR (GET_ISAKMP_HDR_VERSION (buf)) != 1)
983     {
984       log_print ("message_recv: invalid version major %d",
985 		 ISAKMP_VERSION_MAJOR (GET_ISAKMP_HDR_VERSION (buf)));
986       message_drop (msg, ISAKMP_NOTIFY_INVALID_MAJOR_VERSION, 0, 1, 1);
987       return -1;
988     }
989 
990   if (ISAKMP_VERSION_MINOR (GET_ISAKMP_HDR_VERSION (buf)) != 0)
991     {
992       log_print ("message_recv: invalid version minor %d",
993 		 ISAKMP_VERSION_MINOR (GET_ISAKMP_HDR_VERSION (buf)));
994       message_drop (msg, ISAKMP_NOTIFY_INVALID_MINOR_VERSION, 0, 1, 1);
995       return -1;
996     }
997 
998   /*
999    * Validate the exchange type.  If it's a DOI-specified exchange wait until
1000    * after all payloads have been seen for the validation as the SA payload
1001    * might not yet have been parsed, thus the DOI might be unknown.
1002    */
1003   exch_type = GET_ISAKMP_HDR_EXCH_TYPE (buf);
1004   if (exch_type == ISAKMP_EXCH_NONE
1005       || (exch_type >= ISAKMP_EXCH_FUTURE_MIN &&
1006 	  exch_type <= ISAKMP_EXCH_FUTURE_MAX)
1007       || (setup_isakmp_sa && exch_type >= ISAKMP_EXCH_DOI_MIN))
1008     {
1009       log_print ("message_recv: invalid exchange type %s",
1010 		 constant_name (isakmp_exch_cst, exch_type));
1011       message_drop (msg, ISAKMP_NOTIFY_INVALID_EXCHANGE_TYPE, 0, 1, 1);
1012       return -1;
1013     }
1014 
1015   /*
1016    * Check for unrecognized flags, or the encryption flag when we don't
1017    * have an ISAKMP SA to decrypt with.
1018    */
1019   flags = GET_ISAKMP_HDR_FLAGS (buf);
1020   if (flags
1021       & ~(ISAKMP_FLAGS_ENC | ISAKMP_FLAGS_COMMIT | ISAKMP_FLAGS_AUTH_ONLY))
1022     {
1023       log_print ("message_recv: invalid flags 0x%x",
1024 		 GET_ISAKMP_HDR_FLAGS (buf));
1025       message_drop (msg, ISAKMP_NOTIFY_INVALID_FLAGS, 0, 1, 1);
1026       return -1;
1027     }
1028 
1029   /* If we are about to setup an ISAKMP SA, the message ID must be zero.  */
1030   msgid_is_zero = zero_test (buf + ISAKMP_HDR_MESSAGE_ID_OFF,
1031 			     ISAKMP_HDR_MESSAGE_ID_LEN);
1032   if (setup_isakmp_sa && !msgid_is_zero)
1033     {
1034       log_print ("message_recv: invalid message id");
1035       message_drop (msg, ISAKMP_NOTIFY_INVALID_MESSAGE_ID, 0, 1, 1);
1036       return -1;
1037     }
1038 
1039   if (!setup_isakmp_sa && msgid_is_zero)
1040     {
1041       /*
1042        * XXX Very likely redundant, look at the  else clause of the
1043        * if (setup_isakmp_sa) statement above.
1044        */
1045       msg->exchange = exchange_lookup (buf, 0);
1046       if (!msg->exchange)
1047 	{
1048 	  log_print ("message_recv: phase 1 message after ISAKMP SA is ready");
1049 	  message_free (msg);
1050 	  return -1;
1051 	}
1052       else if (msg->exchange->last_sent)
1053 	{
1054 	  LOG_DBG ((LOG_MESSAGE, 80,
1055 		    "message_recv: resending last message from phase 1"));
1056 	  message_send (msg->exchange->last_sent);
1057 	}
1058     }
1059 
1060   if (flags & ISAKMP_FLAGS_ENC)
1061     {
1062       if (!msg->isakmp_sa)
1063 	{
1064 	  LOG_DBG ((LOG_MISC, 10,
1065 		    "message_recv: no isakmp_sa for encrypted message"));
1066 	  return -1;
1067 	}
1068 
1069       /* Decrypt rest of message using a DOI-specified IV.  */
1070       ks = msg->isakmp_sa->doi->get_keystate (msg);
1071       if (!ks)
1072 	{
1073 	  message_free (msg);
1074 	  return -1;
1075 	}
1076       msg->orig = malloc (sz);
1077       if (!msg->orig)
1078 	{
1079 	  message_free (msg);
1080 	  free (ks);
1081 	  return -1;
1082 	}
1083       memcpy (msg->orig, buf, sz);
1084       crypto_decrypt (ks, buf + ISAKMP_HDR_SZ, sz - ISAKMP_HDR_SZ);
1085     }
1086   else
1087     msg->orig = buf;
1088   msg->orig_sz = sz;
1089 
1090   /* IKE packet capture */
1091   message_packet_log (msg);
1092 
1093   /*
1094    * Check the overall payload structure at the same time as indexing them by
1095    * type.
1096    */
1097   if (GET_ISAKMP_HDR_NEXT_PAYLOAD (buf) != ISAKMP_PAYLOAD_NONE
1098       && message_sort_payloads (msg, GET_ISAKMP_HDR_NEXT_PAYLOAD (buf)))
1099     {
1100       if (ks)
1101 	free (ks);
1102       return -1;
1103     }
1104 
1105   /*
1106    * Run generic payload tests now.  If anything fails these checks, the
1107    * message needs either to be retained for later duplicate checks or
1108    * freed entirely.
1109    * XXX Should SAs and even transports be cleaned up then too?
1110    */
1111   if (message_validate_payloads (msg))
1112     {
1113       if (ks)
1114 	free (ks);
1115       return -1;
1116     }
1117 
1118   /* If we have not found an exchange by now something is definitely wrong.  */
1119   if (!msg->exchange)
1120     {
1121       log_print ("message_recv: no exchange");
1122       message_drop (msg, ISAKMP_NOTIFY_PAYLOAD_MALFORMED, 0, 1, 1);
1123       if (ks)
1124 	free (ks);
1125       return -1;
1126     }
1127 
1128   /*
1129    * Now we can validate DOI-specific exchange types.  If we have no SA
1130    * DOI-specific exchange types are definitely wrong.
1131    */
1132   if (exch_type >= ISAKMP_EXCH_DOI_MIN && exch_type <= ISAKMP_EXCH_DOI_MAX
1133       && msg->exchange->doi->validate_exchange (exch_type))
1134     {
1135       log_print ("message_recv: invalid DOI exchange type %d", exch_type);
1136       message_drop (msg, ISAKMP_NOTIFY_INVALID_EXCHANGE_TYPE, 0, 1, 1);
1137       if (ks)
1138 	free (ks);
1139       return -1;
1140     }
1141 
1142   /* Make sure the IV we used gets saved in the proper SA.  */
1143   if (ks)
1144     {
1145       if (!msg->exchange->keystate)
1146 	{
1147 	  msg->exchange->keystate = ks;
1148 	  msg->exchange->crypto = ks->xf;
1149 	}
1150       else
1151 	free (ks);
1152     }
1153 
1154   /* Handle the flags.  */
1155   if (flags & ISAKMP_FLAGS_ENC)
1156     msg->exchange->flags |= EXCHANGE_FLAG_ENCRYPT;
1157   if ((msg->exchange->flags & EXCHANGE_FLAG_COMMITTED) == 0
1158       && (flags & ISAKMP_FLAGS_COMMIT))
1159     msg->exchange->flags |= EXCHANGE_FLAG_HE_COMMITTED;
1160 
1161   /* OK let the exchange logic do the rest.  */
1162   exchange_run (msg);
1163 
1164   return 0;
1165 }
1166 
1167 void
1168 message_send_expire (struct message *msg)
1169 {
1170   msg->retrans = 0;
1171 
1172   message_send (msg);
1173 }
1174 
1175 /* Queue up message MSG for transmittal.  */
1176 void
1177 message_send (struct message *msg)
1178 {
1179   struct exchange *exchange = msg->exchange;
1180   struct message *m;
1181 
1182   /* Remove retransmissions on this message  */
1183   if (msg->retrans)
1184     {
1185       timer_remove_event (msg->retrans);
1186       msg->retrans = 0;
1187     }
1188 
1189   /* IKE packet capture */
1190   message_packet_log (msg);
1191 
1192   /*
1193    * If the ISAKMP SA has set up encryption, encrypt the message.
1194    * However, in a retransmit, it is already encrypted.
1195    */
1196   if ((msg->flags & MSG_ENCRYPTED) == 0
1197       && exchange->flags & EXCHANGE_FLAG_ENCRYPT)
1198     {
1199       if (!exchange->keystate)
1200 	{
1201 	  exchange->keystate = exchange->doi->get_keystate (msg);
1202 	  exchange->crypto = exchange->keystate->xf;
1203 	  exchange->flags |= EXCHANGE_FLAG_ENCRYPT;
1204 	}
1205 
1206       if (message_encrypt (msg))
1207 	{
1208 	  /* XXX Log.  */
1209 	  return;
1210 	}
1211     }
1212 
1213   /* Keep the COMMIT bit on.  */
1214   if (exchange->flags & EXCHANGE_FLAG_COMMITTED)
1215     SET_ISAKMP_HDR_FLAGS (msg->iov[0].iov_base,
1216 			  GET_ISAKMP_HDR_FLAGS (msg->iov[0].iov_base)
1217 			  | ISAKMP_FLAGS_COMMIT);
1218 
1219   message_dump_raw ("message_send", msg, LOG_MESSAGE);
1220   msg->flags |= MSG_IN_TRANSIT;
1221   exchange->in_transit = msg;
1222 
1223   /*
1224    * If we get a retransmission of a message before our response
1225    * has left the queue, don't queue it again, as it will result
1226    * in a circular list.
1227    */
1228   for (m = TAILQ_FIRST (&msg->transport->sendq); m; m = TAILQ_NEXT (m, link))
1229     if (m == msg)
1230       {
1231 	LOG_DBG ((LOG_MESSAGE, 60, "message_send: msg %p already on sendq",
1232 		  m));
1233 	return;
1234       }
1235 
1236   TAILQ_INSERT_TAIL (&msg->transport->sendq, msg, link);
1237 }
1238 
1239 /*
1240  * Setup the ISAKMP message header for message MSG.  EXCHANGE is the exchange
1241  * type, FLAGS are the ISAKMP header flags and MSG_ID is message ID
1242  * identifying the exchange.
1243  */
1244 void
1245 message_setup_header (struct message *msg, u_int8_t exchange, u_int8_t flags,
1246 		      u_int8_t *msg_id)
1247 {
1248   u_int8_t *buf = msg->iov[0].iov_base;
1249 
1250   SET_ISAKMP_HDR_ICOOKIE (buf, msg->exchange->cookies);
1251   SET_ISAKMP_HDR_RCOOKIE (buf,
1252 			  msg->exchange->cookies + ISAKMP_HDR_ICOOKIE_LEN);
1253   SET_ISAKMP_HDR_NEXT_PAYLOAD (buf, ISAKMP_PAYLOAD_NONE);
1254   SET_ISAKMP_HDR_VERSION (buf, ISAKMP_VERSION_MAKE (1, 0));
1255   SET_ISAKMP_HDR_EXCH_TYPE (buf, exchange);
1256   SET_ISAKMP_HDR_FLAGS (buf, flags);
1257   SET_ISAKMP_HDR_MESSAGE_ID (buf, msg_id);
1258   SET_ISAKMP_HDR_LENGTH (buf, msg->iov[0].iov_len);
1259 }
1260 
1261 /*
1262  * Add the payload of type PAYLOAD in BUF sized SZ to the MSG message.
1263  * The caller thereby is released from the responsibility of freeing BUF,
1264  * unless we return a failure of course.  If LINK is set the former
1265  * payload's "next payload" field to PAYLOAD.
1266  *
1267  * XXX We might want to resize the iov array several slots at a time.
1268  */
1269 int
1270 message_add_payload (struct message *msg, u_int8_t payload, u_int8_t *buf,
1271 		     size_t sz, int link)
1272 {
1273   struct iovec *new_iov;
1274   struct payload *payload_node;
1275 
1276   payload_node = malloc (sizeof *payload_node);
1277   if (!payload_node)
1278     {
1279       log_error ("message_add_payload: malloc (%d) failed",
1280 		 sizeof *payload_node);
1281       return -1;
1282     }
1283   new_iov
1284     = (struct iovec *)realloc (msg->iov, (msg->iovlen + 1) * sizeof *msg->iov);
1285   if (!new_iov)
1286     {
1287       log_error ("message_add_payload: realloc (%p, %d) failed", msg->iov,
1288 		 (msg->iovlen + 1) * sizeof *msg->iov);
1289       free (payload_node);
1290       return -1;
1291     }
1292   msg->iov = new_iov;
1293   new_iov[msg->iovlen].iov_base = buf;
1294   new_iov[msg->iovlen].iov_len = sz;
1295   msg->iovlen++;
1296   if (link)
1297     *msg->nextp = payload;
1298   msg->nextp = buf + ISAKMP_GEN_NEXT_PAYLOAD_OFF;
1299   *msg->nextp = ISAKMP_PAYLOAD_NONE;
1300   SET_ISAKMP_GEN_RESERVED (buf, 0);
1301   SET_ISAKMP_GEN_LENGTH (buf, sz);
1302   SET_ISAKMP_HDR_LENGTH (msg->iov[0].iov_base,
1303 			 GET_ISAKMP_HDR_LENGTH (msg->iov[0].iov_base) + sz);
1304 
1305   /*
1306    * For the sake of exchange_validate we index the payloads even in outgoing
1307    * messages, however context and flags are uninteresting in this situation.
1308    */
1309   payload_node->p = buf;
1310   TAILQ_INSERT_TAIL (&msg->payload[payload], payload_node, link);
1311   return 0;
1312 }
1313 
1314 /* XXX Move up when ready.  */
1315 struct info_args {
1316   char discr;
1317   u_int32_t doi;
1318   u_int8_t proto;
1319   u_int16_t spi_sz;
1320   union {
1321     struct {
1322       u_int16_t msg_type;
1323       u_int8_t *spi;
1324     } n;
1325     struct {
1326       u_int16_t nspis;
1327       u_int8_t *spis;
1328     } d;
1329   } u;
1330 };
1331 
1332 /*
1333  * As a reaction to the incoming message MSG create an informational exchange
1334  * protected by ISAKMP_SA and send a notify payload of type NOTIFY, with
1335  * fields initialized from SA.  INCOMING is true if the SPI field should be
1336  * filled with the incoming SPI and false if it is to be filled with the
1337  * outgoing one.
1338  *
1339  * XXX Should we handle sending multiple notify payloads?  The draft allows
1340  * it, but do we need it?  Furthermore, should we not return a success
1341  * status value?
1342  */
1343 void
1344 message_send_notification (struct message *msg, struct sa *isakmp_sa,
1345 			   u_int16_t notify, struct proto *proto,
1346 			   int incoming)
1347 {
1348   struct info_args args;
1349   struct sa *doi_sa = proto ? proto->sa : isakmp_sa;
1350 
1351   args.discr = 'N';
1352   args.doi = doi_sa ? doi_sa->doi->id : ISAKMP_DOI_ISAKMP;
1353   args.proto = proto ? proto->proto : ISAKMP_PROTO_ISAKMP;
1354   args.spi_sz = proto ? proto->spi_sz[incoming] : 0;
1355   args.u.n.msg_type = notify;
1356   args.u.n.spi = proto ? proto->spi[incoming] : 0;
1357   if (isakmp_sa && (isakmp_sa->flags & SA_FLAG_READY))
1358     exchange_establish_p2 (isakmp_sa, ISAKMP_EXCH_INFO, 0, &args, 0 ,0);
1359   else
1360     exchange_establish_p1 (msg->transport, ISAKMP_EXCH_INFO,
1361 			   msg->exchange
1362 			   ? msg->exchange->doi->id : ISAKMP_DOI_ISAKMP,
1363 			   0, &args, 0, 0);
1364 }
1365 
1366 /* Send a DELETE inside an informational exchange for each protocol in SA.  */
1367 void
1368 message_send_delete (struct sa *sa)
1369 {
1370   struct info_args args;
1371   struct proto *proto;
1372   struct sa *isakmp_sa;
1373   struct sockaddr *dst;
1374 
1375   sa->transport->vtbl->get_dst (sa->transport, &dst);
1376   isakmp_sa = sa_isakmp_lookup_by_peer (dst, dst->sa_len);
1377   if (!isakmp_sa)
1378     {
1379       /*
1380        * XXX We ought to setup an ISAKMP SA with our peer here and send
1381        * the DELETE over that one.
1382        */
1383       return;
1384     }
1385 
1386   args.discr = 'D';
1387   args.doi = sa->doi->id;
1388   args.u.d.nspis = 1;
1389   for (proto = TAILQ_FIRST (&sa->protos); proto;
1390        proto = TAILQ_NEXT (proto, link))
1391     {
1392       args.proto = proto->proto;
1393       args.spi_sz = proto->spi_sz[1];
1394       args.u.d.spis = proto->spi[1];
1395       exchange_establish_p2 (isakmp_sa, ISAKMP_EXCH_INFO, 0, &args, 0 ,0);
1396     }
1397 }
1398 
1399 /* Build the informational message into MSG.  */
1400 int
1401 message_send_info (struct message *msg)
1402 {
1403   u_int8_t *buf;
1404   size_t sz;
1405   struct info_args *args = msg->extra;
1406   u_int8_t payload;
1407 
1408   /* Let the DOI get the first hand on the message.  */
1409   if (msg->exchange->doi->informational_pre_hook)
1410     if (msg->exchange->doi->informational_pre_hook (msg))
1411       return -1;
1412 
1413   sz = (args->discr == 'N' ? ISAKMP_NOTIFY_SPI_OFF + args->spi_sz
1414 	: ISAKMP_DELETE_SPI_OFF + args->u.d.nspis * args->spi_sz);
1415   buf = calloc (1, sz);
1416   if (!buf)
1417     {
1418       log_error ("message_send_info: calloc (1, %d) failed", sz);
1419       message_free (msg);
1420       return -1;
1421     }
1422 
1423   switch (args->discr)
1424     {
1425     case 'N':
1426       /* Build the NOTIFY payload.  */
1427       payload = ISAKMP_PAYLOAD_NOTIFY;
1428       SET_ISAKMP_NOTIFY_DOI (buf, args->doi);
1429       SET_ISAKMP_NOTIFY_PROTO (buf, args->proto);
1430       SET_ISAKMP_NOTIFY_SPI_SZ (buf, args->spi_sz);
1431       SET_ISAKMP_NOTIFY_MSG_TYPE (buf, args->u.n.msg_type);
1432       memcpy (buf + ISAKMP_NOTIFY_SPI_OFF, args->u.n.spi, args->spi_sz);
1433       break;
1434 
1435     case 'D':
1436     default:			/* Silence GCC.  */
1437       /* Build the DELETE payload.  */
1438       payload = ISAKMP_PAYLOAD_DELETE;
1439       SET_ISAKMP_DELETE_DOI (buf, args->doi);
1440       SET_ISAKMP_DELETE_PROTO (buf, args->proto);
1441       SET_ISAKMP_DELETE_SPI_SZ (buf, args->spi_sz);
1442       SET_ISAKMP_DELETE_NSPIS (buf, args->u.d.nspis);
1443       memcpy (buf + ISAKMP_DELETE_SPI_OFF, args->u.d.spis,
1444 	      args->u.d.nspis * args->spi_sz);
1445       break;
1446     }
1447 
1448   if (message_add_payload (msg, payload, buf, sz, 1))
1449     {
1450       free (buf);
1451       message_free (msg);
1452       return -1;
1453     }
1454 
1455   /* Let the DOI get the last hand on the message.  */
1456   if (msg->exchange->doi->informational_post_hook)
1457     if (msg->exchange->doi->informational_post_hook (msg))
1458       {
1459 	message_free (msg);
1460 	return -1;
1461       }
1462 
1463   return 0;
1464 }
1465 
1466 /*
1467  * Drop the MSG message due to reason given in NOTIFY.  If NOTIFY is set
1468  * send out a notification to the originator.  Fill this notification with
1469  * values from PROTO.  INCOMING decides which SPI to include.  If CLEAN is
1470  * set, free the message when ready with it.
1471  */
1472 void
1473 message_drop (struct message *msg, int notify, struct proto *proto,
1474 	      int incoming, int clean)
1475 {
1476   struct transport *t = msg->transport;
1477   struct sockaddr *dst;
1478   char *address;
1479   short port = 0;
1480 
1481   t->vtbl->get_dst (t, &dst);
1482   if (sockaddr2text (dst, &address, 0))
1483     {
1484       log_error ("message_drop: sockaddr2text () failed");
1485       address = 0;
1486     }
1487 
1488   switch (dst->sa_family)
1489     {
1490     case AF_INET:
1491       port = ((struct sockaddr_in *)dst)->sin_port;
1492       break;
1493     case AF_INET6:
1494       port = ((struct sockaddr_in6 *)dst)->sin6_port;
1495       break;
1496     default:
1497       log_print ("message_drop: unknown protocol family %d", dst->sa_family);
1498     }
1499 
1500   log_print ("dropped message from %s port %d due to notification type %s",
1501              address ? address : "<unknown>", htons(port),
1502 	     constant_name (isakmp_notify_cst, notify));
1503 
1504   /* If specified, return a notification.  */
1505   if (notify)
1506     message_send_notification (msg, msg->isakmp_sa, notify, proto, incoming);
1507   if (clean)
1508     message_free (msg);
1509 }
1510 
1511 /*
1512  * If the user demands debug printouts, printout MSG with as much detail
1513  * as we can without resorting to per-payload handling.
1514  */
1515 void
1516 message_dump_raw (char *header, struct message *msg, int class)
1517 {
1518   int i, j, k = 0;
1519   char buf[80], *p = buf;
1520 
1521   LOG_DBG ((class, 70, "%s: message %p", header, msg));
1522   field_dump_payload (isakmp_hdr_fld, msg->iov[0].iov_base);
1523   for (i = 0; i < msg->iovlen; i++)
1524     for (j = 0; j < msg->iov[i].iov_len; j++)
1525       {
1526 	sprintf (p, "%02x", ((u_int8_t *)msg->iov[i].iov_base)[j]);
1527 	p += 2;
1528 	if (++k % 32 == 0)
1529 	  {
1530 	    *p = '\0';
1531 	    LOG_DBG ((class, 70, "%s: %s", header, buf));
1532 	    p = buf;
1533 	  }
1534 	else if (k % 4 == 0)
1535 	  *p++ = ' ';
1536       }
1537   *p = '\0';
1538   if (p != buf)
1539     LOG_DBG ((class, 70, "%s: %s", header, buf));
1540 }
1541 
1542 static void
1543 message_packet_log (struct message *msg)
1544 {
1545 #ifdef USE_DEBUG
1546   struct sockaddr *src, *dst;
1547 
1548   /* Don't log retransmissions. Redundant for incoming packets... */
1549   if (msg->xmits > 0)
1550     return;
1551 
1552   /* Figure out direction. */
1553   if (msg->exchange && msg->exchange->initiator ^ (msg->exchange->step % 2))
1554     {
1555       msg->transport->vtbl->get_src (msg->transport, &src);
1556       msg->transport->vtbl->get_dst (msg->transport, &dst);
1557     }
1558   else
1559     {
1560       msg->transport->vtbl->get_src (msg->transport, &dst);
1561       msg->transport->vtbl->get_dst (msg->transport, &src);
1562     }
1563 
1564   log_packet_iov (src, dst, msg->iov, msg->iovlen);
1565 #endif /* USE_DEBUG */
1566 }
1567 
1568 /*
1569  * Encrypt an outgoing message MSG.  As outgoing messages are represented
1570  * with an iovec with one segment per payload, we need to coalesce them
1571  * into just une buffer containing all payloads and some padding before
1572  * we encrypt.
1573  */
1574 static int
1575 message_encrypt (struct message *msg)
1576 {
1577   struct exchange *exchange = msg->exchange;
1578   size_t sz = 0;
1579   u_int8_t *buf;
1580   int i;
1581 
1582   /* If no payloads, nothing to do.  */
1583   if (msg->iovlen == 1)
1584     return 0;
1585 
1586   /*
1587    * For encryption we need to put all payloads together in a single buffer.
1588    * This buffer should be padded to the current crypto transform's blocksize.
1589    */
1590   for (i = 1; i < msg->iovlen; i++)
1591     sz += msg->iov[i].iov_len;
1592   sz = ((sz + exchange->crypto->blocksize - 1) / exchange->crypto->blocksize)
1593     * exchange->crypto->blocksize;
1594   buf = realloc (msg->iov[1].iov_base, sz);
1595   if (!buf)
1596     {
1597       log_error ("message_encrypt: realloc (%p, %d) failed",
1598 		 msg->iov[1].iov_base, sz);
1599       return -1;
1600     }
1601   msg->iov[1].iov_base = buf;
1602   for (i = 2; i < msg->iovlen; i++)
1603     {
1604       memcpy (buf + msg->iov[1].iov_len, msg->iov[i].iov_base,
1605 	      msg->iov[i].iov_len);
1606       msg->iov[1].iov_len += msg->iov[i].iov_len;
1607       free (msg->iov[i].iov_base);
1608     }
1609 
1610   /* Pad with zeroes.  */
1611   memset (buf + msg->iov[1].iov_len, '\0', sz - msg->iov[1].iov_len);
1612   msg->iov[1].iov_len = sz;
1613   msg->iovlen = 2;
1614 
1615   SET_ISAKMP_HDR_FLAGS (msg->iov[0].iov_base,
1616 			GET_ISAKMP_HDR_FLAGS (msg->iov[0].iov_base)
1617 			| ISAKMP_FLAGS_ENC);
1618   SET_ISAKMP_HDR_LENGTH (msg->iov[0].iov_base, ISAKMP_HDR_SZ + sz);
1619   crypto_encrypt (exchange->keystate, buf, msg->iov[1].iov_len);
1620   msg->flags |= MSG_ENCRYPTED;
1621 
1622   /* Update the IV so we can decrypt the next incoming message.  */
1623   crypto_update_iv (exchange->keystate);
1624 
1625   return 0;
1626 }
1627 
1628 /*
1629  * Check whether the message MSG is a duplicate of the last one negotiating
1630  * this specific SA.
1631  */
1632 static int
1633 message_check_duplicate (struct message *msg)
1634 {
1635   struct exchange *exchange = msg->exchange;
1636   size_t sz = msg->iov[0].iov_len;
1637   u_int8_t *pkt = msg->iov[0].iov_base;
1638 
1639   /* If no SA has been found, we cannot test, thus it's good.  */
1640   if (!exchange)
1641     return 0;
1642 
1643   LOG_DBG ((LOG_MESSAGE, 90, "message_check_duplicate: last_received 0x%x",
1644 	    exchange->last_received));
1645   if (exchange->last_received)
1646     {
1647       LOG_DBG_BUF ((LOG_MESSAGE, 95,
1648 		    "message_check_duplicate: last_received",
1649 		    exchange->last_received->orig,
1650 		    exchange->last_received->orig_sz));
1651       /* Is it a duplicate, lose the new one.  */
1652       if (sz == exchange->last_received->orig_sz
1653 	  && memcmp (pkt, exchange->last_received->orig, sz) == 0)
1654 	{
1655 	  LOG_DBG ((LOG_MESSAGE, 80,
1656 		    "message_check_duplicate: dropping dup"));
1657 
1658 	  /*
1659 	   * Retransmit if the previos sent message was the last of an
1660 	   * exchange, otherwise just wait for the ordinary retransmission.
1661 	   */
1662 	  if (exchange->last_sent && (exchange->last_sent->flags & MSG_LAST))
1663 	    message_send (exchange->last_sent);
1664 	  message_free (msg);
1665 	  return -1;
1666 	}
1667     }
1668 
1669   /*
1670    * As this new message is an indication that state is moving forward
1671    * at the peer, remove the retransmit timer on our last message.
1672    */
1673   if (exchange->last_sent)
1674     {
1675       if (exchange->last_sent == exchange->in_transit)
1676 	{
1677 	  TAILQ_REMOVE (&exchange->in_transit->transport->sendq,
1678 			exchange->in_transit, link);
1679 	  exchange->in_transit = 0;
1680 	}
1681       message_free (exchange->last_sent);
1682       exchange->last_sent = 0;
1683     }
1684 
1685   return 0;
1686 }
1687 
1688 /* Helper to message_negotiate_sa.  */
1689 static INLINE struct payload *
1690 step_transform (struct payload *tp, struct payload **propp,
1691 		struct payload **sap)
1692 {
1693   tp = TAILQ_NEXT (tp, link);
1694   if (tp)
1695     {
1696       *propp = tp->context;
1697       *sap = (*propp)->context;
1698     }
1699   return tp;
1700 }
1701 
1702 /*
1703  * Pick out the first transforms out of MSG (which should contain at least one
1704  * SA payload) we accept as a full protection suite.
1705  */
1706 int
1707 message_negotiate_sa (struct message *msg,
1708 		      int (*validate) (struct exchange *, struct sa *,
1709 				       struct sa *))
1710 {
1711   struct payload *tp, *propp, *sap, *next_tp = 0, *next_propp, *next_sap;
1712   struct payload *saved_tp = 0, *saved_propp = 0, *saved_sap = 0;
1713   struct sa *sa;
1714   struct proto *proto;
1715   int suite_ok_so_far = 0;
1716   struct exchange *exchange = msg->exchange;
1717 
1718   /*
1719    * This algorithm is a weird bottom-up thing... mostly due to the
1720    * payload links pointing upwards.
1721    *
1722    * The algorithm goes something like this:
1723    * Foreach transform
1724    *   If transform is compatible
1725    *     Remember that this protocol can work
1726    *     Skip to last transform of this protocol
1727    *   If next transform belongs to a new protocol inside the same suite
1728    *     If no transform was found for the current protocol
1729    *       Forget all earlier transforms for protocols in this suite
1730    *       Skip to last transform of this suite
1731    *   If next transform belongs to a new suite
1732    *     If the current protocol had an OK transform
1733    *       Skip to the last transform of this SA
1734    *   If the next transform belongs to a new SA
1735    *     If no transforms have been chosen
1736    *       Issue a NO_PROPOSAL_CHOSEN notification
1737    */
1738 
1739   sa = TAILQ_FIRST (&exchange->sa_list);
1740   for (tp = TAILQ_FIRST (&msg->payload[ISAKMP_PAYLOAD_TRANSFORM]); tp;
1741        tp = next_tp)
1742     {
1743       propp = tp->context;
1744       sap = propp->context;
1745       sap->flags |= PL_MARK;
1746       next_tp = step_transform (tp, &next_propp, &next_sap);
1747 
1748       /* For each transform, see if it is compatible.  */
1749       if (!attribute_map (tp->p + ISAKMP_TRANSFORM_SA_ATTRS_OFF,
1750 			  GET_ISAKMP_GEN_LENGTH (tp->p)
1751 			  - ISAKMP_TRANSFORM_SA_ATTRS_OFF,
1752 			  exchange->doi->is_attribute_incompatible, msg))
1753 	{
1754 	  LOG_DBG ((LOG_NEGOTIATION, 30,
1755 		    "message_negotiate_sa: "
1756 		    "transform %d proto %d proposal %d ok",
1757 		    GET_ISAKMP_TRANSFORM_NO (tp->p),
1758 		    GET_ISAKMP_PROP_PROTO (propp->p),
1759 		    GET_ISAKMP_PROP_NO (propp->p)));
1760 	  if (sa_add_transform (sa, tp, exchange->initiator, &proto))
1761 	    goto cleanup;
1762 	  suite_ok_so_far = 1;
1763 
1764 	  saved_tp = next_tp;
1765 	  saved_propp = next_propp;
1766 	  saved_sap = next_sap;
1767 	  /* Skip to last transform of this protocol proposal.  */
1768 	  while ((next_tp = step_transform (tp, &next_propp, &next_sap))
1769 		 && next_propp == propp)
1770 	    tp = next_tp;
1771 	}
1772 
1773     retry_transform:
1774       /*
1775        * Figure out if we will be looking at a new protocol proposal
1776        * inside the current protection suite.
1777        */
1778       if (next_tp && propp != next_propp && sap == next_sap
1779 	  && (GET_ISAKMP_PROP_NO (propp->p)
1780 	      == GET_ISAKMP_PROP_NO (next_propp->p)))
1781 	{
1782 	  if (!suite_ok_so_far)
1783 	    {
1784 	      LOG_DBG ((LOG_NEGOTIATION, 30,
1785 			"message_negotiate_sa: proto %d proposal %d failed",
1786 			GET_ISAKMP_PROP_PROTO (propp->p),
1787 			GET_ISAKMP_PROP_NO (propp->p)));
1788 	      /* Remove potentially succeeded choices from the SA.  */
1789 	      while (TAILQ_FIRST (&sa->protos))
1790 		TAILQ_REMOVE (&sa->protos, TAILQ_FIRST (&sa->protos), link);
1791 
1792 	      /* Skip to the last transform of this protection suite.  */
1793 	      while ((next_tp = step_transform (tp, &next_propp, &next_sap))
1794 		     && (GET_ISAKMP_PROP_NO (next_propp->p)
1795 			 == GET_ISAKMP_PROP_NO (propp->p))
1796 		     && next_sap == sap)
1797 		tp = next_tp;
1798 	    }
1799 	  suite_ok_so_far = 0;
1800 	}
1801 
1802       /* Figure out if we will be looking at a new protection suite.  */
1803       if (!next_tp
1804 	  || (propp != next_propp
1805 	      && (GET_ISAKMP_PROP_NO (propp->p)
1806 		  != GET_ISAKMP_PROP_NO (next_propp->p)))
1807 	  || sap != next_sap)
1808 	{
1809 	  /*
1810 	   * Check if the suite we just considered was OK, if so we check
1811 	   * it against the accepted ones.
1812 	   */
1813 	  if (suite_ok_so_far)
1814 	    {
1815 	      if (!validate || validate (exchange, sa, msg->isakmp_sa))
1816 		{
1817 		  LOG_DBG ((LOG_NEGOTIATION, 30,
1818 			    "message_negotiate_sa: proposal %d succeeded",
1819 			    GET_ISAKMP_PROP_NO (propp->p)));
1820 
1821 		  /* Skip to the last transform of this SA.  */
1822 		  while ((next_tp
1823 			  = step_transform (tp, &next_propp, &next_sap))
1824 			 && next_sap == sap)
1825 		    tp = next_tp;
1826 		}
1827 	      else
1828 		{
1829 		  /* Backtrack.  */
1830 		  LOG_DBG ((LOG_NEGOTIATION, 30,
1831 			    "message_negotiate_sa: proposal %d failed",
1832 			    GET_ISAKMP_PROP_NO (propp->p)));
1833 		  next_tp = saved_tp;
1834 		  next_propp = saved_propp;
1835 		  next_sap = saved_sap;
1836 		  suite_ok_so_far = 0;
1837 
1838 		  /* Remove potentially succeeded choices from the SA.  */
1839 		  while (TAILQ_FIRST (&sa->protos))
1840 		    TAILQ_REMOVE (&sa->protos, TAILQ_FIRST (&sa->protos),
1841 				  link);
1842 		  goto retry_transform;
1843 		}
1844 	    }
1845 	}
1846 
1847       /* Have we walked all the proposals of an SA?  */
1848       if (!next_tp || sap != next_sap)
1849 	{
1850 	  if (!suite_ok_so_far)
1851 	    {
1852 	      /*
1853 	       * XXX We cannot possibly call this a drop... seeing we just turn
1854 	       * down one of the offers, can we?  I suggest renaming
1855 	       * message_drop to something else.
1856 	       */
1857 	      log_print ("message_negotiate_sa: no compatible proposal found");
1858 	      message_drop (msg, ISAKMP_NOTIFY_NO_PROPOSAL_CHOSEN, 0, 1, 0);
1859 	    }
1860 	  sa = TAILQ_NEXT (sa, next);
1861 	}
1862     }
1863   return 0;
1864 
1865  cleanup:
1866   /*
1867    * Remove potentially succeeded choices from the SA.
1868    * XXX Do we leak struct protos and related data here?
1869    */
1870   while (TAILQ_FIRST (&sa->protos))
1871     TAILQ_REMOVE (&sa->protos, TAILQ_FIRST (&sa->protos), link);
1872   return -1;
1873 }
1874 
1875 /*
1876  * Add SA, proposal and transform payload(s) to MSG out of information
1877  * found in the exchange MSG is part of..
1878  */
1879 int
1880 message_add_sa_payload (struct message *msg)
1881 {
1882   struct exchange *exchange = msg->exchange;
1883   u_int8_t *sa_buf, *saved_nextp_sa, *saved_nextp_prop;
1884   size_t sa_len, extra_sa_len;
1885   int i, nprotos = 0;
1886   struct proto *proto;
1887   u_int8_t **transforms = 0, **proposals = 0;
1888   size_t *transform_lens = 0, *proposal_lens = 0;
1889   struct sa *sa;
1890   struct doi *doi = exchange->doi;
1891   u_int8_t *spi = 0;
1892   size_t spi_sz;
1893 
1894   /*
1895    * Generate SA payloads.
1896    */
1897   for (sa = TAILQ_FIRST (&exchange->sa_list); sa;
1898        sa = TAILQ_NEXT (sa, next))
1899     {
1900       /* Setup a SA payload.  */
1901       sa_len = ISAKMP_SA_SIT_OFF + doi->situation_size ();
1902       extra_sa_len = 0;
1903       sa_buf = malloc (sa_len);
1904       if (!sa_buf)
1905 	{
1906 	  log_error ("message_add_sa_payload: malloc (%d) failed", sa_len);
1907 	  goto cleanup;
1908 	}
1909 
1910       SET_ISAKMP_SA_DOI (sa_buf, doi->id);
1911       doi->setup_situation (sa_buf);
1912 
1913       /* Count transforms.  */
1914       nprotos = 0;
1915       for (proto = TAILQ_FIRST (&sa->protos); proto;
1916 	   proto = TAILQ_NEXT (proto, link))
1917 	nprotos++;
1918 
1919       /* Allocate transient transform and proposal payload/size vectors.  */
1920       transforms = calloc (nprotos, sizeof *transforms);
1921       if (!transforms)
1922 	{
1923 	  log_error ("message_add_sa_payload: calloc (%d, %d) failed", nprotos,
1924 		     sizeof *transforms);
1925 	  goto cleanup;
1926 	}
1927 
1928       transform_lens = calloc (nprotos, sizeof *transform_lens);
1929       if (!transform_lens)
1930 	{
1931 	  log_error ("message_add_sa_payload: calloc (%d, %d) failed", nprotos,
1932 		     sizeof *transform_lens);
1933 	  goto cleanup;
1934 	}
1935 
1936       proposals = calloc (nprotos, sizeof *proposals);
1937       if (!proposals)
1938 	{
1939 	  log_error ("message_add_sa_payload: calloc (%d, %d) failed", nprotos,
1940 		     sizeof *proposals);
1941 	  goto cleanup;
1942 	}
1943 
1944       proposal_lens = calloc (nprotos, sizeof *proposal_lens);
1945       if (!proposal_lens)
1946 	{
1947 	  log_error ("message_add_sa_payload: calloc (%d, %d) failed", nprotos,
1948 		     sizeof *proposal_lens);
1949 	  goto cleanup;
1950 	}
1951 
1952       /* Pick out the chosen transforms.  */
1953       for (proto = TAILQ_FIRST (&sa->protos), i = 0; proto;
1954 	   proto = TAILQ_NEXT (proto, link), i++)
1955 	{
1956 	  transform_lens[i] = GET_ISAKMP_GEN_LENGTH (proto->chosen->p);
1957 	  transforms[i] = malloc (transform_lens[i]);
1958 	  if (!transforms[i])
1959 	    {
1960 	      log_error ("message_add_sa_payload: malloc (%d) failed",
1961 			 transform_lens[i]);
1962 	      goto cleanup;
1963 	    }
1964 
1965 	  /* Get incoming SPI from application.  */
1966 	  if (doi->get_spi)
1967 	    {
1968 	      spi = doi->get_spi (&spi_sz,
1969 				  GET_ISAKMP_PROP_PROTO (proto->chosen
1970 							 ->context->p),
1971 				  msg);
1972 	      if (spi_sz && !spi)
1973 		goto cleanup;
1974 	      proto->spi[1] = spi;
1975 	      proto->spi_sz[1] = spi_sz;
1976 	    }
1977 	  else
1978 	    spi_sz = 0;
1979 
1980 	  proposal_lens[i] = ISAKMP_PROP_SPI_OFF + spi_sz;
1981 	  proposals[i] = malloc (proposal_lens[i]);
1982 	  if (!proposals[i])
1983 	    {
1984 	      log_error ("message_add_sa_payload: malloc (%d) failed",
1985 			 proposal_lens[i]);
1986 	      goto cleanup;
1987 	    }
1988 
1989 	  memcpy (transforms[i], proto->chosen->p, transform_lens[i]);
1990 	  memcpy (proposals[i], proto->chosen->context->p,
1991 		  ISAKMP_PROP_SPI_OFF);
1992 	  SET_ISAKMP_PROP_NTRANSFORMS (proposals[i], 1);
1993 	  SET_ISAKMP_PROP_SPI_SZ (proposals[i], spi_sz);
1994 	  if (spi_sz)
1995 	    memcpy (proposals[i] + ISAKMP_PROP_SPI_OFF, spi, spi_sz);
1996 	  extra_sa_len += proposal_lens[i] + transform_lens[i];
1997 	}
1998 
1999       /*
2000        * Add the payloads.  As this is a SA, we need to recompute the
2001        * lengths of the payloads containing others.  We also need to
2002        * reset these payload's "next payload type" field.
2003        */
2004       if (message_add_payload (msg, ISAKMP_PAYLOAD_SA, sa_buf, sa_len, 1))
2005 	goto cleanup;
2006       SET_ISAKMP_GEN_LENGTH (sa_buf, sa_len + extra_sa_len);
2007       sa_buf = 0;
2008 
2009       saved_nextp_sa = msg->nextp;
2010       for (proto = TAILQ_FIRST (&sa->protos), i = 0; proto;
2011 	   proto = TAILQ_NEXT (proto, link), i++)
2012 	{
2013 	  if (message_add_payload (msg, ISAKMP_PAYLOAD_PROPOSAL, proposals[i],
2014 				   proposal_lens[i], i > 1))
2015 	    goto cleanup;
2016 	  SET_ISAKMP_GEN_LENGTH (proposals[i],
2017 				 proposal_lens[i] + transform_lens[i]);
2018 	  proposals[i] = 0;
2019 
2020 	  saved_nextp_prop = msg->nextp;
2021 	  if (message_add_payload (msg, ISAKMP_PAYLOAD_TRANSFORM,
2022 				   transforms[i], transform_lens[i], 0))
2023 	    goto cleanup;
2024 	  msg->nextp = saved_nextp_prop;
2025 	  transforms[i] = 0;
2026 	}
2027       msg->nextp = saved_nextp_sa;
2028 
2029       /* Free the temporary allocations made above.  */
2030       free (transforms);
2031       free (transform_lens);
2032       free (proposals);
2033       free (proposal_lens);
2034     }
2035   return 0;
2036 
2037  cleanup:
2038   if (sa_buf)
2039     free (sa_buf);
2040   for (i = 0; i < nprotos; i++)
2041     {
2042       if (transforms[i])
2043 	free (transforms[i]);
2044       if (proposals[i])
2045 	free (proposals[i]);
2046     }
2047   if (transforms)
2048     free (transforms);
2049   if (transform_lens)
2050     free (transform_lens);
2051   if (proposals)
2052     free (proposals);
2053   if (proposal_lens)
2054     free (proposal_lens);
2055   return -1;
2056 }
2057 
2058 /*
2059  * Return a copy of MSG's constants starting from OFFSET and stash the size
2060  * in SZP.  It is the callers responsibility to free this up.
2061  */
2062 u_int8_t *
2063 message_copy (struct message *msg, size_t offset, size_t *szp)
2064 {
2065   int i, skip = 0;
2066   size_t sz = 0;
2067   ssize_t start = -1;
2068   u_int8_t *buf, *p;
2069 
2070   /* Calculate size of message and where we want to start to copy.  */
2071   for (i = 1; i < msg->iovlen; i++)
2072     {
2073       sz += msg->iov[i].iov_len;
2074       if (sz <= offset)
2075 	skip = i;
2076       else if (start < 0)
2077 	start = offset - (sz - msg->iov[i].iov_len);
2078     }
2079 
2080   /* Allocate and copy.  */
2081   *szp = sz - offset;
2082   buf = malloc (*szp);
2083   if (!buf)
2084     return 0;
2085   p = buf;
2086   for (i = skip + 1; i < msg->iovlen; i++)
2087     {
2088       memcpy (p, msg->iov[i].iov_base + start, msg->iov[i].iov_len - start);
2089       p += msg->iov[i].iov_len - start;
2090       start = 0;
2091     }
2092   return buf;
2093 }
2094 
2095 /* Register a post-send function POST_SEND with message MSG.  */
2096 int
2097 message_register_post_send (struct message *msg,
2098 			    void (*post_send) (struct message *))
2099 {
2100   struct post_send *node;
2101 
2102   node = malloc (sizeof *node);
2103   if (!node)
2104     return -1;
2105   node->func = post_send;
2106   TAILQ_INSERT_TAIL (&msg->post_send, node, link);
2107   return 0;
2108 }
2109 
2110 /* Run the post-send functions of message MSG.  */
2111 void
2112 message_post_send (struct message *msg)
2113 {
2114   struct post_send *node;
2115 
2116   while ((node = TAILQ_FIRST (&msg->post_send)) != 0)
2117     {
2118       TAILQ_REMOVE (&msg->post_send, node, link);
2119       node->func (msg);
2120       free (node);
2121     }
2122 }
2123