xref: /openbsd/sbin/iked/policy.c (revision 73471bf0)
1 /*	$OpenBSD: policy.c,v 1.89 2021/12/01 16:42:13 deraadt 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 	unsigned int		 cnt = 0;
226 
227 	p = TAILQ_FIRST(&env->sc_policies);
228 	while (p != NULL) {
229 		cnt++;
230 		if (p->pol_flags & IKED_POLICY_SKIP)
231 			p = p->pol_skip[IKED_SKIP_FLAGS];
232 		else if (key->pol_af && p->pol_af &&
233 		    key->pol_af != p->pol_af)
234 			p = p->pol_skip[IKED_SKIP_AF];
235 		else if (sockaddr_cmp((struct sockaddr *)&key->pol_peer.addr,
236 		    (struct sockaddr *)&p->pol_peer.addr,
237 		    p->pol_peer.addr_mask) != 0)
238 			p = p->pol_skip[IKED_SKIP_DST_ADDR];
239 		else if (sockaddr_cmp((struct sockaddr *)&key->pol_local.addr,
240 		    (struct sockaddr *)&p->pol_local.addr,
241 		    p->pol_local.addr_mask) != 0)
242 			p = p->pol_skip[IKED_SKIP_SRC_ADDR];
243 		else {
244 			/*
245 			 * Check if flows are requested and if they
246 			 * are compatible.
247 			 */
248 			if (key->pol_nflows && policy_test_flows(key, p)) {
249 				p = TAILQ_NEXT(p, pol_entry);
250 				continue;
251 			}
252 			/* make sure the peer ID matches */
253 			if (key->pol_peerid.id_type &&
254 			    p->pol_peerid.id_type &&
255 			    (key->pol_peerid.id_type != p->pol_peerid.id_type ||
256 			    memcmp(key->pol_peerid.id_data,
257 			    p->pol_peerid.id_data,
258 			    sizeof(key->pol_peerid.id_data)) != 0)) {
259 				p = TAILQ_NEXT(p, pol_entry);
260 				continue;
261 			}
262 
263 			/* make sure the local ID matches */
264 			if (key->pol_localid.id_type &&
265 			    p->pol_localid.id_type &&
266 			    (key->pol_localid.id_type != p->pol_localid.id_type ||
267 			    memcmp(key->pol_localid.id_data,
268 			    p->pol_localid.id_data,
269 			    sizeof(key->pol_localid.id_data)) != 0)) {
270 				log_info("%s: localid mismatch", __func__);
271 				p = TAILQ_NEXT(p, pol_entry);
272 				continue;
273 			}
274 
275 			/* check transport mode */
276 			if ((key->pol_flags & IKED_POLICY_TRANSPORT) &&
277 			    !(p->pol_flags & IKED_POLICY_TRANSPORT)) {
278 				p = TAILQ_NEXT(p, pol_entry);
279 				continue;
280 			}
281 
282 			/* Make sure the proposals are compatible */
283 			if (TAILQ_FIRST(&key->pol_proposals) &&
284 			    proposals_negotiate(NULL, &p->pol_proposals,
285 			    &key->pol_proposals, 0, -1) == -1) {
286 				p = TAILQ_NEXT(p, pol_entry);
287 				continue;
288 			}
289 
290 			/* Policy matched */
291 			pol = p;
292 
293 			if (pol->pol_flags & IKED_POLICY_QUICK)
294 				break;
295 
296 			/* Continue to find last matching policy */
297 			p = TAILQ_NEXT(p, pol_entry);
298 		}
299 	}
300 
301 	return (pol);
302 }
303 
304 static int
305 policy_test_flows(struct iked_policy *key, struct iked_policy *p)
306 {
307 	struct iked_flow	*f;
308 
309 	for (f = RB_MIN(iked_flows, &key->pol_flows); f != NULL;
310 	    f = RB_NEXT(iked_flows, &key->pol_flows, f))
311 		if (RB_FIND(iked_flows, &p->pol_flows, f) == NULL)
312 			return (-1);
313 
314 	return (0);
315 }
316 
317 #define	IKED_SET_SKIP_STEPS(i)						\
318 	do {								\
319 		while (head[i] != cur) {				\
320 			head[i]->pol_skip[i] = cur;			\
321 			head[i] = TAILQ_NEXT(head[i], pol_entry);	\
322 		}							\
323 	} while (0)
324 
325 /* This code is derived from pf_calc_skip_steps() from pf.c */
326 void
327 policy_calc_skip_steps(struct iked_policies *policies)
328 {
329 	struct iked_policy	*head[IKED_SKIP_COUNT], *cur, *prev;
330 	int			 i;
331 
332 	cur = TAILQ_FIRST(policies);
333 	prev = cur;
334 	for (i = 0; i < IKED_SKIP_COUNT; ++i)
335 		head[i] = cur;
336 	while (cur != NULL) {
337 		if (cur->pol_flags & IKED_POLICY_SKIP)
338 			IKED_SET_SKIP_STEPS(IKED_SKIP_FLAGS);
339 		if (cur->pol_af != AF_UNSPEC &&
340 		    prev->pol_af != AF_UNSPEC &&
341 		    cur->pol_af != prev->pol_af)
342 			IKED_SET_SKIP_STEPS(IKED_SKIP_AF);
343 		if (IKED_ADDR_NEQ(&cur->pol_peer, &prev->pol_peer))
344 			IKED_SET_SKIP_STEPS(IKED_SKIP_DST_ADDR);
345 		if (IKED_ADDR_NEQ(&cur->pol_local, &prev->pol_local))
346 			IKED_SET_SKIP_STEPS(IKED_SKIP_SRC_ADDR);
347 
348 		prev = cur;
349 		cur = TAILQ_NEXT(cur, pol_entry);
350 	}
351 	for (i = 0; i < IKED_SKIP_COUNT; ++i)
352 		IKED_SET_SKIP_STEPS(i);
353 }
354 
355 void
356 policy_ref(struct iked *env, struct iked_policy *pol)
357 {
358 	pol->pol_refcnt++;
359 	pol->pol_flags |= IKED_POLICY_REFCNT;
360 }
361 
362 void
363 policy_unref(struct iked *env, struct iked_policy *pol)
364 {
365 	if (pol == NULL || (pol->pol_flags & IKED_POLICY_REFCNT) == 0)
366 		return;
367 	if (--(pol->pol_refcnt) <= 0)
368 		config_free_policy(env, pol);
369 	else {
370 		struct iked_sa		*tmp;
371 		int			 count = 0;
372 
373 		TAILQ_FOREACH(tmp, &pol->pol_sapeers, sa_peer_entry)
374 			count++;
375 		if (count != pol->pol_refcnt)
376 			log_warnx("%s: ERROR pol %p pol_refcnt %d != count %d",
377 			    __func__, pol, pol->pol_refcnt, count);
378 	}
379 }
380 
381 void
382 sa_state(struct iked *env, struct iked_sa *sa, int state)
383 {
384 	const char		*a;
385 	const char		*b;
386 	int			 ostate = sa->sa_state;
387 
388 	a = print_map(ostate, ikev2_state_map);
389 	b = print_map(state, ikev2_state_map);
390 
391 	sa->sa_state = state;
392 	if (ostate != IKEV2_STATE_INIT &&
393 	    !sa_stateok(sa, state)) {
394 		log_debug("%s: cannot switch: %s -> %s",
395 		    SPI_SA(sa, __func__), a, b);
396 		sa->sa_state = ostate;
397 	} else if (ostate != sa->sa_state) {
398 		switch (state) {
399 		case IKEV2_STATE_ESTABLISHED:
400 		case IKEV2_STATE_CLOSED:
401 			log_debug("%s: %s -> %s from %s to %s policy '%s'",
402 			    SPI_SA(sa, __func__), a, b,
403 			    print_host((struct sockaddr *)&sa->sa_peer.addr,
404 			    NULL, 0),
405 			    print_host((struct sockaddr *)&sa->sa_local.addr,
406 			    NULL, 0),
407 			    sa->sa_policy ? sa->sa_policy->pol_name :
408 			    "<unknown>");
409 			break;
410 		default:
411 			log_debug("%s: %s -> %s",
412 			    SPI_SA(sa, __func__), a, b);
413 			break;
414 		}
415 	}
416 
417 }
418 
419 void
420 sa_stateflags(struct iked_sa *sa, unsigned int flags)
421 {
422 	unsigned int	require;
423 
424 	if (sa->sa_state > IKEV2_STATE_SA_INIT)
425 		require = sa->sa_statevalid;
426 	else
427 		require = sa->sa_stateinit;
428 
429 	log_debug("%s: 0x%04x -> 0x%04x %s (required 0x%04x %s)", __func__,
430 	    sa->sa_stateflags, sa->sa_stateflags | flags,
431 	    print_bits(sa->sa_stateflags | flags, IKED_REQ_BITS), require,
432 	    print_bits(require, IKED_REQ_BITS));
433 
434 	sa->sa_stateflags |= flags;
435 }
436 
437 int
438 sa_stateok(const struct iked_sa *sa, int state)
439 {
440 	unsigned int	 require;
441 
442 	if (sa->sa_state < state)
443 		return (0);
444 
445 	if (state == IKEV2_STATE_SA_INIT)
446 		require = sa->sa_stateinit;
447 	else
448 		require = sa->sa_statevalid;
449 
450 	if (state == IKEV2_STATE_SA_INIT ||
451 	    state == IKEV2_STATE_VALID ||
452 	    state == IKEV2_STATE_EAP_VALID) {
453 		log_debug("%s: %s flags 0x%04x, require 0x%04x %s", __func__,
454 		    print_map(state, ikev2_state_map),
455 		    (sa->sa_stateflags & require), require,
456 		    print_bits(require, IKED_REQ_BITS));
457 
458 		if ((sa->sa_stateflags & require) != require)
459 			return (0);	/* not ready, ignore */
460 	}
461 	return (1);
462 }
463 
464 struct iked_sa *
465 sa_new(struct iked *env, uint64_t ispi, uint64_t rspi,
466     unsigned int initiator, struct iked_policy *pol)
467 {
468 	struct iked_sa	*sa;
469 	struct iked_sa	*old;
470 	struct iked_id	*localid;
471 	unsigned int	 diff;
472 
473 	if ((ispi == 0 && rspi == 0) ||
474 	    (sa = sa_lookup(env, ispi, rspi, initiator)) == NULL) {
475 		/* Create new SA */
476 		if (!initiator && ispi == 0) {
477 			log_debug("%s: cannot create responder IKE SA w/o ispi",
478 			    __func__);
479 			return (NULL);
480 		}
481 		sa = config_new_sa(env, initiator);
482 		if (sa == NULL) {
483 			log_debug("%s: failed to allocate IKE SA", __func__);
484 			return (NULL);
485 		}
486 		if (!initiator)
487 			sa->sa_hdr.sh_ispi = ispi;
488 		old = RB_INSERT(iked_sas, &env->sc_sas, sa);
489 		if (old && old != sa) {
490 			log_warnx("%s: duplicate IKE SA", __func__);
491 			config_free_sa(env, sa);
492 			return (NULL);
493 		}
494 	}
495 	/* Update rspi in the initator case */
496 	if (initiator && sa->sa_hdr.sh_rspi == 0 && rspi)
497 		sa->sa_hdr.sh_rspi = rspi;
498 
499 	if (pol == NULL && sa->sa_policy == NULL)
500 		fatalx("%s: sa %p no policy", __func__, sa);
501 	else if (sa->sa_policy == NULL) {
502 		/* Increment refcount if the policy has refcounting enabled. */
503 		if (pol->pol_flags & IKED_POLICY_REFCNT) {
504 			log_info("%s: sa %p old pol %p pol_refcnt %d",
505 			    __func__, sa, pol, pol->pol_refcnt);
506 			policy_ref(env, pol);
507 		}
508 		sa->sa_policy = pol;
509 		TAILQ_INSERT_TAIL(&pol->pol_sapeers, sa, sa_peer_entry);
510 	} else
511 		pol = sa->sa_policy;
512 
513 	sa->sa_statevalid = IKED_REQ_AUTH|IKED_REQ_AUTHVALID|IKED_REQ_SA;
514 	if (pol != NULL && pol->pol_auth.auth_eap) {
515 		sa->sa_statevalid |= IKED_REQ_CERT|IKED_REQ_EAPVALID;
516 	} else if (pol != NULL && pol->pol_auth.auth_method !=
517 	    IKEV2_AUTH_SHARED_KEY_MIC) {
518 		sa->sa_statevalid |= IKED_REQ_CERTVALID|IKED_REQ_CERT;
519 	}
520 
521 	if (initiator) {
522 		localid = &sa->sa_iid;
523 		diff = IKED_REQ_CERTVALID|IKED_REQ_AUTHVALID|IKED_REQ_SA|
524 		    IKED_REQ_EAPVALID;
525 		sa->sa_stateinit = sa->sa_statevalid & ~diff;
526 		sa->sa_statevalid = sa->sa_statevalid & diff;
527 	} else
528 		localid = &sa->sa_rid;
529 
530 	if (pol != NULL &&
531 	    ikev2_policy2id(&pol->pol_localid, localid, 1) != 0) {
532 		log_debug("%s: failed to get local id", __func__);
533 		ikev2_ike_sa_setreason(sa, "failed to get local id");
534 		sa_free(env, sa);
535 		return (NULL);
536 	}
537 
538 	return (sa);
539 }
540 
541 int
542 policy_generate_ts(struct iked_policy *pol)
543 {
544 	struct iked_flow	*flow;
545 
546 	/* Generate list of traffic selectors from flows */
547 	RB_FOREACH(flow, iked_flows, &pol->pol_flows) {
548 		if (ts_insert_unique(&flow->flow_src, &pol->pol_tssrc,
549 		    flow->flow_ipproto) == 1)
550 			pol->pol_tssrc_count++;
551 		if (ts_insert_unique(&flow->flow_dst, &pol->pol_tsdst,
552 		    flow->flow_ipproto) == 1)
553 			pol->pol_tsdst_count++;
554 	}
555 	if (pol->pol_tssrc_count > IKEV2_MAXNUM_TSS ||
556 	    pol->pol_tsdst_count > IKEV2_MAXNUM_TSS)
557 		return (-1);
558 
559 	return (0);
560 }
561 
562 int
563 ts_insert_unique(struct iked_addr *addr, struct iked_tss *tss, int ipproto)
564 {
565 	struct iked_ts		*ts;
566 
567 	/* Remove duplicates */
568 	TAILQ_FOREACH(ts, tss, ts_entry) {
569 		if (addr_cmp(addr, &ts->ts_addr, 1) == 0)
570 			return (0);
571 	}
572 
573 	if ((ts = calloc(1, sizeof(*ts))) == NULL)
574 		return (-1);
575 
576 	ts->ts_ipproto = ipproto;
577 	ts->ts_addr = *addr;
578 
579 	TAILQ_INSERT_TAIL(tss, ts, ts_entry);
580 	return (1);
581 }
582 
583 void
584 sa_free(struct iked *env, struct iked_sa *sa)
585 {
586 	struct iked_sa	*osa;
587 
588 	if (sa->sa_reason)
589 		log_info("%s: %s", SPI_SA(sa, __func__), sa->sa_reason);
590 	else
591 		log_debug("%s: ispi %s rspi %s", SPI_SA(sa, __func__),
592 		    print_spi(sa->sa_hdr.sh_ispi, 8),
593 		    print_spi(sa->sa_hdr.sh_rspi, 8));
594 
595 	/* IKE rekeying running? (old sa freed before new sa) */
596 	if (sa->sa_nexti) {
597 		RB_REMOVE(iked_sas, &env->sc_sas, sa->sa_nexti);
598 		if (sa->sa_nexti->sa_dstid_entry_valid) {
599 			log_info("%s: nexti established? %s",
600 			    SPI_SA(sa, __func__), SPI_SA(sa->sa_nexti, NULL));
601 			sa_dstid_remove(env, sa->sa_nexti);
602 		}
603 		config_free_sa(env, sa->sa_nexti);
604 	}
605 	if (sa->sa_nextr) {
606 		RB_REMOVE(iked_sas, &env->sc_sas, sa->sa_nextr);
607 		if (sa->sa_nextr->sa_dstid_entry_valid) {
608 			log_info("%s: nextr established? %s",
609 			    SPI_SA(sa, __func__), SPI_SA(sa->sa_nextr, NULL));
610 			sa_dstid_remove(env, sa->sa_nextr);
611 		}
612 		config_free_sa(env, sa->sa_nextr);
613 	}
614 	/* reset matching backpointers (new sa freed before old sa) */
615 	if ((osa = sa->sa_previ) != NULL) {
616 		if (osa->sa_nexti == sa) {
617 			log_debug("%s: resetting: sa %p == osa->sa_nexti %p"
618 			    " (osa %p)",
619 			    SPI_SA(sa, __func__), osa, sa, osa->sa_nexti);
620 			osa->sa_nexti = NULL;
621 		} else {
622 			log_info("%s: inconsistent: sa %p != osa->sa_nexti %p"
623 			    " (osa %p)",
624 			    SPI_SA(sa, __func__), osa, sa, osa->sa_nexti);
625 		}
626 	}
627 	if ((osa = sa->sa_prevr) != NULL) {
628 		if (osa->sa_nextr == sa) {
629 			log_debug("%s: resetting: sa %p == osa->sa_nextr %p"
630 			    " (osa %p)",
631 			    SPI_SA(sa, __func__), osa, sa, osa->sa_nextr);
632 			osa->sa_nextr = NULL;
633 		} else {
634 			log_info("%s: inconsistent: sa %p != osa->sa_nextr %p"
635 			    " (osa %p)",
636 			    SPI_SA(sa, __func__), osa, sa, osa->sa_nextr);
637 		}
638 	}
639 	RB_REMOVE(iked_sas, &env->sc_sas, sa);
640 	if (sa->sa_dstid_entry_valid)
641 		sa_dstid_remove(env, sa);
642 	config_free_sa(env, sa);
643 }
644 
645 void
646 sa_free_flows(struct iked *env, struct iked_saflows *head)
647 {
648 	struct iked_flow	*flow, *flowtmp;
649 
650 	TAILQ_FOREACH_SAFE(flow, head, flow_entry, flowtmp) {
651 		log_debug("%s: free %p", __func__, flow);
652 
653 		if (flow->flow_loaded)
654 			RB_REMOVE(iked_flows, &env->sc_activeflows, flow);
655 		TAILQ_REMOVE(head, flow, flow_entry);
656 		(void)pfkey_flow_delete(env, flow);
657 		flow_free(flow);
658 	}
659 }
660 
661 
662 int
663 sa_address(struct iked_sa *sa, struct iked_addr *addr, struct sockaddr *peer)
664 {
665 	bzero(addr, sizeof(*addr));
666 	addr->addr_af = peer->sa_family;
667 	addr->addr_port = htons(socket_getport(peer));
668 	memcpy(&addr->addr, peer, peer->sa_len);
669 	if (socket_af((struct sockaddr *)&addr->addr, addr->addr_port) == -1) {
670 		log_debug("%s: invalid address", __func__);
671 		return (-1);
672 	}
673 	return (0);
674 }
675 
676 int
677 sa_configure_iface(struct iked *env, struct iked_sa *sa, int add)
678 {
679 	struct iked_flow	*saflow;
680 	struct sockaddr		*caddr;
681 	int			 rdomain;
682 
683 	if (sa->sa_policy == NULL || sa->sa_policy->pol_iface == 0)
684 		return (0);
685 
686 	if (sa->sa_cp_dns) {
687 		if (vroute_setdns(env, add,
688 		    (struct sockaddr *)&sa->sa_cp_dns->addr,
689 		    sa->sa_policy->pol_iface) != 0)
690 			return (-1);
691 	}
692 
693 	if (!sa->sa_cp_addr && !sa->sa_cp_addr6)
694 		return (0);
695 
696 	if (sa->sa_cp_addr) {
697 		if (vroute_setaddr(env, add,
698 		    (struct sockaddr *)&sa->sa_cp_addr->addr,
699 		    sa->sa_cp_addr->addr_mask, sa->sa_policy->pol_iface) != 0)
700 			return (-1);
701 	}
702 	if (sa->sa_cp_addr6) {
703 		if (vroute_setaddr(env, add,
704 		    (struct sockaddr *)&sa->sa_cp_addr6->addr,
705 		    sa->sa_cp_addr6->addr_mask, sa->sa_policy->pol_iface) != 0)
706 			return (-1);
707 	}
708 
709 	if (add) {
710 		/* Add direct route to peer */
711 		if (vroute_setcloneroute(env, getrtable(),
712 		    (struct sockaddr *)&sa->sa_peer.addr, 0, NULL))
713 			return (-1);
714 	} else {
715 		if (vroute_setdelroute(env, getrtable(),
716 		    (struct sockaddr *)&sa->sa_peer.addr,
717 		    0, NULL))
718 			return (-1);
719 	}
720 
721 	TAILQ_FOREACH(saflow, &sa->sa_flows, flow_entry) {
722 		rdomain = saflow->flow_rdomain == -1 ?
723 		    getrtable() : saflow->flow_rdomain;
724 
725 		switch(saflow->flow_src.addr_af) {
726 		case AF_INET:
727 			caddr = (struct sockaddr *)&sa->sa_cp_addr->addr;
728 			break;
729 		case AF_INET6:
730 			caddr = (struct sockaddr *)&sa->sa_cp_addr6->addr;
731 			break;
732 		default:
733 			return (-1);
734 		}
735 		if (sockaddr_cmp((struct sockaddr *)&saflow->flow_src.addr,
736 		    caddr, -1) != 0)
737 			continue;
738 
739 		if (add) {
740 			if (vroute_setaddroute(env, rdomain,
741 			    (struct sockaddr *)&saflow->flow_dst.addr,
742 			    saflow->flow_dst.addr_mask, caddr))
743 				return (-1);
744 		} else {
745 			if (vroute_setdelroute(env, rdomain,
746 			    (struct sockaddr *)&saflow->flow_dst.addr,
747 			    saflow->flow_dst.addr_mask, caddr))
748 				return (-1);
749 		}
750 	}
751 
752 	return (0);
753 }
754 
755 void
756 childsa_free(struct iked_childsa *csa)
757 {
758 	struct iked_childsa *csb;
759 
760 	if (csa == NULL)
761 		return;
762 
763 	if (csa->csa_loaded)
764 		log_info("%s: CHILD SA spi %s is still loaded",
765 		    csa->csa_ikesa ? SPI_SA(csa->csa_ikesa, __func__) :
766 		    __func__,
767 		    print_spi(csa->csa_spi.spi, csa->csa_spi.spi_size));
768 	if ((csb = csa->csa_bundled) != NULL)
769 		csb->csa_bundled = NULL;
770 	if ((csb = csa->csa_peersa) != NULL)
771 		csb->csa_peersa = NULL;
772 	ibuf_release(csa->csa_encrkey);
773 	ibuf_release(csa->csa_integrkey);
774 	free(csa);
775 }
776 
777 struct iked_childsa *
778 childsa_lookup(struct iked_sa *sa, uint64_t spi, uint8_t protoid)
779 {
780 	struct iked_childsa	*csa;
781 
782 	if (sa == NULL || spi == 0 || protoid == 0)
783 		return (NULL);
784 
785 	TAILQ_FOREACH(csa, &sa->sa_childsas, csa_entry) {
786 		if (csa->csa_spi.spi_protoid == protoid &&
787 		    (csa->csa_spi.spi == spi))
788 			break;
789 	}
790 	return (csa);
791 }
792 
793 void
794 flow_free(struct iked_flow *flow)
795 {
796 	free(flow);
797 }
798 
799 struct iked_sa *
800 sa_lookup(struct iked *env, uint64_t ispi, uint64_t rspi,
801     unsigned int initiator)
802 {
803 	struct iked_sa	*sa, key;
804 
805 	key.sa_hdr.sh_ispi = ispi;
806 	key.sa_hdr.sh_initiator = initiator;
807 
808 	if ((sa = RB_FIND(iked_sas, &env->sc_sas, &key)) != NULL) {
809 		gettimeofday(&sa->sa_timeused, NULL);
810 
811 		/* Validate if SPIr matches */
812 		if ((sa->sa_hdr.sh_rspi != 0) &&
813 		    (rspi != 0) &&
814 		    (sa->sa_hdr.sh_rspi != rspi))
815 			return (NULL);
816 	}
817 
818 	return (sa);
819 }
820 
821 static __inline int
822 sa_cmp(struct iked_sa *a, struct iked_sa *b)
823 {
824 	if (a->sa_hdr.sh_initiator > b->sa_hdr.sh_initiator)
825 		return (-1);
826 	if (a->sa_hdr.sh_initiator < b->sa_hdr.sh_initiator)
827 		return (1);
828 
829 	if (a->sa_hdr.sh_ispi > b->sa_hdr.sh_ispi)
830 		return (-1);
831 	if (a->sa_hdr.sh_ispi < b->sa_hdr.sh_ispi)
832 		return (1);
833 
834 	return (0);
835 }
836 
837 static struct iked_id *
838 sa_dstid_checked(struct iked_sa *sa)
839 {
840 	struct iked_id *id;
841 
842 	id = IKESA_DSTID(sa);
843 	if (id == NULL || id->id_buf == NULL ||
844 	    ibuf_data(id->id_buf) == NULL)
845 		return (NULL);
846 	if (ibuf_size(id->id_buf) <= id->id_offset)
847 		return (NULL);
848 	return (id);
849 }
850 
851 struct iked_sa *
852 sa_dstid_lookup(struct iked *env, struct iked_sa *key)
853 {
854 	struct iked_sa *sa;
855 
856 	if (sa_dstid_checked(key) == NULL)
857 		fatalx("%s: no id for key %p", __func__, key);
858 	sa = RB_FIND(iked_dstid_sas, &env->sc_dstid_sas, key);
859 	if (sa != NULL && !sa->sa_dstid_entry_valid)
860 		fatalx("%s: sa %p not estab (key %p)", __func__, sa, key);
861 	return (sa);
862 }
863 
864 struct iked_sa *
865 sa_dstid_insert(struct iked *env, struct iked_sa *sa)
866 {
867 	struct iked_sa *osa;
868 
869 	if (sa->sa_dstid_entry_valid)
870 		fatalx("%s: sa %p is estab", __func__, sa);
871 	if (sa_dstid_checked(sa) == NULL)
872 		fatalx("%s: no id for sa %p", __func__, sa);
873 	osa = RB_FIND(iked_dstid_sas, &env->sc_dstid_sas, sa);
874 	if (osa == NULL) {
875 		osa = RB_INSERT(iked_dstid_sas, &env->sc_dstid_sas, sa);
876 		if (osa && osa != sa) {
877 			log_warnx("%s: duplicate IKE SA", SPI_SA(sa, __func__));
878 			return (osa);
879 		}
880 		sa->sa_dstid_entry_valid = 1;
881 		return (NULL);
882 	}
883 	if (!osa->sa_dstid_entry_valid)
884 		fatalx("%s: osa %p not estab (sa %p)", __func__, osa, sa);
885 	return (osa);
886 }
887 
888 void
889 sa_dstid_remove(struct iked *env, struct iked_sa *sa)
890 {
891 	if (!sa->sa_dstid_entry_valid)
892 		fatalx("%s: sa %p is not estab", __func__, sa);
893 	if (sa_dstid_checked(sa) == NULL)
894 		fatalx("%s: no id for sa %p", __func__, sa);
895 	RB_REMOVE(iked_dstid_sas, &env->sc_dstid_sas, sa);
896 	sa->sa_dstid_entry_valid = 0;
897 }
898 
899 static __inline int
900 sa_dstid_cmp(struct iked_sa *a, struct iked_sa *b)
901 {
902 	struct iked_id		*aid = NULL, *bid = NULL;
903 	size_t			 alen, blen;
904 	uint8_t			*aptr, *bptr;
905 
906 	aid = sa_dstid_checked(a);
907 	bid = sa_dstid_checked(b);
908 	if (aid == NULL || bid == NULL)
909 		fatalx("corrupt IDs");
910 	if (aid->id_type > bid->id_type)
911 		return (-1);
912 	else if (aid->id_type < bid->id_type)
913 		return (1);
914 	alen = ibuf_size(aid->id_buf);
915 	blen = ibuf_size(bid->id_buf);
916 	aptr = ibuf_data(aid->id_buf);
917 	bptr = ibuf_data(bid->id_buf);
918 	if (aptr == NULL || bptr == NULL)
919 		fatalx("corrupt ID bufs");
920 	if (alen <= aid->id_offset || blen <= bid->id_offset)
921 		fatalx("corrupt ID lens");
922 	aptr += aid->id_offset;
923 	alen -= aid->id_offset;
924 	bptr += bid->id_offset;
925 	blen -= bid->id_offset;
926 	if (alen > blen)
927 		return (-1);
928 	if (alen < blen)
929 		return (1);
930 	return (memcmp(aptr, bptr, alen));
931 }
932 
933 static __inline int
934 sa_addrpool_cmp(struct iked_sa *a, struct iked_sa *b)
935 {
936 	return (sockaddr_cmp((struct sockaddr *)&a->sa_addrpool->addr,
937 	    (struct sockaddr *)&b->sa_addrpool->addr, -1));
938 }
939 
940 static __inline int
941 sa_addrpool6_cmp(struct iked_sa *a, struct iked_sa *b)
942 {
943 	return (sockaddr_cmp((struct sockaddr *)&a->sa_addrpool6->addr,
944 	    (struct sockaddr *)&b->sa_addrpool6->addr, -1));
945 }
946 
947 struct iked_user *
948 user_lookup(struct iked *env, const char *user)
949 {
950 	struct iked_user	 key;
951 
952 	if (strlcpy(key.usr_name, user,
953 	    sizeof(key.usr_name)) >= sizeof(key.usr_name))
954 		return (NULL);
955 
956 	return (RB_FIND(iked_users, &env->sc_users, &key));
957 }
958 
959 static __inline int
960 user_cmp(struct iked_user *a, struct iked_user *b)
961 {
962 	return (strcmp(a->usr_name, b->usr_name));
963 }
964 
965 /*
966  * Find a matching subset of the proposal lists 'local' and 'peer'.
967  * The resulting proposal is stored in 'result' if 'result' is not NULL.
968  * The 'rekey' parameter indicates a CREATE_CHILD_SA exchange where
969  * an extra group is necessary for PFS. For the initial IKE_AUTH exchange
970  * the ESP SA proposal never includes an explicit DH group.
971  *
972  * Return 0 if a matching subset was found and -1 if no subset was found
973  * or an error occured.
974  */
975 int
976 proposals_negotiate(struct iked_proposals *result, struct iked_proposals *local,
977     struct iked_proposals *peer, int rekey, int groupid)
978 {
979 	struct iked_proposal	*ppeer = NULL, *plocal, *prop, vpeer, vlocal;
980 	struct iked_transform	 chosen[IKEV2_XFORMTYPE_MAX];
981 	struct iked_transform	*valid[IKEV2_XFORMTYPE_MAX];
982 	struct iked_transform	*match[IKEV2_XFORMTYPE_MAX];
983 	unsigned int		 i, score, chosen_score = 0;
984 	uint8_t			 protoid = 0;
985 
986 	bzero(valid, sizeof(valid));
987 	bzero(&vlocal, sizeof(vlocal));
988 	bzero(&vpeer, sizeof(vpeer));
989 
990 	if (TAILQ_EMPTY(peer)) {
991 		log_debug("%s: peer did not send %s proposals", __func__,
992 		    print_map(protoid, ikev2_saproto_map));
993 		return (-1);
994 	}
995 
996 	TAILQ_FOREACH(plocal, local, prop_entry) {
997 		TAILQ_FOREACH(ppeer, peer, prop_entry) {
998 			if (ppeer->prop_protoid != plocal->prop_protoid)
999 				continue;
1000 			bzero(match, sizeof(match));
1001 			score = proposals_match(plocal, ppeer, match,
1002 			    rekey, groupid);
1003 			log_debug("%s: score %d", __func__, score);
1004 			if (score && (!chosen_score || score < chosen_score)) {
1005 				chosen_score = score;
1006 				for (i = 0; i < IKEV2_XFORMTYPE_MAX; i++) {
1007 					if ((valid[i] = match[i]))
1008 						memcpy(&chosen[i], match[i],
1009 						    sizeof(chosen[0]));
1010 				}
1011 				memcpy(&vpeer, ppeer, sizeof(vpeer));
1012 				memcpy(&vlocal, plocal, sizeof(vlocal));
1013 			}
1014 		}
1015 		if (chosen_score != 0)
1016 			break;
1017 	}
1018 
1019 	if (chosen_score == 0)
1020 		return (-1);
1021 	else if (result == NULL)
1022 		return (0);
1023 
1024 	(void)config_free_proposals(result, vpeer.prop_protoid);
1025 	prop = config_add_proposal(result, vpeer.prop_id, vpeer.prop_protoid);
1026 
1027 	if (vpeer.prop_localspi.spi_size) {
1028 		prop->prop_localspi.spi_size = vpeer.prop_localspi.spi_size;
1029 		prop->prop_peerspi = vpeer.prop_peerspi;
1030 	}
1031 	if (vlocal.prop_localspi.spi_size) {
1032 		prop->prop_localspi.spi_size = vlocal.prop_localspi.spi_size;
1033 		prop->prop_localspi.spi = vlocal.prop_localspi.spi;
1034 	}
1035 
1036 	for (i = 0; i < IKEV2_XFORMTYPE_MAX; i++) {
1037 		if (valid[i] == NULL)
1038 			continue;
1039 		print_debug("%s: score %d: %s %s", __func__,
1040 		    chosen[i].xform_score, print_map(i, ikev2_xformtype_map),
1041 		    print_map(chosen[i].xform_id, chosen[i].xform_map));
1042 		if (chosen[i].xform_length)
1043 			print_debug(" %d", chosen[i].xform_length);
1044 		print_debug("\n");
1045 
1046 		if (config_add_transform(prop, chosen[i].xform_type,
1047 		    chosen[i].xform_id, chosen[i].xform_length,
1048 		    chosen[i].xform_keylength) != 0)
1049 			break;
1050 	}
1051 
1052 	return (0);
1053 }
1054 
1055 static int
1056 proposals_match(struct iked_proposal *local, struct iked_proposal *peer,
1057     struct iked_transform **xforms, int rekey, int dhgroup)
1058 {
1059 	struct iked_transform	*tpeer, *tlocal;
1060 	unsigned int		 i, j, type, score, requiredh = 0, nodh = 0, noauth = 0;
1061 	unsigned int		 dhforced = 0;
1062 	uint8_t			 protoid = peer->prop_protoid;
1063 	uint8_t			 peerxfs[IKEV2_XFORMTYPE_MAX];
1064 
1065 	bzero(peerxfs, sizeof(peerxfs));
1066 
1067 	for (i = 0; i < peer->prop_nxforms; i++) {
1068 		tpeer = peer->prop_xforms + i;
1069 		/* If any of the ENC transforms is an AEAD, ignore auth */
1070 		if (tpeer->xform_type == IKEV2_XFORMTYPE_ENCR &&
1071 		    encxf_noauth(tpeer->xform_id))
1072 			noauth = 1;
1073 	}
1074 
1075 	for (i = 0; i < peer->prop_nxforms; i++) {
1076 		tpeer = peer->prop_xforms + i;
1077 		if (tpeer->xform_type > IKEV2_XFORMTYPE_MAX)
1078 			continue;
1079 		if (noauth && tpeer->xform_type == IKEV2_XFORMTYPE_INTEGR)
1080 			return (0);
1081 
1082 		/*
1083 		 * Record all transform types from the peer's proposal,
1084 		 * because if we want this proposal we have to select
1085 		 * a transform for each proposed transform type.
1086 		 */
1087 		peerxfs[tpeer->xform_type] = 1;
1088 
1089 		for (j = 0; j < local->prop_nxforms; j++) {
1090 			tlocal = local->prop_xforms + j;
1091 
1092 			/*
1093 			 * We require a DH group for ESP if there is any
1094 			 * local proposal with DH enabled.
1095 			 */
1096 			if (rekey && requiredh == 0 &&
1097 			    protoid == IKEV2_SAPROTO_ESP &&
1098 			    tlocal->xform_type == IKEV2_XFORMTYPE_DH &&
1099 			    tlocal->xform_id != IKEV2_XFORMDH_NONE)
1100 				requiredh = 1;
1101 
1102 			/*
1103 			 * If none is an explicit option, don't require
1104 			 * DH group. Overrides requiredh = 1.
1105 			 */
1106 			if (rekey && nodh == 0 &&
1107 			    protoid == IKEV2_SAPROTO_ESP &&
1108 			    tlocal->xform_type == IKEV2_XFORMTYPE_DH &&
1109 			    tlocal->xform_id == IKEV2_XFORMDH_NONE)
1110 				nodh = 1;
1111 
1112 			/* Compare peer and local proposals */
1113 			if (tpeer->xform_type != tlocal->xform_type ||
1114 			    tpeer->xform_id != tlocal->xform_id ||
1115 			    tpeer->xform_length != tlocal->xform_length)
1116 				continue;
1117 			type = tpeer->xform_type;
1118 
1119 			if (rekey && nodh == 0 && dhgroup >= 0 &&
1120 			    protoid == IKEV2_SAPROTO_ESP &&
1121 			    type == IKEV2_XFORMTYPE_DH) {
1122 				if (dhforced)
1123 					continue;
1124 				/* reset xform, so this xform w/matching group is enforced */
1125 				if (tlocal->xform_id == dhgroup) {
1126 					xforms[type] = NULL;
1127 					dhforced = 1;
1128 				}
1129 			}
1130 
1131 			if (xforms[type] == NULL || tlocal->xform_score <
1132 			    xforms[type]->xform_score) {
1133 				xforms[type] = tlocal;
1134 			} else
1135 				continue;
1136 
1137 			print_debug("%s: xform %d <-> %d (%d): %s %s "
1138 			    "(keylength %d <-> %d)", __func__,
1139 			    peer->prop_id, local->prop_id, tlocal->xform_score,
1140 			    print_map(type, ikev2_xformtype_map),
1141 			    print_map(tpeer->xform_id, tpeer->xform_map),
1142 			    tpeer->xform_keylength, tlocal->xform_keylength);
1143 			if (tpeer->xform_length)
1144 				print_debug(" %d", tpeer->xform_length);
1145 			print_debug("\n");
1146 		}
1147 	}
1148 
1149 	for (i = score = 0; i < IKEV2_XFORMTYPE_MAX; i++) {
1150 		if (protoid == IKEV2_SAPROTO_IKE && xforms[i] == NULL &&
1151 		    (i == IKEV2_XFORMTYPE_ENCR || i == IKEV2_XFORMTYPE_PRF ||
1152 		    (!noauth && i == IKEV2_XFORMTYPE_INTEGR) ||
1153 		    i == IKEV2_XFORMTYPE_DH)) {
1154 			score = 0;
1155 			break;
1156 		} else if (protoid == IKEV2_SAPROTO_AH && xforms[i] == NULL &&
1157 		    (i == IKEV2_XFORMTYPE_INTEGR || i == IKEV2_XFORMTYPE_ESN)) {
1158 			score = 0;
1159 			break;
1160 		} else if (protoid == IKEV2_SAPROTO_ESP && xforms[i] == NULL &&
1161 		    (i == IKEV2_XFORMTYPE_ENCR || i == IKEV2_XFORMTYPE_ESN ||
1162 		    (requiredh && !nodh && i == IKEV2_XFORMTYPE_DH))) {
1163 			score = 0;
1164 			break;
1165 		} else if (peerxfs[i] && xforms[i] == NULL) {
1166 			score = 0;
1167 			break;
1168 		} else if (xforms[i] == NULL)
1169 			continue;
1170 
1171 		score += xforms[i]->xform_score;
1172 	}
1173 
1174 	return (score);
1175 }
1176 
1177 static __inline int
1178 childsa_cmp(struct iked_childsa *a, struct iked_childsa *b)
1179 {
1180 	if (a->csa_spi.spi > b->csa_spi.spi)
1181 		return (1);
1182 	if (a->csa_spi.spi < b->csa_spi.spi)
1183 		return (-1);
1184 	return (0);
1185 }
1186 
1187 static __inline int
1188 addr_cmp(struct iked_addr *a, struct iked_addr *b, int useports)
1189 {
1190 	int		diff = 0;
1191 
1192 	diff = sockaddr_cmp((struct sockaddr *)&a->addr,
1193 	    (struct sockaddr *)&b->addr, 128);
1194 	if (!diff)
1195 		diff = (int)a->addr_mask - (int)b->addr_mask;
1196 	if (!diff && useports)
1197 		diff = a->addr_port - b->addr_port;
1198 
1199 	return (diff);
1200 }
1201 
1202 static __inline int
1203 flow_cmp(struct iked_flow *a, struct iked_flow *b)
1204 {
1205 	int		diff = 0;
1206 
1207 	if (!diff)
1208 		diff = a->flow_rdomain - b->flow_rdomain;
1209 	if (!diff)
1210 		diff = (int)a->flow_ipproto - (int)b->flow_ipproto;
1211 	if (!diff)
1212 		diff = (int)a->flow_saproto - (int)b->flow_saproto;
1213 	if (!diff)
1214 		diff = (int)a->flow_dir - (int)b->flow_dir;
1215 	if (!diff)
1216 		diff = addr_cmp(&a->flow_dst, &b->flow_dst, 1);
1217 	if (!diff)
1218 		diff = addr_cmp(&a->flow_src, &b->flow_src, 1);
1219 
1220 	return (diff);
1221 }
1222 
1223 int
1224 flow_equal(struct iked_flow *a, struct iked_flow *b)
1225 {
1226 	return (flow_cmp(a, b) == 0);
1227 }
1228 
1229 RB_GENERATE(iked_sas, iked_sa, sa_entry, sa_cmp);
1230 RB_GENERATE(iked_dstid_sas, iked_sa, sa_dstid_entry, sa_dstid_cmp);
1231 RB_GENERATE(iked_addrpool, iked_sa, sa_addrpool_entry, sa_addrpool_cmp);
1232 RB_GENERATE(iked_addrpool6, iked_sa, sa_addrpool6_entry, sa_addrpool6_cmp);
1233 RB_GENERATE(iked_users, iked_user, usr_entry, user_cmp);
1234 RB_GENERATE(iked_activesas, iked_childsa, csa_node, childsa_cmp);
1235 RB_GENERATE(iked_flows, iked_flow, flow_node, flow_cmp);
1236