xref: /openbsd/sbin/isakmpd/ipsec.c (revision 1821443c)
1 /*	$OpenBSD: ipsec.c,v 1.80 2003/09/02 18:15:55 ho Exp $	*/
2 /*	$EOM: ipsec.c,v 1.143 2000/12/11 23:57:42 niklas Exp $	*/
3 
4 /*
5  * Copyright (c) 1998, 1999, 2000, 2001 Niklas Hallqvist.  All rights reserved.
6  * Copyright (c) 2001 Angelos D. Keromytis.  All rights reserved.
7  * Copyright (c) 2001 H�kan Olsson.  All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
19  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
20  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
21  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
22  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
23  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
27  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28  */
29 
30 /*
31  * This code was written under funding by Ericsson Radio Systems.
32  */
33 
34 #include <sys/types.h>
35 #include <sys/socket.h>
36 #include <netdb.h>
37 #include <netinet/in.h>
38 #include <arpa/inet.h>
39 #include <stdlib.h>
40 #include <string.h>
41 
42 #include "sysdep.h"
43 
44 #include "attribute.h"
45 #include "conf.h"
46 #include "constants.h"
47 #include "crypto.h"
48 #include "dh.h"
49 #include "doi.h"
50 #include "exchange.h"
51 #include "hash.h"
52 #include "ike_aggressive.h"
53 #include "ike_auth.h"
54 #include "ike_main_mode.h"
55 #include "ike_quick_mode.h"
56 #include "ipsec.h"
57 #include "ipsec_doi.h"
58 #include "isakmp.h"
59 #include "isakmp_cfg.h"
60 #include "isakmp_fld.h"
61 #include "isakmp_num.h"
62 #include "log.h"
63 #include "math_group.h"
64 #include "message.h"
65 #include "prf.h"
66 #include "sa.h"
67 #include "timer.h"
68 #include "transport.h"
69 #include "util.h"
70 #include "x509.h"
71 
72 /* Backwards compatibility.  */
73 #ifndef NI_MAXHOST
74 #define NI_MAXHOST 1025
75 #endif
76 
77 /* The replay window size used for all IPsec protocols if not overridden.  */
78 #define DEFAULT_REPLAY_WINDOW 16
79 
80 struct ipsec_decode_arg {
81   struct message *msg;
82   struct sa *sa;
83   struct proto *proto;
84 };
85 
86 /* These variables hold the contacted peers ADT state.  */
87 struct contact {
88   struct sockaddr *addr;
89   socklen_t len;
90 } *contacts = 0;
91 int contact_cnt = 0, contact_limit = 0;
92 
93 static int addr_cmp (const void *, const void *);
94 static int ipsec_add_contact (struct message *msg);
95 static int ipsec_contacted (struct message *msg);
96 #ifdef USE_DEBUG
97 static int ipsec_debug_attribute (u_int16_t, u_int8_t *, u_int16_t, void *);
98 #endif
99 static void ipsec_delete_spi (struct sa *, struct proto *, int);
100 static int16_t *ipsec_exchange_script (u_int8_t);
101 static void ipsec_finalize_exchange (struct message *);
102 static void ipsec_free_exchange_data (void *);
103 static void ipsec_free_proto_data (void *);
104 static void ipsec_free_sa_data (void *);
105 static struct keystate *ipsec_get_keystate (struct message *);
106 static u_int8_t *ipsec_get_spi (size_t *, u_int8_t, struct message *);
107 static int ipsec_handle_leftover_payload (struct message *, u_int8_t,
108 					  struct payload *);
109 static int ipsec_informational_post_hook (struct message *);
110 static int ipsec_informational_pre_hook (struct message *);
111 static int ipsec_initiator (struct message *);
112 static void ipsec_proto_init (struct proto *, char *);
113 static int ipsec_responder (struct message *);
114 static void ipsec_setup_situation (u_int8_t *);
115 static int ipsec_set_network (u_int8_t *, u_int8_t *, struct ipsec_sa *);
116 static size_t ipsec_situation_size (void);
117 static u_int8_t ipsec_spi_size (u_int8_t);
118 static int ipsec_validate_attribute (u_int16_t, u_int8_t *, u_int16_t, void *);
119 static int ipsec_validate_exchange (u_int8_t);
120 static int ipsec_validate_id_information (u_int8_t, u_int8_t *, u_int8_t *,
121 					  size_t, struct exchange *);
122 static int ipsec_validate_key_information (u_int8_t *, size_t);
123 static int ipsec_validate_notification (u_int16_t);
124 static int ipsec_validate_proto (u_int8_t);
125 static int ipsec_validate_situation (u_int8_t *, size_t *);
126 static int ipsec_validate_transform_id (u_int8_t, u_int8_t);
127 
128 static struct doi ipsec_doi = {
129   { 0 }, IPSEC_DOI_IPSEC,
130   sizeof (struct ipsec_exch), sizeof (struct ipsec_sa),
131   sizeof (struct ipsec_proto),
132 #ifdef USE_DEBUG
133   ipsec_debug_attribute,
134 #endif
135   ipsec_delete_spi,
136   ipsec_exchange_script,
137   ipsec_finalize_exchange,
138   ipsec_free_exchange_data,
139   ipsec_free_proto_data,
140   ipsec_free_sa_data,
141   ipsec_get_keystate,
142   ipsec_get_spi,
143   ipsec_handle_leftover_payload,
144   ipsec_informational_post_hook,
145   ipsec_informational_pre_hook,
146   ipsec_is_attribute_incompatible,
147   ipsec_proto_init,
148   ipsec_setup_situation,
149   ipsec_situation_size,
150   ipsec_spi_size,
151   ipsec_validate_attribute,
152   ipsec_validate_exchange,
153   ipsec_validate_id_information,
154   ipsec_validate_key_information,
155   ipsec_validate_notification,
156   ipsec_validate_proto,
157   ipsec_validate_situation,
158   ipsec_validate_transform_id,
159   ipsec_initiator,
160   ipsec_responder,
161   ipsec_decode_ids
162 };
163 
164 int16_t script_quick_mode[] = {
165   ISAKMP_PAYLOAD_HASH,		/* Initiator -> responder.  */
166   ISAKMP_PAYLOAD_SA,
167   ISAKMP_PAYLOAD_NONCE,
168   EXCHANGE_SCRIPT_SWITCH,
169   ISAKMP_PAYLOAD_HASH,		/* Responder -> initiator.  */
170   ISAKMP_PAYLOAD_SA,
171   ISAKMP_PAYLOAD_NONCE,
172   EXCHANGE_SCRIPT_SWITCH,
173   ISAKMP_PAYLOAD_HASH,		/* Initiator -> responder.  */
174   EXCHANGE_SCRIPT_END
175 };
176 
177 int16_t script_new_group_mode[] = {
178   ISAKMP_PAYLOAD_HASH,		/* Initiator -> responder.  */
179   ISAKMP_PAYLOAD_SA,
180   EXCHANGE_SCRIPT_SWITCH,
181   ISAKMP_PAYLOAD_HASH,		/* Responder -> initiator.  */
182   ISAKMP_PAYLOAD_SA,
183   EXCHANGE_SCRIPT_END
184 };
185 
186 struct dst_spi_proto_arg {
187   struct sockaddr *dst;
188   u_int32_t spi;
189   u_int8_t proto;
190 };
191 
192 /*
193  * Check if SA matches what we are asking for through V_ARG.  It has to
194  * be a finished phase 2 SA.
195  * if "proto" arg is 0, match any proto
196  */
197 static int
198 ipsec_sa_check (struct sa *sa, void *v_arg)
199 {
200   struct dst_spi_proto_arg *arg = v_arg;
201   struct proto *proto;
202   struct sockaddr *dst, *src;
203   int incoming;
204 
205   if (sa->phase != 2 || !(sa->flags & SA_FLAG_READY))
206     return 0;
207 
208   sa->transport->vtbl->get_dst (sa->transport, &dst);
209   if (memcmp (sockaddr_addrdata (dst), sockaddr_addrdata (arg->dst),
210 	      sockaddr_addrlen (dst)) == 0)
211     incoming = 0;
212   else
213     {
214       sa->transport->vtbl->get_src (sa->transport, &src);
215       if (memcmp (sockaddr_addrdata (src), sockaddr_addrdata (arg->dst),
216 		  sockaddr_addrlen (src)) == 0)
217 	incoming = 1;
218       else
219 	return 0;
220     }
221 
222   for (proto = TAILQ_FIRST (&sa->protos); proto;
223        proto = TAILQ_NEXT (proto, link))
224     if ((arg->proto == 0 || proto->proto == arg->proto)
225        && memcmp (proto->spi[incoming], &arg->spi, sizeof arg->spi) == 0)
226       return 1;
227   return 0;
228 }
229 
230 /* Find an SA with a "name" of DST, SPI & PROTO.  */
231 struct sa *
232 ipsec_sa_lookup (struct sockaddr *dst, u_int32_t spi, u_int8_t proto)
233 {
234   struct dst_spi_proto_arg arg;
235 
236   arg.dst = dst;
237   arg.spi = spi;
238   arg.proto = proto;
239 
240   return sa_find (ipsec_sa_check, &arg);
241 }
242 
243 /*
244  * Check if SA matches the flow of another SA in V_ARG.  It has to
245  * be a finished non-replaced phase 2 SA.
246  * XXX At some point other selectors will matter here too.
247  */
248 static int
249 ipsec_sa_check_flow (struct sa *sa, void *v_arg)
250 {
251   struct sa *sa2 = v_arg;
252   struct ipsec_sa *isa = sa->data, *isa2 = sa2->data;
253 
254   if (sa == sa2 || sa->phase != 2
255       || (sa->flags & (SA_FLAG_READY | SA_FLAG_REPLACED)) != SA_FLAG_READY)
256     return 0;
257 
258   if (isa->tproto != isa2->tproto || isa->sport != isa2->sport
259       || isa->dport != isa2->dport)
260     return 0;
261 
262   return isa->src_net->sa_family == isa2->src_net->sa_family
263     && memcmp (sockaddr_addrdata (isa->src_net),
264 	       sockaddr_addrdata (isa2->src_net),
265 	       sockaddr_addrlen (isa->src_net)) == 0
266     && memcmp (sockaddr_addrdata (isa->src_mask),
267 	       sockaddr_addrdata (isa2->src_mask),
268 	       sockaddr_addrlen (isa->src_mask)) == 0
269     && memcmp (sockaddr_addrdata (isa->dst_net),
270 	       sockaddr_addrdata (isa2->dst_net),
271 	       sockaddr_addrlen (isa->dst_net)) == 0
272     && memcmp (sockaddr_addrdata (isa->dst_mask),
273 	       sockaddr_addrdata (isa2->dst_mask),
274 	       sockaddr_addrlen (isa->dst_mask)) == 0;
275 }
276 
277 /*
278  * Do IPsec DOI specific finalizations task for the exchange where MSG was
279  * the final message.
280  */
281 static void
282 ipsec_finalize_exchange (struct message *msg)
283 {
284   struct sa *isakmp_sa = msg->isakmp_sa;
285   struct ipsec_sa *isa;
286   struct exchange *exchange = msg->exchange;
287   struct ipsec_exch *ie = exchange->data;
288   struct sa *sa = 0, *old_sa;
289   struct proto *proto, *last_proto = 0;
290 #ifdef USE_DEBUG
291   char *addr1, *addr2, *mask1, *mask2;
292 #endif
293 
294   switch (exchange->phase)
295     {
296     case 1:
297       switch (exchange->type)
298 	{
299 	case ISAKMP_EXCH_ID_PROT:
300 	case ISAKMP_EXCH_AGGRESSIVE:
301 	  isa = isakmp_sa->data;
302 	  isa->hash = ie->hash->type;
303 	  isa->prf_type = ie->prf_type;
304 	  isa->skeyid_len = ie->skeyid_len;
305 	  isa->skeyid_d = ie->skeyid_d;
306 	  isa->skeyid_a = ie->skeyid_a;
307 	  /* Prevents early free of SKEYID_*.  */
308 	  ie->skeyid_a = ie->skeyid_d = 0;
309 
310 	  /* If a lifetime was negotiated setup the expiration timers.  */
311 	  if (isakmp_sa->seconds)
312 	    sa_setup_expirations (isakmp_sa);
313 	  break;
314 	}
315       break;
316 
317     case 2:
318       switch (exchange->type)
319 	{
320 	case IKE_EXCH_QUICK_MODE:
321 	  /*
322 	   * Tell the application(s) about the SPIs and key material.
323 	   */
324 	  for (sa = TAILQ_FIRST (&exchange->sa_list); sa;
325 	       sa = TAILQ_NEXT (sa, next))
326 	    {
327 	      isa = sa->data;
328 
329 	      if (exchange->initiator)
330 		{
331 		  /* Initiator is source, responder is destination.  */
332 		  if (ipsec_set_network (ie->id_ci, ie->id_cr, isa))
333 		    {
334 		      log_print ("ipsec_finalize_exchange: "
335 				 "ipsec_set_network failed");
336 		      return;
337 		    }
338 		}
339 	      else
340 		{
341 		  /* Responder is source, initiator is destination.  */
342 		  if (ipsec_set_network (ie->id_cr, ie->id_ci, isa))
343 		    {
344 		      log_print ("ipsec_finalize_exchange: "
345 				 "ipsec_set_network failed");
346 		      return;
347 		    }
348 		}
349 
350 	      for (proto = TAILQ_FIRST (&sa->protos), last_proto = 0; proto;
351 		   proto = TAILQ_NEXT (proto, link))
352 		{
353 		  if (sysdep_ipsec_set_spi (sa, proto, 0, isakmp_sa)
354 		      || (last_proto
355 			  && sysdep_ipsec_group_spis (sa, last_proto, proto,
356 						      0))
357 		      || sysdep_ipsec_set_spi (sa, proto, 1, isakmp_sa)
358 		      || (last_proto
359 			  && sysdep_ipsec_group_spis (sa, last_proto, proto,
360 						      1)))
361 		    /* XXX Tear down this exchange.  */
362 		    return;
363 		  last_proto = proto;
364 		}
365 
366 #ifdef USE_DEBUG
367 	      if (sockaddr2text (isa->src_net, &addr1, 0))
368 		addr1 = 0;
369 	      if (sockaddr2text (isa->src_mask, &mask1, 0))
370 		mask1 = 0;
371 	      if (sockaddr2text (isa->dst_net, &addr2, 0))
372 		addr2 = 0;
373 	      if (sockaddr2text (isa->dst_mask, &mask2, 0))
374 		mask2 = 0;
375 
376 	      LOG_DBG ((LOG_EXCHANGE, 50,
377 			"ipsec_finalize_exchange: "
378 			"src %s %s dst %s %s tproto %u sport %u dport %u",
379 			addr1 ? addr1 : "<??\?>" , mask1 ? mask1 : "<??\?>",
380 			addr2 ? addr2 : "<??\?>" , mask2 ? mask2 : "<??\?>",
381 			isa->tproto, ntohs (isa->sport), ntohs (isa->dport)));
382 
383 	      if (addr1)
384 		free (addr1);
385 	      if (mask1)
386 		free (mask1);
387 	      if (addr2)
388 		free (addr2);
389 	      if (mask2)
390 		free (mask2);
391 
392 #endif /* USE_DEBUG */
393 
394 	      /*
395 	       * If this is not an SA acquired by the kernel, it needs
396 	       * to have a SPD entry (a.k.a. flow) set up.
397 	       */
398 	      if (!(sa->flags & SA_FLAG_ONDEMAND)
399 		  && sysdep_ipsec_enable_sa (sa, isakmp_sa))
400 		/* XXX Tear down this exchange.  */
401 		return;
402 
403 	      /* Mark elder SAs with the same flow information as replaced.  */
404 	      while ((old_sa = sa_find (ipsec_sa_check_flow, sa)) != 0)
405 		sa_mark_replaced (old_sa);
406 	    }
407 	  break;
408 	}
409     }
410 }
411 
412 /* Set the client addresses in ISA from SRC_ID and DST_ID.  */
413 static int
414 ipsec_set_network (u_int8_t *src_id, u_int8_t *dst_id, struct ipsec_sa *isa)
415 {
416   int id;
417   char *v;
418 
419   /* Set source address/mask.  */
420   id = GET_ISAKMP_ID_TYPE (src_id);
421   switch (id)
422     {
423     case IPSEC_ID_IPV4_ADDR:
424     case IPSEC_ID_IPV4_ADDR_SUBNET:
425       isa->src_net =
426 	(struct sockaddr *)calloc (1, sizeof (struct sockaddr_in));
427       if (!isa->src_net)
428 	goto memfail;
429       isa->src_net->sa_family = AF_INET;
430 #ifndef USE_OLD_SOCKADDR
431       isa->src_net->sa_len = sizeof (struct sockaddr_in);
432 #endif
433 
434       isa->src_mask =
435 	(struct sockaddr *)calloc (1, sizeof (struct sockaddr_in));
436       if (!isa->src_mask)
437 	goto memfail;
438       isa->src_mask->sa_family = AF_INET;
439 #ifndef USE_OLD_SOCKADDR
440       isa->src_mask->sa_len = sizeof (struct sockaddr_in);
441 #endif
442       break;
443 
444     case IPSEC_ID_IPV6_ADDR:
445     case IPSEC_ID_IPV6_ADDR_SUBNET:
446       isa->src_net =
447 	(struct sockaddr *)calloc (1, sizeof (struct sockaddr_in6));
448       if (!isa->src_net)
449 	goto memfail;
450       isa->src_net->sa_family = AF_INET6;
451 #ifndef USE_OLD_SOCKADDR
452       isa->src_net->sa_len = sizeof (struct sockaddr_in6);
453 #endif
454 
455       isa->src_mask =
456 	(struct sockaddr *)calloc (1, sizeof (struct sockaddr_in6));
457       if (!isa->src_mask)
458 	goto memfail;
459       isa->src_mask->sa_family = AF_INET6;
460 #ifndef USE_OLD_SOCKADDR
461       isa->src_mask->sa_len = sizeof (struct sockaddr_in6);
462 #endif
463       break;
464 
465     case IPSEC_ID_IPV4_RANGE:
466     case IPSEC_ID_IPV6_RANGE:
467     case IPSEC_ID_DER_ASN1_DN:
468     case IPSEC_ID_DER_ASN1_GN:
469     case IPSEC_ID_KEY_ID:
470     default:
471       v = constant_lookup (ipsec_id_cst, id);
472       log_print ("ipsec_set_network: ID type %d (%s) not supported",
473 		 id, v ? v : "<unknown>");
474       return -1;
475     }
476 
477   /* Net */
478   memcpy (sockaddr_addrdata (isa->src_net), src_id + ISAKMP_ID_DATA_OFF,
479 	  sockaddr_addrlen (isa->src_net));
480 
481   /* Mask */
482   switch (id)
483     {
484     case IPSEC_ID_IPV4_ADDR:
485     case IPSEC_ID_IPV6_ADDR:
486       memset (sockaddr_addrdata (isa->src_mask), 0xff,
487 	      sockaddr_addrlen (isa->src_mask));
488       break;
489     case IPSEC_ID_IPV4_ADDR_SUBNET:
490     case IPSEC_ID_IPV6_ADDR_SUBNET:
491       memcpy (sockaddr_addrdata (isa->src_mask), src_id + ISAKMP_ID_DATA_OFF +
492 	      sockaddr_addrlen (isa->src_net),
493 	      sockaddr_addrlen (isa->src_mask));
494       break;
495     }
496 
497   memcpy (&isa->sport, src_id + ISAKMP_ID_DOI_DATA_OFF + IPSEC_ID_PORT_OFF,
498 	  IPSEC_ID_PORT_LEN);
499 
500   /* Set destination address.  */
501   id = GET_ISAKMP_ID_TYPE (dst_id);
502   switch (id)
503     {
504     case IPSEC_ID_IPV4_ADDR:
505     case IPSEC_ID_IPV4_ADDR_SUBNET:
506       isa->dst_net =
507 	(struct sockaddr *)calloc (1, sizeof (struct sockaddr_in));
508       if (!isa->dst_net)
509 	goto memfail;
510       isa->dst_net->sa_family = AF_INET;
511 #ifndef USE_OLD_SOCKADDR
512       isa->dst_net->sa_len = sizeof (struct sockaddr_in);
513 #endif
514 
515       isa->dst_mask =
516 	(struct sockaddr *)calloc (1, sizeof (struct sockaddr_in));
517       if (!isa->dst_mask)
518 	goto memfail;
519       isa->dst_mask->sa_family = AF_INET;
520 #ifndef USE_OLD_SOCKADDR
521       isa->dst_mask->sa_len = sizeof (struct sockaddr_in);
522 #endif
523       break;
524 
525     case IPSEC_ID_IPV6_ADDR:
526     case IPSEC_ID_IPV6_ADDR_SUBNET:
527       isa->dst_net =
528 	(struct sockaddr *)calloc (1, sizeof (struct sockaddr_in6));
529       if (!isa->dst_net)
530 	goto memfail;
531       isa->dst_net->sa_family = AF_INET6;
532 #ifndef USE_OLD_SOCKADDR
533       isa->dst_net->sa_len = sizeof (struct sockaddr_in6);
534 #endif
535 
536       isa->dst_mask =
537 	(struct sockaddr *)calloc (1, sizeof (struct sockaddr_in6));
538       if (!isa->dst_mask)
539 	goto memfail;
540       isa->dst_mask->sa_family = AF_INET6;
541 #ifndef USE_OLD_SOCKADDR
542       isa->dst_mask->sa_len = sizeof (struct sockaddr_in6);
543 #endif
544       break;
545     }
546 
547   /* Net */
548   memcpy (sockaddr_addrdata (isa->dst_net), dst_id + ISAKMP_ID_DATA_OFF,
549 	  sockaddr_addrlen (isa->dst_net));
550 
551   /* Mask */
552   switch (id)
553     {
554     case IPSEC_ID_IPV4_ADDR:
555     case IPSEC_ID_IPV6_ADDR:
556       memset (sockaddr_addrdata (isa->dst_mask), 0xff,
557 	      sockaddr_addrlen (isa->dst_mask));
558       break;
559     case IPSEC_ID_IPV4_ADDR_SUBNET:
560     case IPSEC_ID_IPV6_ADDR_SUBNET:
561       memcpy (sockaddr_addrdata (isa->dst_mask), dst_id + ISAKMP_ID_DATA_OFF +
562 	      sockaddr_addrlen (isa->dst_net),
563 	      sockaddr_addrlen (isa->dst_mask));
564       break;
565     }
566 
567   memcpy (&isa->tproto, dst_id + ISAKMP_ID_DOI_DATA_OFF + IPSEC_ID_PROTO_OFF,
568 	  IPSEC_ID_PROTO_LEN);
569   memcpy (&isa->dport, dst_id + ISAKMP_ID_DOI_DATA_OFF + IPSEC_ID_PORT_OFF,
570 	  IPSEC_ID_PORT_LEN);
571   return 0;
572 
573  memfail:
574   log_error ("ipsec_set_network: calloc () failed");
575   return -1;
576 }
577 
578 /* Free the DOI-specific exchange data pointed to by VIE.  */
579 static void
580 ipsec_free_exchange_data (void *vie)
581 {
582   struct ipsec_exch *ie = vie;
583 #ifdef USE_ISAKMP_CFG
584   struct isakmp_cfg_attr *attr;
585 #endif
586 
587   if (ie->sa_i_b)
588     free (ie->sa_i_b);
589   if (ie->id_ci)
590     free (ie->id_ci);
591   if (ie->id_cr)
592     free (ie->id_cr);
593   if (ie->g_xi)
594     free (ie->g_xi);
595   if (ie->g_xr)
596     free (ie->g_xr);
597   if (ie->g_xy)
598     free (ie->g_xy);
599   if (ie->skeyid)
600     free (ie->skeyid);
601   if (ie->skeyid_d)
602     free (ie->skeyid_d);
603   if (ie->skeyid_a)
604     free (ie->skeyid_a);
605   if (ie->skeyid_e)
606     free (ie->skeyid_e);
607   if (ie->hash_i)
608     free (ie->hash_i);
609   if (ie->hash_r)
610     free (ie->hash_r);
611   if (ie->group)
612     group_free (ie->group);
613 #ifdef USE_ISAKMP_CFG
614   for (attr = LIST_FIRST (&ie->attrs); attr; attr = LIST_FIRST (&ie->attrs))
615     {
616       LIST_REMOVE (attr, link);
617       if (attr->length)
618 	free (attr->value);
619       free (attr);
620     }
621 #endif
622 }
623 
624 /* Free the DOI-specific SA data pointed to by VISA.  */
625 static void
626 ipsec_free_sa_data (void *visa)
627 {
628   struct ipsec_sa *isa = visa;
629 
630   if (isa->src_net)
631     free (isa->src_net);
632   if (isa->src_mask)
633     free (isa->src_mask);
634   if (isa->dst_net)
635     free (isa->dst_net);
636   if (isa->dst_mask)
637     free (isa->dst_mask);
638   if (isa->skeyid_a)
639     free (isa->skeyid_a);
640   if (isa->skeyid_d)
641     free (isa->skeyid_d);
642 }
643 
644 /* Free the DOI-specific protocol data of an SA pointed to by VIPROTO.  */
645 static void
646 ipsec_free_proto_data (void *viproto)
647 {
648   struct ipsec_proto *iproto = viproto;
649   int i;
650 
651   for (i = 0; i < 2; i++)
652     if (iproto->keymat[i])
653       free (iproto->keymat[i]);
654 }
655 
656 /* Return exchange script based on TYPE.  */
657 static int16_t *
658 ipsec_exchange_script (u_int8_t type)
659 {
660   switch (type)
661     {
662 #ifdef USE_ISAKMP_CFG
663     case ISAKMP_EXCH_TRANSACTION:
664       return script_transaction;
665 #endif
666     case IKE_EXCH_QUICK_MODE:
667       return script_quick_mode;
668     case IKE_EXCH_NEW_GROUP_MODE:
669       return script_new_group_mode;
670     }
671   return 0;
672 }
673 
674 /* Initialize this DOI, requires doi_init to already have been called.  */
675 void
676 ipsec_init (void)
677 {
678   doi_register (&ipsec_doi);
679 }
680 
681 /* Given a message MSG, return a suitable IV (or rather keystate).  */
682 static struct keystate *
683 ipsec_get_keystate (struct message *msg)
684 {
685   struct keystate *ks;
686   struct hash *hash;
687 
688   /* If we have already have an IV, use it.  */
689   if (msg->exchange && msg->exchange->keystate)
690     {
691       ks = malloc (sizeof *ks);
692       if (!ks)
693 	{
694 	  log_error ("ipsec_get_keystate: malloc (%lu) failed",
695 		(unsigned long)sizeof *ks);
696 	  return 0;
697 	}
698       memcpy (ks, msg->exchange->keystate, sizeof *ks);
699       return ks;
700     }
701 
702   /*
703    * For phase 2 when no SA yet is setup we need to hash the IV used by
704    * the ISAKMP SA concatenated with the message ID, and use that as an
705    * IV for further cryptographic operations.
706    */
707   if (!msg->isakmp_sa->keystate)
708     {
709       log_print ("ipsec_get_keystate: no keystate in ISAKMP SA %p",
710 		 msg->isakmp_sa);
711       return 0;
712     }
713   ks = crypto_clone_keystate (msg->isakmp_sa->keystate);
714   if (!ks)
715     return 0;
716 
717   hash = hash_get (((struct ipsec_sa *)msg->isakmp_sa->data)->hash);
718   hash->Init (hash->ctx);
719   LOG_DBG_BUF ((LOG_CRYPTO, 80, "ipsec_get_keystate: final phase 1 IV",
720 		ks->riv, ks->xf->blocksize));
721   hash->Update (hash->ctx, ks->riv, ks->xf->blocksize);
722   LOG_DBG_BUF ((LOG_CRYPTO, 80, "ipsec_get_keystate: message ID",
723 		((u_int8_t *)msg->iov[0].iov_base)
724 		+ ISAKMP_HDR_MESSAGE_ID_OFF,
725 		ISAKMP_HDR_MESSAGE_ID_LEN));
726   hash->Update (hash->ctx,
727 		((u_int8_t *)msg->iov[0].iov_base) + ISAKMP_HDR_MESSAGE_ID_OFF,
728 		ISAKMP_HDR_MESSAGE_ID_LEN);
729   hash->Final (hash->digest, hash->ctx);
730   crypto_init_iv (ks, hash->digest, ks->xf->blocksize);
731   LOG_DBG_BUF ((LOG_CRYPTO, 80, "ipsec_get_keystate: phase 2 IV",
732 		hash->digest, ks->xf->blocksize));
733   return ks;
734 }
735 
736 static void
737 ipsec_setup_situation (u_int8_t *buf)
738 {
739   SET_IPSEC_SIT_SIT (buf + ISAKMP_SA_SIT_OFF, IPSEC_SIT_IDENTITY_ONLY);
740 }
741 
742 static size_t
743 ipsec_situation_size (void)
744 {
745   return IPSEC_SIT_SIT_LEN;
746 }
747 
748 static u_int8_t
749 ipsec_spi_size (u_int8_t proto)
750 {
751   return IPSEC_SPI_SIZE;
752 }
753 
754 static int
755 ipsec_validate_attribute (u_int16_t type, u_int8_t *value, u_int16_t len,
756 			  void *vmsg)
757 {
758   struct message *msg = vmsg;
759 
760   if ((msg->exchange->phase == 1
761        && (type < IKE_ATTR_ENCRYPTION_ALGORITHM
762 	   || type > IKE_ATTR_GROUP_ORDER))
763       || (msg->exchange->phase == 2
764 	  && (type < IPSEC_ATTR_SA_LIFE_TYPE
765 	      || type > IPSEC_ATTR_ECN_TUNNEL)))
766     return -1;
767   return 0;
768 }
769 
770 static int
771 ipsec_validate_exchange (u_int8_t exch)
772 {
773   return exch != IKE_EXCH_QUICK_MODE && exch != IKE_EXCH_NEW_GROUP_MODE;
774 }
775 
776 static int
777 ipsec_validate_id_information (u_int8_t type, u_int8_t *extra, u_int8_t *buf,
778 			       size_t sz, struct exchange *exchange)
779 {
780   u_int8_t proto = GET_IPSEC_ID_PROTO (extra);
781   u_int16_t port = GET_IPSEC_ID_PORT (extra);
782 
783   LOG_DBG ((LOG_MESSAGE, 40,
784 	    "ipsec_validate_id_information: proto %d port %d type %d",
785 	    proto, port, type));
786   if (type < IPSEC_ID_IPV4_ADDR || type > IPSEC_ID_KEY_ID)
787     return -1;
788 
789   switch (type)
790     {
791     case IPSEC_ID_IPV4_ADDR:
792       LOG_DBG_BUF ((LOG_MESSAGE, 40, "ipsec_validate_id_information: IPv4",
793 		    buf, sizeof (struct in_addr)));
794       break;
795 
796     case IPSEC_ID_IPV6_ADDR:
797       LOG_DBG_BUF ((LOG_MESSAGE, 40, "ipsec_validate_id_information: IPv6",
798 		    buf, sizeof (struct in6_addr)));
799       break;
800 
801     case IPSEC_ID_IPV4_ADDR_SUBNET:
802       LOG_DBG_BUF ((LOG_MESSAGE, 40,
803 		    "ipsec_validate_id_information: IPv4 network/netmask",
804 		    buf, 2 * sizeof (struct in_addr)));
805       break;
806 
807     case IPSEC_ID_IPV6_ADDR_SUBNET:
808       LOG_DBG_BUF ((LOG_MESSAGE, 40,
809 		    "ipsec_validate_id_information: IPv6 network/netmask",
810 		    buf, 2 * sizeof (struct in6_addr)));
811       break;
812 
813     default:
814       break;
815     }
816 
817   if (exchange->phase == 1
818       && (proto != IPPROTO_UDP || port != UDP_DEFAULT_PORT)
819       && (proto != 0 || port != 0))
820     {
821 /* XXX SSH's ISAKMP tester fails this test (proto 17 - port 0).  */
822 #ifdef notyet
823       return -1;
824 #else
825       log_print ("ipsec_validate_id_information: "
826 		 "dubious ID information accepted");
827 #endif
828     }
829 
830   /* XXX More checks?  */
831 
832   return 0;
833 }
834 
835 static int
836 ipsec_validate_key_information (u_int8_t *buf, size_t sz)
837 {
838   /* XXX Not implemented yet.  */
839   return 0;
840 }
841 
842 static int
843 ipsec_validate_notification (u_int16_t type)
844 {
845   return type < IPSEC_NOTIFY_RESPONDER_LIFETIME
846     || type > IPSEC_NOTIFY_INITIAL_CONTACT ? -1 : 0;
847 }
848 
849 static int
850 ipsec_validate_proto (u_int8_t proto)
851 {
852   return proto < IPSEC_PROTO_IPSEC_AH || proto > IPSEC_PROTO_IPCOMP ? -1 : 0;
853 }
854 
855 static int
856 ipsec_validate_situation (u_int8_t *buf, size_t *sz)
857 {
858   int sit = GET_IPSEC_SIT_SIT (buf);
859   int off;
860 
861   if (sit & (IPSEC_SIT_SECRECY | IPSEC_SIT_INTEGRITY))
862     {
863       /*
864        * XXX All the roundups below, round up to 32 bit boundaries given
865        * that the situation field is aligned.  This is not necessarily so,
866        * but I interpret the drafts as this is like this they want it.
867        */
868       off = ROUNDUP_32 (GET_IPSEC_SIT_SECRECY_LENGTH (buf));
869       off += ROUNDUP_32 (GET_IPSEC_SIT_SECRECY_CAT_LENGTH (buf + off));
870       off += ROUNDUP_32 (GET_IPSEC_SIT_INTEGRITY_LENGTH (buf + off));
871       off += ROUNDUP_32 (GET_IPSEC_SIT_INTEGRITY_CAT_LENGTH (buf + off));
872       *sz = off + IPSEC_SIT_SZ;
873     }
874   else
875     *sz = IPSEC_SIT_SIT_LEN;
876 
877   /* Currently only "identity only" situations are supported.  */
878 #ifdef notdef
879   return
880     sit & ~(IPSEC_SIT_IDENTITY_ONLY | IPSEC_SIT_SECRECY | IPSEC_SIT_INTEGRITY);
881 #else
882    return sit & ~IPSEC_SIT_IDENTITY_ONLY;
883 #endif
884     return 1;
885   return 0;
886 }
887 
888 static int
889 ipsec_validate_transform_id (u_int8_t proto, u_int8_t transform_id)
890 {
891   switch (proto)
892     {
893       /*
894        * As no unexpected protocols can occur, we just tie the default case
895        * to the first case, in orer to silence a GCC warning.
896        */
897     default:
898     case ISAKMP_PROTO_ISAKMP:
899       return transform_id != IPSEC_TRANSFORM_KEY_IKE;
900     case IPSEC_PROTO_IPSEC_AH:
901       return
902 	transform_id < IPSEC_AH_MD5 || transform_id > IPSEC_AH_DES ? -1 : 0;
903     case IPSEC_PROTO_IPSEC_ESP:
904       return transform_id < IPSEC_ESP_DES_IV64
905 	|| (transform_id > IPSEC_ESP_AES_128_CTR
906 	    && transform_id < IPSEC_ESP_AES_MARS)
907 	|| transform_id > IPSEC_ESP_AES_TWOFISH ? -1 : 0;
908     case IPSEC_PROTO_IPCOMP:
909       return transform_id < IPSEC_IPCOMP_OUI
910 	|| transform_id > IPSEC_IPCOMP_V42BIS ? -1 : 0;
911     }
912 }
913 
914 static int
915 ipsec_initiator (struct message *msg)
916 {
917   struct exchange *exchange = msg->exchange;
918   int (**script) (struct message *) = 0;
919 
920   /* Check that the SA is coherent with the IKE rules.  */
921   if (exchange->type != ISAKMP_EXCH_TRANSACTION
922       && ((exchange->phase == 1 && exchange->type != ISAKMP_EXCH_ID_PROT
923 	   && exchange->type != ISAKMP_EXCH_AGGRESSIVE
924 	   && exchange->type != ISAKMP_EXCH_INFO)
925 	  || (exchange->phase == 2 && exchange->type != IKE_EXCH_QUICK_MODE
926 	      && exchange->type != ISAKMP_EXCH_INFO)))
927     {
928       log_print ("ipsec_initiator: unsupported exchange type %d in phase %d",
929 		 exchange->type, exchange->phase);
930       return -1;
931     }
932 
933   switch (exchange->type)
934     {
935     case ISAKMP_EXCH_ID_PROT:
936       script = ike_main_mode_initiator;
937       break;
938 #ifdef USE_AGGRESSIVE
939     case ISAKMP_EXCH_AGGRESSIVE:
940       script = ike_aggressive_initiator;
941       break;
942 #endif
943 #ifdef USE_ISAKMP_CFG
944     case ISAKMP_EXCH_TRANSACTION:
945       script = isakmp_cfg_initiator;
946       break;
947 #endif
948     case ISAKMP_EXCH_INFO:
949       return message_send_info (msg);
950     case IKE_EXCH_QUICK_MODE:
951       script = ike_quick_mode_initiator;
952       break;
953     default:
954       log_print ("ipsec_initiator: unsupported exchange type %d",
955 		 exchange->type);
956       return -1;
957     }
958 
959   /* Run the script code for this step.  */
960   if (script)
961     return script[exchange->step] (msg);
962 
963   return 0;
964 }
965 
966 /*
967  * delete all SA's from addr with the associated proto and SPI's
968  *
969  * spis[] is an array of SPIs of size 16-octet for proto ISAKMP
970  * or 4-octet otherwise.
971  */
972 static void
973 ipsec_delete_spi_list (struct sockaddr *addr, u_int8_t proto,
974                        u_int8_t *spis, int nspis, char *type)
975 {
976   struct sa *sa;
977   int i;
978 
979   for (i = 0; i < nspis; i++)
980     {
981       if (proto == ISAKMP_PROTO_ISAKMP)
982         {
983           u_int8_t *spi = spis + i * ISAKMP_HDR_COOKIES_LEN;
984 
985           /*
986            * This really shouldn't happen in IPSEC DOI
987            * code, but Cisco VPN 3000 sends ISAKMP DELETE's
988            * this way.
989            */
990           sa = sa_lookup_isakmp_sa (addr, spi);
991         }
992       else
993         {
994           u_int32_t spi = ((u_int32_t *)spis)[i];
995 
996           sa = ipsec_sa_lookup (addr, spi, proto);
997         }
998 
999       if (sa == NULL)
1000         {
1001 	  LOG_DBG ((LOG_SA, 30, "ipsec_delete_spi_list: "
1002 		   "could not locate SA (SPI %08x, proto %u)",
1003 		   spis[i], proto));
1004 	  continue;
1005 	}
1006 
1007       /* Delete the SA and search for the next */
1008       LOG_DBG ((LOG_SA, 30, "ipsec_delete_spi_list: "
1009 	       "%s made us delete SA %p (%d references) for proto %d",
1010 	       type, sa, sa->refcnt, proto));
1011 
1012       sa_free (sa);
1013     }
1014 }
1015 
1016 /*
1017  * deal with a NOTIFY of INVALID_SPI
1018  */
1019 static void
1020 ipsec_invalid_spi (struct message *msg, struct payload *p)
1021 {
1022   struct sockaddr *dst;
1023   int invspisz, off;
1024   u_int32_t spi;
1025   u_int16_t totsiz;
1026   u_int8_t spisz;
1027 
1028   /*
1029    * get the invalid spi out of the variable sized notification data
1030    * field, which is after the variable sized SPI field [which specifies
1031    * the receiving entity's phase-1 SPI, not the invalid spi]
1032    */
1033   totsiz = GET_ISAKMP_GEN_LENGTH (p->p);
1034   spisz = GET_ISAKMP_NOTIFY_SPI_SZ (p->p);
1035   off = ISAKMP_NOTIFY_SPI_OFF + spisz;
1036   invspisz = totsiz - off;
1037 
1038   if (invspisz != sizeof spi)
1039     {
1040       LOG_DBG ((LOG_SA, 40,
1041 	       "ipsec_invalid_spi: SPI size %d in INVALID_SPI "
1042 	       "payload unsupported", spisz));
1043        return;
1044     }
1045   memcpy (&spi, p->p + off, sizeof spi);
1046 
1047   msg->transport->vtbl->get_dst (msg->transport, &dst);
1048 
1049   /* delete matching SPI's from this peer */
1050   ipsec_delete_spi_list (dst, 0, (u_int8_t *)&spi, 1, "INVALID_SPI");
1051 }
1052 
1053 static int
1054 ipsec_responder (struct message *msg)
1055 {
1056   struct exchange *exchange = msg->exchange;
1057   int (**script) (struct message *) = 0;
1058   struct payload *p;
1059   char *tag;
1060   u_int16_t type;
1061 
1062   /* Check that a new exchange is coherent with the IKE rules.  */
1063   if (exchange->step == 0 && exchange->type != ISAKMP_EXCH_TRANSACTION
1064       && ((exchange->phase == 1 && exchange->type != ISAKMP_EXCH_ID_PROT
1065 	   && exchange->type != ISAKMP_EXCH_AGGRESSIVE
1066 	   && exchange->type != ISAKMP_EXCH_INFO)
1067 	  || (exchange->phase == 2 && exchange->type == ISAKMP_EXCH_ID_PROT)))
1068     {
1069       message_drop (msg, ISAKMP_NOTIFY_UNSUPPORTED_EXCHANGE_TYPE, 0, 1, 0);
1070       return -1;
1071     }
1072 
1073   LOG_DBG ((LOG_MISC, 30,
1074 	    "ipsec_responder: phase %d exchange %d step %d", exchange->phase,
1075 	    exchange->type, exchange->step));
1076   switch (exchange->type)
1077     {
1078     case ISAKMP_EXCH_ID_PROT:
1079       script = ike_main_mode_responder;
1080       break;
1081 
1082 #ifdef USE_AGGRESSIVE
1083     case ISAKMP_EXCH_AGGRESSIVE:
1084       script = ike_aggressive_responder;
1085       break;
1086 #endif
1087 
1088 #ifdef USE_ISAKMP_CFG
1089     case ISAKMP_EXCH_TRANSACTION:
1090       script = isakmp_cfg_responder;
1091       break;
1092 #endif
1093 
1094     case ISAKMP_EXCH_INFO:
1095       for (p = TAILQ_FIRST (&msg->payload[ISAKMP_PAYLOAD_NOTIFY]); p;
1096 	   p = TAILQ_NEXT (p, link))
1097 	{
1098 	  type = GET_ISAKMP_NOTIFY_MSG_TYPE (p->p);
1099 	  tag = constant_lookup (isakmp_notify_cst, type);
1100 	  LOG_DBG ((LOG_EXCHANGE, 10,
1101 		    "ipsec_responder: got NOTIFY of type %s",
1102 		    tag ? tag : "<unknown>"));
1103 
1104 	  if (type == ISAKMP_NOTIFY_INVALID_SPI)
1105 	    ipsec_invalid_spi (msg, p);
1106 
1107 	  p->flags |= PL_MARK;
1108 	}
1109 
1110       /*
1111        * If any DELETEs are in here, let the logic of leftover payloads deal
1112        * with them.
1113        */
1114 
1115       return 0;
1116 
1117     case IKE_EXCH_QUICK_MODE:
1118       script = ike_quick_mode_responder;
1119       break;
1120 
1121     default:
1122       message_drop (msg, ISAKMP_NOTIFY_UNSUPPORTED_EXCHANGE_TYPE, 0, 1, 0);
1123       return -1;
1124     }
1125 
1126   /* Run the script code for this step.  */
1127   if (script)
1128     return script[exchange->step] (msg);
1129 
1130   /*
1131    * XXX So far we don't accept any proposals for exchanges we don't support.
1132    */
1133   if (TAILQ_FIRST (&msg->payload[ISAKMP_PAYLOAD_SA]))
1134     {
1135       message_drop (msg, ISAKMP_NOTIFY_NO_PROPOSAL_CHOSEN, 0, 1, 0);
1136       return -1;
1137     }
1138   return 0;
1139 }
1140 
1141 static enum hashes from_ike_hash (u_int16_t hash)
1142 {
1143   switch (hash)
1144     {
1145     case IKE_HASH_MD5:
1146       return HASH_MD5;
1147     case IKE_HASH_SHA:
1148       return HASH_SHA1;
1149     }
1150   return -1;
1151 }
1152 
1153 static enum transform from_ike_crypto (u_int16_t crypto)
1154 {
1155   /* Coincidentally this is the null operation :-)  */
1156   return crypto;
1157 }
1158 
1159 /*
1160  * Find out whether the attribute of type TYPE with a LEN length value
1161  * pointed to by VALUE is incompatible with what we can handle.
1162  * VMSG is a pointer to the current message.
1163  */
1164 int
1165 ipsec_is_attribute_incompatible (u_int16_t type, u_int8_t *value,
1166 				 u_int16_t len, void *vmsg)
1167 {
1168   struct message *msg = vmsg;
1169 
1170   if (msg->exchange->phase == 1)
1171     {
1172       switch (type)
1173 	{
1174 	case IKE_ATTR_ENCRYPTION_ALGORITHM:
1175 	  return !crypto_get (from_ike_crypto (decode_16 (value)));
1176 	case IKE_ATTR_HASH_ALGORITHM:
1177 	  return !hash_get (from_ike_hash (decode_16 (value)));
1178 	case IKE_ATTR_AUTHENTICATION_METHOD:
1179 	  return !ike_auth_get (decode_16 (value));
1180 	case IKE_ATTR_GROUP_DESCRIPTION:
1181 	  return decode_16 (value) < IKE_GROUP_DESC_MODP_768
1182 	    || decode_16 (value) > IKE_GROUP_DESC_MODP_1536;
1183 	case IKE_ATTR_GROUP_TYPE:
1184 	  return 1;
1185 	case IKE_ATTR_GROUP_PRIME:
1186 	  return 1;
1187 	case IKE_ATTR_GROUP_GENERATOR_1:
1188 	  return 1;
1189 	case IKE_ATTR_GROUP_GENERATOR_2:
1190 	  return 1;
1191 	case IKE_ATTR_GROUP_CURVE_A:
1192 	  return 1;
1193 	case IKE_ATTR_GROUP_CURVE_B:
1194 	  return 1;
1195 	case IKE_ATTR_LIFE_TYPE:
1196 	  return decode_16 (value) < IKE_DURATION_SECONDS
1197 	    || decode_16 (value) > IKE_DURATION_KILOBYTES;
1198 	case IKE_ATTR_LIFE_DURATION:
1199 	  return len != 2 && len != 4;
1200 	case IKE_ATTR_PRF:
1201 	  return 1;
1202 	case IKE_ATTR_KEY_LENGTH:
1203 	  /*
1204 	   * Our crypto routines only allows key-lengths which are multiples
1205 	   * of an octet.
1206 	   */
1207 	  return decode_16 (value) % 8 != 0;
1208 	case IKE_ATTR_FIELD_SIZE:
1209 	  return 1;
1210 	case IKE_ATTR_GROUP_ORDER:
1211 	  return 1;
1212 	}
1213     }
1214   else
1215     {
1216       switch (type)
1217 	{
1218 	case IPSEC_ATTR_SA_LIFE_TYPE:
1219 	  return decode_16 (value) < IPSEC_DURATION_SECONDS
1220 	    || decode_16 (value) > IPSEC_DURATION_KILOBYTES;
1221 	case IPSEC_ATTR_SA_LIFE_DURATION:
1222 	  return len != 2 && len != 4;
1223 	case IPSEC_ATTR_GROUP_DESCRIPTION:
1224 	  return decode_16 (value) < IKE_GROUP_DESC_MODP_768
1225 	    || decode_16 (value) > IKE_GROUP_DESC_MODP_1536;
1226 	case IPSEC_ATTR_ENCAPSULATION_MODE:
1227 	  return decode_16 (value) < IPSEC_ENCAP_TUNNEL
1228 	    || decode_16 (value) > IPSEC_ENCAP_TRANSPORT;
1229 	case IPSEC_ATTR_AUTHENTICATION_ALGORITHM:
1230 	  return decode_16 (value) < IPSEC_AUTH_HMAC_MD5
1231 	    || decode_16 (value) > IPSEC_AUTH_HMAC_RIPEMD;
1232 	case IPSEC_ATTR_KEY_LENGTH:
1233 	  /* XXX Blowfish needs '0'. Others appear to disregard this attr?  */
1234 	  return 0;
1235 	case IPSEC_ATTR_KEY_ROUNDS:
1236 	  return 1;
1237 	case IPSEC_ATTR_COMPRESS_DICTIONARY_SIZE:
1238 	  return 1;
1239 	case IPSEC_ATTR_COMPRESS_PRIVATE_ALGORITHM:
1240 	  return 1;
1241 	case IPSEC_ATTR_ECN_TUNNEL:
1242 	  return 1;
1243 	}
1244     }
1245   /* XXX Silence gcc.  */
1246   return 1;
1247 }
1248 
1249 #ifdef USE_DEBUG
1250 /*
1251  * Log the attribute of TYPE with a LEN length value pointed to by VALUE
1252  * in human-readable form.  VMSG is a pointer to the current message.
1253  */
1254 int
1255 ipsec_debug_attribute (u_int16_t type, u_int8_t *value, u_int16_t len,
1256 		       void *vmsg)
1257 {
1258   struct message *msg = vmsg;
1259   char val[20];
1260 
1261   /* XXX Transient solution.  */
1262   if (len == 2)
1263     snprintf (val, sizeof val, "%d", decode_16 (value));
1264   else if (len == 4)
1265     snprintf (val, sizeof val, "%d", decode_32 (value));
1266   else
1267     snprintf (val, sizeof val, "unrepresentable");
1268 
1269   LOG_DBG ((LOG_MESSAGE, 50, "Attribute %s value %s",
1270 	    constant_name (msg->exchange->phase == 1
1271 			   ? ike_attr_cst : ipsec_attr_cst, type),
1272 	    val));
1273   return 0;
1274 }
1275 #endif
1276 
1277 /*
1278  * Decode the attribute of type TYPE with a LEN length value pointed to by
1279  * VALUE.  VIDA is a pointer to a context structure where we can find the
1280  * current message, SA and protocol.
1281  */
1282 int
1283 ipsec_decode_attribute (u_int16_t type, u_int8_t *value, u_int16_t len,
1284 			void *vida)
1285 {
1286   struct ipsec_decode_arg *ida = vida;
1287   struct message *msg = ida->msg;
1288   struct sa *sa = ida->sa;
1289   struct ipsec_sa *isa = sa->data;
1290   struct proto *proto = ida->proto;
1291   struct ipsec_proto *iproto = proto->data;
1292   struct exchange *exchange = msg->exchange;
1293   struct ipsec_exch *ie = exchange->data;
1294   static int lifetype = 0;
1295 
1296   if (exchange->phase == 1)
1297     {
1298       switch (type)
1299 	{
1300 	case IKE_ATTR_ENCRYPTION_ALGORITHM:
1301 	  /* XXX Errors possible?  */
1302 	  exchange->crypto = crypto_get (from_ike_crypto (decode_16 (value)));
1303 	  break;
1304 	case IKE_ATTR_HASH_ALGORITHM:
1305 	  /* XXX Errors possible?  */
1306 	  ie->hash = hash_get (from_ike_hash (decode_16 (value)));
1307 	  break;
1308 	case IKE_ATTR_AUTHENTICATION_METHOD:
1309 	  /* XXX Errors possible?  */
1310 	  ie->ike_auth = ike_auth_get (decode_16 (value));
1311 	  break;
1312 	case IKE_ATTR_GROUP_DESCRIPTION:
1313 	  isa->group_desc = decode_16 (value);
1314 	  break;
1315 	case IKE_ATTR_GROUP_TYPE:
1316 	  break;
1317 	case IKE_ATTR_GROUP_PRIME:
1318 	  break;
1319 	case IKE_ATTR_GROUP_GENERATOR_1:
1320 	  break;
1321 	case IKE_ATTR_GROUP_GENERATOR_2:
1322 	  break;
1323 	case IKE_ATTR_GROUP_CURVE_A:
1324 	  break;
1325 	case IKE_ATTR_GROUP_CURVE_B:
1326 	  break;
1327 	case IKE_ATTR_LIFE_TYPE:
1328 	  lifetype = decode_16 (value);
1329 	  return 0;
1330 	case IKE_ATTR_LIFE_DURATION:
1331 	  switch (lifetype)
1332 	    {
1333 	    case IKE_DURATION_SECONDS:
1334 	      switch (len)
1335 		{
1336 		case 2:
1337 		  sa->seconds = decode_16 (value);
1338 		  break;
1339 		case 4:
1340 		  sa->seconds = decode_32 (value);
1341 		  break;
1342 		default:
1343 		  log_print ("ipsec_decode_attribute: unreasonable lifetime");
1344 		}
1345 	      break;
1346 	    case IKE_DURATION_KILOBYTES:
1347 	      switch (len)
1348 		{
1349 		case 2:
1350 		  sa->kilobytes = decode_16 (value);
1351 		  break;
1352 		case 4:
1353 		  sa->kilobytes = decode_32 (value);
1354 		  break;
1355 		default:
1356 		  log_print ("ipsec_decode_attribute: unreasonable lifetime");
1357 		}
1358 	      break;
1359 	    default:
1360 	      log_print ("ipsec_decode_attribute: unknown lifetime type");
1361 	    }
1362 	  break;
1363 	case IKE_ATTR_PRF:
1364 	  break;
1365 	case IKE_ATTR_KEY_LENGTH:
1366 	  exchange->key_length = decode_16 (value) / 8;
1367 	  break;
1368 	case IKE_ATTR_FIELD_SIZE:
1369 	  break;
1370 	case IKE_ATTR_GROUP_ORDER:
1371 	  break;
1372 	}
1373     }
1374   else
1375     {
1376       switch (type)
1377 	{
1378 	case IPSEC_ATTR_SA_LIFE_TYPE:
1379 	  lifetype = decode_16 (value);
1380 	  return 0;
1381 	case IPSEC_ATTR_SA_LIFE_DURATION:
1382 	  switch (lifetype)
1383 	    {
1384 	    case IPSEC_DURATION_SECONDS:
1385 	      switch (len)
1386 		{
1387 		case 2:
1388 		  sa->seconds = decode_16 (value);
1389 		  break;
1390 		case 4:
1391 		  sa->seconds = decode_32 (value);
1392 		  break;
1393 		default:
1394 		  log_print ("ipsec_decode_attribute: unreasonable lifetime");
1395 		}
1396 	      break;
1397 	    case IPSEC_DURATION_KILOBYTES:
1398 	      switch (len)
1399 		{
1400 		case 2:
1401 		  sa->kilobytes = decode_16 (value);
1402 		  break;
1403 		case 4:
1404 		  sa->kilobytes = decode_32 (value);
1405 		  break;
1406 		default:
1407 		  log_print ("ipsec_decode_attribute: unreasonable lifetime");
1408 		}
1409 	      break;
1410 	    default:
1411 	      log_print ("ipsec_decode_attribute: unknown lifetime type");
1412 	    }
1413 	  break;
1414 	case IPSEC_ATTR_GROUP_DESCRIPTION:
1415 	  isa->group_desc = decode_16 (value);
1416 	  break;
1417 	case IPSEC_ATTR_ENCAPSULATION_MODE:
1418 	  /* XXX Multiple protocols must have same encapsulation mode, no?  */
1419 	  iproto->encap_mode = decode_16 (value);
1420 	  break;
1421 	case IPSEC_ATTR_AUTHENTICATION_ALGORITHM:
1422 	  iproto->auth = decode_16 (value);
1423 	  break;
1424 	case IPSEC_ATTR_KEY_LENGTH:
1425 	  iproto->keylen = decode_16 (value);
1426 	  break;
1427 	case IPSEC_ATTR_KEY_ROUNDS:
1428 	  iproto->keyrounds = decode_16 (value);
1429 	  break;
1430 	case IPSEC_ATTR_COMPRESS_DICTIONARY_SIZE:
1431 	  break;
1432 	case IPSEC_ATTR_COMPRESS_PRIVATE_ALGORITHM:
1433 	  break;
1434 	case IPSEC_ATTR_ECN_TUNNEL:
1435 	  break;
1436 	}
1437     }
1438   lifetype = 0;
1439   return 0;
1440 }
1441 
1442 /*
1443  * Walk over the attributes of the transform payload found in BUF, and
1444  * fill out the fields of the SA attached to MSG.  Also mark the SA as
1445  * processed.
1446  */
1447 void
1448 ipsec_decode_transform (struct message *msg, struct sa *sa,
1449 			struct proto *proto, u_int8_t *buf)
1450 {
1451   struct ipsec_exch *ie = msg->exchange->data;
1452   struct ipsec_decode_arg ida;
1453 
1454   LOG_DBG ((LOG_MISC, 20, "ipsec_decode_transform: transform %d chosen",
1455 	    GET_ISAKMP_TRANSFORM_NO (buf)));
1456 
1457   ida.msg = msg;
1458   ida.sa = sa;
1459   ida.proto = proto;
1460 
1461   /* The default IKE lifetime is 8 hours.  */
1462   if (sa->phase == 1)
1463     sa->seconds = 28800;
1464 
1465   /* Extract the attributes and stuff them into the SA.  */
1466   attribute_map (buf + ISAKMP_TRANSFORM_SA_ATTRS_OFF,
1467 		 GET_ISAKMP_GEN_LENGTH (buf) - ISAKMP_TRANSFORM_SA_ATTRS_OFF,
1468 		 ipsec_decode_attribute, &ida);
1469 
1470   /*
1471    * If no pseudo-random function was negotiated, it's HMAC.
1472    * XXX As PRF_HMAC currently is zero, this is a no-op.
1473    */
1474   if (!ie->prf_type)
1475     ie->prf_type = PRF_HMAC;
1476 }
1477 
1478 /*
1479  * Delete the IPsec SA represented by the INCOMING direction in protocol PROTO
1480  * of the IKE security association SA.
1481  */
1482 static void
1483 ipsec_delete_spi (struct sa *sa, struct proto *proto, int incoming)
1484 {
1485   if (sa->phase == 1)
1486     return;
1487   /* XXX Error handling?  Is it interesting?  */
1488   sysdep_ipsec_delete_spi (sa, proto, incoming);
1489 }
1490 
1491 /*
1492  * Store BUF into the g^x entry of the exchange that message MSG belongs to.
1493  * PEER is non-zero when the value is our peer's, and zero when it is ours.
1494  */
1495 static int
1496 ipsec_g_x (struct message *msg, int peer, u_int8_t *buf)
1497 {
1498   struct exchange *exchange = msg->exchange;
1499   struct ipsec_exch *ie = exchange->data;
1500   u_int8_t **g_x;
1501   int initiator = exchange->initiator ^ peer;
1502   char header[32];
1503 
1504   g_x = initiator ? &ie->g_xi : &ie->g_xr;
1505   *g_x = malloc (ie->g_x_len);
1506   if (!*g_x)
1507     {
1508       log_error ("ipsec_g_x: malloc (%lu) failed", (unsigned long)ie->g_x_len);
1509       return -1;
1510     }
1511   memcpy (*g_x, buf, ie->g_x_len);
1512   snprintf (header, sizeof header, "ipsec_g_x: g^x%c", initiator ? 'i' : 'r');
1513   LOG_DBG_BUF ((LOG_MISC, 80, header, *g_x, ie->g_x_len));
1514   return 0;
1515 }
1516 
1517 /* Generate our DH value.  */
1518 int
1519 ipsec_gen_g_x (struct message *msg)
1520 {
1521   struct exchange *exchange = msg->exchange;
1522   struct ipsec_exch *ie = exchange->data;
1523   u_int8_t *buf;
1524 
1525   buf = malloc (ISAKMP_KE_SZ + ie->g_x_len);
1526   if (!buf)
1527     {
1528       log_error ("ipsec_gen_g_x: malloc (%lu) failed",
1529 		 ISAKMP_KE_SZ + (unsigned long)ie->g_x_len);
1530       return -1;
1531     }
1532 
1533   if (message_add_payload (msg, ISAKMP_PAYLOAD_KEY_EXCH, buf,
1534 			   ISAKMP_KE_SZ + ie->g_x_len, 1))
1535     {
1536       free (buf);
1537       return -1;
1538     }
1539 
1540   if (dh_create_exchange (ie->group, buf + ISAKMP_KE_DATA_OFF))
1541     {
1542       log_print ("ipsec_gen_g_x: dh_create_exchange failed");
1543       free (buf);
1544       return -1;
1545     }
1546   return ipsec_g_x (msg, 0, buf + ISAKMP_KE_DATA_OFF);
1547 }
1548 
1549 /* Save the peer's DH value.  */
1550 int
1551 ipsec_save_g_x (struct message *msg)
1552 {
1553   struct exchange *exchange = msg->exchange;
1554   struct ipsec_exch *ie = exchange->data;
1555   struct payload *kep;
1556 
1557   kep = TAILQ_FIRST (&msg->payload[ISAKMP_PAYLOAD_KEY_EXCH]);
1558   kep->flags |= PL_MARK;
1559   ie->g_x_len = GET_ISAKMP_GEN_LENGTH (kep->p) - ISAKMP_KE_DATA_OFF;
1560 
1561   /* Check that the given length matches the group's expectancy.  */
1562   if (ie->g_x_len != dh_getlen (ie->group))
1563     {
1564       /* XXX Is this a good notify type?  */
1565       message_drop (msg, ISAKMP_NOTIFY_PAYLOAD_MALFORMED, 0, 1, 0);
1566       return -1;
1567     }
1568 
1569   return ipsec_g_x (msg, 1, kep->p + ISAKMP_KE_DATA_OFF);
1570 }
1571 
1572 /*
1573  * Get a SPI for PROTO and the transport MSG passed over.  Store the
1574  * size where SZ points.  NB!  A zero return is OK if *SZ is zero.
1575  */
1576 static u_int8_t *
1577 ipsec_get_spi (size_t *sz, u_int8_t proto, struct message *msg)
1578 {
1579   struct sockaddr *dst, *src;
1580   struct transport *transport = msg->transport;
1581 
1582   if (msg->exchange->phase == 1)
1583     {
1584       *sz = 0;
1585       return 0;
1586     }
1587   else
1588     {
1589       /* We are the destination in the SA we want a SPI for.  */
1590       transport->vtbl->get_src (transport, &dst);
1591       /* The peer is the source.  */
1592       transport->vtbl->get_dst (transport, &src);
1593       return sysdep_ipsec_get_spi (sz, proto, src, dst, msg->exchange->seq);
1594     }
1595 }
1596 
1597 /*
1598  * We have gotten a payload PAYLOAD of type TYPE, which did not get handled
1599  * by the logic of the exchange MSG takes part in.  Now is the time to deal
1600  * with such a payload if we know how to, if we don't, return -1, otherwise
1601  * 0.
1602  */
1603 int
1604 ipsec_handle_leftover_payload (struct message *msg, u_int8_t type,
1605 			       struct payload *payload)
1606 {
1607   u_int32_t spisz, nspis;
1608   struct sockaddr *dst;
1609   int reenter = 0;
1610   u_int8_t *spis, proto;
1611   struct sa *sa;
1612 
1613   switch (type)
1614     {
1615     case ISAKMP_PAYLOAD_DELETE:
1616       proto = GET_ISAKMP_DELETE_PROTO (payload->p);
1617       nspis = GET_ISAKMP_DELETE_NSPIS (payload->p);
1618       spisz = GET_ISAKMP_DELETE_SPI_SZ (payload->p);
1619 
1620       if (nspis == 0)
1621         {
1622 	  LOG_DBG ((LOG_SA, 60, "ipsec_handle_leftover_payload: message "
1623 		    "specified zero SPIs, ignoring"));
1624 	  return -1;
1625 	}
1626 
1627       /* verify proper SPI size */
1628       if ((proto == ISAKMP_PROTO_ISAKMP && spisz != ISAKMP_HDR_COOKIES_LEN)
1629           || (proto != ISAKMP_PROTO_ISAKMP && spisz != sizeof (u_int32_t)))
1630         {
1631 	  log_print ("ipsec_handle_leftover_payload: "
1632 		     "invalid SPI size %d for proto %d in DELETE payload",
1633 		     spisz, proto);
1634 	  return -1;
1635         }
1636 
1637       spis = (u_int8_t *)malloc (nspis * spisz);
1638       if (!spis)
1639         {
1640 	  log_error ("ipsec_handle_leftover_payload: malloc (%d) failed",
1641 		     nspis * spisz);
1642 	  return -1;
1643 	}
1644 
1645       /* extract SPI and get dst address */
1646       memcpy (spis, payload->p + ISAKMP_DELETE_SPI_OFF, nspis * spisz);
1647       msg->transport->vtbl->get_dst (msg->transport, &dst);
1648 
1649       ipsec_delete_spi_list (dst, proto, spis, nspis, "DELETE");
1650 
1651       free (spis);
1652       payload->flags |= PL_MARK;
1653       return 0;
1654 
1655     case ISAKMP_PAYLOAD_NOTIFY:
1656       switch (GET_ISAKMP_NOTIFY_MSG_TYPE (payload->p))
1657 	{
1658 	case IPSEC_NOTIFY_INITIAL_CONTACT:
1659 	  /*
1660 	   * Find out who is sending this and then delete every SA that is
1661 	   * ready.  Exchanges will timeout themselves and then the
1662 	   * non-ready SAs will disappear too.
1663 	   */
1664 	  msg->transport->vtbl->get_dst (msg->transport, &dst);
1665 	  while ((sa = sa_lookup_by_peer (dst, sysdep_sa_len (dst))) != 0)
1666 	    {
1667 	      /*
1668 	       * Don't delete the current SA -- we received the notification
1669 	       * over it, so it's obviously still active. We temporarily need
1670                * to remove the SA from the list to avoid an endless loop,
1671 	       * but keep a reference so it won't disappear meanwhile.
1672 	       */
1673 	      if (sa == msg->isakmp_sa)
1674 	        {
1675 		  sa_reference (sa);
1676                   sa_remove (sa);
1677                   reenter = 1;
1678 		  continue;
1679 		}
1680 
1681 	      LOG_DBG ((LOG_SA, 30,
1682 			"ipsec_handle_leftover_payload: "
1683 			"INITIAL-CONTACT made us delete SA %p",
1684 			sa));
1685 	      sa_delete (sa, 0);
1686 	    }
1687 
1688           if (reenter)
1689 	    {
1690 	      sa_enter (msg->isakmp_sa);
1691 	      sa_release (msg->isakmp_sa);
1692 	    }
1693 	  payload->flags |= PL_MARK;
1694 	  return 0;
1695 	}
1696     }
1697   return -1;
1698 }
1699 
1700 /* Return the encryption keylength in octets of the ESP protocol PROTO.  */
1701 int
1702 ipsec_esp_enckeylength (struct proto *proto)
1703 {
1704   struct ipsec_proto *iproto = proto->data;
1705 
1706   /* Compute the keylength to use.  */
1707   switch (proto->id)
1708     {
1709     case IPSEC_ESP_DES:
1710     case IPSEC_ESP_DES_IV32:
1711     case IPSEC_ESP_DES_IV64:
1712       return 8;
1713     case IPSEC_ESP_3DES:
1714       return 24;
1715     case IPSEC_ESP_CAST:
1716       if (!iproto->keylen)
1717         return 16;
1718       return iproto->keylen / 8;
1719     case IPSEC_ESP_AES:
1720     case IPSEC_ESP_AES_128_CTR:
1721       if (!iproto->keylen)
1722 	return 16;
1723       /* Fallthrough */
1724     default:
1725       return iproto->keylen / 8;
1726     }
1727 }
1728 
1729 /* Return the authentication keylength in octets of the ESP protocol PROTO.  */
1730 int
1731 ipsec_esp_authkeylength (struct proto *proto)
1732 {
1733   struct ipsec_proto *iproto = proto->data;
1734 
1735   switch (iproto->auth)
1736     {
1737     case IPSEC_AUTH_HMAC_MD5:
1738       return 16;
1739     case IPSEC_AUTH_HMAC_SHA:
1740     case IPSEC_AUTH_HMAC_RIPEMD:
1741       return 20;
1742     case IPSEC_AUTH_HMAC_SHA2_256:
1743       return 32;
1744     case IPSEC_AUTH_HMAC_SHA2_384:
1745       return 48;
1746     case IPSEC_AUTH_HMAC_SHA2_512:
1747       return 64;
1748     default:
1749       return 0;
1750     }
1751 }
1752 
1753 /* Return the authentication keylength in octets of the AH protocol PROTO.  */
1754 int
1755 ipsec_ah_keylength (struct proto *proto)
1756 {
1757   switch (proto->id)
1758     {
1759     case IPSEC_AH_MD5:
1760       return 16;
1761     case IPSEC_AH_SHA:
1762     case IPSEC_AH_RIPEMD:
1763       return 20;
1764     case IPSEC_AH_SHA2_256:
1765       return 32;
1766     case IPSEC_AH_SHA2_384:
1767       return 48;
1768     case IPSEC_AH_SHA2_512:
1769       return 64;
1770     default:
1771       return -1;
1772     }
1773 }
1774 
1775 /* Return the total keymaterial length of the protocol PROTO.  */
1776 int
1777 ipsec_keymat_length (struct proto *proto)
1778 {
1779   switch (proto->proto)
1780     {
1781     case IPSEC_PROTO_IPSEC_ESP:
1782       return ipsec_esp_enckeylength (proto) + ipsec_esp_authkeylength (proto);
1783     case IPSEC_PROTO_IPSEC_AH:
1784       return ipsec_ah_keylength (proto);
1785     default:
1786       return -1;
1787     }
1788 }
1789 
1790 /*
1791  * Out of a named section SECTION in the configuration file find out
1792  * the network address and mask as well as the ID type.  Put the info
1793  * in the areas pointed to by ADDR, MASK, TPROTO, PORT, and ID respectively.
1794  * Return 0 on success and -1 on failure.
1795  */
1796 int
1797 ipsec_get_id (char *section, int *id, struct sockaddr **addr,
1798 	      struct sockaddr **mask, u_int8_t *tproto, u_int16_t *port)
1799 {
1800   char *type, *address, *netmask;
1801 
1802   type = conf_get_str (section, "ID-type");
1803   if (!type)
1804     {
1805       log_print ("ipsec_get_id: section %s has no \"ID-type\" tag", section);
1806       return -1;
1807     }
1808 
1809   *id = constant_value (ipsec_id_cst, type);
1810   switch (*id)
1811     {
1812     case IPSEC_ID_IPV4_ADDR:
1813     case IPSEC_ID_IPV6_ADDR:
1814       address = conf_get_str (section, "Address");
1815       if (!address)
1816 	{
1817 	  log_print ("ipsec_get_id: section %s has no \"Address\" tag",
1818 		     section);
1819 	  return -1;
1820 	}
1821 
1822       if (text2sockaddr (address, NULL, addr))
1823 	{
1824 	  log_print ("ipsec_get_id: invalid address %s in section %s", address,
1825 		     section);
1826 	  return -1;
1827 	}
1828 
1829       *tproto = conf_get_num (section, "Protocol", 0);
1830       if (*tproto)
1831 	*port = conf_get_num (section, "Port", 0);
1832       break;
1833 
1834 #ifdef notyet
1835     case IPSEC_ID_FQDN:
1836       return -1;
1837 
1838     case IPSEC_ID_USER_FQDN:
1839       return -1;
1840 #endif
1841 
1842     case IPSEC_ID_IPV4_ADDR_SUBNET:
1843     case IPSEC_ID_IPV6_ADDR_SUBNET:
1844       address = conf_get_str (section, "Network");
1845       if (!address)
1846 	{
1847 	  log_print ("ipsec_get_id: section %s has no \"Network\" tag",
1848 		     section);
1849 	  return -1;
1850 	}
1851 
1852       if (text2sockaddr (address, NULL, addr))
1853 	{
1854 	  log_print ("ipsec_get_id: invalid section %s network %s", section,
1855 		     address);
1856 	  return -1;
1857 	}
1858 
1859       netmask = conf_get_str (section, "Netmask");
1860       if (!netmask)
1861 	{
1862 	  log_print ("ipsec_get_id: section %s has no \"Netmask\" tag",
1863 		     section);
1864 	  return -1;
1865 	}
1866 
1867       if (text2sockaddr (netmask, NULL, mask))
1868 	{
1869 	  log_print ("ipsec_id_build: invalid section %s network %s", section,
1870 		     netmask);
1871 	  return -1;
1872 	}
1873 
1874       *tproto = conf_get_num (section, "Protocol", 0);
1875       if (*tproto)
1876 	*port = conf_get_num (section, "Port", 0);
1877       break;
1878 
1879 #ifdef notyet
1880     case IPSEC_ID_IPV4_RANGE:
1881       return -1;
1882 
1883     case IPSEC_ID_IPV6_RANGE:
1884       return -1;
1885 
1886     case IPSEC_ID_DER_ASN1_DN:
1887       return -1;
1888 
1889     case IPSEC_ID_DER_ASN1_GN:
1890       return -1;
1891 
1892     case IPSEC_ID_KEY_ID:
1893       return -1;
1894 #endif
1895 
1896     default:
1897       log_print ("ipsec_get_id: unknown ID type \"%s\" in section %s", type,
1898 		 section);
1899       return -1;
1900     }
1901 
1902   return 0;
1903 }
1904 
1905 /*
1906  * XXX I rather want this function to return a status code, and fail if
1907  * we cannot fit the information in the supplied buffer.
1908  */
1909 static void
1910 ipsec_decode_id (char *buf, int size, u_int8_t *id, size_t id_len,
1911 		 int isakmpform)
1912 {
1913   int id_type;
1914   char *addr = 0, *mask = 0;
1915   u_int32_t *idp;
1916 
1917   if (id)
1918     {
1919       if (!isakmpform)
1920 	{
1921 	  /* Exchanges and SAs dont carry the IDs in ISAKMP form.  */
1922 	  id -= ISAKMP_GEN_SZ;
1923 	  id_len += ISAKMP_GEN_SZ;
1924 	}
1925 
1926       id_type = GET_ISAKMP_ID_TYPE (id);
1927       idp = (u_int32_t *)(id + ISAKMP_ID_DATA_OFF);
1928       switch (id_type)
1929 	{
1930 	case IPSEC_ID_IPV4_ADDR:
1931 	  util_ntoa (&addr, AF_INET, id + ISAKMP_ID_DATA_OFF);
1932 	  snprintf (buf, size, "%08x: %s",
1933 		    decode_32 (id + ISAKMP_ID_DATA_OFF), addr);
1934 	  break;
1935 
1936 	case IPSEC_ID_IPV4_ADDR_SUBNET:
1937 	  util_ntoa (&addr, AF_INET, id + ISAKMP_ID_DATA_OFF);
1938 	  util_ntoa (&mask, AF_INET, id + ISAKMP_ID_DATA_OFF + 4);
1939 	  snprintf (buf, size, "%08x/%08x: %s/%s",
1940 		    decode_32 (id + ISAKMP_ID_DATA_OFF),
1941 		    decode_32 (id + ISAKMP_ID_DATA_OFF + 4), addr, mask);
1942 	  break;
1943 
1944 	case IPSEC_ID_IPV6_ADDR:
1945 	  util_ntoa (&addr, AF_INET6, id + ISAKMP_ID_DATA_OFF);
1946 	  snprintf (buf, size, "%08x%08x%08x%08x: %s", *idp, *(idp + 1),
1947 		    *(idp + 2), *(idp + 3), addr);
1948 	  break;
1949 
1950 	case IPSEC_ID_IPV6_ADDR_SUBNET:
1951 	  util_ntoa (&addr, AF_INET6, id + ISAKMP_ID_DATA_OFF);
1952 	  util_ntoa (&addr, AF_INET6, id + ISAKMP_ID_DATA_OFF +
1953 		     sizeof (struct in6_addr));
1954 	  snprintf (buf, size, "%08x%08x%08x%08x/%08x%08x%08x%08x: %s/%s",
1955 		    *idp, *(idp + 1), *(idp + 2), *(idp + 3), *(idp + 4),
1956 		    *(idp + 5), *(idp + 6), *(idp + 7), addr, mask);
1957 	  break;
1958 
1959 	case IPSEC_ID_FQDN:
1960 	case IPSEC_ID_USER_FQDN:
1961 	  /* String is not NUL terminated, be careful */
1962 	  id_len -= ISAKMP_ID_DATA_OFF;
1963 	  id_len = MIN(id_len, size - 1);
1964 	  memcpy (buf, id + ISAKMP_ID_DATA_OFF, id_len);
1965 	  buf[id_len] = '\0';
1966 	  break;
1967 
1968 #ifdef USE_X509
1969 	case IPSEC_ID_DER_ASN1_DN:
1970 	  addr = x509_DN_string (id + ISAKMP_ID_DATA_OFF,
1971 				 id_len - ISAKMP_ID_DATA_OFF);
1972 	  if (!addr)
1973 	    {
1974 	      snprintf(buf, size, "unparsable ASN1 DN ID");
1975 	      return;
1976 	    }
1977 	  strlcpy (buf, addr, size);
1978 	  break;
1979 #endif
1980 
1981 	default:
1982 	  snprintf (buf, size, "<id type unknown: %x>", id_type);
1983 	  break;
1984 	}
1985     }
1986   else
1987     snprintf (buf, size, "<no ipsec id>");
1988   if (addr)
1989     free (addr);
1990   if (mask)
1991     free (mask);
1992 }
1993 
1994 char *
1995 ipsec_decode_ids (char *fmt, u_int8_t *id1, size_t id1_len,
1996 		  u_int8_t *id2, size_t id2_len, int isakmpform)
1997 {
1998   static char result[1024];
1999   char s_id1[256], s_id2[256];
2000 
2001   ipsec_decode_id (s_id1, sizeof s_id1, id1, id1_len, isakmpform);
2002   ipsec_decode_id (s_id2, sizeof s_id2, id2, id2_len, isakmpform);
2003 
2004   snprintf (result, sizeof result, fmt, s_id1, s_id2);
2005   return result;
2006 }
2007 
2008 /*
2009  * Out of a named section SECTION in the configuration file build an
2010  * ISAKMP ID payload.  Ths payload size should be stashed in SZ.
2011  * The caller is responsible for freeing the payload.
2012  */
2013 u_int8_t *
2014 ipsec_build_id (char *section, size_t *sz)
2015 {
2016   struct sockaddr *addr, *mask;
2017   u_int8_t *p;
2018   int id, subnet = 0;
2019   u_int8_t tproto = 0;
2020   u_int16_t port = 0;
2021 
2022   if (ipsec_get_id (section, &id, &addr, &mask, &tproto, &port))
2023     return 0;
2024 
2025   if (id == IPSEC_ID_IPV4_ADDR_SUBNET || id == IPSEC_ID_IPV6_ADDR_SUBNET)
2026     subnet = 1;
2027 
2028   *sz = ISAKMP_ID_SZ + sockaddr_addrlen (addr);
2029   if (subnet)
2030     *sz += sockaddr_addrlen (mask);
2031 
2032   p = malloc (*sz);
2033   if (!p)
2034     {
2035       log_print ("ipsec_build_id: malloc(%lu) failed", (unsigned long)*sz);
2036       return 0;
2037     }
2038 
2039   SET_ISAKMP_ID_TYPE (p, id);
2040   SET_ISAKMP_ID_DOI_DATA (p, (unsigned char *)"\000\000\000");
2041 
2042   memcpy (p + ISAKMP_ID_DATA_OFF, sockaddr_addrdata (addr),
2043 	  sockaddr_addrlen (addr));
2044   if (subnet)
2045     memcpy (p + ISAKMP_ID_DATA_OFF + sockaddr_addrlen (addr),
2046 	    sockaddr_addrdata (mask), sockaddr_addrlen (mask));
2047 
2048   SET_IPSEC_ID_PROTO (p + ISAKMP_ID_DOI_DATA_OFF, tproto);
2049   SET_IPSEC_ID_PORT (p + ISAKMP_ID_DOI_DATA_OFF, port);
2050 
2051   return p;
2052 }
2053 
2054 /*
2055  * copy an ISAKMPD id
2056  */
2057 int
2058 ipsec_clone_id (u_int8_t **did, size_t *did_len, u_int8_t *id, size_t id_len)
2059 {
2060   if (*did)
2061     free (*did);
2062 
2063   if (!id_len || !id)
2064     {
2065       *did = 0;
2066       *did_len = 0;
2067       return 0;
2068     }
2069 
2070   *did = malloc (id_len);
2071   if (!*did)
2072     {
2073       *did_len = 0;
2074       log_error ("ipsec_clone_id: malloc(%lu) failed", (unsigned long)id_len);
2075       return -1;
2076     }
2077 
2078   *did_len = id_len;
2079   memcpy (*did, id, id_len);
2080 
2081   return 0;
2082 }
2083 
2084 /*
2085  * IPsec-specific PROTO initializations.  SECTION is only set if we are the
2086  * initiator thus only usable there.
2087  * XXX I want to fix this later.
2088  */
2089 void
2090 ipsec_proto_init (struct proto *proto, char *section)
2091 {
2092   struct ipsec_proto *iproto = proto->data;
2093 
2094   if (proto->sa->phase == 2 && section)
2095     iproto->replay_window
2096       = conf_get_num (section, "ReplayWindow", DEFAULT_REPLAY_WINDOW);
2097 }
2098 
2099 /*
2100  * Add a notification payload of type INITIAL CONTACT to MSG if this is
2101  * the first contact we have made to our peer.
2102  */
2103 int
2104 ipsec_initial_contact (struct message *msg)
2105 {
2106   u_int8_t *buf;
2107 
2108   if (ipsec_contacted (msg))
2109     return 0;
2110 
2111   buf = malloc (ISAKMP_NOTIFY_SZ + ISAKMP_HDR_COOKIES_LEN);
2112   if (!buf)
2113     {
2114       log_error ("ike_phase_1_initial_contact: malloc (%d) failed",
2115 		 ISAKMP_NOTIFY_SZ + ISAKMP_HDR_COOKIES_LEN);
2116       return -1;
2117     }
2118   SET_ISAKMP_NOTIFY_DOI (buf, IPSEC_DOI_IPSEC);
2119   SET_ISAKMP_NOTIFY_PROTO (buf, ISAKMP_PROTO_ISAKMP);
2120   SET_ISAKMP_NOTIFY_SPI_SZ (buf, ISAKMP_HDR_COOKIES_LEN);
2121   SET_ISAKMP_NOTIFY_MSG_TYPE (buf, IPSEC_NOTIFY_INITIAL_CONTACT);
2122   memcpy (buf + ISAKMP_NOTIFY_SPI_OFF, msg->isakmp_sa->cookies,
2123 	  ISAKMP_HDR_COOKIES_LEN);
2124   if (message_add_payload (msg, ISAKMP_PAYLOAD_NOTIFY, buf,
2125 			   ISAKMP_NOTIFY_SZ + ISAKMP_HDR_COOKIES_LEN, 1))
2126     {
2127       free (buf);
2128       return -1;
2129     }
2130 
2131   return ipsec_add_contact (msg);
2132 }
2133 
2134 /*
2135  * Compare the two contacts pointed to by A and B.  Return negative if
2136  * *A < *B, 0 if they are equal, and positive if *A is the largest of them.
2137  */
2138 static int
2139 addr_cmp (const void *a, const void *b)
2140 {
2141   const struct contact *x = a, *y = b;
2142   int minlen = MIN (x->len, y->len);
2143   int rv = memcmp (x->addr, y->addr, minlen);
2144 
2145   return rv ? rv : (x->len - y->len);
2146 }
2147 
2148 /*
2149  * Add the peer that MSG is bound to as an address we don't want to send
2150  * INITIAL CONTACT too from now on.  Do not call this function with a
2151  * specific address duplicate times. We want fast lookup, speed of insertion
2152  * is unimportant, if this is to scale.
2153  */
2154 static int
2155 ipsec_add_contact (struct message *msg)
2156 {
2157   struct contact *new_contacts;
2158   struct sockaddr *dst, *addr;
2159   int cnt;
2160 
2161   if (contact_cnt == contact_limit)
2162     {
2163       cnt = contact_limit ? 2 * contact_limit : 64;
2164       new_contacts = realloc (contacts, cnt * sizeof contacts[0]);
2165       if (!new_contacts)
2166 	{
2167 	  log_error ("ipsec_add_contact: realloc (%p, %lu) failed", contacts,
2168 		     cnt * (unsigned long)sizeof contacts[0]);
2169 	  return -1;
2170 	}
2171       contact_limit = cnt;
2172       contacts = new_contacts;
2173     }
2174   msg->transport->vtbl->get_dst (msg->transport, &dst);
2175   addr = malloc (sysdep_sa_len (dst));
2176   if (!addr)
2177     {
2178       log_error ("ipsec_add_contact: malloc (%d) failed", sysdep_sa_len (dst));
2179       return -1;
2180     }
2181   memcpy (addr, dst, sysdep_sa_len (dst));
2182   contacts[contact_cnt].addr = addr;
2183   contacts[contact_cnt++].len = sysdep_sa_len (dst);
2184 
2185   /*
2186    * XXX There are better algorithms for already mostly-sorted data like
2187    * this, but only qsort is standard.  I will someday do this inline.
2188    */
2189   qsort (contacts, contact_cnt, sizeof *contacts, addr_cmp);
2190   return 0;
2191 }
2192 
2193 /* Return true if the recipient of MSG has already been contacted.  */
2194 static int
2195 ipsec_contacted (struct message *msg)
2196 {
2197   struct contact contact;
2198 
2199   msg->transport->vtbl->get_dst (msg->transport, &contact.addr);
2200   contact.len = sysdep_sa_len (contact.addr);
2201   return contacts
2202     ? (bsearch (&contact, contacts, contact_cnt, sizeof *contacts, addr_cmp)
2203        != 0)
2204     : 0;
2205 }
2206 
2207 /* Add a HASH for to MSG.  */
2208 u_int8_t *
2209 ipsec_add_hash_payload (struct message *msg, size_t hashsize)
2210 {
2211   u_int8_t *buf;
2212 
2213   buf = malloc (ISAKMP_HASH_SZ + hashsize);
2214   if (!buf)
2215     {
2216       log_error ("ipsec_add_hash_payload: malloc (%lu) failed",
2217 		 ISAKMP_HASH_SZ + (unsigned long)hashsize);
2218       return 0;
2219     }
2220 
2221   if (message_add_payload (msg, ISAKMP_PAYLOAD_HASH, buf,
2222 			   ISAKMP_HASH_SZ + hashsize, 1))
2223     {
2224       free (buf);
2225       return 0;
2226     }
2227 
2228   return buf;
2229 }
2230 
2231 /* Fill in the HASH payload of MSG.  */
2232 int
2233 ipsec_fill_in_hash (struct message *msg)
2234 {
2235   struct exchange *exchange = msg->exchange;
2236   struct sa *isakmp_sa = msg->isakmp_sa;
2237   struct ipsec_sa *isa = isakmp_sa->data;
2238   struct hash *hash = hash_get (isa->hash);
2239   struct prf *prf;
2240   struct payload *payload;
2241   u_int8_t *buf;
2242   int i;
2243   char header[80];
2244 
2245   /* If no SKEYID_a, we need not do anything.  */
2246   if (!isa->skeyid_a)
2247     return 0;
2248 
2249   payload = TAILQ_FIRST (&msg->payload[ISAKMP_PAYLOAD_HASH]);
2250   if (!payload)
2251     {
2252       log_print ("ipsec_fill_in_hash: no HASH payload found");
2253       return -1;
2254     }
2255   buf = payload->p;
2256 
2257   /* Allocate the prf and start calculating our HASH(1).  */
2258   LOG_DBG_BUF ((LOG_MISC, 90, "ipsec_fill_in_hash: SKEYID_a", isa->skeyid_a,
2259 		isa->skeyid_len));
2260   prf = prf_alloc (isa->prf_type, hash->type, isa->skeyid_a, isa->skeyid_len);
2261   if (!prf)
2262     return -1;
2263 
2264   prf->Init (prf->prfctx);
2265   LOG_DBG_BUF ((LOG_MISC, 90, "ipsec_fill_in_hash: message_id",
2266 		exchange->message_id, ISAKMP_HDR_MESSAGE_ID_LEN));
2267   prf->Update (prf->prfctx, exchange->message_id, ISAKMP_HDR_MESSAGE_ID_LEN);
2268 
2269   /* Loop over all payloads after HASH(1).  */
2270   for (i = 2; i < msg->iovlen; i++)
2271     {
2272       /* XXX Misleading payload type printouts.  */
2273       snprintf (header, sizeof header,
2274 		"ipsec_fill_in_hash: payload %d after HASH(1)",	i - 1);
2275       LOG_DBG_BUF ((LOG_MISC, 90, header, msg->iov[i].iov_base,
2276 		    msg->iov[i].iov_len));
2277       prf->Update (prf->prfctx, msg->iov[i].iov_base, msg->iov[i].iov_len);
2278     }
2279   prf->Final (buf + ISAKMP_HASH_DATA_OFF, prf->prfctx);
2280   prf_free (prf);
2281   LOG_DBG_BUF ((LOG_MISC, 80, "ipsec_fill_in_hash: HASH(1)",
2282 		buf + ISAKMP_HASH_DATA_OFF, hash->hashsize));
2283 
2284   return 0;
2285 }
2286 
2287 /* Add a HASH payload to MSG, if we have an ISAKMP SA we're protected by.  */
2288 static int
2289 ipsec_informational_pre_hook (struct message *msg)
2290 {
2291   struct sa *isakmp_sa = msg->isakmp_sa;
2292   struct ipsec_sa *isa;
2293   struct hash *hash;
2294 
2295   if (!isakmp_sa)
2296     return 0;
2297   isa = isakmp_sa->data;
2298   hash = hash_get (isa->hash);
2299   return ipsec_add_hash_payload (msg, hash->hashsize) == 0;
2300 }
2301 
2302 /*
2303  * Fill in the HASH payload in MSG, if we have an ISAKMP SA we're protected by.
2304  */
2305 static int
2306 ipsec_informational_post_hook (struct message *msg)
2307 {
2308   if (!msg->isakmp_sa)
2309     return 0;
2310   return ipsec_fill_in_hash (msg);
2311 }
2312 
2313 ssize_t
2314 ipsec_id_size (char *section, u_int8_t *id)
2315 {
2316   char *type, *data;
2317 
2318   type = conf_get_str (section, "ID-type");
2319   if (!type)
2320     {
2321       log_print ("ipsec_id_size: section %s has no \"ID-type\" tag", section);
2322       return -1;
2323     }
2324 
2325   *id = constant_value (ipsec_id_cst, type);
2326   switch (*id)
2327     {
2328     case IPSEC_ID_IPV4_ADDR:
2329       return sizeof (struct in_addr);
2330     case IPSEC_ID_IPV4_ADDR_SUBNET:
2331       return 2 * sizeof (struct in_addr);
2332     case IPSEC_ID_IPV6_ADDR:
2333       return sizeof (struct in6_addr);
2334     case IPSEC_ID_IPV6_ADDR_SUBNET:
2335       return 2 * sizeof (struct in6_addr);
2336     case IPSEC_ID_FQDN:
2337     case IPSEC_ID_USER_FQDN:
2338     case IPSEC_ID_KEY_ID:
2339     case IPSEC_ID_DER_ASN1_DN:
2340     case IPSEC_ID_DER_ASN1_GN:
2341       data = conf_get_str (section, "Name");
2342       if (!data)
2343 	{
2344 	  log_print ("ipsec_id_size: section %s has no \"Name\" tag", section);
2345 	  return -1;
2346 	}
2347       return strlen (data);
2348     }
2349   log_print ("ipsec_id_size: unrecognized/unsupported ID-type %d (%s)",
2350 	     *id, type);
2351   return -1;
2352 }
2353 
2354 /*
2355  * Generate a string version of the ID.
2356  */
2357 char *
2358 ipsec_id_string (u_int8_t *id, size_t id_len)
2359 {
2360   char *buf = 0;
2361   char *addrstr = 0;
2362   size_t len, size;
2363 
2364   /*
2365    * XXX Real ugly way of making the offsets correct.  Be aware that id now
2366    * will point before the actual buffer and cannot be dereferenced without
2367    * an offset larger than or equal to ISAKM_GEN_SZ.
2368    */
2369   id -= ISAKMP_GEN_SZ;
2370 
2371   /* This is the actual length of the ID data field.  */
2372   id_len += ISAKMP_GEN_SZ - ISAKMP_ID_DATA_OFF;
2373 
2374   /*
2375    * Conservative allocation.
2376    * XXX I think the ASN1 DN case can be thought through to give a better
2377    * estimate.
2378    */
2379   size = MAX (sizeof "ipv6/ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff",
2380 	      sizeof "asn1_dn/" + id_len - ISAKMP_ID_DATA_OFF);
2381   buf = malloc (size);
2382   if (!buf)
2383     /* XXX Log?  */
2384     goto fail;
2385 
2386   switch (GET_ISAKMP_ID_TYPE (id))
2387     {
2388     case IPSEC_ID_IPV4_ADDR:
2389       if (id_len < sizeof (struct in_addr))
2390 	goto fail;
2391       util_ntoa (&addrstr, AF_INET, id + ISAKMP_ID_DATA_OFF);
2392       if (!addrstr)
2393 	goto fail;
2394       snprintf (buf, size, "ipv4/%s", addrstr);
2395       break;
2396 
2397     case IPSEC_ID_IPV6_ADDR:
2398       if (id_len < sizeof (struct in6_addr))
2399 	goto fail;
2400       util_ntoa (&addrstr, AF_INET6, id + ISAKMP_ID_DATA_OFF);
2401       if (!addrstr)
2402 	goto fail;
2403       snprintf (buf, size, "ipv6/%s", addrstr);
2404       break;
2405 
2406     case IPSEC_ID_FQDN:
2407     case IPSEC_ID_USER_FQDN:
2408       strlcpy (buf,
2409 	       GET_ISAKMP_ID_TYPE (id) == IPSEC_ID_FQDN ? "fqdn/" : "ufqdn/",
2410 	       size);
2411       len = strlen(buf);
2412 
2413       memcpy (buf + len, id + ISAKMP_ID_DATA_OFF, id_len);
2414       *(buf + len + id_len) = '\0';
2415       break;
2416 
2417 #ifdef USE_X509
2418     case IPSEC_ID_DER_ASN1_DN:
2419       strlcpy (buf, "asn1_dn/", size);
2420       len = strlen(buf);
2421       addrstr = x509_DN_string (id + ISAKMP_ID_DATA_OFF,
2422 				id_len - ISAKMP_ID_DATA_OFF);
2423       if (!addrstr)
2424 	goto fail;
2425       if (size < len + strlen (addrstr) + 1)
2426 	goto fail;
2427       strlcpy (buf + len, addrstr, size - len);
2428       break;
2429 #endif
2430 
2431     default:
2432       /* Unknown type.  */
2433       LOG_DBG ((LOG_MISC, 10, "ipsec_id_string: unknown identity type %d\n",
2434 		GET_ISAKMP_ID_TYPE (id)));
2435       goto fail;
2436     }
2437 
2438   if (addrstr)
2439     free (addrstr);
2440   return buf;
2441 
2442  fail:
2443   if (buf)
2444     free (buf);
2445   if (addrstr)
2446     free (addrstr);
2447   return 0;
2448 }
2449