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