in6_src.c revision 1.71 1 /* $NetBSD: in6_src.c,v 1.71 2016/10/31 02:50:31 ozaki-r Exp $ */
2 /* $KAME: in6_src.c,v 1.159 2005/10/19 01:40:32 t-momose Exp $ */
3
4 /*
5 * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
6 * All rights reserved.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. Neither the name of the project nor the names of its contributors
17 * may be used to endorse or promote products derived from this software
18 * without specific prior written permission.
19 *
20 * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30 * SUCH DAMAGE.
31 */
32
33 /*
34 * Copyright (c) 1982, 1986, 1991, 1993
35 * The Regents of the University of California. All rights reserved.
36 *
37 * Redistribution and use in source and binary forms, with or without
38 * modification, are permitted provided that the following conditions
39 * are met:
40 * 1. Redistributions of source code must retain the above copyright
41 * notice, this list of conditions and the following disclaimer.
42 * 2. Redistributions in binary form must reproduce the above copyright
43 * notice, this list of conditions and the following disclaimer in the
44 * documentation and/or other materials provided with the distribution.
45 * 3. All advertising materials mentioning features or use of this software
46 * must display the following acknowledgement:
47 * This product includes software developed by the University of
48 * California, Berkeley and its contributors.
49 * 4. Neither the name of the University nor the names of its contributors
50 * may be used to endorse or promote products derived from this software
51 * without specific prior written permission.
52 *
53 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
54 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
55 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
56 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
57 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
58 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
59 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
60 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
61 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
62 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
63 * SUCH DAMAGE.
64 *
65 * @(#)in_pcb.c 8.2 (Berkeley) 1/4/94
66 */
67
68 #include <sys/cdefs.h>
69 __KERNEL_RCSID(0, "$NetBSD: in6_src.c,v 1.71 2016/10/31 02:50:31 ozaki-r Exp $");
70
71 #ifdef _KERNEL_OPT
72 #include "opt_inet.h"
73 #endif
74
75 #include <sys/param.h>
76 #include <sys/systm.h>
77 #include <sys/malloc.h>
78 #include <sys/mbuf.h>
79 #include <sys/protosw.h>
80 #include <sys/socket.h>
81 #include <sys/socketvar.h>
82 #include <sys/ioctl.h>
83 #include <sys/errno.h>
84 #include <sys/time.h>
85 #include <sys/kernel.h>
86 #include <sys/proc.h>
87 #include <sys/kauth.h>
88
89 #include <net/if.h>
90 #include <net/if_types.h>
91 #include <net/route.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/portalgo.h>
99 #include <netinet6/in6_var.h>
100 #include <netinet/ip6.h>
101 #include <netinet6/in6_pcb.h>
102 #include <netinet6/ip6_var.h>
103 #include <netinet6/ip6_private.h>
104 #include <netinet6/nd6.h>
105 #include <netinet6/scope6_var.h>
106
107 #include <net/net_osdep.h>
108
109 #ifdef MIP6
110 #include <netinet6/mip6.h>
111 #include <netinet6/mip6_var.h>
112 #include "mip.h"
113 #if NMIP > 0
114 #include <net/if_mip.h>
115 #endif /* NMIP > 0 */
116 #endif /* MIP6 */
117
118 #include <netinet/tcp_vtw.h>
119
120 #define ADDR_LABEL_NOTAPP (-1)
121 struct in6_addrpolicy defaultaddrpolicy;
122
123 int ip6_prefer_tempaddr = 0;
124
125 static int selectroute(struct sockaddr_in6 *, struct ip6_pktopts *,
126 struct ip6_moptions *, struct route *, struct ifnet **, struct psref *,
127 struct rtentry **, int, int);
128 static int in6_selectif(struct sockaddr_in6 *, struct ip6_pktopts *,
129 struct ip6_moptions *, struct route *, struct ifnet **, struct psref *);
130
131 static struct in6_addrpolicy *lookup_addrsel_policy(struct sockaddr_in6 *);
132
133 static void init_policy_queue(void);
134 static int add_addrsel_policyent(struct in6_addrpolicy *);
135 static int delete_addrsel_policyent(struct in6_addrpolicy *);
136 static int walk_addrsel_policy(int (*)(struct in6_addrpolicy *, void *),
137 void *);
138 static int dump_addrsel_policyent(struct in6_addrpolicy *, void *);
139 static struct in6_addrpolicy *match_addrsel_policy(struct sockaddr_in6 *);
140
141 /*
142 * Return an IPv6 address, which is the most appropriate for a given
143 * destination and user specified options.
144 * If necessary, this function lookups the routing table and returns
145 * an entry to the caller for later use.
146 */
147 #if 0 /* diabled ad-hoc */
148 #define REPLACE(r) do {\
149 if ((r) < sizeof(ip6stat.ip6s_sources_rule) / \
150 sizeof(ip6stat.ip6s_sources_rule[0])) /* check for safety */ \
151 ip6stat.ip6s_sources_rule[(r)]++; \
152 /* printf("in6_selectsrc: replace %s with %s by %d\n", ia_best ? ip6_sprintf(&ia_best->ia_addr.sin6_addr) : "none", ip6_sprintf(&ia->ia_addr.sin6_addr), (r)); */ \
153 goto replace; \
154 } while(0)
155 #define NEXT(r) do {\
156 if ((r) < sizeof(ip6stat.ip6s_sources_rule) / \
157 sizeof(ip6stat.ip6s_sources_rule[0])) /* check for safety */ \
158 ip6stat.ip6s_sources_rule[(r)]++; \
159 /* printf("in6_selectsrc: keep %s against %s by %d\n", ia_best ? ip6_sprintf(&ia_best->ia_addr.sin6_addr) : "none", ip6_sprintf(&ia->ia_addr.sin6_addr), (r)); */ \
160 goto next; /* XXX: we can't use 'continue' here */ \
161 } while(0)
162 #define BREAK(r) do { \
163 if ((r) < sizeof(ip6stat.ip6s_sources_rule) / \
164 sizeof(ip6stat.ip6s_sources_rule[0])) /* check for safety */ \
165 ip6stat.ip6s_sources_rule[(r)]++; \
166 goto out; /* XXX: we can't use 'break' here */ \
167 } while(0)
168 #else
169 #define REPLACE(r) goto replace
170 #define NEXT(r) goto next
171 #define BREAK(r) goto out
172 #endif
173
174 struct in6_addr *
175 in6_selectsrc(struct sockaddr_in6 *dstsock, struct ip6_pktopts *opts,
176 struct ip6_moptions *mopts, struct route *ro, struct in6_addr *laddr,
177 struct ifnet **ifpp, struct psref *psref, int *errorp)
178 {
179 struct in6_addr dst;
180 struct ifnet *ifp = NULL;
181 struct in6_ifaddr *ia = NULL, *ia_best = NULL;
182 struct in6_pktinfo *pi = NULL;
183 int dst_scope = -1, best_scope = -1, best_matchlen = -1;
184 struct in6_addrpolicy *dst_policy = NULL, *best_policy = NULL;
185 u_int32_t odstzone;
186 int error;
187 int prefer_tempaddr;
188 #if defined(MIP6) && NMIP > 0
189 u_int8_t ip6po_usecoa = 0;
190 #endif /* MIP6 && NMIP > 0 */
191 struct psref local_psref;
192 struct in6_addr *ret_ia = NULL;
193 int bound = curlwp_bind();
194 #define PSREF (psref == NULL) ? &local_psref : psref
195 int s;
196
197 KASSERT((ifpp != NULL && psref != NULL) ||
198 (ifpp == NULL && psref == NULL));
199
200 dst = dstsock->sin6_addr; /* make a copy for local operation */
201 *errorp = 0;
202 if (ifpp)
203 *ifpp = NULL;
204
205 /*
206 * Try to determine the outgoing interface for the given destination.
207 * We do this regardless of whether the socket is bound, since the
208 * caller may need this information as a side effect of the call
209 * to this function (e.g., for identifying the appropriate scope zone
210 * ID).
211 */
212 error = in6_selectif(dstsock, opts, mopts, ro, &ifp, PSREF);
213 if (ifpp != NULL)
214 *ifpp = ifp;
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 struct sockaddr_in6 srcsock;
225 struct in6_ifaddr *ia6;
226 int _s;
227 struct ifaddr *ifa;
228
229 /*
230 * Determine the appropriate zone id of the source based on
231 * the zone of the destination and the outgoing interface.
232 * If the specified address is ambiguous wrt the scope zone,
233 * the interface must be specified; otherwise, ifa_ifwithaddr()
234 * will fail matching the address.
235 */
236 memset(&srcsock, 0, sizeof(srcsock));
237 srcsock.sin6_family = AF_INET6;
238 srcsock.sin6_len = sizeof(srcsock);
239 srcsock.sin6_addr = pi->ipi6_addr;
240 if (ifp) {
241 *errorp = in6_setscope(&srcsock.sin6_addr, ifp, NULL);
242 if (*errorp != 0)
243 goto exit;
244 }
245
246 _s = pserialize_read_enter();
247 ifa = ifa_ifwithaddr(sin6tosa(&srcsock));
248 if ((ia6 = ifatoia6(ifa)) == NULL ||
249 ia6->ia6_flags &
250 (IN6_IFF_ANYCAST | IN6_IFF_NOTREADY)) {
251 pserialize_read_exit(_s);
252 *errorp = EADDRNOTAVAIL;
253 goto exit;
254 }
255 pi->ipi6_addr = srcsock.sin6_addr; /* XXX: this overrides pi */
256 if (ifpp)
257 *ifpp = ifp;
258 ret_ia = &ia6->ia_addr.sin6_addr;
259 pserialize_read_exit(_s);
260 /* XXX don't return pointer */
261 goto exit;
262 }
263
264 /*
265 * If the socket has already bound the source, just use it. We don't
266 * care at the moment whether in6_selectif() succeeded above, even
267 * though it would eventually cause an error.
268 */
269 if (laddr && !IN6_IS_ADDR_UNSPECIFIED(laddr)) {
270 ret_ia = laddr;
271 goto exit;
272 }
273
274 /*
275 * The outgoing interface is crucial in the general selection procedure
276 * below. If it is not known at this point, we fail.
277 */
278 if (ifp == NULL) {
279 *errorp = error;
280 goto exit;
281 }
282
283 /*
284 * If the address is not yet determined, choose the best one based on
285 * the outgoing interface and the destination address.
286 */
287
288 #if defined(MIP6) && NMIP > 0
289 /*
290 * a caller can specify IP6PO_USECOA to not to use a home
291 * address. for example, the case that the neighbour
292 * unreachability detection to the global address.
293 */
294 if (opts != NULL &&
295 (opts->ip6po_flags & IP6PO_USECOA) != 0) {
296 ip6po_usecoa = 1;
297 }
298 #endif /* MIP6 && NMIP > 0 */
299
300 *errorp = in6_setscope(&dst, ifp, &odstzone);
301 if (*errorp != 0)
302 goto exit;
303
304 s = pserialize_read_enter();
305 IN6_ADDRLIST_READER_FOREACH(ia) {
306 int new_scope = -1, new_matchlen = -1;
307 struct in6_addrpolicy *new_policy = NULL;
308 u_int32_t srczone, osrczone, dstzone;
309 struct in6_addr src;
310 struct ifnet *ifp1 = ia->ia_ifp;
311
312 /*
313 * We'll never take an address that breaks the scope zone
314 * of the destination. We also skip an address if its zone
315 * does not contain the outgoing interface.
316 * XXX: we should probably use sin6_scope_id here.
317 */
318 if (in6_setscope(&dst, ifp1, &dstzone) ||
319 odstzone != dstzone) {
320 continue;
321 }
322 src = ia->ia_addr.sin6_addr;
323 if (in6_setscope(&src, ifp, &osrczone) ||
324 in6_setscope(&src, ifp1, &srczone) ||
325 osrczone != srczone) {
326 continue;
327 }
328
329 /* avoid unusable addresses */
330 if ((ia->ia6_flags &
331 (IN6_IFF_NOTREADY | IN6_IFF_ANYCAST | IN6_IFF_DETACHED))) {
332 continue;
333 }
334 if (!ip6_use_deprecated && IFA6_IS_DEPRECATED(ia))
335 continue;
336
337 #if defined(MIP6) && NMIP > 0
338 /* avoid unusable home addresses. */
339 if ((ia->ia6_flags & IN6_IFF_HOME) &&
340 !mip6_ifa6_is_addr_valid_hoa(ia))
341 continue;
342 #endif /* MIP6 && NMIP > 0 */
343
344 /* Rule 1: Prefer same address */
345 if (IN6_ARE_ADDR_EQUAL(&dst, &ia->ia_addr.sin6_addr)) {
346 ia_best = ia;
347 BREAK(1); /* there should be no better candidate */
348 }
349
350 if (ia_best == NULL)
351 REPLACE(0);
352
353 /* Rule 2: Prefer appropriate scope */
354 if (dst_scope < 0)
355 dst_scope = in6_addrscope(&dst);
356 new_scope = in6_addrscope(&ia->ia_addr.sin6_addr);
357 if (IN6_ARE_SCOPE_CMP(best_scope, new_scope) < 0) {
358 if (IN6_ARE_SCOPE_CMP(best_scope, dst_scope) < 0)
359 REPLACE(2);
360 NEXT(2);
361 } else if (IN6_ARE_SCOPE_CMP(new_scope, best_scope) < 0) {
362 if (IN6_ARE_SCOPE_CMP(new_scope, dst_scope) < 0)
363 NEXT(2);
364 REPLACE(2);
365 }
366
367 /*
368 * Rule 3: Avoid deprecated addresses. Note that the case of
369 * !ip6_use_deprecated is already rejected above.
370 */
371 if (!IFA6_IS_DEPRECATED(ia_best) && IFA6_IS_DEPRECATED(ia))
372 NEXT(3);
373 if (IFA6_IS_DEPRECATED(ia_best) && !IFA6_IS_DEPRECATED(ia))
374 REPLACE(3);
375
376 /* Rule 4: Prefer home addresses */
377 #if defined(MIP6) && NMIP > 0
378 if (!MIP6_IS_MN)
379 goto skip_rule4;
380
381 if ((ia_best->ia6_flags & IN6_IFF_HOME) == 0 &&
382 (ia->ia6_flags & IN6_IFF_HOME) == 0) {
383 /* both address are not home addresses. */
384 goto skip_rule4;
385 }
386
387 /*
388 * If SA is simultaneously a home address and care-of
389 * address and SB is not, then prefer SA. Similarly,
390 * if SB is simultaneously a home address and care-of
391 * address and SA is not, then prefer SB.
392 */
393 if (((ia_best->ia6_flags & IN6_IFF_HOME) != 0 &&
394 ia_best->ia_ifp->if_type != IFT_MIP)
395 &&
396 ((ia->ia6_flags & IN6_IFF_HOME) != 0 &&
397 ia->ia_ifp->if_type == IFT_MIP))
398 NEXT(4);
399 if (((ia_best->ia6_flags & IN6_IFF_HOME) != 0 &&
400 ia_best->ia_ifp->if_type == IFT_MIP)
401 &&
402 ((ia->ia6_flags & IN6_IFF_HOME) != 0 &&
403 ia->ia_ifp->if_type != IFT_MIP))
404 REPLACE(4);
405 if (ip6po_usecoa == 0) {
406 /*
407 * If SA is just a home address and SB is just
408 * a care-of address, then prefer
409 * SA. Similarly, if SB is just a home address
410 * and SA is just a care-of address, then
411 * prefer SB.
412 */
413 if ((ia_best->ia6_flags & IN6_IFF_HOME) != 0 &&
414 (ia->ia6_flags & IN6_IFF_HOME) == 0) {
415 NEXT(4);
416 }
417 if ((ia_best->ia6_flags & IN6_IFF_HOME) == 0 &&
418 (ia->ia6_flags & IN6_IFF_HOME) != 0) {
419 REPLACE(4);
420 }
421 } else {
422 /*
423 * a sender don't want to use a home address
424 * because:
425 *
426 * 1) we cannot use. (ex. NS or NA to global
427 * addresses.)
428 *
429 * 2) a user specified not to use.
430 * (ex. mip6control -u)
431 */
432 if ((ia_best->ia6_flags & IN6_IFF_HOME) == 0 &&
433 (ia->ia6_flags & IN6_IFF_HOME) != 0) {
434 /* XXX breaks stat */
435 NEXT(0);
436 }
437 if ((ia_best->ia6_flags & IN6_IFF_HOME) != 0 &&
438 (ia->ia6_flags & IN6_IFF_HOME) == 0) {
439 /* XXX breaks stat */
440 REPLACE(0);
441 }
442 }
443 skip_rule4:
444 #endif /* MIP6 && NMIP > 0 */
445
446 /* Rule 5: Prefer outgoing interface */
447 if (ia_best->ia_ifp == ifp && ia->ia_ifp != ifp)
448 NEXT(5);
449 if (ia_best->ia_ifp != ifp && ia->ia_ifp == ifp)
450 REPLACE(5);
451
452 /*
453 * Rule 6: Prefer matching label
454 * Note that best_policy should be non-NULL here.
455 */
456 if (dst_policy == NULL)
457 dst_policy = lookup_addrsel_policy(dstsock);
458 if (dst_policy->label != ADDR_LABEL_NOTAPP) {
459 new_policy = lookup_addrsel_policy(&ia->ia_addr);
460 if (dst_policy->label == best_policy->label &&
461 dst_policy->label != new_policy->label)
462 NEXT(6);
463 if (dst_policy->label != best_policy->label &&
464 dst_policy->label == new_policy->label)
465 REPLACE(6);
466 }
467
468 /*
469 * Rule 7: Prefer public addresses.
470 * We allow users to reverse the logic by configuring
471 * a sysctl variable, so that privacy conscious users can
472 * always prefer temporary addresses.
473 */
474 if (opts == NULL ||
475 opts->ip6po_prefer_tempaddr == IP6PO_TEMPADDR_SYSTEM) {
476 prefer_tempaddr = ip6_prefer_tempaddr;
477 } else if (opts->ip6po_prefer_tempaddr ==
478 IP6PO_TEMPADDR_NOTPREFER) {
479 prefer_tempaddr = 0;
480 } else
481 prefer_tempaddr = 1;
482 if (!(ia_best->ia6_flags & IN6_IFF_TEMPORARY) &&
483 (ia->ia6_flags & IN6_IFF_TEMPORARY)) {
484 if (prefer_tempaddr)
485 REPLACE(7);
486 else
487 NEXT(7);
488 }
489 if ((ia_best->ia6_flags & IN6_IFF_TEMPORARY) &&
490 !(ia->ia6_flags & IN6_IFF_TEMPORARY)) {
491 if (prefer_tempaddr)
492 NEXT(7);
493 else
494 REPLACE(7);
495 }
496
497 /*
498 * Rule 8: prefer addresses on alive interfaces.
499 * This is a KAME specific rule.
500 */
501 if ((ia_best->ia_ifp->if_flags & IFF_UP) &&
502 !(ia->ia_ifp->if_flags & IFF_UP))
503 NEXT(8);
504 if (!(ia_best->ia_ifp->if_flags & IFF_UP) &&
505 (ia->ia_ifp->if_flags & IFF_UP))
506 REPLACE(8);
507
508 /*
509 * Rule 9: prefer addresses on "preferred" interfaces.
510 * This is a KAME specific rule.
511 */
512 #ifdef notyet /* until introducing address selection */
513 #define NDI_BEST ND_IFINFO(ia_best->ia_ifp)
514 #define NDI_NEW ND_IFINFO(ia->ia_ifp)
515 if ((NDI_BEST->flags & ND6_IFF_PREFER_SOURCE) &&
516 !(NDI_NEW->flags & ND6_IFF_PREFER_SOURCE))
517 NEXT(9);
518 if (!(NDI_BEST->flags & ND6_IFF_PREFER_SOURCE) &&
519 (NDI_NEW->flags & ND6_IFF_PREFER_SOURCE))
520 REPLACE(9);
521 #undef NDI_BEST
522 #undef NDI_NEW
523 #endif
524
525 /*
526 * Rule 14: Use longest matching prefix.
527 * Note: in the address selection draft, this rule is
528 * documented as "Rule 8". However, since it is also
529 * documented that this rule can be overridden, we assign
530 * a large number so that it is easy to assign smaller numbers
531 * to more preferred rules.
532 */
533 new_matchlen = in6_matchlen(&ia->ia_addr.sin6_addr, &dst);
534 if (best_matchlen < new_matchlen)
535 REPLACE(14);
536 if (new_matchlen < best_matchlen)
537 NEXT(14);
538
539 /* Rule 15 is reserved. */
540
541 /*
542 * Last resort: just keep the current candidate.
543 * Or, do we need more rules?
544 */
545 continue;
546
547 replace:
548 ia_best = ia;
549 best_scope = (new_scope >= 0 ? new_scope :
550 in6_addrscope(&ia_best->ia_addr.sin6_addr));
551 best_policy = (new_policy ? new_policy :
552 lookup_addrsel_policy(&ia_best->ia_addr));
553 best_matchlen = (new_matchlen >= 0 ? new_matchlen :
554 in6_matchlen(&ia_best->ia_addr.sin6_addr,
555 &dst));
556
557 next:
558 continue;
559
560 out:
561 break;
562 }
563 pserialize_read_exit(s);
564
565 if ((ia = ia_best) == NULL) {
566 *errorp = EADDRNOTAVAIL;
567 goto exit;
568 }
569
570 ret_ia = &ia->ia_addr.sin6_addr;
571 exit:
572 if (ifpp == NULL)
573 if_put(ifp, PSREF);
574 curlwp_bindx(bound);
575 return ret_ia;
576 #undef PSREF
577 }
578 #undef REPLACE
579 #undef BREAK
580 #undef NEXT
581
582 static int
583 selectroute(struct sockaddr_in6 *dstsock, struct ip6_pktopts *opts,
584 struct ip6_moptions *mopts, struct route *ro, struct ifnet **retifp,
585 struct psref *psref, struct rtentry **retrt, int clone, int norouteok)
586 {
587 int error = 0;
588 struct ifnet *ifp = NULL;
589 struct rtentry *rt = NULL;
590 struct sockaddr_in6 *sin6_next;
591 struct in6_pktinfo *pi = NULL;
592 struct in6_addr *dst;
593 union {
594 struct sockaddr dst;
595 struct sockaddr_in6 dst6;
596 } u;
597
598 KASSERT(ro != NULL);
599 KASSERT(retifp != NULL && psref != NULL);
600 KASSERT(retrt != NULL);
601
602 dst = &dstsock->sin6_addr;
603
604 #if 0
605 if (dstsock->sin6_addr.s6_addr32[0] == 0 &&
606 dstsock->sin6_addr.s6_addr32[1] == 0 &&
607 !IN6_IS_ADDR_LOOPBACK(&dstsock->sin6_addr)) {
608 printf("in6_selectroute: strange destination %s\n",
609 ip6_sprintf(&dstsock->sin6_addr));
610 } else {
611 printf("in6_selectroute: destination = %s%%%d\n",
612 ip6_sprintf(&dstsock->sin6_addr),
613 dstsock->sin6_scope_id); /* for debug */
614 }
615 #endif
616
617 /* If the caller specify the outgoing interface explicitly, use it. */
618 if (opts && (pi = opts->ip6po_pktinfo) != NULL && pi->ipi6_ifindex) {
619 /* XXX boundary check is assumed to be already done. */
620 ifp = if_get_byindex(pi->ipi6_ifindex, psref);
621 if (ifp != NULL &&
622 (norouteok || IN6_IS_ADDR_MULTICAST(dst))) {
623 /*
624 * we do not have to check or get the route for
625 * multicast.
626 */
627 goto done;
628 } else {
629 if_put(ifp, psref);
630 ifp = NULL;
631 goto getroute;
632 }
633 }
634
635 /*
636 * If the destination address is a multicast address and the outgoing
637 * interface for the address is specified by the caller, use it.
638 */
639 if (IN6_IS_ADDR_MULTICAST(dst) && mopts != NULL) {
640 ifp = if_get_byindex(mopts->im6o_multicast_if_index, psref);
641 if (ifp != NULL)
642 goto done; /* we do not need a route for multicast. */
643 }
644
645 getroute:
646 /*
647 * If the next hop address for the packet is specified by the caller,
648 * use it as the gateway.
649 */
650 if (opts && opts->ip6po_nexthop) {
651 struct route *ron;
652
653 sin6_next = satosin6(opts->ip6po_nexthop);
654
655 /* at this moment, we only support AF_INET6 next hops */
656 if (sin6_next->sin6_family != AF_INET6) {
657 error = EAFNOSUPPORT; /* or should we proceed? */
658 goto done;
659 }
660
661 /*
662 * If the next hop is an IPv6 address, then the node identified
663 * by that address must be a neighbor of the sending host.
664 */
665 ron = &opts->ip6po_nextroute;
666 if ((rt = rtcache_lookup(ron, sin6tosa(sin6_next))) == NULL ||
667 (rt->rt_flags & RTF_GATEWAY) != 0 ||
668 !nd6_is_addr_neighbor(sin6_next, rt->rt_ifp)) {
669 rtcache_free(ron);
670 error = EHOSTUNREACH;
671 goto done;
672 }
673 ifp = rt->rt_ifp;
674 if (ifp != NULL) {
675 if (!if_is_deactivated(ifp))
676 if_acquire_NOMPSAFE(ifp, psref);
677 else
678 ifp = NULL;
679 }
680
681 /*
682 * When cloning is required, try to allocate a route to the
683 * destination so that the caller can store path MTU
684 * information.
685 */
686 if (!clone)
687 goto done;
688 }
689
690 /*
691 * Use a cached route if it exists and is valid, else try to allocate
692 * a new one. Note that we should check the address family of the
693 * cached destination, in case of sharing the cache with IPv4.
694 */
695 u.dst6 = *dstsock;
696 u.dst6.sin6_scope_id = 0;
697 rt = rtcache_lookup1(ro, &u.dst, clone);
698
699 /*
700 * do not care about the result if we have the nexthop
701 * explicitly specified.
702 */
703 if (opts && opts->ip6po_nexthop)
704 goto done;
705
706 if (rt == NULL)
707 error = EHOSTUNREACH;
708 else {
709 if_put(ifp, psref);
710 ifp = rt->rt_ifp;
711 if (ifp != NULL) {
712 if (!if_is_deactivated(ifp))
713 if_acquire_NOMPSAFE(ifp, psref);
714 else
715 ifp = NULL;
716 }
717 }
718
719 /*
720 * Check if the outgoing interface conflicts with
721 * the interface specified by ipi6_ifindex (if specified).
722 * Note that loopback interface is always okay.
723 * (this may happen when we are sending a packet to one of
724 * our own addresses.)
725 */
726 if (opts && opts->ip6po_pktinfo && opts->ip6po_pktinfo->ipi6_ifindex) {
727 if (!(ifp->if_flags & IFF_LOOPBACK) &&
728 ifp->if_index != opts->ip6po_pktinfo->ipi6_ifindex) {
729 error = EHOSTUNREACH;
730 goto done;
731 }
732 }
733
734 done:
735 if (ifp == NULL && rt == NULL) {
736 /*
737 * This can happen if the caller did not pass a cached route
738 * nor any other hints. We treat this case an error.
739 */
740 error = EHOSTUNREACH;
741 }
742 if (error == EHOSTUNREACH)
743 IP6_STATINC(IP6_STAT_NOROUTE);
744
745 *retifp = ifp;
746 *retrt = rt; /* rt may be NULL */
747
748 return (error);
749 }
750
751 static int
752 in6_selectif(struct sockaddr_in6 *dstsock, struct ip6_pktopts *opts,
753 struct ip6_moptions *mopts, struct route *ro, struct ifnet **retifp,
754 struct psref *psref)
755 {
756 int error, clone;
757 struct rtentry *rt = NULL;
758
759 KASSERT(retifp != NULL);
760 *retifp = NULL;
761
762 clone = IN6_IS_ADDR_MULTICAST(&dstsock->sin6_addr) ? 0 : 1;
763 if ((error = selectroute(dstsock, opts, mopts, ro, retifp, psref,
764 &rt, clone, 1)) != 0) {
765 return (error);
766 }
767
768 /*
769 * do not use a rejected or black hole route.
770 * XXX: this check should be done in the L2 output routine.
771 * However, if we skipped this check here, we'd see the following
772 * scenario:
773 * - install a rejected route for a scoped address prefix
774 * (like fe80::/10)
775 * - send a packet to a destination that matches the scoped prefix,
776 * with ambiguity about the scope zone.
777 * - pick the outgoing interface from the route, and disambiguate the
778 * scope zone with the interface.
779 * - ip6_output() would try to get another route with the "new"
780 * destination, which may be valid.
781 * - we'd see no error on output.
782 * Although this may not be very harmful, it should still be confusing.
783 * We thus reject the case here.
784 */
785 if (rt && (rt->rt_flags & (RTF_REJECT | RTF_BLACKHOLE)))
786 return (rt->rt_flags & RTF_HOST ? EHOSTUNREACH : ENETUNREACH);
787
788 /*
789 * Adjust the "outgoing" interface. If we're going to loop the packet
790 * back to ourselves, the ifp would be the loopback interface.
791 * However, we'd rather know the interface associated to the
792 * destination address (which should probably be one of our own
793 * addresses.)
794 */
795 if (rt && rt->rt_ifa && rt->rt_ifa->ifa_ifp &&
796 rt->rt_ifa->ifa_ifp != *retifp &&
797 !if_is_deactivated(rt->rt_ifa->ifa_ifp)) {
798 if_put(*retifp, psref);
799 *retifp = rt->rt_ifa->ifa_ifp;
800 if_acquire_NOMPSAFE(*retifp, psref);
801 }
802
803 return (0);
804 }
805
806 /*
807 * close - meaningful only for bsdi and freebsd.
808 */
809
810 int
811 in6_selectroute(struct sockaddr_in6 *dstsock, struct ip6_pktopts *opts,
812 struct ip6_moptions *mopts, struct route *ro, struct ifnet **retifp,
813 struct psref *psref, struct rtentry **retrt, int clone)
814 {
815 return selectroute(dstsock, opts, mopts, ro, retifp, psref,
816 retrt, clone, 0);
817 }
818
819 /*
820 * Default hop limit selection. The precedence is as follows:
821 * 1. Hoplimit value specified via ioctl.
822 * 2. (If the outgoing interface is detected) the current
823 * hop limit of the interface specified by router advertisement.
824 * 3. The system default hoplimit.
825 */
826 int
827 in6_selecthlim(struct in6pcb *in6p, struct ifnet *ifp)
828 {
829 if (in6p && in6p->in6p_hops >= 0)
830 return (in6p->in6p_hops);
831 else if (ifp)
832 return (ND_IFINFO(ifp)->chlim);
833 else
834 return (ip6_defhlim);
835 }
836
837 int
838 in6_selecthlim_rt(struct in6pcb *in6p)
839 {
840 struct rtentry *rt;
841
842 if (in6p == NULL)
843 return in6_selecthlim(in6p, NULL);
844
845 rt = rtcache_validate(&in6p->in6p_route);
846 if (rt != NULL)
847 return in6_selecthlim(in6p, rt->rt_ifp);
848 else
849 return in6_selecthlim(in6p, NULL);
850 }
851
852 /*
853 * Find an empty port and set it to the specified PCB.
854 */
855 int
856 in6_pcbsetport(struct sockaddr_in6 *sin6, struct in6pcb *in6p, struct lwp *l)
857 {
858 struct socket *so = in6p->in6p_socket;
859 struct inpcbtable *table = in6p->in6p_table;
860 u_int16_t lport, *lastport;
861 enum kauth_network_req req;
862 int error = 0;
863
864 if (in6p->in6p_flags & IN6P_LOWPORT) {
865 #ifndef IPNOPRIVPORTS
866 req = KAUTH_REQ_NETWORK_BIND_PRIVPORT;
867 #else
868 req = KAUTH_REQ_NETWORK_BIND_PORT;
869 #endif
870 lastport = &table->inpt_lastlow;
871 } else {
872 req = KAUTH_REQ_NETWORK_BIND_PORT;
873
874 lastport = &table->inpt_lastport;
875 }
876
877 /* XXX-kauth: KAUTH_REQ_NETWORK_BIND_AUTOASSIGN_{,PRIV}PORT */
878 error = kauth_authorize_network(l->l_cred, KAUTH_NETWORK_BIND, req, so,
879 sin6, NULL);
880 if (error)
881 return (EACCES);
882
883 /*
884 * Use RFC6056 randomized port selection
885 */
886 error = portalgo_randport(&lport, &in6p->in6p_head, l->l_cred);
887 if (error)
888 return error;
889
890 in6p->in6p_flags |= IN6P_ANONPORT;
891 *lastport = lport;
892 in6p->in6p_lport = htons(lport);
893 in6_pcbstate(in6p, IN6P_BOUND);
894 return (0); /* success */
895 }
896
897 void
898 addrsel_policy_init(void)
899 {
900 init_policy_queue();
901
902 /* initialize the "last resort" policy */
903 memset(&defaultaddrpolicy, 0, sizeof(defaultaddrpolicy));
904 defaultaddrpolicy.label = ADDR_LABEL_NOTAPP;
905 }
906
907 static struct in6_addrpolicy *
908 lookup_addrsel_policy(struct sockaddr_in6 *key)
909 {
910 struct in6_addrpolicy *match = NULL;
911
912 match = match_addrsel_policy(key);
913
914 if (match == NULL)
915 match = &defaultaddrpolicy;
916 else
917 match->use++;
918
919 return (match);
920 }
921
922 /*
923 * Subroutines to manage the address selection policy table via sysctl.
924 */
925 struct sel_walkarg {
926 size_t w_total;
927 size_t w_given;
928 void * w_where;
929 void *w_limit;
930 };
931
932 int sysctl_net_inet6_addrctlpolicy(SYSCTLFN_ARGS);
933 int
934 sysctl_net_inet6_addrctlpolicy(SYSCTLFN_ARGS)
935 {
936 int error = 0;
937 int s;
938
939 s = splsoftnet();
940
941 if (newp) {
942 error = EPERM;
943 goto end;
944 }
945 if (oldp && oldlenp == NULL) {
946 error = EINVAL;
947 goto end;
948 }
949 if (oldp || oldlenp) {
950 struct sel_walkarg w;
951 size_t oldlen = *oldlenp;
952
953 memset(&w, 0, sizeof(w));
954 w.w_given = oldlen;
955 w.w_where = oldp;
956 if (oldp)
957 w.w_limit = (char *)oldp + oldlen;
958
959 error = walk_addrsel_policy(dump_addrsel_policyent, &w);
960
961 *oldlenp = w.w_total;
962 if (oldp && w.w_total > oldlen && error == 0)
963 error = ENOMEM;
964 }
965
966 end:
967 splx(s);
968
969 return (error);
970 }
971
972 int
973 in6_src_ioctl(u_long cmd, void *data)
974 {
975 int i;
976 struct in6_addrpolicy ent0;
977
978 if (cmd != SIOCAADDRCTL_POLICY && cmd != SIOCDADDRCTL_POLICY)
979 return (EOPNOTSUPP); /* check for safety */
980
981 ent0 = *(struct in6_addrpolicy *)data;
982
983 if (ent0.label == ADDR_LABEL_NOTAPP)
984 return (EINVAL);
985 /* check if the prefix mask is consecutive. */
986 if (in6_mask2len(&ent0.addrmask.sin6_addr, NULL) < 0)
987 return (EINVAL);
988 /* clear trailing garbages (if any) of the prefix address. */
989 for (i = 0; i < 4; i++) {
990 ent0.addr.sin6_addr.s6_addr32[i] &=
991 ent0.addrmask.sin6_addr.s6_addr32[i];
992 }
993 ent0.use = 0;
994
995 switch (cmd) {
996 case SIOCAADDRCTL_POLICY:
997 return (add_addrsel_policyent(&ent0));
998 case SIOCDADDRCTL_POLICY:
999 return (delete_addrsel_policyent(&ent0));
1000 }
1001
1002 return (0); /* XXX: compromise compilers */
1003 }
1004
1005 /*
1006 * The followings are implementation of the policy table using a
1007 * simple tail queue.
1008 * XXX such details should be hidden.
1009 * XXX implementation using binary tree should be more efficient.
1010 */
1011 struct addrsel_policyent {
1012 TAILQ_ENTRY(addrsel_policyent) ape_entry;
1013 struct in6_addrpolicy ape_policy;
1014 };
1015
1016 TAILQ_HEAD(addrsel_policyhead, addrsel_policyent);
1017
1018 struct addrsel_policyhead addrsel_policytab;
1019
1020 static void
1021 init_policy_queue(void)
1022 {
1023 TAILQ_INIT(&addrsel_policytab);
1024 }
1025
1026 static int
1027 add_addrsel_policyent(struct in6_addrpolicy *newpolicy)
1028 {
1029 struct addrsel_policyent *newpol, *pol;
1030
1031 /* duplication check */
1032 TAILQ_FOREACH(pol, &addrsel_policytab, ape_entry) {
1033 if (IN6_ARE_ADDR_EQUAL(&newpolicy->addr.sin6_addr,
1034 &pol->ape_policy.addr.sin6_addr) &&
1035 IN6_ARE_ADDR_EQUAL(&newpolicy->addrmask.sin6_addr,
1036 &pol->ape_policy.addrmask.sin6_addr)) {
1037 return (EEXIST); /* or override it? */
1038 }
1039 }
1040
1041 newpol = malloc(sizeof(*newpol), M_IFADDR, M_WAITOK|M_ZERO);
1042
1043 /* XXX: should validate entry */
1044 newpol->ape_policy = *newpolicy;
1045
1046 TAILQ_INSERT_TAIL(&addrsel_policytab, newpol, ape_entry);
1047
1048 return (0);
1049 }
1050
1051 static int
1052 delete_addrsel_policyent(struct in6_addrpolicy *key)
1053 {
1054 struct addrsel_policyent *pol;
1055
1056 /* search for the entry in the table */
1057 for (pol = TAILQ_FIRST(&addrsel_policytab); pol;
1058 pol = TAILQ_NEXT(pol, ape_entry)) {
1059 if (IN6_ARE_ADDR_EQUAL(&key->addr.sin6_addr,
1060 &pol->ape_policy.addr.sin6_addr) &&
1061 IN6_ARE_ADDR_EQUAL(&key->addrmask.sin6_addr,
1062 &pol->ape_policy.addrmask.sin6_addr)) {
1063 break;
1064 }
1065 }
1066 if (pol == NULL) {
1067 return (ESRCH);
1068 }
1069
1070 TAILQ_REMOVE(&addrsel_policytab, pol, ape_entry);
1071
1072 return (0);
1073 }
1074
1075 static int
1076 walk_addrsel_policy(int (*callback)(struct in6_addrpolicy *, void *), void *w)
1077 {
1078 struct addrsel_policyent *pol;
1079 int error = 0;
1080
1081 TAILQ_FOREACH(pol, &addrsel_policytab, ape_entry) {
1082 if ((error = (*callback)(&pol->ape_policy, w)) != 0)
1083 return error;
1084 }
1085
1086 return error;
1087 }
1088
1089 static int
1090 dump_addrsel_policyent(struct in6_addrpolicy *pol, void *arg)
1091 {
1092 int error = 0;
1093 struct sel_walkarg *w = arg;
1094
1095 if (w->w_where && (char *)w->w_where + sizeof(*pol) <= (char *)w->w_limit) {
1096 if ((error = copyout(pol, w->w_where, sizeof(*pol))) != 0)
1097 return error;
1098 w->w_where = (char *)w->w_where + sizeof(*pol);
1099 }
1100 w->w_total += sizeof(*pol);
1101
1102 return error;
1103 }
1104
1105 static struct in6_addrpolicy *
1106 match_addrsel_policy(struct sockaddr_in6 *key)
1107 {
1108 struct addrsel_policyent *pent;
1109 struct in6_addrpolicy *bestpol = NULL, *pol;
1110 int matchlen, bestmatchlen = -1;
1111 u_char *mp, *ep, *k, *p, m;
1112
1113 for (pent = TAILQ_FIRST(&addrsel_policytab); pent;
1114 pent = TAILQ_NEXT(pent, ape_entry)) {
1115 matchlen = 0;
1116
1117 pol = &pent->ape_policy;
1118 mp = (u_char *)&pol->addrmask.sin6_addr;
1119 ep = mp + 16; /* XXX: scope field? */
1120 k = (u_char *)&key->sin6_addr;
1121 p = (u_char *)&pol->addr.sin6_addr;
1122 for (; mp < ep && *mp; mp++, k++, p++) {
1123 m = *mp;
1124 if ((*k & m) != *p)
1125 goto next; /* not match */
1126 if (m == 0xff) /* short cut for a typical case */
1127 matchlen += 8;
1128 else {
1129 while (m >= 0x80) {
1130 matchlen++;
1131 m <<= 1;
1132 }
1133 }
1134 }
1135
1136 /* matched. check if this is better than the current best. */
1137 if (bestpol == NULL ||
1138 matchlen > bestmatchlen) {
1139 bestpol = pol;
1140 bestmatchlen = matchlen;
1141 }
1142
1143 next:
1144 continue;
1145 }
1146
1147 return (bestpol);
1148 }
1149