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