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