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