xref: /openbsd-src/sbin/iked/policy.c (revision 1a8dbaac879b9f3335ad7fb25429ce63ac1d6bac)
1 /*	$OpenBSD: policy.c,v 1.70 2020/09/09 21:25:42 tobhe Exp $	*/
2 
3 /*
4  * Copyright (c) 2010-2013 Reyk Floeter <reyk@openbsd.org>
5  * Copyright (c) 2001 Daniel Hartmeier
6  *
7  * Permission to use, copy, modify, and distribute this software for any
8  * purpose with or without fee is hereby granted, provided that the above
9  * copyright notice and this permission notice appear in all copies.
10  *
11  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18  */
19 
20 #include <sys/queue.h>
21 #include <sys/socket.h>
22 #include <sys/uio.h>
23 #include <sys/tree.h>
24 
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <unistd.h>
28 #include <string.h>
29 #include <errno.h>
30 #include <fcntl.h>
31 #include <event.h>
32 
33 #include "iked.h"
34 #include "ikev2.h"
35 
36 static __inline int
37 	 sa_cmp(struct iked_sa *, struct iked_sa *);
38 static __inline int
39 	 sa_dstid_cmp(struct iked_sa *, struct iked_sa *);
40 static __inline int
41 	 user_cmp(struct iked_user *, struct iked_user *);
42 static __inline int
43 	 childsa_cmp(struct iked_childsa *, struct iked_childsa *);
44 static __inline int
45 	 flow_cmp(struct iked_flow *, struct iked_flow *);
46 static __inline int
47 	 addr_cmp(struct iked_addr *, struct iked_addr *, int);
48 static __inline int
49 	 ts_insert_unique(struct iked_addr *, struct iked_tss *, int);
50 
51 static int	proposals_match(struct iked_proposal *, struct iked_proposal *,
52 		    struct iked_transform **, int);
53 
54 void
55 policy_init(struct iked *env)
56 {
57 	TAILQ_INIT(&env->sc_policies);
58 	TAILQ_INIT(&env->sc_ocsp);
59 	RB_INIT(&env->sc_users);
60 	RB_INIT(&env->sc_sas);
61 	RB_INIT(&env->sc_dstid_sas);
62 	RB_INIT(&env->sc_activesas);
63 	RB_INIT(&env->sc_activeflows);
64 }
65 
66 /*
67  * Lookup an iked policy matching the IKE_AUTH message msg
68  * and store a pointer to the found policy in msg.  If no policy
69  * matches a pointer to the default policy is stored in msg.
70  * If 'proposals' is not NULL policy_lookup only returns policies
71  * compatible with 'proposals'.
72  *
73  * Returns 0 on success and -1 if no matching policy was
74  * found and no default exists.
75  */
76 int
77 policy_lookup(struct iked *env, struct iked_message *msg,
78     struct iked_proposals *proposals)
79 {
80 	struct iked_policy	 pol;
81 	char			*s, idstr[IKED_ID_SIZE];
82 
83 
84 	if (msg->msg_sa != NULL && msg->msg_sa->sa_policy != NULL) {
85 		/* Existing SA with policy */
86 		msg->msg_policy = msg->msg_sa->sa_policy;
87 		return (0);
88 	}
89 
90 	bzero(&pol, sizeof(pol));
91 	if (proposals != NULL)
92 		pol.pol_proposals = *proposals;
93 	pol.pol_af = msg->msg_peer.ss_family;
94 	if (msg->msg_flags & IKED_MSG_FLAGS_USE_TRANSPORT)
95 		pol.pol_flags |= IKED_POLICY_TRANSPORT;
96 	memcpy(&pol.pol_peer.addr, &msg->msg_peer, sizeof(msg->msg_peer));
97 	memcpy(&pol.pol_local.addr, &msg->msg_local, sizeof(msg->msg_local));
98 	if (msg->msg_id.id_type &&
99 	    ikev2_print_id(&msg->msg_id, idstr, IKED_ID_SIZE) == 0 &&
100 	    (s = strchr(idstr, '/')) != NULL) {
101 		pol.pol_peerid.id_type = msg->msg_id.id_type;
102 		pol.pol_peerid.id_length = strlen(s+1);
103 		strlcpy(pol.pol_peerid.id_data, s+1,
104 		    sizeof(pol.pol_peerid.id_data));
105 		log_debug("%s: peerid '%s'", __func__, s+1);
106 	}
107 
108 	/* Try to find a matching policy for this message */
109 	if ((msg->msg_policy = policy_test(env, &pol)) != NULL) {
110 		log_debug("%s: setting policy '%s'", __func__,
111 		    msg->msg_policy->pol_name);
112 		return (0);
113 	}
114 
115 	/* No matching policy found, try the default */
116 	if ((msg->msg_policy = env->sc_defaultcon) != NULL)
117 		return (0);
118 
119 	/* No policy found */
120 	return (-1);
121 }
122 
123 /*
124  * Find a policy matching the query policy key in the global env.
125  * If multiple matching policies are found the policy with the highest
126  * priority is selected.
127  *
128  * Returns a pointer to a matching policy, or NULL if no policy matches.
129  */
130 struct iked_policy *
131 policy_test(struct iked *env, struct iked_policy *key)
132 {
133 	struct iked_policy	*p = NULL, *pol = NULL;
134 	struct iked_flow	*flowkey;
135 	unsigned int		 cnt = 0;
136 
137 	p = TAILQ_FIRST(&env->sc_policies);
138 	while (p != NULL) {
139 		cnt++;
140 		if (p->pol_flags & IKED_POLICY_SKIP)
141 			p = p->pol_skip[IKED_SKIP_FLAGS];
142 		else if (key->pol_af && p->pol_af &&
143 		    key->pol_af != p->pol_af)
144 			p = p->pol_skip[IKED_SKIP_AF];
145 		else if (key->pol_ipproto && p->pol_ipproto &&
146 		    key->pol_ipproto != p->pol_ipproto)
147 			p = p->pol_skip[IKED_SKIP_PROTO];
148 		else if (sockaddr_cmp((struct sockaddr *)&key->pol_peer.addr,
149 		    (struct sockaddr *)&p->pol_peer.addr,
150 		    p->pol_peer.addr_mask) != 0)
151 			p = p->pol_skip[IKED_SKIP_DST_ADDR];
152 		else if (sockaddr_cmp((struct sockaddr *)&key->pol_local.addr,
153 		    (struct sockaddr *)&p->pol_local.addr,
154 		    p->pol_local.addr_mask) != 0)
155 			p = p->pol_skip[IKED_SKIP_SRC_ADDR];
156 		else {
157 			/*
158 			 * Check if a specific flow is requested
159 			 * (eg. for acquire messages from the kernel)
160 			 * and find a matching flow.
161 			 */
162 			if (key->pol_nflows &&
163 			    (flowkey = RB_MIN(iked_flows,
164 			    &key->pol_flows)) != NULL &&
165 			    RB_FIND(iked_flows, &p->pol_flows,
166 			    flowkey) == NULL) {
167 				p = TAILQ_NEXT(p, pol_entry);
168 				continue;
169 			}
170 			/* make sure the peer ID matches */
171 			if (key->pol_peerid.id_type &&
172 			    p->pol_peerid.id_type &&
173 			    (key->pol_peerid.id_type != p->pol_peerid.id_type ||
174 			    memcmp(key->pol_peerid.id_data,
175 			    p->pol_peerid.id_data,
176 			    sizeof(key->pol_peerid.id_data)) != 0)) {
177 				p = TAILQ_NEXT(p, pol_entry);
178 				continue;
179 			}
180 
181 			/* check transport mode */
182 			if ((key->pol_flags & IKED_POLICY_TRANSPORT) &&
183 			    !(p->pol_flags & IKED_POLICY_TRANSPORT)) {
184 				p = TAILQ_NEXT(p, pol_entry);
185 				continue;
186 			}
187 
188 			/* Make sure the proposals are compatible */
189 			if (TAILQ_FIRST(&key->pol_proposals) &&
190 			    proposals_negotiate(NULL, &p->pol_proposals,
191 			    &key->pol_proposals, 0) == -1) {
192 				p = TAILQ_NEXT(p, pol_entry);
193 				continue;
194 			}
195 
196 			/* Policy matched */
197 			pol = p;
198 
199 			if (pol->pol_flags & IKED_POLICY_QUICK)
200 				break;
201 
202 			/* Continue to find last matching policy */
203 			p = TAILQ_NEXT(p, pol_entry);
204 		}
205 	}
206 
207 	return (pol);
208 }
209 
210 #define	IKED_SET_SKIP_STEPS(i)						\
211 	do {								\
212 		while (head[i] != cur) {				\
213 			head[i]->pol_skip[i] = cur;			\
214 			head[i] = TAILQ_NEXT(head[i], pol_entry);	\
215 		}							\
216 	} while (0)
217 
218 /* This code is derived from pf_calc_skip_steps() from pf.c */
219 void
220 policy_calc_skip_steps(struct iked_policies *policies)
221 {
222 	struct iked_policy	*head[IKED_SKIP_COUNT], *cur, *prev;
223 	int			 i;
224 
225 	cur = TAILQ_FIRST(policies);
226 	prev = cur;
227 	for (i = 0; i < IKED_SKIP_COUNT; ++i)
228 		head[i] = cur;
229 	while (cur != NULL) {
230 		if (cur->pol_flags & IKED_POLICY_SKIP)
231 			IKED_SET_SKIP_STEPS(IKED_SKIP_FLAGS);
232 		else if (cur->pol_af != AF_UNSPEC &&
233 		    prev->pol_af != AF_UNSPEC &&
234 		    cur->pol_af != prev->pol_af)
235 			IKED_SET_SKIP_STEPS(IKED_SKIP_AF);
236 		else if (cur->pol_ipproto && prev->pol_ipproto &&
237 		    cur->pol_ipproto != prev->pol_ipproto)
238 			IKED_SET_SKIP_STEPS(IKED_SKIP_PROTO);
239 		else if (IKED_ADDR_NEQ(&cur->pol_peer, &prev->pol_peer))
240 			IKED_SET_SKIP_STEPS(IKED_SKIP_DST_ADDR);
241 		else if (IKED_ADDR_NEQ(&cur->pol_local, &prev->pol_local))
242 			IKED_SET_SKIP_STEPS(IKED_SKIP_SRC_ADDR);
243 
244 		prev = cur;
245 		cur = TAILQ_NEXT(cur, pol_entry);
246 	}
247 	for (i = 0; i < IKED_SKIP_COUNT; ++i)
248 		IKED_SET_SKIP_STEPS(i);
249 }
250 
251 void
252 policy_ref(struct iked *env, struct iked_policy *pol)
253 {
254 	pol->pol_refcnt++;
255 	pol->pol_flags |= IKED_POLICY_REFCNT;
256 }
257 
258 void
259 policy_unref(struct iked *env, struct iked_policy *pol)
260 {
261 	if (pol == NULL || (pol->pol_flags & IKED_POLICY_REFCNT) == 0)
262 		return;
263 	if (--(pol->pol_refcnt) <= 0)
264 		config_free_policy(env, pol);
265 	else {
266 		struct iked_sa		*tmp;
267 		int			 count = 0;
268 
269 		TAILQ_FOREACH(tmp, &pol->pol_sapeers, sa_peer_entry)
270 			count++;
271 		if (count != pol->pol_refcnt)
272 			log_warnx("%s: ERROR pol %p pol_refcnt %d != count %d",
273 			    __func__, pol, pol->pol_refcnt, count);
274 	}
275 }
276 
277 void
278 sa_state(struct iked *env, struct iked_sa *sa, int state)
279 {
280 	const char		*a;
281 	const char		*b;
282 	int			 ostate = sa->sa_state;
283 
284 	a = print_map(ostate, ikev2_state_map);
285 	b = print_map(state, ikev2_state_map);
286 
287 	sa->sa_state = state;
288 	if (ostate != IKEV2_STATE_INIT &&
289 	    !sa_stateok(sa, state)) {
290 		log_debug("%s: cannot switch: %s -> %s",
291 		    SPI_SA(sa, __func__), a, b);
292 		sa->sa_state = ostate;
293 	} else if (ostate != sa->sa_state) {
294 		switch (state) {
295 		case IKEV2_STATE_ESTABLISHED:
296 		case IKEV2_STATE_CLOSED:
297 			log_debug("%s: %s -> %s from %s to %s policy '%s'",
298 			    SPI_SA(sa, __func__), a, b,
299 			    print_host((struct sockaddr *)&sa->sa_peer.addr,
300 			    NULL, 0),
301 			    print_host((struct sockaddr *)&sa->sa_local.addr,
302 			    NULL, 0),
303 			    sa->sa_policy ? sa->sa_policy->pol_name :
304 			    "<unknown>");
305 			break;
306 		default:
307 			log_debug("%s: %s -> %s",
308 			    SPI_SA(sa, __func__), a, b);
309 			break;
310 		}
311 	}
312 
313 }
314 
315 void
316 sa_stateflags(struct iked_sa *sa, unsigned int flags)
317 {
318 	unsigned int	require;
319 
320 	if (sa->sa_state > IKEV2_STATE_SA_INIT)
321 		require = sa->sa_statevalid;
322 	else
323 		require = sa->sa_stateinit;
324 
325 	log_debug("%s: 0x%04x -> 0x%04x %s (required 0x%04x %s)", __func__,
326 	    sa->sa_stateflags, sa->sa_stateflags | flags,
327 	    print_bits(sa->sa_stateflags | flags, IKED_REQ_BITS), require,
328 	    print_bits(require, IKED_REQ_BITS));
329 
330 	sa->sa_stateflags |= flags;
331 }
332 
333 int
334 sa_stateok(struct iked_sa *sa, int state)
335 {
336 	unsigned int	 require;
337 
338 	if (sa->sa_state < state)
339 		return (0);
340 
341 	if (state == IKEV2_STATE_SA_INIT)
342 		require = sa->sa_stateinit;
343 	else
344 		require = sa->sa_statevalid;
345 
346 	if (state == IKEV2_STATE_SA_INIT ||
347 	    state == IKEV2_STATE_VALID ||
348 	    state == IKEV2_STATE_EAP_VALID) {
349 		log_debug("%s: %s flags 0x%04x, require 0x%04x %s", __func__,
350 		    print_map(state, ikev2_state_map),
351 		    (sa->sa_stateflags & require), require,
352 		    print_bits(require, IKED_REQ_BITS));
353 
354 		if ((sa->sa_stateflags & require) != require)
355 			return (0);	/* not ready, ignore */
356 	}
357 	return (1);
358 }
359 
360 struct iked_sa *
361 sa_new(struct iked *env, uint64_t ispi, uint64_t rspi,
362     unsigned int initiator, struct iked_policy *pol)
363 {
364 	struct iked_sa	*sa;
365 	struct iked_sa	*old;
366 	struct iked_id	*localid;
367 	unsigned int	 diff;
368 
369 	if ((ispi == 0 && rspi == 0) ||
370 	    (sa = sa_lookup(env, ispi, rspi, initiator)) == NULL) {
371 		/* Create new SA */
372 		if (!initiator && ispi == 0) {
373 			log_debug("%s: cannot create responder IKE SA w/o ispi",
374 			    __func__);
375 			return (NULL);
376 		}
377 		sa = config_new_sa(env, initiator);
378 		if (sa == NULL) {
379 			log_debug("%s: failed to allocate IKE SA", __func__);
380 			return (NULL);
381 		}
382 		if (!initiator)
383 			sa->sa_hdr.sh_ispi = ispi;
384 		old = RB_INSERT(iked_sas, &env->sc_sas, sa);
385 		if (old && old != sa) {
386 			log_warnx("%s: duplicate IKE SA", __func__);
387 			config_free_sa(env, sa);
388 			return (NULL);
389 		}
390 	}
391 	/* Update rspi in the initator case */
392 	if (initiator && sa->sa_hdr.sh_rspi == 0 && rspi)
393 		sa->sa_hdr.sh_rspi = rspi;
394 
395 	if (pol == NULL && sa->sa_policy == NULL)
396 		fatalx("%s: sa %p no policy", __func__, sa);
397 	else if (sa->sa_policy == NULL) {
398 		/* Increment refcount if the policy has refcounting enabled. */
399 		if (pol->pol_flags & IKED_POLICY_REFCNT) {
400 			log_info("%s: sa %p old pol %p pol_refcnt %d",
401 			    __func__, sa, pol, pol->pol_refcnt);
402 			policy_ref(env, pol);
403 		}
404 		sa->sa_policy = pol;
405 		TAILQ_INSERT_TAIL(&pol->pol_sapeers, sa, sa_peer_entry);
406 	} else
407 		pol = sa->sa_policy;
408 
409 	sa->sa_statevalid = IKED_REQ_AUTH|IKED_REQ_AUTHVALID|IKED_REQ_SA;
410 	if (pol != NULL && pol->pol_auth.auth_eap) {
411 		sa->sa_statevalid |= IKED_REQ_CERT|IKED_REQ_EAPVALID;
412 	} else if (pol != NULL && pol->pol_auth.auth_method !=
413 	    IKEV2_AUTH_SHARED_KEY_MIC) {
414 		sa->sa_statevalid |= IKED_REQ_CERTVALID|IKED_REQ_CERT;
415 	}
416 
417 	if (initiator) {
418 		localid = &sa->sa_iid;
419 		diff = IKED_REQ_CERTVALID|IKED_REQ_AUTHVALID|IKED_REQ_SA|
420 		    IKED_REQ_EAPVALID;
421 		sa->sa_stateinit = sa->sa_statevalid & ~diff;
422 		sa->sa_statevalid = sa->sa_statevalid & diff;
423 	} else
424 		localid = &sa->sa_rid;
425 
426 	if (pol != NULL &&
427 	    ikev2_policy2id(&pol->pol_localid, localid, 1) != 0) {
428 		log_debug("%s: failed to get local id", __func__);
429 		ikev2_ike_sa_setreason(sa, "failed to get local id");
430 		sa_free(env, sa);
431 		return (NULL);
432 	}
433 
434 	return (sa);
435 }
436 
437 int
438 policy_generate_ts(struct iked_policy *pol)
439 {
440 	struct iked_flow	*flow;
441 
442 	/* Generate list of traffic selectors from flows */
443 	RB_FOREACH(flow, iked_flows, &pol->pol_flows) {
444 		if (ts_insert_unique(&flow->flow_src, &pol->pol_tssrc,
445 		    flow->flow_ipproto) == 1)
446 			pol->pol_tssrc_count++;
447 		if (ts_insert_unique(&flow->flow_dst, &pol->pol_tsdst,
448 		    flow->flow_ipproto) == 1)
449 			pol->pol_tsdst_count++;
450 	}
451 	if (pol->pol_tssrc_count > IKEV2_MAXNUM_TSS ||
452 	    pol->pol_tsdst_count > IKEV2_MAXNUM_TSS)
453 		return (-1);
454 
455 	return (0);
456 }
457 
458 int
459 ts_insert_unique(struct iked_addr *addr, struct iked_tss *tss, int ipproto)
460 {
461 	struct iked_ts		*ts;
462 
463 	/* Remove duplicates */
464 	TAILQ_FOREACH(ts, tss, ts_entry) {
465 		if (addr_cmp(addr, &ts->ts_addr, 1) == 0)
466 			return (0);
467 	}
468 
469 	if ((ts = calloc(1, sizeof(*ts))) == NULL)
470 		return (-1);
471 
472 	ts->ts_ipproto = ipproto;
473 	ts->ts_addr = *addr;
474 
475 	TAILQ_INSERT_TAIL(tss, ts, ts_entry);
476 	return (1);
477 }
478 
479 void
480 sa_free(struct iked *env, struct iked_sa *sa)
481 {
482 	struct iked_sa	*osa;
483 
484 	if (sa->sa_reason)
485 		log_info("%s: %s", SPI_SA(sa, __func__), sa->sa_reason);
486 	else
487 		log_debug("%s: ispi %s rspi %s", SPI_SA(sa, __func__),
488 		    print_spi(sa->sa_hdr.sh_ispi, 8),
489 		    print_spi(sa->sa_hdr.sh_rspi, 8));
490 
491 	/* IKE rekeying running? (old sa freed before new sa) */
492 	if (sa->sa_nexti) {
493 		RB_REMOVE(iked_sas, &env->sc_sas, sa->sa_nexti);
494 		if (sa->sa_nexti->sa_dstid_entry_valid) {
495 			log_info("%s: nexti established? %s",
496 			    SPI_SA(sa, __func__), SPI_SA(sa->sa_nexti, NULL));
497 			sa_dstid_remove(env, sa->sa_nexti);
498 		}
499 		config_free_sa(env, sa->sa_nexti);
500 	}
501 	if (sa->sa_nextr) {
502 		RB_REMOVE(iked_sas, &env->sc_sas, sa->sa_nextr);
503 		if (sa->sa_nextr->sa_dstid_entry_valid) {
504 			log_info("%s: nextr established? %s",
505 			    SPI_SA(sa, __func__), SPI_SA(sa->sa_nextr, NULL));
506 			sa_dstid_remove(env, sa->sa_nextr);
507 		}
508 		config_free_sa(env, sa->sa_nextr);
509 	}
510 	/* reset matching backpointers (new sa freed before old sa) */
511 	if ((osa = sa->sa_previ) != NULL) {
512 		if (osa->sa_nexti == sa) {
513 			log_debug("%s: resetting: sa %p == osa->sa_nexti %p"
514 			    " (osa %p)",
515 			    SPI_SA(sa, __func__), osa, sa, osa->sa_nexti);
516 			osa->sa_nexti = NULL;
517 		} else {
518 			log_info("%s: inconsistent: sa %p != osa->sa_nexti %p"
519 			    " (osa %p)",
520 			    SPI_SA(sa, __func__), osa, sa, osa->sa_nexti);
521 		}
522 	}
523 	if ((osa = sa->sa_prevr) != NULL) {
524 		if (osa->sa_nextr == sa) {
525 			log_debug("%s: resetting: sa %p == osa->sa_nextr %p"
526 			    " (osa %p)",
527 			    SPI_SA(sa, __func__), osa, sa, osa->sa_nextr);
528 			osa->sa_nextr = NULL;
529 		} else {
530 			log_info("%s: inconsistent: sa %p != osa->sa_nextr %p"
531 			    " (osa %p)",
532 			    SPI_SA(sa, __func__), osa, sa, osa->sa_nextr);
533 		}
534 	}
535 	RB_REMOVE(iked_sas, &env->sc_sas, sa);
536 	if (sa->sa_dstid_entry_valid)
537 		sa_dstid_remove(env, sa);
538 	config_free_sa(env, sa);
539 }
540 
541 void
542 sa_free_flows(struct iked *env, struct iked_saflows *head)
543 {
544 	struct iked_flow	*flow, *flowtmp;
545 
546 	TAILQ_FOREACH_SAFE(flow, head, flow_entry, flowtmp) {
547 		log_debug("%s: free %p", __func__, flow);
548 
549 		if (flow->flow_loaded)
550 			RB_REMOVE(iked_flows, &env->sc_activeflows, flow);
551 		TAILQ_REMOVE(head, flow, flow_entry);
552 		(void)pfkey_flow_delete(env->sc_pfkey, flow);
553 		flow_free(flow);
554 	}
555 }
556 
557 
558 int
559 sa_address(struct iked_sa *sa, struct iked_addr *addr, struct sockaddr *peer)
560 {
561 	bzero(addr, sizeof(*addr));
562 	addr->addr_af = peer->sa_family;
563 	addr->addr_port = htons(socket_getport(peer));
564 	memcpy(&addr->addr, peer, peer->sa_len);
565 	if (socket_af((struct sockaddr *)&addr->addr, addr->addr_port) == -1) {
566 		log_debug("%s: invalid address", __func__);
567 		return (-1);
568 	}
569 	return (0);
570 }
571 
572 void
573 childsa_free(struct iked_childsa *csa)
574 {
575 	struct iked_childsa *csb;
576 
577 	if (csa == NULL)
578 		return;
579 
580 	if (csa->csa_loaded)
581 		log_info("%s: CHILD SA spi %s is still loaded",
582 		    csa->csa_ikesa ? SPI_SA(csa->csa_ikesa, __func__) :
583 		    __func__,
584 		    print_spi(csa->csa_spi.spi, csa->csa_spi.spi_size));
585 	if ((csb = csa->csa_bundled) != NULL)
586 		csb->csa_bundled = NULL;
587 	if ((csb = csa->csa_peersa) != NULL)
588 		csb->csa_peersa = NULL;
589 	ibuf_release(csa->csa_encrkey);
590 	ibuf_release(csa->csa_integrkey);
591 	free(csa);
592 }
593 
594 struct iked_childsa *
595 childsa_lookup(struct iked_sa *sa, uint64_t spi, uint8_t protoid)
596 {
597 	struct iked_childsa	*csa;
598 
599 	if (sa == NULL || spi == 0 || protoid == 0)
600 		return (NULL);
601 
602 	TAILQ_FOREACH(csa, &sa->sa_childsas, csa_entry) {
603 		if (csa->csa_spi.spi_protoid == protoid &&
604 		    (csa->csa_spi.spi == spi))
605 			break;
606 	}
607 	return (csa);
608 }
609 
610 void
611 flow_free(struct iked_flow *flow)
612 {
613 	free(flow);
614 }
615 
616 struct iked_sa *
617 sa_lookup(struct iked *env, uint64_t ispi, uint64_t rspi,
618     unsigned int initiator)
619 {
620 	struct iked_sa	*sa, key;
621 
622 	key.sa_hdr.sh_ispi = ispi;
623 	key.sa_hdr.sh_initiator = initiator;
624 
625 	if ((sa = RB_FIND(iked_sas, &env->sc_sas, &key)) != NULL) {
626 		gettimeofday(&sa->sa_timeused, NULL);
627 
628 		/* Validate if SPIr matches */
629 		if ((sa->sa_hdr.sh_rspi != 0) &&
630 		    (rspi != 0) &&
631 		    (sa->sa_hdr.sh_rspi != rspi))
632 			return (NULL);
633 	}
634 
635 	return (sa);
636 }
637 
638 static __inline int
639 sa_cmp(struct iked_sa *a, struct iked_sa *b)
640 {
641 	if (a->sa_hdr.sh_initiator > b->sa_hdr.sh_initiator)
642 		return (-1);
643 	if (a->sa_hdr.sh_initiator < b->sa_hdr.sh_initiator)
644 		return (1);
645 
646 	if (a->sa_hdr.sh_ispi > b->sa_hdr.sh_ispi)
647 		return (-1);
648 	if (a->sa_hdr.sh_ispi < b->sa_hdr.sh_ispi)
649 		return (1);
650 
651 	return (0);
652 }
653 
654 static struct iked_id *
655 sa_dstid_checked(struct iked_sa *sa)
656 {
657 	struct iked_id *id;
658 
659 	id = IKESA_DSTID(sa);
660 	if (id == NULL || id->id_buf == NULL ||
661 	    ibuf_data(id->id_buf) == NULL)
662 		return (NULL);
663 	if (ibuf_size(id->id_buf) <= id->id_offset)
664 		return (NULL);
665 	return (id);
666 }
667 
668 struct iked_sa *
669 sa_dstid_lookup(struct iked *env, struct iked_sa *key)
670 {
671 	struct iked_sa *sa;
672 
673 	if (sa_dstid_checked(key) == NULL)
674 		fatalx("%s: no id for key %p", __func__, key);
675 	sa = RB_FIND(iked_dstid_sas, &env->sc_dstid_sas, key);
676 	if (sa != NULL && !sa->sa_dstid_entry_valid)
677 		fatalx("%s: sa %p not estab (key %p)", __func__, sa, key);
678 	return (sa);
679 }
680 
681 struct iked_sa *
682 sa_dstid_insert(struct iked *env, struct iked_sa *sa)
683 {
684 	struct iked_sa *osa;
685 
686 	if (sa->sa_dstid_entry_valid)
687 		fatalx("%s: sa %p is estab", __func__, sa);
688 	if (sa_dstid_checked(sa) == NULL)
689 		fatalx("%s: no id for sa %p", __func__, sa);
690 	osa = RB_FIND(iked_dstid_sas, &env->sc_dstid_sas, sa);
691 	if (osa == NULL) {
692 		osa = RB_INSERT(iked_dstid_sas, &env->sc_dstid_sas, sa);
693 		if (osa && osa != sa) {
694 			log_warnx("%s: duplicate IKE SA", SPI_SA(sa, __func__));
695 			return (osa);
696 		}
697 		sa->sa_dstid_entry_valid = 1;
698 		return (NULL);
699 	}
700 	if (!osa->sa_dstid_entry_valid)
701 		fatalx("%s: osa %p not estab (sa %p)", __func__, osa, sa);
702 	return (osa);
703 }
704 
705 void
706 sa_dstid_remove(struct iked *env, struct iked_sa *sa)
707 {
708 	if (!sa->sa_dstid_entry_valid)
709 		fatalx("%s: sa %p is not estab", __func__, sa);
710 	if (sa_dstid_checked(sa) == NULL)
711 		fatalx("%s: no id for sa %p", __func__, sa);
712 	RB_REMOVE(iked_dstid_sas, &env->sc_dstid_sas, sa);
713 	sa->sa_dstid_entry_valid = 0;
714 }
715 
716 static __inline int
717 sa_dstid_cmp(struct iked_sa *a, struct iked_sa *b)
718 {
719 	struct iked_id          *aid = NULL, *bid = NULL;
720 	size_t			 alen, blen;
721 	uint8_t			*aptr, *bptr;
722 
723 	aid = sa_dstid_checked(a);
724 	bid = sa_dstid_checked(b);
725 	if (aid == NULL || bid == NULL)
726 		fatalx("corrupt IDs");
727 	if (aid->id_type > bid->id_type)
728 		return (-1);
729 	else if (aid->id_type < bid->id_type)
730 		return (1);
731 	alen = ibuf_size(aid->id_buf);
732 	blen = ibuf_size(bid->id_buf);
733 	aptr = ibuf_data(aid->id_buf);
734 	bptr = ibuf_data(bid->id_buf);
735 	if (aptr == NULL || bptr == NULL)
736 		fatalx("corrupt ID bufs");
737 	if (alen <= aid->id_offset || blen <= bid->id_offset)
738 		fatalx("corrupt ID lens");
739 	aptr += aid->id_offset;
740 	alen -= aid->id_offset;
741 	bptr += bid->id_offset;
742 	blen -= bid->id_offset;
743 	if (alen > blen)
744 		return (-1);
745 	if (alen < blen)
746 		return (1);
747 	return (memcmp(aptr, bptr, alen));
748 }
749 
750 static __inline int
751 sa_addrpool_cmp(struct iked_sa *a, struct iked_sa *b)
752 {
753 	return (sockaddr_cmp((struct sockaddr *)&a->sa_addrpool->addr,
754 	    (struct sockaddr *)&b->sa_addrpool->addr, -1));
755 }
756 
757 static __inline int
758 sa_addrpool6_cmp(struct iked_sa *a, struct iked_sa *b)
759 {
760 	return (sockaddr_cmp((struct sockaddr *)&a->sa_addrpool6->addr,
761 	    (struct sockaddr *)&b->sa_addrpool6->addr, -1));
762 }
763 
764 struct iked_user *
765 user_lookup(struct iked *env, const char *user)
766 {
767 	struct iked_user	 key;
768 
769 	if (strlcpy(key.usr_name, user,
770 	    sizeof(key.usr_name)) >= sizeof(key.usr_name))
771 		return (NULL);
772 
773 	return (RB_FIND(iked_users, &env->sc_users, &key));
774 }
775 
776 static __inline int
777 user_cmp(struct iked_user *a, struct iked_user *b)
778 {
779 	return (strcmp(a->usr_name, b->usr_name));
780 }
781 
782 /*
783  * Find a matching subset of the proposal lists 'local' and 'peer'.
784  * The resulting proposal is stored in 'result' if 'result' is not NULL.
785  * The 'rekey' parameter indicates a CREATE_CHILD_SA exchange where
786  * an extra group is necessary for PFS. For the initial IKE_AUTH exchange
787  * the ESP SA proposal never includes an explicit DH group.
788  *
789  * Return 0 if a matching subset was found and -1 if no subset was found
790  * or an error occured.
791  */
792 int
793 proposals_negotiate(struct iked_proposals *result, struct iked_proposals *local,
794     struct iked_proposals *peer, int rekey)
795 {
796 	struct iked_proposal	*ppeer = NULL, *plocal, *prop, vpeer, vlocal;
797 	struct iked_transform	 chosen[IKEV2_XFORMTYPE_MAX];
798 	struct iked_transform	*valid[IKEV2_XFORMTYPE_MAX];
799 	struct iked_transform	*match[IKEV2_XFORMTYPE_MAX];
800 	unsigned int		 i, score, chosen_score = 0;
801 	uint8_t			 protoid = 0;
802 
803 	bzero(valid, sizeof(valid));
804 	bzero(&vlocal, sizeof(vlocal));
805 	bzero(&vpeer, sizeof(vpeer));
806 
807 	if (TAILQ_EMPTY(peer)) {
808 		log_debug("%s: peer did not send %s proposals", __func__,
809 		    print_map(protoid, ikev2_saproto_map));
810 		return (-1);
811 	}
812 
813 	TAILQ_FOREACH(plocal, local, prop_entry) {
814 		TAILQ_FOREACH(ppeer, peer, prop_entry) {
815 			if (ppeer->prop_protoid != plocal->prop_protoid)
816 				continue;
817 			bzero(match, sizeof(match));
818 			score = proposals_match(plocal, ppeer, match,
819 			    rekey);
820 			log_debug("%s: score %d", __func__, score);
821 			if (score && (!chosen_score || score < chosen_score)) {
822 				chosen_score = score;
823 				for (i = 0; i < IKEV2_XFORMTYPE_MAX; i++) {
824 					if ((valid[i] = match[i]))
825 						memcpy(&chosen[i], match[i],
826 						    sizeof(chosen[0]));
827 				}
828 				memcpy(&vpeer, ppeer, sizeof(vpeer));
829 				memcpy(&vlocal, plocal, sizeof(vlocal));
830 			}
831 		}
832 		if (chosen_score != 0)
833 			break;
834 	}
835 
836 	if (chosen_score == 0)
837 		return (-1);
838 	else if (result == NULL)
839 		return (0);
840 
841 	(void)config_free_proposals(result, vpeer.prop_protoid);
842 	prop = config_add_proposal(result, vpeer.prop_id, vpeer.prop_protoid);
843 
844 	if (vpeer.prop_localspi.spi_size) {
845 		prop->prop_localspi.spi_size = vpeer.prop_localspi.spi_size;
846 		prop->prop_peerspi = vpeer.prop_peerspi;
847 	}
848 	if (vlocal.prop_localspi.spi_size) {
849 		prop->prop_localspi.spi_size = vlocal.prop_localspi.spi_size;
850 		prop->prop_localspi.spi = vlocal.prop_localspi.spi;
851 	}
852 
853 	for (i = 0; i < IKEV2_XFORMTYPE_MAX; i++) {
854 		if (valid[i] == NULL)
855 			continue;
856 		print_debug("%s: score %d: %s %s", __func__,
857 		    chosen[i].xform_score, print_map(i, ikev2_xformtype_map),
858 		    print_map(chosen[i].xform_id, chosen[i].xform_map));
859 		if (chosen[i].xform_length)
860 			print_debug(" %d", chosen[i].xform_length);
861 		print_debug("\n");
862 
863 		if (config_add_transform(prop, chosen[i].xform_type,
864 		    chosen[i].xform_id, chosen[i].xform_length,
865 		    chosen[i].xform_keylength) == NULL)
866 			break;
867 	}
868 
869 	return (0);
870 }
871 
872 static int
873 proposals_match(struct iked_proposal *local, struct iked_proposal *peer,
874     struct iked_transform **xforms, int rekey)
875 {
876 	struct iked_transform	*tpeer, *tlocal;
877 	unsigned int		 i, j, type, score, requiredh = 0, noauth = 0;
878 	uint8_t			 protoid = peer->prop_protoid;
879 	uint8_t			 peerxfs[IKEV2_XFORMTYPE_MAX];
880 
881 	bzero(peerxfs, sizeof(peerxfs));
882 
883 	for (i = 0; i < peer->prop_nxforms; i++) {
884 		tpeer = peer->prop_xforms + i;
885 		/* If any of the ENC transforms is an AEAD, ignore auth */
886 		if (tpeer->xform_type == IKEV2_XFORMTYPE_ENCR &&
887 		    encxf_noauth(tpeer->xform_id))
888 			noauth = 1;
889 	}
890 
891 	for (i = 0; i < peer->prop_nxforms; i++) {
892 		tpeer = peer->prop_xforms + i;
893 		if (tpeer->xform_type > IKEV2_XFORMTYPE_MAX)
894 			continue;
895 		if (noauth && tpeer->xform_type == IKEV2_XFORMTYPE_INTEGR)
896 			return (0);
897 
898 		/*
899 		 * Record all transform types from the peer's proposal,
900 		 * because if we want this proposal we have to select
901 		 * a transform for each proposed transform type.
902 		 */
903 		peerxfs[tpeer->xform_type] = 1;
904 
905 		for (j = 0; j < local->prop_nxforms; j++) {
906 			tlocal = local->prop_xforms + j;
907 
908 			/*
909 			 * We require a DH group for ESP if there is any
910 			 * local proposal with DH enabled.
911 			 */
912 			if (rekey && requiredh == 0 &&
913 			    protoid == IKEV2_SAPROTO_ESP &&
914 			    tlocal->xform_type == IKEV2_XFORMTYPE_DH)
915 				requiredh = 1;
916 
917 			/* Compare peer and local proposals */
918 			if (tpeer->xform_type != tlocal->xform_type ||
919 			    tpeer->xform_id != tlocal->xform_id ||
920 			    tpeer->xform_length != tlocal->xform_length)
921 				continue;
922 			type = tpeer->xform_type;
923 
924 			if (xforms[type] == NULL || tlocal->xform_score <
925 			    xforms[type]->xform_score) {
926 				xforms[type] = tlocal;
927 			} else
928 				continue;
929 
930 			print_debug("%s: xform %d <-> %d (%d): %s %s "
931 			    "(keylength %d <-> %d)", __func__,
932 			    peer->prop_id, local->prop_id, tlocal->xform_score,
933 			    print_map(type, ikev2_xformtype_map),
934 			    print_map(tpeer->xform_id, tpeer->xform_map),
935 			    tpeer->xform_keylength, tlocal->xform_keylength);
936 			if (tpeer->xform_length)
937 				print_debug(" %d", tpeer->xform_length);
938 			print_debug("\n");
939 		}
940 	}
941 
942 	for (i = score = 0; i < IKEV2_XFORMTYPE_MAX; i++) {
943 		if (protoid == IKEV2_SAPROTO_IKE && xforms[i] == NULL &&
944 		    (i == IKEV2_XFORMTYPE_ENCR || i == IKEV2_XFORMTYPE_PRF ||
945 		    (!noauth && i == IKEV2_XFORMTYPE_INTEGR) ||
946 		    i == IKEV2_XFORMTYPE_DH)) {
947 			score = 0;
948 			break;
949 		} else if (protoid == IKEV2_SAPROTO_AH && xforms[i] == NULL &&
950 		    (i == IKEV2_XFORMTYPE_INTEGR || i == IKEV2_XFORMTYPE_ESN)) {
951 			score = 0;
952 			break;
953 		} else if (protoid == IKEV2_SAPROTO_ESP && xforms[i] == NULL &&
954 		    (i == IKEV2_XFORMTYPE_ENCR || i == IKEV2_XFORMTYPE_ESN ||
955 		    (requiredh && i == IKEV2_XFORMTYPE_DH))) {
956 			score = 0;
957 			break;
958 		} else if (peerxfs[i] && xforms[i] == NULL) {
959 			score = 0;
960 			break;
961 		} else if (xforms[i] == NULL)
962 			continue;
963 
964 		score += xforms[i]->xform_score;
965 	}
966 
967 	return (score);
968 }
969 
970 static __inline int
971 childsa_cmp(struct iked_childsa *a, struct iked_childsa *b)
972 {
973 	if (a->csa_spi.spi > b->csa_spi.spi)
974 		return (1);
975 	if (a->csa_spi.spi < b->csa_spi.spi)
976 		return (-1);
977 	return (0);
978 }
979 
980 static __inline int
981 addr_cmp(struct iked_addr *a, struct iked_addr *b, int useports)
982 {
983 	int		diff = 0;
984 
985 	diff = sockaddr_cmp((struct sockaddr *)&a->addr,
986 	    (struct sockaddr *)&b->addr, 128);
987 	if (!diff)
988 		diff = (int)a->addr_mask - (int)b->addr_mask;
989 	if (!diff && useports)
990 		diff = a->addr_port - b->addr_port;
991 
992 	return (diff);
993 }
994 
995 static __inline int
996 flow_cmp(struct iked_flow *a, struct iked_flow *b)
997 {
998 	int		diff = 0;
999 
1000 	if (!diff)
1001 		diff = a->flow_rdomain - b->flow_rdomain;
1002 	if (!diff)
1003 		diff = (int)a->flow_ipproto - (int)b->flow_ipproto;
1004 	if (!diff)
1005 		diff = (int)a->flow_saproto - (int)b->flow_saproto;
1006 	if (!diff)
1007 		diff = (int)a->flow_dir - (int)b->flow_dir;
1008 	if (!diff)
1009 		diff = addr_cmp(&a->flow_dst, &b->flow_dst, 1);
1010 	if (!diff)
1011 		diff = addr_cmp(&a->flow_src, &b->flow_src, 1);
1012 
1013 	return (diff);
1014 }
1015 
1016 int
1017 flow_equal(struct iked_flow *a, struct iked_flow *b)
1018 {
1019 	return (flow_cmp(a, b) == 0);
1020 }
1021 
1022 RB_GENERATE(iked_sas, iked_sa, sa_entry, sa_cmp);
1023 RB_GENERATE(iked_dstid_sas, iked_sa, sa_dstid_entry, sa_dstid_cmp);
1024 RB_GENERATE(iked_addrpool, iked_sa, sa_addrpool_entry, sa_addrpool_cmp);
1025 RB_GENERATE(iked_addrpool6, iked_sa, sa_addrpool6_entry, sa_addrpool6_cmp);
1026 RB_GENERATE(iked_users, iked_user, usr_entry, user_cmp);
1027 RB_GENERATE(iked_activesas, iked_childsa, csa_node, childsa_cmp);
1028 RB_GENERATE(iked_flows, iked_flow, flow_node, flow_cmp);
1029