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