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