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