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