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