1 /*-
2 * SPDX-License-Identifier: BSD-3-Clause
3 *
4 * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
5 * All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * 3. Neither the name of the project nor the names of its contributors
16 * may be used to endorse or promote products derived from this software
17 * without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 * ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 * SUCH DAMAGE.
30 *
31 * $KAME: in6_src.c,v 1.132 2003/08/26 04:42:27 keiichi Exp $
32 */
33
34 /*-
35 * Copyright (c) 1982, 1986, 1991, 1993
36 * The Regents of the University of California. All rights reserved.
37 *
38 * Redistribution and use in source and binary forms, with or without
39 * modification, are permitted provided that the following conditions
40 * are met:
41 * 1. Redistributions of source code must retain the above copyright
42 * notice, this list of conditions and the following disclaimer.
43 * 2. Redistributions in binary form must reproduce the above copyright
44 * notice, this list of conditions and the following disclaimer in the
45 * documentation and/or other materials provided with the distribution.
46 * 3. Neither the name of the University nor the names of its contributors
47 * may be used to endorse or promote products derived from this software
48 * without specific prior written permission.
49 *
50 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
51 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
52 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
53 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
54 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
55 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
56 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
57 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
58 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
59 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
60 * SUCH DAMAGE.
61 *
62 * @(#)in_pcb.c 8.2 (Berkeley) 1/4/94
63 */
64
65 #include <sys/cdefs.h>
66 #include "opt_inet.h"
67 #include "opt_inet6.h"
68 #include <sys/param.h>
69 #include <sys/systm.h>
70 #include <sys/lock.h>
71 #include <sys/malloc.h>
72 #include <sys/mbuf.h>
73 #include <sys/priv.h>
74 #include <sys/protosw.h>
75 #include <sys/socket.h>
76 #include <sys/socketvar.h>
77 #include <sys/sockio.h>
78 #include <sys/sysctl.h>
79 #include <sys/errno.h>
80 #include <sys/time.h>
81 #include <sys/jail.h>
82 #include <sys/kernel.h>
83 #include <sys/rmlock.h>
84 #include <sys/sx.h>
85
86 #include <net/if.h>
87 #include <net/if_var.h>
88 #include <net/if_dl.h>
89 #include <net/route.h>
90 #include <net/route/nhop.h>
91 #include <net/if_llatbl.h>
92
93 #include <netinet/in.h>
94 #include <netinet/in_var.h>
95 #include <netinet/in_systm.h>
96 #include <netinet/ip.h>
97 #include <netinet/in_pcb.h>
98 #include <netinet/ip_var.h>
99 #include <netinet/udp.h>
100 #include <netinet/udp_var.h>
101
102 #include <netinet6/in6_var.h>
103 #include <netinet/ip6.h>
104 #include <netinet6/in6_fib.h>
105 #include <netinet6/in6_pcb.h>
106 #include <netinet6/ip6_var.h>
107 #include <netinet6/scope6_var.h>
108 #include <netinet6/nd6.h>
109
110 static struct mtx addrsel_lock;
111 #define ADDRSEL_LOCK_INIT() mtx_init(&addrsel_lock, "addrsel_lock", NULL, MTX_DEF)
112 #define ADDRSEL_LOCK() mtx_lock(&addrsel_lock)
113 #define ADDRSEL_UNLOCK() mtx_unlock(&addrsel_lock)
114 #define ADDRSEL_LOCK_ASSERT() mtx_assert(&addrsel_lock, MA_OWNED)
115
116 static struct sx addrsel_sxlock;
117 #define ADDRSEL_SXLOCK_INIT() sx_init(&addrsel_sxlock, "addrsel_sxlock")
118 #define ADDRSEL_SLOCK() sx_slock(&addrsel_sxlock)
119 #define ADDRSEL_SUNLOCK() sx_sunlock(&addrsel_sxlock)
120 #define ADDRSEL_XLOCK() sx_xlock(&addrsel_sxlock)
121 #define ADDRSEL_XUNLOCK() sx_xunlock(&addrsel_sxlock)
122
123 #define ADDR_LABEL_NOTAPP (-1)
124 VNET_DEFINE_STATIC(struct in6_addrpolicy, defaultaddrpolicy);
125 #define V_defaultaddrpolicy VNET(defaultaddrpolicy)
126
127 VNET_DEFINE(int, ip6_prefer_tempaddr) = 0;
128
129 static int selectroute(struct sockaddr_in6 *, struct ip6_pktopts *,
130 struct ip6_moptions *, struct route_in6 *, struct ifnet **,
131 struct nhop_object **, int, u_int, uint32_t);
132 static int in6_selectif(struct sockaddr_in6 *, struct ip6_pktopts *,
133 struct ip6_moptions *, struct ifnet **,
134 struct ifnet *, u_int);
135 static int in6_selectsrc(uint32_t, struct sockaddr_in6 *,
136 struct ip6_pktopts *, struct inpcb *, struct ucred *,
137 struct ifnet **, struct in6_addr *);
138
139 static struct in6_addrpolicy *lookup_addrsel_policy(struct sockaddr_in6 *);
140
141 static void init_policy_queue(void);
142 static int add_addrsel_policyent(struct in6_addrpolicy *);
143 static int delete_addrsel_policyent(struct in6_addrpolicy *);
144 static int walk_addrsel_policy(int (*)(struct in6_addrpolicy *, void *),
145 void *);
146 static int dump_addrsel_policyent(struct in6_addrpolicy *, void *);
147 static struct in6_addrpolicy *match_addrsel_policy(struct sockaddr_in6 *);
148
149 /*
150 * Return an IPv6 address, which is the most appropriate for a given
151 * destination and user specified options.
152 * If necessary, this function lookups the routing table and returns
153 * an entry to the caller for later use.
154 */
155 #define REPLACE(r) do {\
156 IP6STAT_INC(ip6s_sources_rule[(r)]); \
157 /* { \
158 char ip6buf[INET6_ADDRSTRLEN], ip6b[INET6_ADDRSTRLEN]; \
159 printf("in6_selectsrc: replace %s with %s by %d\n", ia_best ? ip6_sprintf(ip6buf, &ia_best->ia_addr.sin6_addr) : "none", ip6_sprintf(ip6b, &ia->ia_addr.sin6_addr), (r)); \
160 } */ \
161 goto replace; \
162 } while(0)
163 #define NEXT(r) do {\
164 /* { \
165 char ip6buf[INET6_ADDRSTRLEN], ip6b[INET6_ADDRSTRLEN]; \
166 printf("in6_selectsrc: keep %s against %s by %d\n", ia_best ? ip6_sprintf(ip6buf, &ia_best->ia_addr.sin6_addr) : "none", ip6_sprintf(ip6b, &ia->ia_addr.sin6_addr), (r)); \
167 } */ \
168 goto next; /* XXX: we can't use 'continue' here */ \
169 } while(0)
170 #define BREAK(r) do { \
171 IP6STAT_INC(ip6s_sources_rule[(r)]); \
172 goto out; /* XXX: we can't use 'break' here */ \
173 } while(0)
174
175 static int
in6_selectsrc(uint32_t fibnum,struct sockaddr_in6 * dstsock,struct ip6_pktopts * opts,struct inpcb * inp,struct ucred * cred,struct ifnet ** ifpp,struct in6_addr * srcp)176 in6_selectsrc(uint32_t fibnum, struct sockaddr_in6 *dstsock,
177 struct ip6_pktopts *opts, struct inpcb *inp, struct ucred *cred,
178 struct ifnet **ifpp, struct in6_addr *srcp)
179 {
180 struct rm_priotracker in6_ifa_tracker;
181 struct in6_addr dst, tmp;
182 struct ifnet *ifp = NULL, *oifp = NULL;
183 struct in6_ifaddr *ia = NULL, *ia_best = NULL;
184 struct in6_pktinfo *pi = NULL;
185 int dst_scope = -1, best_scope = -1, best_matchlen = -1;
186 struct in6_addrpolicy *dst_policy = NULL, *best_policy = NULL;
187 u_int32_t odstzone;
188 int prefer_tempaddr;
189 int error;
190 struct ip6_moptions *mopts;
191
192 NET_EPOCH_ASSERT();
193 KASSERT(srcp != NULL, ("%s: srcp is NULL", __func__));
194
195 dst = dstsock->sin6_addr; /* make a copy for local operation */
196 if (ifpp) {
197 /*
198 * Save a possibly passed in ifp for in6_selectsrc. Only
199 * neighbor discovery code should use this feature, where
200 * we may know the interface but not the FIB number holding
201 * the connected subnet in case someone deleted it from the
202 * default FIB and we need to check the interface.
203 */
204 if (*ifpp != NULL)
205 oifp = *ifpp;
206 *ifpp = NULL;
207 }
208
209 if (inp != NULL) {
210 INP_LOCK_ASSERT(inp);
211 mopts = inp->in6p_moptions;
212 } else {
213 mopts = NULL;
214 }
215
216 /*
217 * If the source address is explicitly specified by the caller,
218 * check if the requested source address is indeed a unicast address
219 * assigned to the node, and can be used as the packet's source
220 * address. If everything is okay, use the address as source.
221 */
222 if (opts && (pi = opts->ip6po_pktinfo) &&
223 !IN6_IS_ADDR_UNSPECIFIED(&pi->ipi6_addr)) {
224 /* get the outgoing interface */
225 if ((error = in6_selectif(dstsock, opts, mopts, &ifp, oifp,
226 fibnum))
227 != 0)
228 return (error);
229
230 /*
231 * determine the appropriate zone id of the source based on
232 * the zone of the destination and the outgoing interface.
233 * If the specified address is ambiguous wrt the scope zone,
234 * the interface must be specified; otherwise, ifa_ifwithaddr()
235 * will fail matching the address.
236 */
237 tmp = pi->ipi6_addr;
238 if (ifp) {
239 error = in6_setscope(&tmp, ifp, &odstzone);
240 if (error)
241 return (error);
242 }
243 if (cred != NULL && (error = prison_local_ip6(cred,
244 &tmp, (inp->inp_flags & IN6P_IPV6_V6ONLY) != 0)) != 0)
245 return (error);
246
247 /*
248 * If IPV6_BINDANY socket option is set, we allow to specify
249 * non local addresses as source address in IPV6_PKTINFO
250 * ancillary data.
251 */
252 if ((inp->inp_flags & INP_BINDANY) == 0) {
253 ia = in6ifa_ifwithaddr(&tmp, 0 /* XXX */, false);
254 if (ia == NULL || (ia->ia6_flags & (IN6_IFF_ANYCAST |
255 IN6_IFF_NOTREADY)))
256 return (EADDRNOTAVAIL);
257 bcopy(&ia->ia_addr.sin6_addr, srcp, sizeof(*srcp));
258 } else
259 bcopy(&tmp, srcp, sizeof(*srcp));
260 pi->ipi6_addr = tmp; /* XXX: this overrides pi */
261 if (ifpp)
262 *ifpp = ifp;
263 return (0);
264 }
265
266 /*
267 * Otherwise, if the socket has already bound the source, just use it.
268 */
269 if (inp != NULL && !IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_laddr)) {
270 if (cred != NULL &&
271 (error = prison_local_ip6(cred, &inp->in6p_laddr,
272 ((inp->inp_flags & IN6P_IPV6_V6ONLY) != 0))) != 0)
273 return (error);
274 bcopy(&inp->in6p_laddr, srcp, sizeof(*srcp));
275 return (0);
276 }
277
278 /*
279 * Bypass source address selection and use the primary jail IP
280 * if requested.
281 */
282 if (cred != NULL && !prison_saddrsel_ip6(cred, srcp))
283 return (0);
284
285 /*
286 * If the address is not specified, choose the best one based on
287 * the outgoing interface and the destination address.
288 */
289 /* get the outgoing interface */
290 if ((error = in6_selectif(dstsock, opts, mopts, &ifp, oifp,
291 (inp != NULL) ? inp->inp_inc.inc_fibnum : fibnum)) != 0)
292 return (error);
293
294 #ifdef DIAGNOSTIC
295 if (ifp == NULL) /* this should not happen */
296 panic("in6_selectsrc: NULL ifp");
297 #endif
298 error = in6_setscope(&dst, ifp, &odstzone);
299 if (error)
300 return (error);
301
302 IN6_IFADDR_RLOCK(&in6_ifa_tracker);
303 CK_STAILQ_FOREACH(ia, &V_in6_ifaddrhead, ia_link) {
304 int new_scope = -1, new_matchlen = -1;
305 struct in6_addrpolicy *new_policy = NULL;
306 u_int32_t srczone, osrczone, dstzone;
307 struct in6_addr src;
308 struct ifnet *ifp1 = ia->ia_ifp;
309
310 /*
311 * We'll never take an address that breaks the scope zone
312 * of the destination. We also skip an address if its zone
313 * does not contain the outgoing interface.
314 * XXX: we should probably use sin6_scope_id here.
315 */
316 if (in6_setscope(&dst, ifp1, &dstzone) ||
317 odstzone != dstzone) {
318 continue;
319 }
320 src = ia->ia_addr.sin6_addr;
321 if (in6_setscope(&src, ifp, &osrczone) ||
322 in6_setscope(&src, ifp1, &srczone) ||
323 osrczone != srczone) {
324 continue;
325 }
326
327 /* avoid unusable addresses */
328 if ((ia->ia6_flags &
329 (IN6_IFF_NOTREADY | IN6_IFF_ANYCAST | IN6_IFF_DETACHED))) {
330 continue;
331 }
332 if (!V_ip6_use_deprecated && IFA6_IS_DEPRECATED(ia))
333 continue;
334
335 /* If jailed only take addresses of the jail into account. */
336 if (cred != NULL &&
337 prison_check_ip6(cred, &ia->ia_addr.sin6_addr) != 0)
338 continue;
339
340 /* Rule 1: Prefer same address */
341 if (IN6_ARE_ADDR_EQUAL(&dst, &ia->ia_addr.sin6_addr)) {
342 ia_best = ia;
343 BREAK(1); /* there should be no better candidate */
344 }
345
346 if (ia_best == NULL)
347 REPLACE(0);
348
349 /* Rule 2: Prefer appropriate scope */
350 if (dst_scope < 0)
351 dst_scope = in6_addrscope(&dst);
352 new_scope = in6_addrscope(&ia->ia_addr.sin6_addr);
353 if (IN6_ARE_SCOPE_CMP(best_scope, new_scope) < 0) {
354 if (IN6_ARE_SCOPE_CMP(best_scope, dst_scope) < 0)
355 REPLACE(2);
356 NEXT(2);
357 } else if (IN6_ARE_SCOPE_CMP(new_scope, best_scope) < 0) {
358 if (IN6_ARE_SCOPE_CMP(new_scope, dst_scope) < 0)
359 NEXT(2);
360 REPLACE(2);
361 }
362
363 /*
364 * Rule 3: Avoid deprecated addresses. Note that the case of
365 * !ip6_use_deprecated is already rejected above.
366 */
367 if (!IFA6_IS_DEPRECATED(ia_best) && IFA6_IS_DEPRECATED(ia))
368 NEXT(3);
369 if (IFA6_IS_DEPRECATED(ia_best) && !IFA6_IS_DEPRECATED(ia))
370 REPLACE(3);
371
372 /* Rule 4: Prefer home addresses */
373 /*
374 * XXX: This is a TODO. We should probably merge the MIP6
375 * case above.
376 */
377
378 /* Rule 5: Prefer outgoing interface */
379 if (!(ND_IFINFO(ifp)->flags & ND6_IFF_NO_PREFER_IFACE)) {
380 if (ia_best->ia_ifp == ifp && ia->ia_ifp != ifp)
381 NEXT(5);
382 if (ia_best->ia_ifp != ifp && ia->ia_ifp == ifp)
383 REPLACE(5);
384 }
385
386 /*
387 * Rule 6: Prefer matching label
388 * Note that best_policy should be non-NULL here.
389 */
390 if (dst_policy == NULL)
391 dst_policy = lookup_addrsel_policy(dstsock);
392 if (dst_policy->label != ADDR_LABEL_NOTAPP) {
393 new_policy = lookup_addrsel_policy(&ia->ia_addr);
394 if (dst_policy->label == best_policy->label &&
395 dst_policy->label != new_policy->label)
396 NEXT(6);
397 if (dst_policy->label != best_policy->label &&
398 dst_policy->label == new_policy->label)
399 REPLACE(6);
400 }
401
402 /*
403 * Rule 7: Prefer public addresses.
404 * We allow users to reverse the logic by configuring
405 * a sysctl variable, so that privacy conscious users can
406 * always prefer temporary addresses.
407 */
408 if (opts == NULL ||
409 opts->ip6po_prefer_tempaddr == IP6PO_TEMPADDR_SYSTEM) {
410 prefer_tempaddr = V_ip6_prefer_tempaddr;
411 } else if (opts->ip6po_prefer_tempaddr ==
412 IP6PO_TEMPADDR_NOTPREFER) {
413 prefer_tempaddr = 0;
414 } else
415 prefer_tempaddr = 1;
416 if (!(ia_best->ia6_flags & IN6_IFF_TEMPORARY) &&
417 (ia->ia6_flags & IN6_IFF_TEMPORARY)) {
418 if (prefer_tempaddr)
419 REPLACE(7);
420 else
421 NEXT(7);
422 }
423 if ((ia_best->ia6_flags & IN6_IFF_TEMPORARY) &&
424 !(ia->ia6_flags & IN6_IFF_TEMPORARY)) {
425 if (prefer_tempaddr)
426 NEXT(7);
427 else
428 REPLACE(7);
429 }
430
431 /*
432 * Rule 8: prefer addresses on alive interfaces.
433 * This is a KAME specific rule.
434 */
435 if ((ia_best->ia_ifp->if_flags & IFF_UP) &&
436 !(ia->ia_ifp->if_flags & IFF_UP))
437 NEXT(8);
438 if (!(ia_best->ia_ifp->if_flags & IFF_UP) &&
439 (ia->ia_ifp->if_flags & IFF_UP))
440 REPLACE(8);
441
442 /*
443 * Rule 9: prefer address with better virtual status.
444 */
445 if (ifa_preferred(&ia_best->ia_ifa, &ia->ia_ifa))
446 REPLACE(9);
447 if (ifa_preferred(&ia->ia_ifa, &ia_best->ia_ifa))
448 NEXT(9);
449
450 /*
451 * Rule 10: prefer address with `prefer_source' flag.
452 */
453 if ((ia_best->ia6_flags & IN6_IFF_PREFER_SOURCE) == 0 &&
454 (ia->ia6_flags & IN6_IFF_PREFER_SOURCE) != 0)
455 REPLACE(10);
456 if ((ia_best->ia6_flags & IN6_IFF_PREFER_SOURCE) != 0 &&
457 (ia->ia6_flags & IN6_IFF_PREFER_SOURCE) == 0)
458 NEXT(10);
459
460 /*
461 * Rule 14: Use longest matching prefix.
462 * Note: in the address selection draft, this rule is
463 * documented as "Rule 8". However, since it is also
464 * documented that this rule can be overridden, we assign
465 * a large number so that it is easy to assign smaller numbers
466 * to more preferred rules.
467 */
468 new_matchlen = in6_matchlen(&ia->ia_addr.sin6_addr, &dst);
469 if (best_matchlen < new_matchlen)
470 REPLACE(14);
471 if (new_matchlen < best_matchlen)
472 NEXT(14);
473
474 /* Rule 15 is reserved. */
475
476 /*
477 * Last resort: just keep the current candidate.
478 * Or, do we need more rules?
479 */
480 continue;
481
482 replace:
483 ia_best = ia;
484 best_scope = (new_scope >= 0 ? new_scope :
485 in6_addrscope(&ia_best->ia_addr.sin6_addr));
486 best_policy = (new_policy ? new_policy :
487 lookup_addrsel_policy(&ia_best->ia_addr));
488 best_matchlen = (new_matchlen >= 0 ? new_matchlen :
489 in6_matchlen(&ia_best->ia_addr.sin6_addr,
490 &dst));
491
492 next:
493 continue;
494
495 out:
496 break;
497 }
498
499 if ((ia = ia_best) == NULL) {
500 IN6_IFADDR_RUNLOCK(&in6_ifa_tracker);
501 IP6STAT_INC(ip6s_sources_none);
502 return (EADDRNOTAVAIL);
503 }
504
505 /*
506 * At this point at least one of the addresses belonged to the jail
507 * but it could still be, that we want to further restrict it, e.g.
508 * theoratically IN6_IS_ADDR_LOOPBACK.
509 * It must not be IN6_IS_ADDR_UNSPECIFIED anymore.
510 * prison_local_ip6() will fix an IN6_IS_ADDR_LOOPBACK but should
511 * let all others previously selected pass.
512 * Use tmp to not change ::1 on lo0 to the primary jail address.
513 */
514 tmp = ia->ia_addr.sin6_addr;
515 if (cred != NULL && prison_local_ip6(cred, &tmp, (inp != NULL &&
516 (inp->inp_flags & IN6P_IPV6_V6ONLY) != 0)) != 0) {
517 IN6_IFADDR_RUNLOCK(&in6_ifa_tracker);
518 IP6STAT_INC(ip6s_sources_none);
519 return (EADDRNOTAVAIL);
520 }
521
522 if (ifpp)
523 *ifpp = ifp;
524
525 bcopy(&tmp, srcp, sizeof(*srcp));
526 if (ia->ia_ifp == ifp)
527 IP6STAT_INC(ip6s_sources_sameif[best_scope]);
528 else
529 IP6STAT_INC(ip6s_sources_otherif[best_scope]);
530 if (dst_scope == best_scope)
531 IP6STAT_INC(ip6s_sources_samescope[best_scope]);
532 else
533 IP6STAT_INC(ip6s_sources_otherscope[best_scope]);
534 if (IFA6_IS_DEPRECATED(ia))
535 IP6STAT_INC(ip6s_sources_deprecated[best_scope]);
536 IN6_IFADDR_RUNLOCK(&in6_ifa_tracker);
537 return (0);
538 }
539
540 /*
541 * Select source address based on @inp, @dstsock and @opts.
542 * Stores selected address to @srcp. If @scope_ambiguous is set,
543 * embed scope from selected outgoing interface. If @hlim pointer
544 * is provided, stores calculated hop limit there.
545 * Returns 0 on success.
546 */
547 int
in6_selectsrc_socket(struct sockaddr_in6 * dstsock,struct ip6_pktopts * opts,struct inpcb * inp,struct ucred * cred,int scope_ambiguous,struct in6_addr * srcp,int * hlim)548 in6_selectsrc_socket(struct sockaddr_in6 *dstsock, struct ip6_pktopts *opts,
549 struct inpcb *inp, struct ucred *cred, int scope_ambiguous,
550 struct in6_addr *srcp, int *hlim)
551 {
552 struct ifnet *retifp;
553 uint32_t fibnum;
554 int error;
555
556 fibnum = inp->inp_inc.inc_fibnum;
557 retifp = NULL;
558
559 error = in6_selectsrc(fibnum, dstsock, opts, inp, cred, &retifp, srcp);
560 if (error != 0)
561 return (error);
562
563 if (hlim != NULL)
564 *hlim = in6_selecthlim(inp, retifp);
565
566 if (retifp == NULL || scope_ambiguous == 0)
567 return (0);
568
569 /*
570 * Application should provide a proper zone ID or the use of
571 * default zone IDs should be enabled. Unfortunately, some
572 * applications do not behave as it should, so we need a
573 * workaround. Even if an appropriate ID is not determined
574 * (when it's required), if we can determine the outgoing
575 * interface. determine the zone ID based on the interface.
576 */
577 error = in6_setscope(&dstsock->sin6_addr, retifp, NULL);
578
579 return (error);
580 }
581
582 /*
583 * Select source address based on @fibnum, @dst and @scopeid.
584 * Stores selected address to @srcp.
585 * Returns 0 on success.
586 *
587 * Used by non-socket based consumers (ND code mostly)
588 */
589 int
in6_selectsrc_addr(uint32_t fibnum,const struct in6_addr * dst,uint32_t scopeid,struct ifnet * ifp,struct in6_addr * srcp,int * hlim)590 in6_selectsrc_addr(uint32_t fibnum, const struct in6_addr *dst,
591 uint32_t scopeid, struct ifnet *ifp, struct in6_addr *srcp,
592 int *hlim)
593 {
594 struct ifnet *retifp;
595 struct sockaddr_in6 dst_sa;
596 int error;
597
598 retifp = ifp;
599 bzero(&dst_sa, sizeof(dst_sa));
600 dst_sa.sin6_family = AF_INET6;
601 dst_sa.sin6_len = sizeof(dst_sa);
602 dst_sa.sin6_addr = *dst;
603 dst_sa.sin6_scope_id = scopeid;
604 sa6_embedscope(&dst_sa, 0);
605
606 error = in6_selectsrc(fibnum, &dst_sa, NULL, NULL, NULL, &retifp, srcp);
607 if (hlim != NULL)
608 *hlim = in6_selecthlim(NULL, retifp);
609
610 return (error);
611 }
612
613 static struct nhop_object *
cache_route(uint32_t fibnum,const struct sockaddr_in6 * dst,struct route_in6 * ro,uint32_t flowid)614 cache_route(uint32_t fibnum, const struct sockaddr_in6 *dst, struct route_in6 *ro,
615 uint32_t flowid)
616 {
617 /*
618 * Use a cached route if it exists and is valid, else try to allocate
619 * a new one. Note that we should check the address family of the
620 * cached destination, in case of sharing the cache with IPv4.
621 * Assumes that 'struct route_in6' is exclusively locked.
622 */
623 if (ro->ro_nh != NULL && (
624 !NH_IS_VALID(ro->ro_nh) || ro->ro_dst.sin6_family != AF_INET6 ||
625 !IN6_ARE_ADDR_EQUAL(&ro->ro_dst.sin6_addr, &dst->sin6_addr)))
626 RO_NHFREE(ro);
627
628 if (ro->ro_nh == NULL) {
629 ro->ro_dst = *dst;
630
631 const struct in6_addr *paddr;
632 struct in6_addr unscoped_addr;
633 uint32_t scopeid = 0;
634 if (IN6_IS_SCOPE_LINKLOCAL(&dst->sin6_addr)) {
635 in6_splitscope(&dst->sin6_addr, &unscoped_addr, &scopeid);
636 paddr = &unscoped_addr;
637 } else
638 paddr = &dst->sin6_addr;
639 ro->ro_nh = fib6_lookup(fibnum, paddr, scopeid, NHR_REF, flowid);
640 }
641 return (ro->ro_nh);
642 }
643
644 static struct nhop_object *
lookup_route(uint32_t fibnum,struct sockaddr_in6 * dst,struct route_in6 * ro,struct ip6_pktopts * opts,uint32_t flowid)645 lookup_route(uint32_t fibnum, struct sockaddr_in6 *dst, struct route_in6 *ro,
646 struct ip6_pktopts *opts, uint32_t flowid)
647 {
648 struct nhop_object *nh = NULL;
649
650 /*
651 * If the next hop address for the packet is specified by the caller,
652 * use it as the gateway.
653 */
654 if (opts && opts->ip6po_nexthop) {
655 struct route_in6 *ron = &opts->ip6po_nextroute;
656 struct sockaddr_in6 *sin6_next = satosin6(opts->ip6po_nexthop);
657
658 nh = cache_route(fibnum, sin6_next, ron, flowid);
659
660 /*
661 * The node identified by that address must be a
662 * neighbor of the sending host.
663 */
664 if (nh != NULL && (nh->nh_flags & NHF_GATEWAY) != 0)
665 nh = NULL;
666 } else if (ro != NULL) {
667 nh = cache_route(fibnum, dst, ro, flowid);
668 if (nh == NULL)
669 return (NULL);
670
671 /*
672 * Check if the outgoing interface conflicts with
673 * the interface specified by ipi6_ifindex (if specified).
674 */
675 struct in6_pktinfo *pi;
676 if (opts && (pi = opts->ip6po_pktinfo) != NULL && pi->ipi6_ifindex) {
677 if (nh->nh_aifp->if_index != pi->ipi6_ifindex)
678 nh = NULL;
679 }
680 }
681
682 return (nh);
683 }
684
685 /*
686 * Finds outgoing nexthop or the outgoing interface for the
687 * @dstsock.
688 * Return 0 on success and stores the lookup result in @retnh and @retifp
689 */
690 static int
selectroute(struct sockaddr_in6 * dstsock,struct ip6_pktopts * opts,struct ip6_moptions * mopts,struct route_in6 * ro,struct ifnet ** retifp,struct nhop_object ** retnh,int norouteok,u_int fibnum,uint32_t flowid)691 selectroute(struct sockaddr_in6 *dstsock, struct ip6_pktopts *opts,
692 struct ip6_moptions *mopts, struct route_in6 *ro,
693 struct ifnet **retifp, struct nhop_object **retnh, int norouteok,
694 u_int fibnum, uint32_t flowid)
695 {
696 int error = 0;
697 struct ifnet *ifp = NULL;
698 struct in6_pktinfo *pi = NULL;
699 struct in6_addr *dst = &dstsock->sin6_addr;
700
701 /* If the caller specify the outgoing interface explicitly, use it. */
702 if (opts && (pi = opts->ip6po_pktinfo) != NULL && pi->ipi6_ifindex) {
703 /* XXX boundary check is assumed to be already done. */
704 ifp = ifnet_byindex(pi->ipi6_ifindex);
705 if (ifp != NULL && (norouteok || IN6_IS_ADDR_MULTICAST(dst))) {
706 /*
707 * we do not have to check or get the route for
708 * multicast.
709 */
710 goto done;
711 } else
712 goto getroute;
713 }
714 /*
715 * If the destination address is a multicast address and the outgoing
716 * interface for the address is specified by the caller, use it.
717 */
718 if (IN6_IS_ADDR_MULTICAST(dst) &&
719 mopts != NULL && (ifp = mopts->im6o_multicast_ifp) != NULL) {
720 goto done; /* we do not need a route for multicast. */
721 }
722 /*
723 * If destination address is LLA or link- or node-local multicast,
724 * use it's embedded scope zone id to determine outgoing interface.
725 */
726 if (IN6_IS_ADDR_MC_LINKLOCAL(dst) ||
727 IN6_IS_ADDR_MC_NODELOCAL(dst)) {
728 uint32_t zoneid = ntohs(in6_getscope(dst));
729 if (zoneid > 0) {
730 ifp = in6_getlinkifnet(zoneid);
731 goto done;
732 }
733 }
734
735 getroute:;
736 struct nhop_object *nh = lookup_route(fibnum, dstsock, ro, opts, flowid);
737 if (nh != NULL) {
738 *retifp = nh->nh_aifp;
739 error = 0;
740 } else {
741 *retifp = NULL;
742 IP6STAT_INC(ip6s_noroute);
743 error = EHOSTUNREACH;
744 }
745 *retnh = nh;
746 return (error);
747
748 done:
749 if (ifp == NULL) {
750 /*
751 * This can happen if the caller did not pass a cached route
752 * nor any other hints. We treat this case an error.
753 */
754 error = EHOSTUNREACH;
755 }
756 if (error == EHOSTUNREACH)
757 IP6STAT_INC(ip6s_noroute);
758
759 *retifp = ifp;
760 *retnh = NULL;
761
762 return (error);
763 }
764
765 static int
in6_selectif(struct sockaddr_in6 * dstsock,struct ip6_pktopts * opts,struct ip6_moptions * mopts,struct ifnet ** retifp,struct ifnet * oifp,u_int fibnum)766 in6_selectif(struct sockaddr_in6 *dstsock, struct ip6_pktopts *opts,
767 struct ip6_moptions *mopts, struct ifnet **retifp,
768 struct ifnet *oifp, u_int fibnum)
769 {
770 int error;
771 struct route_in6 sro;
772 struct nhop_object *nh = NULL;
773 uint16_t nh_flags;
774
775 KASSERT(retifp != NULL, ("%s: retifp is NULL", __func__));
776
777 bzero(&sro, sizeof(sro));
778 nh_flags = 0;
779
780 error = selectroute(dstsock, opts, mopts, &sro, retifp, &nh, 1, fibnum, 0);
781
782 if (nh != NULL)
783 nh_flags = nh->nh_flags;
784 if (nh != NULL && nh == sro.ro_nh)
785 NH_FREE(nh);
786
787 if (error != 0) {
788 /* Help ND. See oifp comment in in6_selectsrc(). */
789 if (oifp != NULL && fibnum == RT_DEFAULT_FIB) {
790 *retifp = oifp;
791 error = 0;
792 }
793 return (error);
794 }
795
796 /*
797 * do not use a rejected or black hole route.
798 * XXX: this check should be done in the L2 output routine.
799 * However, if we skipped this check here, we'd see the following
800 * scenario:
801 * - install a rejected route for a scoped address prefix
802 * (like fe80::/10)
803 * - send a packet to a destination that matches the scoped prefix,
804 * with ambiguity about the scope zone.
805 * - pick the outgoing interface from the route, and disambiguate the
806 * scope zone with the interface.
807 * - ip6_output() would try to get another route with the "new"
808 * destination, which may be valid.
809 * - we'd see no error on output.
810 * Although this may not be very harmful, it should still be confusing.
811 * We thus reject the case here.
812 */
813
814 if (nh_flags & (NHF_REJECT | NHF_BLACKHOLE)) {
815 error = (nh_flags & NHF_HOST ? EHOSTUNREACH : ENETUNREACH);
816 return (error);
817 }
818
819 return (0);
820 }
821
822 /* Public wrapper function to selectroute(). */
823 int
in6_selectroute(struct sockaddr_in6 * dstsock,struct ip6_pktopts * opts,struct ip6_moptions * mopts,struct route_in6 * ro,struct ifnet ** retifp,struct nhop_object ** retnh,u_int fibnum,uint32_t flowid)824 in6_selectroute(struct sockaddr_in6 *dstsock, struct ip6_pktopts *opts,
825 struct ip6_moptions *mopts, struct route_in6 *ro,
826 struct ifnet **retifp, struct nhop_object **retnh, u_int fibnum, uint32_t flowid)
827 {
828 MPASS(retifp != NULL);
829 MPASS(retnh != NULL);
830
831 return (selectroute(dstsock, opts, mopts, ro, retifp,
832 retnh, 0, fibnum, flowid));
833 }
834
835 /*
836 * Default hop limit selection. The precedence is as follows:
837 * 1. Hoplimit value specified via ioctl.
838 * 2. (If the outgoing interface is detected) the current
839 * hop limit of the interface specified by router advertisement.
840 * 3. The system default hoplimit.
841 */
842 int
in6_selecthlim(struct inpcb * inp,struct ifnet * ifp)843 in6_selecthlim(struct inpcb *inp, struct ifnet *ifp)
844 {
845
846 if (inp && inp->in6p_hops >= 0)
847 return (inp->in6p_hops);
848 else if (ifp)
849 return (ND_IFINFO(ifp)->chlim);
850 else if (inp && !IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_faddr)) {
851 struct nhop_object *nh;
852 struct in6_addr dst;
853 uint32_t fibnum, scopeid;
854 int hlim;
855
856 fibnum = inp->inp_inc.inc_fibnum;
857 in6_splitscope(&inp->in6p_faddr, &dst, &scopeid);
858 nh = fib6_lookup(fibnum, &dst, scopeid, 0, 0);
859 if (nh != NULL) {
860 hlim = ND_IFINFO(nh->nh_ifp)->chlim;
861 return (hlim);
862 }
863 }
864 return (V_ip6_defhlim);
865 }
866
867 /*
868 * XXX: this is borrowed from in6_pcbbind(). If possible, we should
869 * share this function by all *bsd*...
870 */
871 int
in6_pcbsetport(struct in6_addr * laddr,struct inpcb * inp,struct ucred * cred)872 in6_pcbsetport(struct in6_addr *laddr, struct inpcb *inp, struct ucred *cred)
873 {
874 struct socket *so = inp->inp_socket;
875 u_int16_t lport = 0;
876 int error, lookupflags = 0;
877 #ifdef INVARIANTS
878 struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
879 #endif
880
881 INP_WLOCK_ASSERT(inp);
882 INP_HASH_WLOCK_ASSERT(pcbinfo);
883
884 error = prison_local_ip6(cred, laddr,
885 ((inp->inp_flags & IN6P_IPV6_V6ONLY) != 0));
886 if (error)
887 return(error);
888
889 /* XXX: this is redundant when called from in6_pcbbind */
890 if ((so->so_options & (SO_REUSEADDR|SO_REUSEPORT|SO_REUSEPORT_LB)) == 0)
891 lookupflags = INPLOOKUP_WILDCARD;
892
893 inp->inp_flags |= INP_ANONPORT;
894
895 error = in_pcb_lport(inp, NULL, &lport, cred, lookupflags);
896 if (error != 0)
897 return (error);
898
899 inp->inp_lport = lport;
900 if (in_pcbinshash(inp) != 0) {
901 inp->in6p_laddr = in6addr_any;
902 inp->inp_lport = 0;
903 return (EAGAIN);
904 }
905
906 return (0);
907 }
908
909 void
addrsel_policy_init(void)910 addrsel_policy_init(void)
911 {
912
913 init_policy_queue();
914
915 /* initialize the "last resort" policy */
916 bzero(&V_defaultaddrpolicy, sizeof(V_defaultaddrpolicy));
917 V_defaultaddrpolicy.label = ADDR_LABEL_NOTAPP;
918
919 if (!IS_DEFAULT_VNET(curvnet))
920 return;
921
922 ADDRSEL_LOCK_INIT();
923 ADDRSEL_SXLOCK_INIT();
924 }
925
926 static struct in6_addrpolicy *
lookup_addrsel_policy(struct sockaddr_in6 * key)927 lookup_addrsel_policy(struct sockaddr_in6 *key)
928 {
929 struct in6_addrpolicy *match = NULL;
930
931 ADDRSEL_LOCK();
932 match = match_addrsel_policy(key);
933
934 if (match == NULL)
935 match = &V_defaultaddrpolicy;
936 else
937 match->use++;
938 ADDRSEL_UNLOCK();
939
940 return (match);
941 }
942
943 /*
944 * Subroutines to manage the address selection policy table via sysctl.
945 */
946 struct walkarg {
947 struct sysctl_req *w_req;
948 };
949
950 static int in6_src_sysctl(SYSCTL_HANDLER_ARGS);
951 SYSCTL_DECL(_net_inet6_ip6);
952 static SYSCTL_NODE(_net_inet6_ip6, IPV6CTL_ADDRCTLPOLICY, addrctlpolicy,
953 CTLFLAG_RD | CTLFLAG_MPSAFE, in6_src_sysctl,
954 "");
955
956 static int
in6_src_sysctl(SYSCTL_HANDLER_ARGS)957 in6_src_sysctl(SYSCTL_HANDLER_ARGS)
958 {
959 struct walkarg w;
960
961 if (req->newptr)
962 return EPERM;
963
964 bzero(&w, sizeof(w));
965 w.w_req = req;
966
967 return (walk_addrsel_policy(dump_addrsel_policyent, &w));
968 }
969
970 int
in6_src_ioctl(u_long cmd,caddr_t data)971 in6_src_ioctl(u_long cmd, caddr_t data)
972 {
973 struct in6_addrpolicy ent0;
974
975 if (cmd != SIOCAADDRCTL_POLICY && cmd != SIOCDADDRCTL_POLICY)
976 return (EOPNOTSUPP); /* check for safety */
977
978 ent0 = *(struct in6_addrpolicy *)data;
979
980 if (ent0.label == ADDR_LABEL_NOTAPP)
981 return (EINVAL);
982 /* check if the prefix mask is consecutive. */
983 if (in6_mask2len(&ent0.addrmask.sin6_addr, NULL) < 0)
984 return (EINVAL);
985 /* clear trailing garbages (if any) of the prefix address. */
986 IN6_MASK_ADDR(&ent0.addr.sin6_addr, &ent0.addrmask.sin6_addr);
987 ent0.use = 0;
988
989 switch (cmd) {
990 case SIOCAADDRCTL_POLICY:
991 return (add_addrsel_policyent(&ent0));
992 case SIOCDADDRCTL_POLICY:
993 return (delete_addrsel_policyent(&ent0));
994 }
995
996 return (0); /* XXX: compromise compilers */
997 }
998
999 /*
1000 * The followings are implementation of the policy table using a
1001 * simple tail queue.
1002 * XXX such details should be hidden.
1003 * XXX implementation using binary tree should be more efficient.
1004 */
1005 struct addrsel_policyent {
1006 TAILQ_ENTRY(addrsel_policyent) ape_entry;
1007 struct in6_addrpolicy ape_policy;
1008 };
1009
1010 TAILQ_HEAD(addrsel_policyhead, addrsel_policyent);
1011
1012 VNET_DEFINE_STATIC(struct addrsel_policyhead, addrsel_policytab);
1013 #define V_addrsel_policytab VNET(addrsel_policytab)
1014
1015 static void
init_policy_queue(void)1016 init_policy_queue(void)
1017 {
1018
1019 TAILQ_INIT(&V_addrsel_policytab);
1020 }
1021
1022 static int
add_addrsel_policyent(struct in6_addrpolicy * newpolicy)1023 add_addrsel_policyent(struct in6_addrpolicy *newpolicy)
1024 {
1025 struct addrsel_policyent *new, *pol;
1026
1027 new = malloc(sizeof(*new), M_IFADDR,
1028 M_WAITOK);
1029 ADDRSEL_XLOCK();
1030 ADDRSEL_LOCK();
1031
1032 /* duplication check */
1033 TAILQ_FOREACH(pol, &V_addrsel_policytab, ape_entry) {
1034 if (IN6_ARE_ADDR_EQUAL(&newpolicy->addr.sin6_addr,
1035 &pol->ape_policy.addr.sin6_addr) &&
1036 IN6_ARE_ADDR_EQUAL(&newpolicy->addrmask.sin6_addr,
1037 &pol->ape_policy.addrmask.sin6_addr)) {
1038 ADDRSEL_UNLOCK();
1039 ADDRSEL_XUNLOCK();
1040 free(new, M_IFADDR);
1041 return (EEXIST); /* or override it? */
1042 }
1043 }
1044
1045 bzero(new, sizeof(*new));
1046
1047 /* XXX: should validate entry */
1048 new->ape_policy = *newpolicy;
1049
1050 TAILQ_INSERT_TAIL(&V_addrsel_policytab, new, ape_entry);
1051 ADDRSEL_UNLOCK();
1052 ADDRSEL_XUNLOCK();
1053
1054 return (0);
1055 }
1056
1057 static int
delete_addrsel_policyent(struct in6_addrpolicy * key)1058 delete_addrsel_policyent(struct in6_addrpolicy *key)
1059 {
1060 struct addrsel_policyent *pol;
1061
1062 ADDRSEL_XLOCK();
1063 ADDRSEL_LOCK();
1064
1065 /* search for the entry in the table */
1066 TAILQ_FOREACH(pol, &V_addrsel_policytab, ape_entry) {
1067 if (IN6_ARE_ADDR_EQUAL(&key->addr.sin6_addr,
1068 &pol->ape_policy.addr.sin6_addr) &&
1069 IN6_ARE_ADDR_EQUAL(&key->addrmask.sin6_addr,
1070 &pol->ape_policy.addrmask.sin6_addr)) {
1071 break;
1072 }
1073 }
1074 if (pol == NULL) {
1075 ADDRSEL_UNLOCK();
1076 ADDRSEL_XUNLOCK();
1077 return (ESRCH);
1078 }
1079
1080 TAILQ_REMOVE(&V_addrsel_policytab, pol, ape_entry);
1081 ADDRSEL_UNLOCK();
1082 ADDRSEL_XUNLOCK();
1083 free(pol, M_IFADDR);
1084
1085 return (0);
1086 }
1087
1088 static int
walk_addrsel_policy(int (* callback)(struct in6_addrpolicy *,void *),void * w)1089 walk_addrsel_policy(int (*callback)(struct in6_addrpolicy *, void *), void *w)
1090 {
1091 struct addrsel_policyent *pol;
1092 int error = 0;
1093
1094 ADDRSEL_SLOCK();
1095 TAILQ_FOREACH(pol, &V_addrsel_policytab, ape_entry) {
1096 if ((error = (*callback)(&pol->ape_policy, w)) != 0) {
1097 ADDRSEL_SUNLOCK();
1098 return (error);
1099 }
1100 }
1101 ADDRSEL_SUNLOCK();
1102 return (error);
1103 }
1104
1105 static int
dump_addrsel_policyent(struct in6_addrpolicy * pol,void * arg)1106 dump_addrsel_policyent(struct in6_addrpolicy *pol, void *arg)
1107 {
1108 int error = 0;
1109 struct walkarg *w = arg;
1110
1111 error = SYSCTL_OUT(w->w_req, pol, sizeof(*pol));
1112
1113 return (error);
1114 }
1115
1116 static struct in6_addrpolicy *
match_addrsel_policy(struct sockaddr_in6 * key)1117 match_addrsel_policy(struct sockaddr_in6 *key)
1118 {
1119 struct addrsel_policyent *pent;
1120 struct in6_addrpolicy *bestpol = NULL, *pol;
1121 int matchlen, bestmatchlen = -1;
1122 u_char *mp, *ep, *k, *p, m;
1123
1124 TAILQ_FOREACH(pent, &V_addrsel_policytab, ape_entry) {
1125 matchlen = 0;
1126
1127 pol = &pent->ape_policy;
1128 mp = (u_char *)&pol->addrmask.sin6_addr;
1129 ep = mp + 16; /* XXX: scope field? */
1130 k = (u_char *)&key->sin6_addr;
1131 p = (u_char *)&pol->addr.sin6_addr;
1132 for (; mp < ep && *mp; mp++, k++, p++) {
1133 m = *mp;
1134 if ((*k & m) != *p)
1135 goto next; /* not match */
1136 if (m == 0xff) /* short cut for a typical case */
1137 matchlen += 8;
1138 else {
1139 while (m >= 0x80) {
1140 matchlen++;
1141 m <<= 1;
1142 }
1143 }
1144 }
1145
1146 /* matched. check if this is better than the current best. */
1147 if (bestpol == NULL ||
1148 matchlen > bestmatchlen) {
1149 bestpol = pol;
1150 bestmatchlen = matchlen;
1151 }
1152
1153 next:
1154 continue;
1155 }
1156
1157 return (bestpol);
1158 }
1159