xref: /openbsd/sbin/isakmpd/ike_quick_mode.c (revision 78b63d65)
1 /*	$OpenBSD: ike_quick_mode.c,v 1.56 2001/10/26 12:03:07 ho Exp $	*/
2 /*	$EOM: ike_quick_mode.c,v 1.139 2001/01/26 10:43:17 niklas Exp $	*/
3 
4 /*
5  * Copyright (c) 1998, 1999, 2000, 2001 Niklas Hallqvist.  All rights reserved.
6  * Copyright (c) 1999, 2000, 2001 Angelos D. Keromytis.  All rights reserved.
7  * Copyright (c) 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 <stdlib.h>
40 #include <string.h>
41 
42 #if defined (USE_POLICY) || defined (USE_KEYNOTE)
43 #include <sys/types.h>
44 #include <regex.h>
45 #include <keynote.h>
46 #endif
47 
48 #include "sysdep.h"
49 
50 #include "attribute.h"
51 #include "conf.h"
52 #include "connection.h"
53 #include "dh.h"
54 #include "doi.h"
55 #include "exchange.h"
56 #include "hash.h"
57 #include "ike_quick_mode.h"
58 #include "ipsec.h"
59 #include "log.h"
60 #include "math_group.h"
61 #include "message.h"
62 #include "policy.h"
63 #include "prf.h"
64 #include "sa.h"
65 #include "transport.h"
66 #include "util.h"
67 #include "key.h"
68 
69 #ifdef USE_X509
70 #include "x509.h"
71 #endif
72 
73 static void gen_g_xy (struct message *);
74 static int initiator_send_HASH_SA_NONCE (struct message *);
75 static int initiator_recv_HASH_SA_NONCE (struct message *);
76 static int initiator_send_HASH (struct message *);
77 static void post_quick_mode (struct message *);
78 static int responder_recv_HASH_SA_NONCE (struct message *);
79 static int responder_send_HASH_SA_NONCE (struct message *);
80 static int responder_recv_HASH (struct message *);
81 
82 #ifdef USE_POLICY
83 static int check_policy (struct exchange *, struct sa *, struct sa *);
84 #endif
85 
86 int (*ike_quick_mode_initiator[]) (struct message *) = {
87   initiator_send_HASH_SA_NONCE,
88   initiator_recv_HASH_SA_NONCE,
89   initiator_send_HASH
90 };
91 
92 int (*ike_quick_mode_responder[]) (struct message *) = {
93   responder_recv_HASH_SA_NONCE,
94   responder_send_HASH_SA_NONCE,
95   responder_recv_HASH
96 };
97 
98 #ifdef USE_POLICY
99 
100 /* How many return values will policy handle -- true/false for now */
101 #define RETVALUES_NUM 2
102 
103 /*
104  * Given an exchange and our policy, check whether the SA and IDs are
105  * acceptable.
106  */
107 static int
108 check_policy (struct exchange *exchange, struct sa *sa, struct sa *isakmp_sa)
109 {
110   char *return_values[RETVALUES_NUM];
111   char **principal = 0;
112   int i, result = 0, nprinc = 0;
113   int *x509_ids = 0, *keynote_ids = 0;
114   unsigned char hashbuf[20]; /* Set to the largest digest result */
115 #ifdef USE_X509
116   struct keynote_deckey dc;
117   X509_NAME *subject;
118 #endif
119 
120   /* Initialize if necessary -- e.g., if pre-shared key auth was used */
121   if (isakmp_sa->policy_id < 0)
122     {
123       if ((isakmp_sa->policy_id = LK (kn_init, ())) == -1)
124         {
125 	  log_print ("check_policy: failed to initialize policy session");
126 	  return 0;
127 	}
128     }
129 
130   /* Add the callback that will handle attributes.  */
131   if (LK (kn_add_action, (isakmp_sa->policy_id, ".*",
132 			  (char *) policy_callback,
133 			  ENVIRONMENT_FLAG_FUNC | ENVIRONMENT_FLAG_REGEX))
134       == -1)
135     {
136       log_print ("check_policy: "
137 		 "kn_add_action (%d, \".*\", %p, FUNC | REGEX) failed",
138 		 isakmp_sa->policy_id, policy_callback);
139       LK (kn_close, (isakmp_sa->policy_id));
140       isakmp_sa->policy_id = -1;
141       return 0;
142     }
143 
144   if (keynote_policy_asserts_num)
145     {
146       keynote_ids = calloc (keynote_policy_asserts_num, sizeof *keynote_ids);
147       if (!keynote_ids)
148         {
149 	  log_error ("check_policy: "
150 		     "failed to allocate %d bytes for book keeping",
151 		     keynote_policy_asserts_num * sizeof *keynote_ids);
152 	  return 0;
153         }
154     }
155 
156   /* Add the policy assertions */
157   for (i = 0; i < keynote_policy_asserts_num; i++)
158     keynote_ids[i] = LK (kn_add_assertion, (isakmp_sa->policy_id,
159 					    keynote_policy_asserts[i],
160 					    strlen (keynote_policy_asserts[i]),
161 					    ASSERT_FLAG_LOCAL));
162 
163   /* Initialize -- we'll let the callback do all the work.  */
164   policy_exchange = exchange;
165   policy_sa = sa;
166   policy_isakmp_sa = isakmp_sa;
167 
168   /* Set the return values; true/false for now at least.  */
169   return_values[0] = "false"; /* Order of values in array is important.  */
170   return_values[1] = "true";
171 
172   /* Create a principal (authorizer) for the SA/ID request.  */
173   switch (isakmp_sa->recv_certtype)
174     {
175     case ISAKMP_CERTENC_NONE:
176       /*
177        * For shared keys, just duplicate the passphrase with the
178        * appropriate prefix tag.
179        */
180       nprinc = 3;
181       principal = calloc (nprinc, sizeof *principal);
182       if (!principal)
183         {
184 	  log_error ("check_policy: calloc (%d, %d) failed", nprinc,
185 		     sizeof *principal);
186 	  goto policydone;
187 	}
188 
189       principal[0] = calloc (strlen (isakmp_sa->recv_key)
190 			     + sizeof "passphrase:", sizeof (char));
191       if (!principal[0])
192         {
193 	  log_error ("check_policy: calloc (%d, %d) failed",
194 		     strlen (isakmp_sa->recv_key) + sizeof "passphrase:",
195 		     sizeof (char));
196 	  goto policydone;
197 	}
198 
199       /* XXX Consider changing the magic hash lengths with constants.  */
200       strcpy (principal[0], "passphrase:");
201       memcpy (principal[0] + sizeof "passphrase:" - 1, isakmp_sa->recv_key,
202 	      strlen (isakmp_sa->recv_key));
203 
204       principal[1] = calloc (sizeof "passphrase-md5-hex:" + 2 * 16,
205 			     sizeof (char));
206       if (!principal[1])
207         {
208 	  log_error ("check_policy: calloc (%d, %d) failed",
209 		     sizeof "passphrase-md5-hex:" + 2 * 16, sizeof (char));
210 	  goto policydone;
211 	}
212 
213       strcpy (principal[1], "passphrase-md5-hex:");
214       MD5 (isakmp_sa->recv_key, strlen (isakmp_sa->recv_key), hashbuf);
215       for (i = 0; i < 16; i++)
216 	sprintf (principal[1] + 2 * i + sizeof "passphrase-md5-hex:" - 1,
217 		 "%02x", hashbuf[i]);
218 
219       principal[2] = calloc (sizeof "passphrase-sha1-hex:" + 2 * 20,
220 			     sizeof (char));
221       if (!principal[2])
222         {
223 	  log_error ("check_policy: calloc (%d, %d) failed",
224 		     sizeof "passphrase-sha1-hex:" + 2 * 20, sizeof (char));
225 	  goto policydone;
226 	}
227 
228       strcpy (principal[2], "passphrase-sha1-hex:");
229       SHA1 (isakmp_sa->recv_key, strlen (isakmp_sa->recv_key), hashbuf);
230       for (i = 0; i < 20; i++)
231 	sprintf (principal[2] + 2 * i + sizeof "passphrase-sha1-hex:" - 1,
232 		 "%02x", hashbuf[i]);
233       break;
234 
235     case ISAKMP_CERTENC_KEYNOTE:
236 #ifdef USE_KEYNOTE
237       nprinc = 1;
238 
239       principal = calloc (nprinc, sizeof *principal);
240       if (!principal)
241         {
242 	  log_error ("check_policy: calloc (%d, %d) failed", nprinc,
243 		     sizeof *principal);
244 	  goto policydone;
245 	}
246 
247       /* Dup the keys */
248       principal[0] = strdup (isakmp_sa->keynote_key);
249       if (!principal[0])
250         {
251 	  log_error ("check_policy: calloc (%d, %d) failed",
252 		     strlen (isakmp_sa->keynote_key), sizeof (char));
253 	  goto policydone;
254 	}
255 #endif
256       break;
257 
258     case ISAKMP_CERTENC_X509_SIG:
259 #ifdef USE_X509
260       principal = calloc (2, sizeof *principal);
261       if (!principal)
262         {
263 	  log_error ("check_policy: calloc (2, %d) failed", sizeof *principal);
264 	  goto policydone;
265 	}
266 
267       if (isakmp_sa->recv_keytype == ISAKMP_KEY_RSA)
268 	dc.dec_algorithm = KEYNOTE_ALGORITHM_RSA;
269       else
270 	{
271 	  log_error ("check_policy: unknown/unsupported public key algorithm "
272 		     "%d", isakmp_sa->recv_keytype);
273 	  goto policydone;
274 	}
275 
276       dc.dec_key = isakmp_sa->recv_key;
277       principal[0] = LK (kn_encode_key, (&dc, INTERNAL_ENC_PKCS1, ENCODING_HEX,
278 					 KEYNOTE_PUBLIC_KEY));
279       if (LKV (keynote_errno) == ERROR_MEMORY)
280 	{
281 	  log_print ("check_policy: failed to get memory for public key");
282 	  goto policydone;
283 	}
284 
285       if (!principal[0])
286 	{
287 	  log_print ("check_policy: failed to allocate memory for principal");
288 	  goto policydone;
289 	}
290 
291       principal[1] = calloc (strlen (principal[0]) + sizeof "rsa-hex:",
292 			     sizeof (char));
293       if (!principal[1])
294 	{
295 	  log_error ("check_policy: calloc (%d, %d) failed",
296 		     strlen (principal[0]) + sizeof "rsa-hex:", sizeof (char));
297 	  goto policydone;
298 	}
299 
300       sprintf (principal[1], "rsa-hex:%s", principal[0]);
301       free (principal[0]);
302       principal[0] = principal[1];
303       principal[1] = 0;
304 
305       /* Generate a "DN:" principal.  */
306       subject = LC (X509_get_subject_name, (isakmp_sa->recv_cert));
307       if (subject)
308 	{
309           principal[1] = calloc (259, sizeof (char));
310           if (!principal[1])
311             {
312 	      log_error ("check_policy: calloc (259, %d) failed",
313 			 sizeof (char));
314 	      goto policydone;
315             }
316 	  strcpy (principal[1], "DN:");
317 	  LC (X509_NAME_oneline, (subject, principal[1] + 3, 256));
318 	  nprinc = 2;
319 	} else {
320 	  nprinc = 1;
321 	}
322       break;
323 #endif
324 
325     /* XXX Eventually handle these.  */
326     case ISAKMP_CERTENC_PKCS:
327     case ISAKMP_CERTENC_PGP:
328     case ISAKMP_CERTENC_DNS:
329     case ISAKMP_CERTENC_X509_KE:
330     case ISAKMP_CERTENC_KERBEROS:
331     case ISAKMP_CERTENC_CRL:
332     case ISAKMP_CERTENC_ARL:
333     case ISAKMP_CERTENC_SPKI:
334     case ISAKMP_CERTENC_X509_ATTR:
335     default:
336       log_print ("check_policy: "
337 		 "unknown/unsupported certificate/authentication method %d",
338 		 isakmp_sa->recv_certtype);
339       goto policydone;
340     }
341 
342   /*
343    * Add the authorizer (who is requesting the SA/ID);
344    * this may be a public or a secret key, depending on
345    * what mode of authentication we used in Phase 1.
346    */
347   for (i = 0; i < nprinc; i++)
348     {
349       LOG_DBG ((LOG_POLICY, 40, "check_policy: adding authorizer [%s]",
350 		principal[i]));
351 
352       if (LK (kn_add_authorizer, (isakmp_sa->policy_id, principal[i])) == -1)
353         {
354 	  int j;
355 
356 	  for (j = 0; j < i; j++)
357 	    LK (kn_remove_authorizer, (isakmp_sa->policy_id, principal[j]));
358 	  log_print ("check_policy: kn_add_authorizer failed");
359 	  goto policydone;
360 	}
361     }
362 
363   /* Ask policy */
364   result = LK (kn_do_query, (isakmp_sa->policy_id, return_values,
365 			     RETVALUES_NUM));
366   LOG_DBG ((LOG_POLICY, 40, "check_policy: kn_do_query returned %d", result));
367 
368   /* Cleanup environment */
369   LK (kn_cleanup_action_environment, (isakmp_sa->policy_id));
370 
371   /* Remove authorizers from the session */
372   for (i = 0; i < nprinc; i++)
373     {
374       LK (kn_remove_authorizer, (isakmp_sa->policy_id, principal[i]));
375       free (principal[i]);
376     }
377 
378   free (principal);
379   principal = 0;
380   nprinc = 0;
381 
382   /* Check what policy said.  */
383   if (result < 0)
384     {
385       LOG_DBG ((LOG_POLICY, 40, "check_policy: proposal refused"));
386       result = 0;
387       goto policydone;
388     }
389 
390  policydone:
391   for (i = 0; i < nprinc; i++)
392     if (principal && principal[i])
393       free (principal[i]);
394 
395   if (principal)
396     free (principal);
397 
398   /* Remove the policies */
399   for (i = 0; i < keynote_policy_asserts_num; i++)
400     {
401       if (keynote_ids[i] != -1)
402 	LK (kn_remove_assertion, (isakmp_sa->policy_id, keynote_ids[i]));
403     }
404 
405   if (keynote_ids)
406     free (keynote_ids);
407 
408   if (x509_ids)
409     free (x509_ids);
410 
411   /*
412    * XXX Currently, check_policy() is only called from message_negotiate_sa(),
413    *     and so this log message reflects this. Change to something better?
414    */
415   if (result == 0)
416     log_print ("check_policy: negotiated SA failed policy check");
417 
418   /*
419    * Given that we have only 2 return values from policy (true/false)
420    * we can just return the query result directly (no pre-processing needed).
421    */
422   return result;
423 }
424 #endif /* USE_POLICY */
425 
426 /*
427  * Offer several sets of transforms to the responder.
428  * XXX Split this huge function up and look for common code with main mode.
429  */
430 static int
431 initiator_send_HASH_SA_NONCE (struct message *msg)
432 {
433   struct exchange *exchange = msg->exchange;
434   struct doi *doi = exchange->doi;
435   struct ipsec_exch *ie = exchange->data;
436   u_int8_t ***transform = 0, ***new_transform;
437   u_int8_t **proposal = 0, **new_proposal;
438   u_int8_t *sa_buf = 0, *attr, *saved_nextp_sa, *saved_nextp_prop, *id, *spi;
439   size_t spi_sz, sz;
440   size_t proposal_len = 0, proposals_len = 0, sa_len;
441   size_t **transform_len = 0, **new_transform_len;
442   size_t *transforms_len = 0, *new_transforms_len;
443   int *transform_cnt = 0, *new_transform_cnt;
444   int i, suite_no, prop_no, prot_no, xf_no, value, update_nextp, protocol_num;
445   int prop_cnt = 0;
446   struct proto *proto;
447   struct conf_list *suite_conf, *prot_conf = 0, *xf_conf = 0, *life_conf;
448   struct conf_list_node *suite, *prot, *xf, *life;
449   struct constant_map *id_map;
450   char *protocol_id, *transform_id;
451   char *local_id, *remote_id;
452   int group_desc = -1, new_group_desc;
453   struct ipsec_sa *isa = msg->isakmp_sa->data;
454   struct hash *hash = hash_get (isa->hash);
455   struct sockaddr *src;
456 
457   if (!ipsec_add_hash_payload (msg, hash->hashsize))
458     return -1;
459 
460   /* Get the list of protocol suites.  */
461   suite_conf = conf_get_list (exchange->policy, "Suites");
462   if (!suite_conf)
463     return -1;
464 
465   for (suite = TAILQ_FIRST (&suite_conf->fields), suite_no = prop_no = 0;
466        suite_no < suite_conf->cnt;
467        suite_no++, suite = TAILQ_NEXT (suite, link))
468     {
469       /* Now get each protocol in this specific protocol suite.  */
470       prot_conf = conf_get_list (suite->field, "Protocols");
471       if (!prot_conf)
472 	goto bail_out;
473 
474       for (prot = TAILQ_FIRST (&prot_conf->fields), prot_no = 0;
475 	   prot_no < prot_conf->cnt;
476 	   prot_no++, prot = TAILQ_NEXT (prot, link))
477 	{
478 	  /* Make sure we have a proposal/transform vectors.  */
479 	  if (prop_no >= prop_cnt)
480 	    {
481 	      /* This resize algorithm is completely arbitrary.  */
482 	      prop_cnt = 2 * prop_cnt + 10;
483 	      new_proposal = realloc (proposal, prop_cnt * sizeof *proposal);
484 	      if (!new_proposal)
485 		{
486 		  log_error ("initiator_send_HASH_SA_NONCE: "
487 			     "realloc (%p, %d) failed",
488 			     proposal, prop_cnt * sizeof *proposal);
489 		  goto bail_out;
490 		}
491 	      proposal = new_proposal;
492 
493 	      new_transforms_len = realloc (transforms_len,
494 					    prop_cnt * sizeof *transforms_len);
495 	      if (!new_transforms_len)
496 		{
497 		  log_error ("initiator_send_HASH_SA_NONCE: "
498 			     "realloc (%p, %d) failed",
499 			     transforms_len,
500 			     prop_cnt * sizeof *transforms_len);
501 		  goto bail_out;
502 		}
503 	      transforms_len = new_transforms_len;
504 
505 	      new_transform = realloc (transform,
506 				       prop_cnt * sizeof *transform);
507 	      if (!new_transform)
508 		{
509 		  log_error ("initiator_send_HASH_SA_NONCE: "
510 			     "realloc (%p, %d) failed",
511 			     transform, prop_cnt * sizeof *transform);
512 		  goto bail_out;
513 		}
514 	      transform = new_transform;
515 
516 	      new_transform_cnt = realloc (transform_cnt,
517 					   prop_cnt * sizeof *transform_cnt);
518 	      if (!new_transform_cnt)
519 		{
520 		  log_error ("initiator_send_HASH_SA_NONCE: "
521 			     "realloc (%p, %d) failed",
522 			     transform_cnt, prop_cnt * sizeof *transform_cnt);
523 		  goto bail_out;
524 		}
525 	      transform_cnt = new_transform_cnt;
526 
527 	      new_transform_len = realloc (transform_len,
528 					   prop_cnt * sizeof *transform_len);
529 	      if (!new_transform_len)
530 		{
531 		  log_error ("initiator_send_HASH_SA_NONCE: "
532 			     "realloc (%p, %d) failed",
533 			     transform_len, prop_cnt * sizeof *transform_len);
534 		  goto bail_out;
535 		}
536 	      transform_len = new_transform_len;
537 	    }
538 
539 	  protocol_id = conf_get_str (prot->field, "PROTOCOL_ID");
540 	  if (!protocol_id)
541 	    goto bail_out;
542 
543 	  /* XXX Not too beautiful, but do we have a choice?  */
544 	  id_map = strcasecmp (protocol_id, "IPSEC_AH") == 0 ? ipsec_ah_cst
545 	    : strcasecmp (protocol_id, "IPSEC_ESP") == 0 ? ipsec_esp_cst
546 	    : strcasecmp (protocol_id, "IPCOMP") == 0 ? ipsec_ipcomp_cst : 0;
547 	  if (!id_map)
548 	    goto bail_out;
549 
550 	  /* Now get each transform we offer for this protocol.  */
551 	  xf_conf = conf_get_list (prot->field, "Transforms");
552 	  if (!xf_conf)
553 	    goto bail_out;
554 	  transform_cnt[prop_no] = xf_conf->cnt;
555 
556 	  transform[prop_no] = calloc (transform_cnt[prop_no],
557 				       sizeof **transform);
558 	  if (!transform[prop_no])
559 	    {
560 	      log_error ("initiator_send_HASH_SA_NONCE: "
561 			 "calloc (%d, %d) failed",
562 			 transform_cnt[prop_no], sizeof **transform);
563 	      goto bail_out;
564 	    }
565 
566 	  transform_len[prop_no]
567 	    = calloc (transform_cnt[prop_no], sizeof **transform_len);
568 	  if (!transform_len[prop_no])
569 	    {
570 	      log_error ("initiator_send_HASH_SA_NONCE: "
571 			 "calloc (%d, %d) failed",
572 			 transform_cnt[prop_no], sizeof **transform_len);
573 	      goto bail_out;
574 	    }
575 
576 	  transforms_len[prop_no] = 0;
577 	  for (xf = TAILQ_FIRST (&xf_conf->fields), xf_no = 0;
578 	       xf_no < transform_cnt[prop_no];
579 	       xf_no++, xf = TAILQ_NEXT (xf, link))
580 	    {
581 
582 	      /* XXX The sizing needs to be dynamic.  */
583 	      transform[prop_no][xf_no] = calloc (ISAKMP_TRANSFORM_SA_ATTRS_OFF
584 						  + 9 * ISAKMP_ATTR_VALUE_OFF,
585 						  1);
586 	      if (!transform[prop_no][xf_no])
587 		{
588 		  log_error ("initiator_send_HASH_SA_NONCE: "
589 			     "calloc (%d, 1) failed",
590 			     ISAKMP_TRANSFORM_SA_ATTRS_OFF
591 			     + 9 * ISAKMP_ATTR_VALUE_OFF);
592 		  goto bail_out;
593 		}
594 
595 	      SET_ISAKMP_TRANSFORM_NO (transform[prop_no][xf_no], xf_no + 1);
596 
597 	      transform_id = conf_get_str (xf->field, "TRANSFORM_ID");
598 	      if (!transform_id)
599 		goto bail_out;
600 	      SET_ISAKMP_TRANSFORM_ID (transform[prop_no][xf_no],
601 				       constant_value (id_map, transform_id));
602 	      SET_ISAKMP_TRANSFORM_RESERVED (transform[prop_no][xf_no], 0);
603 
604 	      attr = transform[prop_no][xf_no] + ISAKMP_TRANSFORM_SA_ATTRS_OFF;
605 
606 	      /*
607 	       * Life durations are special, we should be able to specify
608 	       * several, one per type.
609 	       */
610 	      life_conf = conf_get_list (xf->field, "Life");
611 	      if (life_conf)
612 		{
613 		  for (life = TAILQ_FIRST (&life_conf->fields); life;
614 		       life = TAILQ_NEXT (life, link))
615 		    {
616 		      attribute_set_constant (life->field, "LIFE_TYPE",
617 					      ipsec_duration_cst,
618 					      IPSEC_ATTR_SA_LIFE_TYPE, &attr);
619 
620                       /* XXX Deals with 16 and 32 bit lifetimes only */
621 		      value = conf_get_num (life->field, "LIFE_DURATION", 0);
622 		      if (value)
623                         {
624                           if (value <= 0xffff)
625 			    attr =
626                               attribute_set_basic (attr,
627 						   IPSEC_ATTR_SA_LIFE_DURATION,
628 	              				   value);
629                           else
630                             {
631                               value = htonl (value);
632                               attr =
633                                 attribute_set_var (attr,
634                                                    IPSEC_ATTR_SA_LIFE_DURATION,
635                                                    (char *)&value,
636 						   sizeof value);
637                             }
638                         }
639 		    }
640 		  conf_free_list (life_conf);
641 		}
642 
643 	      attribute_set_constant (xf->field, "ENCAPSULATION_MODE",
644 				      ipsec_encap_cst,
645 				      IPSEC_ATTR_ENCAPSULATION_MODE, &attr);
646 
647 	      attribute_set_constant (xf->field, "AUTHENTICATION_ALGORITHM",
648 				      ipsec_auth_cst,
649 				      IPSEC_ATTR_AUTHENTICATION_ALGORITHM,
650 				      &attr);
651 
652 	      attribute_set_constant (xf->field, "GROUP_DESCRIPTION",
653 				      ike_group_desc_cst,
654 				      IPSEC_ATTR_GROUP_DESCRIPTION, &attr);
655 
656 
657 	      value = conf_get_num (xf->field, "KEY_LENGTH", 0);
658 	      if (value)
659 		attr = attribute_set_basic (attr, IPSEC_ATTR_KEY_LENGTH,
660 					    value);
661 
662 	      value = conf_get_num (xf->field, "KEY_ROUNDS", 0);
663 	      if (value)
664 		attr = attribute_set_basic (attr, IPSEC_ATTR_KEY_ROUNDS,
665 					    value);
666 
667 	      value = conf_get_num (xf->field, "COMPRESS_DICTIONARY_SIZE", 0);
668 	      if (value)
669 		attr
670 		  = attribute_set_basic (attr,
671 					 IPSEC_ATTR_COMPRESS_DICTIONARY_SIZE,
672 					 value);
673 
674 	      value
675 		= conf_get_num (xf->field, "COMPRESS_PRIVATE_ALGORITHM", 0);
676 	      if (value)
677 		attr
678 		  = attribute_set_basic (attr,
679 					 IPSEC_ATTR_COMPRESS_PRIVATE_ALGORITHM,
680 					 value);
681 
682 	      /* Record the real transform size.  */
683 	      transforms_len[prop_no] += (transform_len[prop_no][xf_no]
684 					  = attr - transform[prop_no][xf_no]);
685 
686 	      /*
687 	       * Make sure that if a group description is specified, it is
688 	       * specified for all transforms equally.
689 	       */
690 	      attr = conf_get_str (xf->field, "GROUP_DESCRIPTION");
691 	      new_group_desc
692 		= attr ? constant_value (ike_group_desc_cst, attr) : 0;
693 	      if (group_desc == -1)
694 		group_desc = new_group_desc;
695 	      else if (group_desc != new_group_desc)
696 		{
697 		  log_print ("initiator_send_HASH_SA_NONCE: "
698 			     "differing group descriptions in a proposal");
699 		  goto bail_out;
700 		}
701 	    }
702 	  conf_free_list (xf_conf);
703 	  xf_conf = 0;
704 
705 	  /*
706 	   * Get SPI from application.
707 	   * XXX Should we care about unknown constants?
708 	   */
709 	  protocol_num = constant_value (ipsec_proto_cst, protocol_id);
710 	  spi = doi->get_spi (&spi_sz, protocol_num, msg);
711 	  if (spi_sz && !spi)
712 	    {
713 	      log_print ("initiator_send_HASH_SA_NONCE: doi->get_spi failed");
714 	      goto bail_out;
715 	    }
716 
717 	  proposal_len = ISAKMP_PROP_SPI_OFF + spi_sz;
718 	  proposals_len += proposal_len + transforms_len[prop_no];
719 	  proposal[prop_no] = malloc (proposal_len);
720 	  if (!proposal[prop_no])
721 	    {
722 	      log_error ("initiator_send_HASH_SA_NONCE: malloc (%d) failed",
723 			 proposal_len);
724 	      goto bail_out;
725 	    }
726 
727 	  SET_ISAKMP_PROP_NO (proposal[prop_no], suite_no + 1);
728 	  SET_ISAKMP_PROP_PROTO (proposal[prop_no], protocol_num);
729 
730 	  /* XXX I would like to see this factored out.  */
731 	  proto = calloc (1, sizeof *proto);
732 	  if (!proto)
733 	    {
734 	      log_error ("initiator_send_HASH_SA_NONCE: calloc (1, %d) failed",
735 			 sizeof *proto);
736 	      goto bail_out;
737 	    }
738 
739 	  if (doi->proto_size)
740 	    {
741 	      proto->data = calloc (1, doi->proto_size);
742 	      if (!proto->data)
743 		{
744 		  log_error ("initiator_send_HASH_SA_NONCE: "
745 			     "calloc (1, %d) failed", doi->proto_size);
746 		  goto bail_out;
747 		}
748 	    }
749 
750 	  proto->no = suite_no + 1;
751 	  proto->proto = protocol_num;
752 	  proto->sa = TAILQ_FIRST (&exchange->sa_list);
753 	  TAILQ_INSERT_TAIL (&TAILQ_FIRST (&exchange->sa_list)->protos, proto,
754 			     link);
755 
756 	  /* Setup the incoming SPI.  */
757 	  SET_ISAKMP_PROP_SPI_SZ (proposal[prop_no], spi_sz);
758 	  memcpy (proposal[prop_no] + ISAKMP_PROP_SPI_OFF, spi, spi_sz);
759 	  proto->spi_sz[1] = spi_sz;
760 	  proto->spi[1] = spi;
761 
762 	  /* Let the DOI get at proto for initializing its own data.  */
763 	  if (doi->proto_init)
764 	    doi->proto_init (proto, prot->field);
765 
766 	  SET_ISAKMP_PROP_NTRANSFORMS (proposal[prop_no],
767 				       transform_cnt[prop_no]);
768 	  prop_no++;
769 	}
770       conf_free_list (prot_conf);
771       prot_conf = 0;
772     }
773 
774   sa_len = ISAKMP_SA_SIT_OFF + IPSEC_SIT_SIT_LEN;
775   sa_buf = malloc (sa_len);
776   if (!sa_buf)
777     {
778       log_error ("initiator_send_HASH_SA_NONCE: malloc (%d) failed", sa_len);
779       goto bail_out;
780     }
781   SET_ISAKMP_SA_DOI (sa_buf, IPSEC_DOI_IPSEC);
782   SET_IPSEC_SIT_SIT (sa_buf + ISAKMP_SA_SIT_OFF, IPSEC_SIT_IDENTITY_ONLY);
783 
784   /*
785    * Add the payloads.  As this is a SA, we need to recompute the
786    * lengths of the payloads containing others.  We also need to
787    * reset these payload's "next payload type" field.
788    */
789   if (message_add_payload (msg, ISAKMP_PAYLOAD_SA, sa_buf, sa_len, 1))
790     goto bail_out;
791   SET_ISAKMP_GEN_LENGTH (sa_buf, sa_len + proposals_len);
792   sa_buf = 0;
793 
794   update_nextp = 0;
795   saved_nextp_sa = msg->nextp;
796   for (i = 0; i < prop_no; i++)
797     {
798       if (message_add_payload (msg, ISAKMP_PAYLOAD_PROPOSAL, proposal[i],
799 			       proposal_len, update_nextp))
800 	goto bail_out;
801       SET_ISAKMP_GEN_LENGTH (proposal[i], proposal_len + transforms_len[i]);
802       proposal[i] = 0;
803 
804       update_nextp = 0;
805       saved_nextp_prop = msg->nextp;
806       for (xf_no = 0; xf_no < transform_cnt[i]; xf_no++)
807 	{
808 	  if (message_add_payload (msg, ISAKMP_PAYLOAD_TRANSFORM,
809 				   transform[i][xf_no],
810 				   transform_len[i][xf_no], update_nextp))
811 	    goto bail_out;
812 	  update_nextp = 1;
813 	  transform[i][xf_no] = 0;
814 	}
815       msg->nextp = saved_nextp_prop;
816       update_nextp = 1;
817     }
818   msg->nextp = saved_nextp_sa;
819 
820   /*
821    * Save SA payload body in ie->sa_i_b, length ie->sa_i_b_len.
822    */
823   ie->sa_i_b = message_copy (msg, ISAKMP_GEN_SZ, &ie->sa_i_b_len);
824   if (!ie->sa_i_b)
825     goto bail_out;
826 
827   /*
828    * Generate a nonce, and add it to the message.
829    * XXX I want a better way to specify the nonce's size.
830    */
831   if (exchange_gen_nonce (msg, 16))
832     return -1;
833 
834   /* Generate optional KEY_EXCH payload.  */
835   if (group_desc)
836     {
837       ie->group = group_get (group_desc);
838       ie->g_x_len = dh_getlen (ie->group);
839 
840       if (ipsec_gen_g_x (msg))
841 	{
842 	  group_free (ie->group);
843 	  ie->group = 0;
844 	  return -1;
845 	}
846     }
847 
848   /* Generate optional client ID payloads.  XXX Share with responder.  */
849   local_id = conf_get_str (exchange->name, "Local-ID");
850   remote_id = conf_get_str (exchange->name, "Remote-ID");
851   if (local_id && remote_id)
852     {
853       id = ipsec_build_id (local_id, &sz);
854       if (!id)
855 	return -1;
856       LOG_DBG_BUF ((LOG_NEGOTIATION, 90, "initiator_send_HASH_SA_NONCE: IDic",
857 		    id, sz));
858       if (message_add_payload (msg, ISAKMP_PAYLOAD_ID, id, sz, 1))
859 	{
860 	  free (id);
861 	  return -1;
862 	}
863 
864       id = ipsec_build_id (remote_id, &sz);
865       if (!id)
866 	return -1;
867       LOG_DBG_BUF ((LOG_NEGOTIATION, 90, "initiator_send_HASH_SA_NONCE: IDrc",
868 		    id, sz));
869       if (message_add_payload (msg, ISAKMP_PAYLOAD_ID, id, sz, 1))
870 	{
871 	  free (id);
872 	  return -1;
873 	}
874     }
875   /* XXX I do not judge these as errors, are they?  */
876   else if (local_id)
877     log_print ("initiator_send_HASH_SA_NONCE: "
878 	       "Local-ID given without Remote-ID for \"%s\"",
879 	       exchange->name);
880   else if (remote_id)
881     /* This code supports the "road warrior" case, where the initiator doesn't
882      * have a fixed IP address, but wants to specify a particular remote
883      * network to talk to.
884      * -- Adrian Close <adrian@esec.com.au>
885      */
886     {
887       log_print ("initiator_send_HASH_SA_NONCE: "
888 	       "Remote-ID given without Local-ID for \"%s\"",
889 	       exchange->name);
890 
891       /* If we're here, then we are the initiator, so use initiator
892 	address for local ID */
893       msg->transport->vtbl->get_src (msg->transport, &src);
894       sz = ISAKMP_ID_SZ + sockaddr_addrlen (src);
895 
896       id = calloc (sz, sizeof (char));
897       if (!id)
898 	{
899 	  log_error ("initiator_send_HASH_SA_NONCE: malloc(%d) failed", sz);
900 	  return -1;
901 	}
902 
903       switch (src->sa_family)
904 	{
905 	case AF_INET6:
906 	  SET_ISAKMP_ID_TYPE (id, IPSEC_ID_IPV6_ADDR);
907 	  break;
908 	case AF_INET:
909 	  SET_ISAKMP_ID_TYPE (id, IPSEC_ID_IPV4_ADDR);
910 	  break;
911 	default:
912 	  log_error ("initiator_send_HASH_SA_NONCE: unknown sa_family %d",
913 		     src->sa_family);
914 	  free (id);
915 	  return -1;
916 	}
917       memcpy (id + ISAKMP_ID_DATA_OFF, sockaddr_addrdata (src),
918 	      sockaddr_addrlen (src));
919 
920       LOG_DBG_BUF ((LOG_NEGOTIATION, 90, "initiator_send_HASH_SA_NONCE: IDic",
921 		    id, sz));
922       if (message_add_payload (msg, ISAKMP_PAYLOAD_ID, id, sz, 1))
923 	{
924 	  free (id);
925 	  return -1;
926 	}
927 
928     /* Send supplied remote_id */
929       id = ipsec_build_id (remote_id, &sz);
930       if (!id)
931 	return -1;
932       LOG_DBG_BUF ((LOG_NEGOTIATION, 90, "initiator_send_HASH_SA_NONCE: IDrc",
933 		    id, sz));
934       if (message_add_payload (msg, ISAKMP_PAYLOAD_ID, id, sz, 1))
935 	{
936 	  free (id);
937 	  return -1;
938 	}
939     }
940 
941   if (ipsec_fill_in_hash (msg))
942     goto bail_out;
943 
944   conf_free_list (suite_conf);
945   for (i = 0; i < prop_no; i++)
946     {
947       free (transform[i]);
948       free (transform_len[i]);
949     }
950   free (proposal);
951   free (transform);
952   free (transforms_len);
953   free (transform_len);
954   free (transform_cnt);
955   return 0;
956 
957  bail_out:
958   if (sa_buf)
959     free (sa_buf);
960   if (proposal)
961     {
962       for (i = 0; i < prop_no; i++)
963 	{
964 	  if (proposal[i])
965 	    free (proposal[i]);
966 	  if (transform[i])
967 	    {
968 	      for (xf_no = 0; xf_no < transform_cnt[i]; xf_no++)
969 		if (transform[i][xf_no])
970 		  free (transform[i][xf_no]);
971 	      free (transform[i]);
972 	    }
973 	  if (transform_len[i])
974 	    free (transform_len[i]);
975 	}
976       free (proposal);
977       free (transforms_len);
978       free (transform);
979       free (transform_len);
980       free (transform_cnt);
981     }
982   if (xf_conf)
983     conf_free_list (xf_conf);
984   if (prot_conf)
985     conf_free_list (prot_conf);
986   conf_free_list (suite_conf);
987   return -1;
988 }
989 
990 /* Figure out what transform the responder chose.  */
991 static int
992 initiator_recv_HASH_SA_NONCE (struct message *msg)
993 {
994   struct exchange *exchange = msg->exchange;
995   struct ipsec_exch *ie = exchange->data;
996   struct sa *sa;
997   struct proto *proto, *next_proto;
998   struct payload *sa_p = TAILQ_FIRST (&msg->payload[ISAKMP_PAYLOAD_SA]);
999   struct payload *xf, *idp;
1000   struct payload *hashp = TAILQ_FIRST (&msg->payload[ISAKMP_PAYLOAD_HASH]);
1001   struct payload *kep = TAILQ_FIRST (&msg->payload[ISAKMP_PAYLOAD_KEY_EXCH]);
1002   struct prf *prf;
1003   struct sa *isakmp_sa = msg->isakmp_sa;
1004   struct ipsec_sa *isa = isakmp_sa->data;
1005   struct hash *hash = hash_get (isa->hash);
1006   size_t hashsize = hash->hashsize;
1007   u_int8_t *rest;
1008   size_t rest_len;
1009   struct sockaddr *src, *dst;
1010 
1011   /* Allocate the prf and start calculating our HASH(1).  XXX Share?  */
1012   LOG_DBG_BUF ((LOG_NEGOTIATION, 90, "initiator_recv_HASH_SA_NONCE: SKEYID_a",
1013 		isa->skeyid_a, isa->skeyid_len));
1014   prf = prf_alloc (isa->prf_type, hash->type, isa->skeyid_a, isa->skeyid_len);
1015   if (!prf)
1016     return -1;
1017 
1018   prf->Init (prf->prfctx);
1019   LOG_DBG_BUF ((LOG_NEGOTIATION, 90,
1020 		"initiator_recv_HASH_SA_NONCE: message_id",
1021 		exchange->message_id, ISAKMP_HDR_MESSAGE_ID_LEN));
1022   prf->Update (prf->prfctx, exchange->message_id, ISAKMP_HDR_MESSAGE_ID_LEN);
1023   LOG_DBG_BUF ((LOG_NEGOTIATION, 90, "initiator_recv_HASH_SA_NONCE: NONCE_I_b",
1024 		exchange->nonce_i, exchange->nonce_i_len));
1025   prf->Update (prf->prfctx, exchange->nonce_i, exchange->nonce_i_len);
1026   rest = hashp->p + GET_ISAKMP_GEN_LENGTH (hashp->p);
1027   rest_len = (GET_ISAKMP_HDR_LENGTH (msg->iov[0].iov_base)
1028 	      - (rest - (u_int8_t*)msg->iov[0].iov_base));
1029   LOG_DBG_BUF ((LOG_NEGOTIATION, 90,
1030 		"initiator_recv_HASH_SA_NONCE: payloads after HASH(2)", rest,
1031 		rest_len));
1032   prf->Update (prf->prfctx, rest, rest_len);
1033   prf->Final (hash->digest, prf->prfctx);
1034   prf_free (prf);
1035   LOG_DBG_BUF ((LOG_NEGOTIATION, 80,
1036 		"initiator_recv_HASH_SA_NONCE: computed HASH(2)",
1037 		hash->digest, hashsize));
1038   if (memcmp (hashp->p + ISAKMP_HASH_DATA_OFF, hash->digest, hashsize) != 0)
1039     {
1040       message_drop (msg, ISAKMP_NOTIFY_INVALID_HASH_INFORMATION, 0, 1, 0);
1041       return -1;
1042     }
1043   /* Mark the HASH as handled.  */
1044   hashp->flags |= PL_MARK;
1045 
1046   /*
1047    * As we are getting an answer on our transform offer, only one transform
1048    * should be given.
1049    *
1050    * XXX Currently we only support negotiating one SA per quick mode run.
1051    */
1052   if (TAILQ_NEXT (sa_p, link))
1053     {
1054       log_print ("initiator_recv_HASH_SA_NONCE: "
1055 		 "multiple SA payloads in quick mode not supported yet");
1056       return -1;
1057     }
1058 
1059   sa = TAILQ_FIRST (&exchange->sa_list);
1060 
1061   /* This is here for the policy check */
1062   if (kep)
1063     ie->pfs = 1;
1064 
1065   /* Handle optional client ID payloads.  */
1066   idp = TAILQ_FIRST (&msg->payload[ISAKMP_PAYLOAD_ID]);
1067   if (idp)
1068     {
1069       /* If IDci is there, IDcr must be too.  */
1070       if (!TAILQ_NEXT (idp, link))
1071 	{
1072 	  /* XXX Is this a good notify type?  */
1073 	  message_drop (msg, ISAKMP_NOTIFY_PAYLOAD_MALFORMED, 0, 1, 0);
1074 	  return -1;
1075 	}
1076 
1077       /* XXX We should really compare, not override.  */
1078       ie->id_ci_sz = GET_ISAKMP_GEN_LENGTH (idp->p);
1079       ie->id_ci = malloc (ie->id_ci_sz);
1080       if (!ie->id_ci)
1081 	{
1082 	  log_error ("initiator_recv_HASH_SA_NONCE: malloc (%d) failed",
1083 		     ie->id_ci_sz);
1084 	  return -1;
1085 	}
1086       memcpy (ie->id_ci, idp->p, ie->id_ci_sz);
1087       idp->flags |= PL_MARK;
1088       LOG_DBG_BUF ((LOG_NEGOTIATION, 90,
1089 		    "initiator_recv_HASH_SA_NONCE: IDci",
1090 		    ie->id_ci + ISAKMP_GEN_SZ, ie->id_ci_sz
1091 		    - ISAKMP_GEN_SZ));
1092 
1093       idp = TAILQ_NEXT (idp, link);
1094       ie->id_cr_sz = GET_ISAKMP_GEN_LENGTH (idp->p);
1095       ie->id_cr = malloc (ie->id_cr_sz);
1096       if (!ie->id_cr)
1097 	{
1098 	  log_error ("initiator_recv_HASH_SA_NONCE: malloc (%d) failed",
1099 		     ie->id_cr_sz);
1100 	  return -1;
1101 	}
1102       memcpy (ie->id_cr, idp->p, ie->id_cr_sz);
1103       idp->flags |= PL_MARK;
1104       LOG_DBG_BUF ((LOG_NEGOTIATION, 90,
1105 		    "initiator_recv_HASH_SA_NONCE: IDcr",
1106 		    ie->id_cr + ISAKMP_GEN_SZ, ie->id_cr_sz
1107 		    - ISAKMP_GEN_SZ));
1108     }
1109   else
1110     {
1111       /*
1112        * If client identifiers are not present in the exchange,
1113        * we fake them. RFC 2409 states:
1114        *    The identities of the SAs negotiated in Quick Mode are
1115        *    implicitly assumed to be the IP addresses of the ISAKMP
1116        *    peers, without any constraints on the protocol or port
1117        *    numbers allowed, unless client identifiers are specified
1118        *    in Quick Mode.
1119        *
1120        * -- Michael Paddon (mwp@aba.net.au)
1121        */
1122 
1123       ie->flags = IPSEC_EXCH_FLAG_NO_ID;
1124 
1125       /* Get initiator and responder addresses.  */
1126       msg->transport->vtbl->get_src (msg->transport, &src);
1127       msg->transport->vtbl->get_dst (msg->transport, &dst);
1128       ie->id_ci_sz = ISAKMP_ID_DATA_OFF + sockaddr_addrlen (src);
1129       ie->id_cr_sz = ISAKMP_ID_DATA_OFF + sockaddr_addrlen (dst);
1130       ie->id_ci = calloc (ie->id_ci_sz, sizeof (char));
1131       ie->id_cr = calloc (ie->id_cr_sz, sizeof (char));
1132 
1133       if (!ie->id_ci || !ie->id_cr)
1134 	{
1135 	  log_error ("initiator_recv_HASH_SA_NONCE: malloc (%d) failed",
1136 		     ie->id_cr_sz);
1137 	  if (ie->id_ci)
1138 	    free (ie->id_ci);
1139 	  if (ie->id_cr)
1140 	    free (ie->id_cr);
1141 	  return -1;
1142 	}
1143 
1144       if (src->sa_family != dst->sa_family)
1145 	{
1146 	  log_error ("initiator_recv_HASH_SA_NONCE: sa_family mismatch");
1147 	  free (ie->id_ci);
1148 	  free (ie->id_cr);
1149 	  return -1;
1150 	}
1151 
1152       switch (src->sa_family)
1153 	{
1154 	case AF_INET:
1155 	  SET_ISAKMP_ID_TYPE (ie->id_ci, IPSEC_ID_IPV4_ADDR);
1156 	  SET_ISAKMP_ID_TYPE (ie->id_cr, IPSEC_ID_IPV4_ADDR);
1157 	  break;
1158 
1159 	case AF_INET6:
1160 	  SET_ISAKMP_ID_TYPE (ie->id_ci, IPSEC_ID_IPV6_ADDR);
1161 	  SET_ISAKMP_ID_TYPE (ie->id_cr, IPSEC_ID_IPV6_ADDR);
1162 	  break;
1163 
1164 	default:
1165 	  log_error ("initiator_recv_HASH_SA_NONCE: unknown sa_family %d",
1166 		     src->sa_family);
1167 	  free (ie->id_ci);
1168 	  free (ie->id_cr);
1169 	  return -1;
1170 	}
1171       memcpy (ie->id_ci + ISAKMP_ID_DATA_OFF, sockaddr_addrdata (src),
1172 	      sockaddr_addrlen (src));
1173       memcpy (ie->id_cr + ISAKMP_ID_DATA_OFF, sockaddr_addrdata (dst),
1174 	      sockaddr_addrlen (dst));
1175     }
1176 
1177   /* Build the protection suite in our SA.  */
1178   for (xf = TAILQ_FIRST (&msg->payload[ISAKMP_PAYLOAD_TRANSFORM]); xf;
1179        xf = TAILQ_NEXT (xf, link))
1180     {
1181 
1182       /*
1183        * XXX We could check that the proposal each transform belongs to
1184        * is unique.
1185        */
1186 
1187       if (sa_add_transform (sa, xf, exchange->initiator, &proto))
1188 	return -1;
1189 
1190       /* XXX Check that the chosen transform matches an offer.  */
1191 
1192       ipsec_decode_transform (msg, sa, proto, xf->p);
1193     }
1194 
1195   /* Now remove offers that we don't need anymore.  */
1196   for (proto = TAILQ_FIRST (&sa->protos); proto; proto = next_proto)
1197     {
1198       next_proto = TAILQ_NEXT (proto, link);
1199       if (!proto->chosen)
1200 	proto_free (proto);
1201     }
1202 
1203 #ifdef USE_POLICY
1204   if (!check_policy (exchange, sa, msg->isakmp_sa))
1205     {
1206       message_drop (msg, ISAKMP_NOTIFY_NO_PROPOSAL_CHOSEN, 0, 1, 0);
1207       log_print ("initiator_recv_HASH_SA_NONCE: policy check failed");
1208       return -1;
1209     }
1210 #endif
1211 
1212   /* Mark the SA as handled.  */
1213   sa_p->flags |= PL_MARK;
1214 
1215   isa = sa->data;
1216   if ((isa->group_desc && (!ie->group || ie->group->id != isa->group_desc))
1217       || (!isa->group_desc && ie->group))
1218     {
1219       log_print ("initiator_recv_HASH_SA_NONCE: disagreement on PFS");
1220       return -1;
1221     }
1222 
1223   /* Copy out the initiator's nonce.  */
1224   if (exchange_save_nonce (msg))
1225     return -1;
1226 
1227   /* Handle the optional KEY_EXCH payload.  */
1228   if (kep && ipsec_save_g_x (msg))
1229     return -1;
1230 
1231   return 0;
1232 }
1233 
1234 static int
1235 initiator_send_HASH (struct message *msg)
1236 {
1237   struct exchange *exchange = msg->exchange;
1238   struct ipsec_exch *ie = exchange->data;
1239   struct sa *isakmp_sa = msg->isakmp_sa;
1240   struct ipsec_sa *isa = isakmp_sa->data;
1241   struct prf *prf;
1242   u_int8_t *buf;
1243   struct hash *hash = hash_get (isa->hash);
1244   size_t hashsize = hash->hashsize;
1245 
1246   /* We want a HASH payload to start with.  XXX Share with ike_main_mode.c?  */
1247   buf = malloc (ISAKMP_HASH_SZ + hashsize);
1248   if (!buf)
1249     {
1250       log_error ("initiator_send_HASH: malloc (%d) failed",
1251 		 ISAKMP_HASH_SZ + hashsize);
1252       return -1;
1253     }
1254   if (message_add_payload (msg, ISAKMP_PAYLOAD_HASH, buf,
1255 			   ISAKMP_HASH_SZ + hashsize, 1))
1256     {
1257       free (buf);
1258       return -1;
1259     }
1260 
1261   /* Allocate the prf and start calculating our HASH(3).  XXX Share?  */
1262   LOG_DBG_BUF ((LOG_NEGOTIATION, 90, "initiator_send_HASH: SKEYID_a",
1263 		isa->skeyid_a, isa->skeyid_len));
1264   prf = prf_alloc (isa->prf_type, isa->hash, isa->skeyid_a, isa->skeyid_len);
1265   if (!prf)
1266     return -1;
1267   prf->Init (prf->prfctx);
1268   prf->Update (prf->prfctx, "\0", 1);
1269   LOG_DBG_BUF ((LOG_NEGOTIATION, 90, "initiator_send_HASH: message_id",
1270 		exchange->message_id, ISAKMP_HDR_MESSAGE_ID_LEN));
1271   prf->Update (prf->prfctx, exchange->message_id, ISAKMP_HDR_MESSAGE_ID_LEN);
1272   LOG_DBG_BUF ((LOG_NEGOTIATION, 90, "initiator_send_HASH: NONCE_I_b",
1273 		exchange->nonce_i, exchange->nonce_i_len));
1274   prf->Update (prf->prfctx, exchange->nonce_i, exchange->nonce_i_len);
1275   LOG_DBG_BUF ((LOG_NEGOTIATION, 90, "initiator_send_HASH: NONCE_R_b",
1276 		exchange->nonce_r, exchange->nonce_r_len));
1277   prf->Update (prf->prfctx, exchange->nonce_r, exchange->nonce_r_len);
1278   prf->Final (buf + ISAKMP_GEN_SZ, prf->prfctx);
1279   prf_free (prf);
1280   LOG_DBG_BUF ((LOG_NEGOTIATION, 90, "initiator_send_HASH: HASH(3)",
1281 		buf + ISAKMP_GEN_SZ, hashsize));
1282 
1283   if (ie->group)
1284     message_register_post_send (msg, gen_g_xy);
1285 
1286   message_register_post_send (msg, post_quick_mode);
1287 
1288   return 0;
1289 }
1290 
1291 static void
1292 post_quick_mode (struct message *msg)
1293 {
1294   struct sa *isakmp_sa = msg->isakmp_sa;
1295   struct ipsec_sa *isa = isakmp_sa->data;
1296   struct exchange *exchange = msg->exchange;
1297   struct ipsec_exch *ie = exchange->data;
1298   struct prf *prf;
1299   struct sa *sa;
1300   struct proto *proto;
1301   struct ipsec_proto *iproto;
1302   u_int8_t *keymat;
1303   int i;
1304 
1305   /*
1306    * Loop over all SA negotiations and do both an in- and an outgoing SA
1307    * per protocol.
1308    */
1309   for (sa = TAILQ_FIRST (&exchange->sa_list); sa; sa = TAILQ_NEXT (sa, next))
1310     {
1311       for (proto = TAILQ_FIRST (&sa->protos); proto;
1312 	   proto = TAILQ_NEXT (proto, link))
1313 	{
1314 	  iproto = proto->data;
1315 
1316 	  /*
1317 	   * There are two SAs for each SA negotiation, incoming and outcoing.
1318 	   */
1319 	  for (i = 0; i < 2; i++)
1320 	    {
1321 	      prf = prf_alloc (isa->prf_type, isa->hash, isa->skeyid_d,
1322 			       isa->skeyid_len);
1323 	      if (!prf)
1324 		{
1325 		  /* XXX What to do?  */
1326 		  continue;
1327 		}
1328 
1329 	      ie->keymat_len = ipsec_keymat_length (proto);
1330 
1331 	      /*
1332 	       * We need to roundup the length of the key material buffer
1333 	       * to a multiple of the PRF's blocksize as it is generated
1334 	       * in chunks of that blocksize.
1335 	       */
1336 	      iproto->keymat[i]
1337 		= malloc (((ie->keymat_len + prf->blocksize - 1)
1338 			   / prf->blocksize) * prf->blocksize);
1339 	      if (!iproto->keymat[i])
1340 		{
1341 		  log_error ("post_quick_mode: malloc (%d) failed",
1342 			     ((ie->keymat_len + prf->blocksize - 1)
1343 			      / prf->blocksize) * prf->blocksize);
1344 		  /* XXX What more to do?  */
1345 		  free (prf);
1346 		  continue;
1347 		}
1348 
1349 	      for (keymat = iproto->keymat[i];
1350 		   keymat < iproto->keymat[i] + ie->keymat_len;
1351 		   keymat += prf->blocksize)
1352 		{
1353 		  prf->Init (prf->prfctx);
1354 
1355 		  if (keymat != iproto->keymat[i])
1356 		    {
1357 		      /* Hash in last round's KEYMAT.  */
1358 		      LOG_DBG_BUF ((LOG_NEGOTIATION, 90,
1359 				    "post_quick_mode: last KEYMAT",
1360 				    keymat - prf->blocksize,
1361 				    prf->blocksize));
1362 		      prf->Update (prf->prfctx, keymat - prf->blocksize,
1363 				   prf->blocksize);
1364 		    }
1365 
1366 		  /* If PFS is used hash in g^xy.  */
1367 		  if (ie->g_xy)
1368 		    {
1369 		      LOG_DBG_BUF ((LOG_NEGOTIATION, 90,
1370 				    "post_quick_mode: g^xy", ie->g_xy,
1371 				    ie->g_x_len));
1372 		      prf->Update (prf->prfctx, ie->g_xy, ie->g_x_len);
1373 		    }
1374 		  LOG_DBG ((LOG_NEGOTIATION, 90,
1375 			    "post_quick_mode: suite %d proto %d", proto->no,
1376 			    proto->proto));
1377 		  prf->Update (prf->prfctx, &proto->proto, 1);
1378 		  LOG_DBG_BUF ((LOG_NEGOTIATION, 90, "post_quick_mode: SPI",
1379 				proto->spi[i], proto->spi_sz[i]));
1380 		  prf->Update (prf->prfctx, proto->spi[i], proto->spi_sz[i]);
1381 		  LOG_DBG_BUF ((LOG_NEGOTIATION, 90, "post_quick_mode: Ni_b",
1382 				exchange->nonce_i, exchange->nonce_i_len));
1383 		  prf->Update (prf->prfctx, exchange->nonce_i,
1384 			       exchange->nonce_i_len);
1385 		  LOG_DBG_BUF ((LOG_NEGOTIATION, 90, "post_quick_mode: Nr_b",
1386 				exchange->nonce_r, exchange->nonce_r_len));
1387 		  prf->Update (prf->prfctx, exchange->nonce_r,
1388 			       exchange->nonce_r_len);
1389 		  prf->Final (keymat, prf->prfctx);
1390 		}
1391 	      prf_free (prf);
1392 	      LOG_DBG_BUF ((LOG_NEGOTIATION, 90, "post_quick_mode: KEYMAT",
1393 			    iproto->keymat[i], ie->keymat_len));
1394 	    }
1395 	}
1396     }
1397 }
1398 
1399 /*
1400  * Accept a set of transforms offered by the initiator and chose one we can
1401  * handle.
1402  * XXX Describe in more detail.
1403  */
1404 static int
1405 responder_recv_HASH_SA_NONCE (struct message *msg)
1406 {
1407   struct payload *hashp, *kep, *idp;
1408   struct sa *sa;
1409   struct sa *isakmp_sa = msg->isakmp_sa;
1410   struct ipsec_sa *isa = isakmp_sa->data;
1411   struct exchange *exchange = msg->exchange;
1412   struct ipsec_exch *ie = exchange->data;
1413   struct prf *prf;
1414   u_int8_t *hash, *my_hash = 0;
1415   size_t hash_len;
1416   u_int8_t *pkt = msg->iov[0].iov_base;
1417   u_int8_t group_desc = 0;
1418   int retval = -1;
1419   struct proto *proto;
1420   struct sockaddr *src, *dst;
1421   char *name;
1422 
1423   hashp = TAILQ_FIRST (&msg->payload[ISAKMP_PAYLOAD_HASH]);
1424   hash = hashp->p;
1425   hashp->flags |= PL_MARK;
1426 
1427   /* The HASH payload should be the first one.  */
1428   if (hash != pkt + ISAKMP_HDR_SZ)
1429     {
1430       /* XXX Is there a better notification type?  */
1431       message_drop (msg, ISAKMP_NOTIFY_PAYLOAD_MALFORMED, 0, 1, 0);
1432       goto cleanup;
1433     }
1434   hash_len = GET_ISAKMP_GEN_LENGTH (hash);
1435   my_hash = malloc (hash_len - ISAKMP_GEN_SZ);
1436   if (!my_hash)
1437     {
1438       log_error ("responder_recv_HASH_SA_NONCE: malloc (%d) failed",
1439 		 hash_len - ISAKMP_GEN_SZ);
1440       goto cleanup;
1441     }
1442 
1443   /*
1444    * Check the payload's integrity.
1445    * XXX Share with ipsec_fill_in_hash?
1446    */
1447   LOG_DBG_BUF ((LOG_NEGOTIATION, 90, "responder_recv_HASH_SA_NONCE: SKEYID_a",
1448 		isa->skeyid_a, isa->skeyid_len));
1449   prf = prf_alloc (isa->prf_type, isa->hash, isa->skeyid_a, isa->skeyid_len);
1450   if (!prf)
1451     goto cleanup;
1452   prf->Init (prf->prfctx);
1453   LOG_DBG_BUF ((LOG_NEGOTIATION, 90,
1454 		"responder_recv_HASH_SA_NONCE: message_id",
1455 		exchange->message_id, ISAKMP_HDR_MESSAGE_ID_LEN));
1456   prf->Update (prf->prfctx, exchange->message_id, ISAKMP_HDR_MESSAGE_ID_LEN);
1457   LOG_DBG_BUF ((LOG_NEGOTIATION, 90,
1458 		"responder_recv_HASH_SA_NONCE: message after HASH",
1459 		hash + hash_len,
1460 		msg->iov[0].iov_len - ISAKMP_HDR_SZ - hash_len));
1461   prf->Update (prf->prfctx, hash + hash_len,
1462 	       msg->iov[0].iov_len - ISAKMP_HDR_SZ - hash_len);
1463   prf->Final (my_hash, prf->prfctx);
1464   prf_free (prf);
1465   LOG_DBG_BUF ((LOG_NEGOTIATION, 90,
1466 		"responder_recv_HASH_SA_NONCE: computed HASH(1)", my_hash,
1467 		hash_len - ISAKMP_GEN_SZ));
1468   if (memcmp (hash + ISAKMP_GEN_SZ, my_hash, hash_len - ISAKMP_GEN_SZ) != 0)
1469     {
1470       message_drop (msg, ISAKMP_NOTIFY_INVALID_HASH_INFORMATION, 0, 1, 0);
1471       goto cleanup;
1472     }
1473   free (my_hash);
1474   my_hash = 0;
1475 
1476   kep = TAILQ_FIRST (&msg->payload[ISAKMP_PAYLOAD_KEY_EXCH]);
1477   if (kep)
1478     ie->pfs = 1;
1479 
1480   /* Handle optional client ID payloads.  */
1481   idp = TAILQ_FIRST (&msg->payload[ISAKMP_PAYLOAD_ID]);
1482   if (idp)
1483     {
1484       /* If IDci is there, IDcr must be too.  */
1485       if (!TAILQ_NEXT (idp, link))
1486 	{
1487 	  /* XXX Is this a good notify type?  */
1488 	  message_drop (msg, ISAKMP_NOTIFY_PAYLOAD_MALFORMED, 0, 1, 0);
1489 	  goto cleanup;
1490 	}
1491 
1492       ie->id_ci_sz = GET_ISAKMP_GEN_LENGTH (idp->p);
1493       ie->id_ci = malloc (ie->id_ci_sz);
1494       if (!ie->id_ci)
1495 	{
1496 	  log_error ("responder_recv_HASH_SA_NONCE: malloc (%d) failed",
1497 		     ie->id_ci_sz);
1498 	  goto cleanup;
1499 	}
1500       memcpy (ie->id_ci, idp->p, ie->id_ci_sz);
1501       idp->flags |= PL_MARK;
1502       LOG_DBG_BUF ((LOG_NEGOTIATION, 90,
1503 		    "responder_recv_HASH_SA_NONCE: IDci",
1504 		    ie->id_ci + ISAKMP_GEN_SZ, ie->id_ci_sz
1505 		    - ISAKMP_GEN_SZ));
1506 
1507       idp = TAILQ_NEXT (idp, link);
1508       ie->id_cr_sz = GET_ISAKMP_GEN_LENGTH (idp->p);
1509       ie->id_cr = malloc (ie->id_cr_sz);
1510       if (!ie->id_cr)
1511 	{
1512 	  log_error ("responder_recv_HASH_SA_NONCE: malloc (%d) failed",
1513 		     ie->id_cr_sz);
1514 	  goto cleanup;
1515 	}
1516       memcpy (ie->id_cr, idp->p, ie->id_cr_sz);
1517       idp->flags |= PL_MARK;
1518       LOG_DBG_BUF ((LOG_NEGOTIATION, 90,
1519 		    "responder_recv_HASH_SA_NONCE: IDcr",
1520 		    ie->id_cr + ISAKMP_GEN_SZ, ie->id_cr_sz
1521 		    - ISAKMP_GEN_SZ));
1522     }
1523   else
1524     {
1525       /*
1526        * If client identifiers are not present in the exchange,
1527        * we fake them. RFC 2409 states:
1528        *    The identities of the SAs negotiated in Quick Mode are
1529        *    implicitly assumed to be the IP addresses of the ISAKMP
1530        *    peers, without any constraints on the protocol or port
1531        *    numbers allowed, unless client identifiers are specified
1532        *    in Quick Mode.
1533        *
1534        * -- Michael Paddon (mwp@aba.net.au)
1535        */
1536 
1537       ie->flags = IPSEC_EXCH_FLAG_NO_ID;
1538 
1539       /* Get initiator and responder addresses.  */
1540       msg->transport->vtbl->get_src (msg->transport, &src);
1541       msg->transport->vtbl->get_dst (msg->transport, &dst);
1542       ie->id_ci_sz = ISAKMP_ID_DATA_OFF + sockaddr_addrlen (src);
1543       ie->id_cr_sz = ISAKMP_ID_DATA_OFF + sockaddr_addrlen (dst);
1544       ie->id_ci = calloc (ie->id_ci_sz, sizeof (char));
1545       ie->id_cr = calloc (ie->id_cr_sz, sizeof (char));
1546 
1547       if (!ie->id_ci || !ie->id_cr)
1548 	{
1549 	  log_error ("responder_recv_HASH_SA_NONCE: malloc (%d) failed",
1550 		     ie->id_ci_sz);
1551 	  goto cleanup;
1552 	}
1553 
1554       if (src->sa_family != dst->sa_family)
1555 	{
1556 	  log_error ("initiator_recv_HASH_SA_NONCE: sa_family mismatch");
1557 	  goto cleanup;
1558 	}
1559 
1560       switch (src->sa_family)
1561 	{
1562 	case AF_INET:
1563 	  SET_ISAKMP_ID_TYPE (ie->id_ci, IPSEC_ID_IPV4_ADDR);
1564 	  SET_ISAKMP_ID_TYPE (ie->id_cr, IPSEC_ID_IPV4_ADDR);
1565 	  break;
1566 
1567 	case AF_INET6:
1568 	  SET_ISAKMP_ID_TYPE (ie->id_ci, IPSEC_ID_IPV6_ADDR);
1569 	  SET_ISAKMP_ID_TYPE (ie->id_cr, IPSEC_ID_IPV6_ADDR);
1570 	  break;
1571 
1572 	default:
1573 	  log_error ("initiator_recv_HASH_SA_NONCE: unknown sa_family %d",
1574 		     src->sa_family);
1575 	  goto cleanup;
1576 	}
1577 
1578       memcpy (ie->id_cr + ISAKMP_ID_DATA_OFF, sockaddr_addrdata (src),
1579 	      sockaddr_addrlen (src));
1580       memcpy (ie->id_ci + ISAKMP_ID_DATA_OFF, sockaddr_addrdata (dst),
1581 	      sockaddr_addrlen (dst));
1582     }
1583 
1584 #ifdef USE_POLICY
1585 #ifdef USE_KEYNOTE
1586   if (message_negotiate_sa (msg, check_policy))
1587     goto cleanup;
1588 #else
1589   if (message_negotiate_sa (msg, libkeynote ? check_policy : 0))
1590     goto cleanup;
1591 #endif
1592 #else
1593   if (message_negotiate_sa (msg, 0))
1594     goto cleanup;
1595 #endif /* USE_POLICY */
1596 
1597   for (sa = TAILQ_FIRST (&exchange->sa_list); sa; sa = TAILQ_NEXT (sa, next))
1598     {
1599       for (proto = TAILQ_FIRST (&sa->protos); proto;
1600 	   proto = TAILQ_NEXT (proto, link))
1601 	{
1602 	  /* XXX we need to have some attributes per proto, not all per SA.  */
1603 	  ipsec_decode_transform (msg, sa, proto, proto->chosen->p);
1604 	  if (proto->proto == IPSEC_PROTO_IPSEC_AH
1605 	      && !((struct ipsec_proto *)proto->data)->auth)
1606 	    {
1607 	      log_print ("responder_recv_HASH_SA_NONCE: "
1608 			 "AH proposed without an algorithm attribute");
1609 	      message_drop (msg, ISAKMP_NOTIFY_NO_PROPOSAL_CHOSEN, 0, 1, 0);
1610 	      goto next_sa;
1611 	    }
1612 	}
1613 
1614       isa = sa->data;
1615 
1616       /* The group description is mandatory if we got a KEY_EXCH payload.  */
1617       if (kep)
1618 	{
1619 	  if (!isa->group_desc)
1620 	    {
1621 	      log_print ("responder_recv_HASH_SA_NONCE: "
1622 			 "KEY_EXCH payload without a group desc. attribute");
1623 	      message_drop (msg, ISAKMP_NOTIFY_NO_PROPOSAL_CHOSEN, 0, 1, 0);
1624 	      continue;
1625 	    }
1626 
1627 	  /* Also, all SAs must have equal groups.  */
1628 	  if (!group_desc)
1629 	    group_desc = isa->group_desc;
1630 	  else if (group_desc != isa->group_desc)
1631 	    {
1632 	      log_print ("responder_recv_HASH_SA_NONCE: "
1633 			 "differing group descriptions in one QM");
1634 	      message_drop (msg, ISAKMP_NOTIFY_NO_PROPOSAL_CHOSEN, 0, 1, 0);
1635 	      continue;
1636 	    }
1637 	}
1638 
1639       /* At least one SA was accepted.  */
1640       retval = 0;
1641 
1642     next_sa:
1643     }
1644 
1645   if (kep)
1646     {
1647       ie->group = group_get (group_desc);
1648       if (!ie->group)
1649 	{
1650 	  /*
1651 	   * XXX If the error was due to an out-of-range group description
1652 	   * we should notify our peer, but this should probably be done
1653 	   * by the attribute validation.  Is it?
1654 	   */
1655 	  goto cleanup;
1656 	}
1657     }
1658 
1659   /* Copy out the initiator's nonce.  */
1660   if (exchange_save_nonce (msg))
1661     goto cleanup;
1662 
1663   /* Handle the optional KEY_EXCH payload.  */
1664   if (kep && ipsec_save_g_x (msg))
1665     goto cleanup;
1666 
1667   /*
1668    * Try to find and set the connection name on the exchange.
1669    */
1670 
1671   /*
1672    * Check for accepted identities as well as lookup the connection
1673    * name and set it on the exchange.
1674    */
1675   name = connection_passive_lookup_by_ids (ie->id_ci, ie->id_cr);
1676   if (name)
1677     {
1678       exchange->name = strdup (name);
1679       if (!exchange->name)
1680 	{
1681 	  log_error ("responder_recv_HASH_SA_NONCE: strdup (\"%s\") failed",
1682 		     name);
1683 	  goto cleanup;
1684 	}
1685     }
1686 #if !defined (USE_POLICY) && !defined (USE_KEYNOTE)
1687 #ifdef USE_POLICY
1688   else if (!libkeynote)
1689 #else
1690   else
1691 #endif
1692     {
1693       /*
1694        * This code is no longer necessary, as policy determines acceptance
1695        * of IDs/SAs. (angelos@openbsd.org)
1696        *
1697        * XXX Keep it if not USE_POLICY for now, though.
1698        */
1699 
1700       /* XXX Notify peer and log.  */
1701       goto cleanup;
1702     }
1703 #endif /* !USE_POLICY && !USE_KEYNOTE */
1704 
1705   return retval;
1706 
1707 cleanup:
1708   /* Remove all potential protocols that have been added to the SAs.  */
1709   for (sa = TAILQ_FIRST (&exchange->sa_list); sa; sa = TAILQ_NEXT (sa, next))
1710     while ((proto = TAILQ_FIRST (&sa->protos)) != 0)
1711       proto_free (proto);
1712   if (my_hash)
1713     free (my_hash);
1714   if (ie->id_ci)
1715     free (ie->id_ci);
1716   if (ie->id_cr)
1717     free (ie->id_cr);
1718   return -1;
1719 }
1720 
1721 /* Reply with the transform we chose.  */
1722 static int
1723 responder_send_HASH_SA_NONCE (struct message *msg)
1724 {
1725   struct exchange *exchange = msg->exchange;
1726   struct ipsec_exch *ie = exchange->data;
1727   struct sa *isakmp_sa = msg->isakmp_sa;
1728   struct ipsec_sa *isa = isakmp_sa->data;
1729   struct prf *prf;
1730   struct hash *hash = hash_get (isa->hash);
1731   size_t hashsize = hash->hashsize;
1732   size_t nonce_sz = exchange->nonce_i_len;
1733   u_int8_t *buf;
1734   int initiator = exchange->initiator;
1735   char header[80];
1736   int i;
1737   u_int8_t *id;
1738   size_t sz;
1739 
1740   /* We want a HASH payload to start with.  XXX Share with ike_main_mode.c?  */
1741   buf = malloc (ISAKMP_HASH_SZ + hashsize);
1742   if (!buf)
1743     {
1744       log_error ("responder_send_HASH_SA_NONCE: malloc (%d) failed",
1745 		 ISAKMP_HASH_SZ + hashsize);
1746       return -1;
1747     }
1748   if (message_add_payload (msg, ISAKMP_PAYLOAD_HASH, buf,
1749 			   ISAKMP_HASH_SZ + hashsize, 1))
1750     {
1751       free (buf);
1752       return -1;
1753     }
1754 
1755   /* Add the SA payload(s) with the transform(s) that was/were chosen.  */
1756   if (message_add_sa_payload (msg))
1757     return -1;
1758 
1759   /* Generate a nonce, and add it to the message.  */
1760   if (exchange_gen_nonce (msg, nonce_sz))
1761     return -1;
1762 
1763   /* Generate optional KEY_EXCH payload.  This is known as PFS.  */
1764   if (ie->group && ipsec_gen_g_x (msg))
1765     return -1;
1766 
1767   /* If the initiator client ID's were acceptable, just mirror them back.  */
1768   if (!(ie->flags & IPSEC_EXCH_FLAG_NO_ID))
1769     {
1770       sz = ie->id_ci_sz;
1771       id = malloc (sz);
1772       if (!id)
1773 	{
1774 	  log_error ("responder_send_HASH_SA_NONCE: malloc (%d) failed", sz);
1775 	  return -1;
1776 	}
1777       memcpy (id, ie->id_ci, sz);
1778       LOG_DBG_BUF ((LOG_NEGOTIATION, 90, "responder_send_HASH_SA_NONCE: IDic",
1779 		    id, sz));
1780       if (message_add_payload (msg, ISAKMP_PAYLOAD_ID, id, sz, 1))
1781 	{
1782 	  free (id);
1783 	  return -1;
1784 	}
1785 
1786       sz = ie->id_cr_sz;
1787       id = malloc (sz);
1788       if (!id)
1789 	{
1790 	  log_error ("responder_send_HASH_SA_NONCE: malloc (%d) failed", sz);
1791 	  return -1;
1792 	}
1793       memcpy (id, ie->id_cr, sz);
1794       LOG_DBG_BUF ((LOG_NEGOTIATION, 90, "responder_send_HASH_SA_NONCE: IDrc",
1795 		    id, sz));
1796       if (message_add_payload (msg, ISAKMP_PAYLOAD_ID, id, sz, 1))
1797 	{
1798 	  free (id);
1799 	  return -1;
1800 	}
1801     }
1802 
1803   /* Allocate the prf and start calculating our HASH(2).  XXX Share?  */
1804   LOG_DBG ((LOG_NEGOTIATION, 90, "responder_recv_HASH: isakmp_sa %p isa %p",
1805 	    isakmp_sa, isa));
1806   LOG_DBG_BUF ((LOG_NEGOTIATION, 90, "responder_send_HASH_SA_NONCE: SKEYID_a",
1807 		isa->skeyid_a, isa->skeyid_len));
1808   prf = prf_alloc (isa->prf_type, hash->type, isa->skeyid_a, isa->skeyid_len);
1809   if (!prf)
1810     return -1;
1811   prf->Init (prf->prfctx);
1812   LOG_DBG_BUF ((LOG_NEGOTIATION, 90,
1813 		"responder_send_HASH_SA_NONCE: message_id",
1814 		exchange->message_id, ISAKMP_HDR_MESSAGE_ID_LEN));
1815   prf->Update (prf->prfctx, exchange->message_id, ISAKMP_HDR_MESSAGE_ID_LEN);
1816   LOG_DBG_BUF ((LOG_NEGOTIATION, 90, "responder_send_HASH_SA_NONCE: NONCE_I_b",
1817 		exchange->nonce_i, exchange->nonce_i_len));
1818   prf->Update (prf->prfctx, exchange->nonce_i, exchange->nonce_i_len);
1819 
1820   /* Loop over all payloads after HASH(2).  */
1821   for (i = 2; i < msg->iovlen; i++)
1822     {
1823       /* XXX Misleading payload type printouts.  */
1824       snprintf (header, 80,
1825 		"responder_send_HASH_SA_NONCE: payload %d after HASH(2)",
1826 		i - 1);
1827       LOG_DBG_BUF ((LOG_NEGOTIATION, 90, header, msg->iov[i].iov_base,
1828 		    msg->iov[i].iov_len));
1829       prf->Update (prf->prfctx, msg->iov[i].iov_base, msg->iov[i].iov_len);
1830     }
1831   prf->Final (buf + ISAKMP_HASH_DATA_OFF, prf->prfctx);
1832   prf_free (prf);
1833   snprintf (header, 80, "responder_send_HASH_SA_NONCE: HASH_%c",
1834 	    initiator ? 'I' : 'R');
1835   LOG_DBG_BUF ((LOG_NEGOTIATION, 80, header, buf + ISAKMP_HASH_DATA_OFF,
1836 		hashsize));
1837 
1838   if (ie->group)
1839     message_register_post_send (msg, gen_g_xy);
1840 
1841   return 0;
1842 }
1843 
1844 static void
1845 gen_g_xy (struct message *msg)
1846 {
1847   struct exchange *exchange = msg->exchange;
1848   struct ipsec_exch *ie = exchange->data;
1849 
1850   /* Compute Diffie-Hellman shared value.  */
1851   ie->g_xy = malloc (ie->g_x_len);
1852   if (!ie->g_xy)
1853     {
1854       log_error ("gen_g_xy: malloc (%d) failed", ie->g_x_len);
1855       return;
1856     }
1857   if (dh_create_shared (ie->group, ie->g_xy,
1858 			exchange->initiator ? ie->g_xr : ie->g_xi))
1859     {
1860       log_print ("gen_g_xy: dh_create_shared failed");
1861       return;
1862     }
1863   LOG_DBG_BUF ((LOG_NEGOTIATION, 80, "gen_g_xy: g^xy", ie->g_xy, ie->g_x_len));
1864 }
1865 
1866 static int
1867 responder_recv_HASH (struct message *msg)
1868 {
1869   struct exchange *exchange = msg->exchange;
1870   struct sa *isakmp_sa = msg->isakmp_sa;
1871   struct ipsec_sa *isa = isakmp_sa->data;
1872   struct prf *prf;
1873   u_int8_t *hash, *my_hash = 0;
1874   size_t hash_len;
1875   struct payload *hashp;
1876 
1877   /* Find HASH(3) and create our own hash, just as big.  */
1878   hashp = TAILQ_FIRST (&msg->payload[ISAKMP_PAYLOAD_HASH]);
1879   hash = hashp->p;
1880   hashp->flags |= PL_MARK;
1881   hash_len = GET_ISAKMP_GEN_LENGTH (hash);
1882   my_hash = malloc (hash_len - ISAKMP_GEN_SZ);
1883   if (!my_hash)
1884     {
1885       log_error ("responder_recv_HASH: malloc (%d) failed",
1886 		 hash_len - ISAKMP_GEN_SZ);
1887       goto cleanup;
1888     }
1889 
1890   /* Allocate the prf and start calculating our HASH(3).  XXX Share?  */
1891   LOG_DBG ((LOG_NEGOTIATION, 90, "responder_recv_HASH: isakmp_sa %p isa %p",
1892 	    isakmp_sa, isa));
1893   LOG_DBG_BUF ((LOG_NEGOTIATION, 90, "responder_recv_HASH: SKEYID_a",
1894 		isa->skeyid_a, isa->skeyid_len));
1895   prf = prf_alloc (isa->prf_type, isa->hash, isa->skeyid_a, isa->skeyid_len);
1896   if (!prf)
1897     goto cleanup;
1898   prf->Init (prf->prfctx);
1899   prf->Update (prf->prfctx, "\0", 1);
1900   LOG_DBG_BUF ((LOG_NEGOTIATION, 90, "responder_recv_HASH: message_id",
1901 		exchange->message_id, ISAKMP_HDR_MESSAGE_ID_LEN));
1902   prf->Update (prf->prfctx, exchange->message_id, ISAKMP_HDR_MESSAGE_ID_LEN);
1903   LOG_DBG_BUF ((LOG_NEGOTIATION, 90, "responder_recv_HASH: NONCE_I_b",
1904 		exchange->nonce_i, exchange->nonce_i_len));
1905   prf->Update (prf->prfctx, exchange->nonce_i, exchange->nonce_i_len);
1906   LOG_DBG_BUF ((LOG_NEGOTIATION, 90, "responder_recv_HASH: NONCE_R_b",
1907 		exchange->nonce_r, exchange->nonce_r_len));
1908   prf->Update (prf->prfctx, exchange->nonce_r, exchange->nonce_r_len);
1909   prf->Final (my_hash, prf->prfctx);
1910   prf_free (prf);
1911   LOG_DBG_BUF ((LOG_NEGOTIATION, 90,
1912 		"responder_recv_HASH: computed HASH(3)", my_hash,
1913 		hash_len - ISAKMP_GEN_SZ));
1914   if (memcmp (hash + ISAKMP_GEN_SZ, my_hash, hash_len - ISAKMP_GEN_SZ) != 0)
1915     {
1916       message_drop (msg, ISAKMP_NOTIFY_INVALID_HASH_INFORMATION, 0, 1, 0);
1917       goto cleanup;
1918     }
1919   free (my_hash);
1920 
1921   post_quick_mode (msg);
1922 
1923   return 0;
1924 
1925  cleanup:
1926   if (my_hash)
1927     free (my_hash);
1928   return -1;
1929 }
1930