xref: /src/sys/netinet6/nd6_rtr.c (revision 0616521adc35cb252cb399f1147f103284f0f188)
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: nd6_rtr.c,v 1.111 2001/04/27 01:37:15 jinmei Exp $
32  */
33 
34 #include "opt_inet.h"
35 #include "opt_inet6.h"
36 
37 #include <sys/param.h>
38 #include <sys/systm.h>
39 #include <sys/malloc.h>
40 #include <sys/mbuf.h>
41 #include <sys/refcount.h>
42 #include <sys/socket.h>
43 #include <sys/sockio.h>
44 #include <sys/time.h>
45 #include <sys/kernel.h>
46 #include <sys/lock.h>
47 #include <sys/errno.h>
48 #include <sys/rmlock.h>
49 #include <sys/rwlock.h>
50 #include <sys/sysctl.h>
51 #include <sys/syslog.h>
52 #include <sys/queue.h>
53 #include <sys/random.h>
54 
55 #include <net/if.h>
56 #include <net/if_var.h>
57 #include <net/if_private.h>
58 #include <net/if_types.h>
59 #include <net/if_dl.h>
60 #include <net/route.h>
61 #include <net/route/nhop.h>
62 #include <net/route/route_ctl.h>
63 #include <net/radix.h>
64 #include <net/vnet.h>
65 
66 #include <netinet/in.h>
67 #include <net/if_llatbl.h>
68 #include <netinet6/in6_var.h>
69 #include <netinet6/in6_ifattach.h>
70 #include <netinet/ip6.h>
71 #include <netinet6/ip6_var.h>
72 #include <netinet6/nd6.h>
73 #include <netinet/icmp6.h>
74 #include <netinet6/scope6_var.h>
75 
76 #include <machine/atomic.h>
77 
78 MALLOC_DEFINE(M_IP6NDP, "ip6ndp", "IPv6 Neighbor Discovery");
79 
80 static struct nd_defrouter *defrtrlist_update(struct nd_defrouter *);
81 static int prelist_update(struct nd_prefixctl *, struct nd_defrouter *,
82     bool, int);
83 static int nd6_prefix_onlink(struct nd_prefix *);
84 static int in6_get_tmp_ifid(struct in6_aliasreq *);
85 
86 TAILQ_HEAD(nd6_drhead, nd_defrouter);
87 VNET_DEFINE_STATIC(struct nd6_drhead, nd6_defrouter);
88 #define	V_nd6_defrouter			VNET(nd6_defrouter)
89 
90 VNET_DECLARE(int, nd6_recalc_reachtm_interval);
91 #define	V_nd6_recalc_reachtm_interval	VNET(nd6_recalc_reachtm_interval)
92 
93 VNET_DEFINE_STATIC(struct ifnet *, nd6_defifp);
94 VNET_DEFINE(int, nd6_defifindex);
95 #define	V_nd6_defifp			VNET(nd6_defifp)
96 
97 VNET_DEFINE(int, ip6_use_tempaddr) = 0;
98 VNET_DEFINE(bool, ip6_use_stableaddr) = 1;
99 
100 VNET_DEFINE(int, ip6_desync_factor);
101 VNET_DEFINE(uint32_t, ip6_temp_max_desync_factor) = TEMP_MAX_DESYNC_FACTOR_BASE;
102 VNET_DEFINE(u_int32_t, ip6_temp_preferred_lifetime) = DEF_TEMP_PREFERRED_LIFETIME;
103 VNET_DEFINE(u_int32_t, ip6_temp_valid_lifetime) = DEF_TEMP_VALID_LIFETIME;
104 
105 VNET_DEFINE(int, ip6_temp_regen_advance) = TEMPADDR_REGEN_ADVANCE;
106 
107 #ifdef EXPERIMENTAL
108 VNET_DEFINE_STATIC(int, nd6_ignore_ipv6_only_ra) = 1;
109 #define	V_nd6_ignore_ipv6_only_ra	VNET(nd6_ignore_ipv6_only_ra)
110 SYSCTL_INT(_net_inet6_icmp6, OID_AUTO,
111     nd6_ignore_ipv6_only_ra, CTLFLAG_VNET | CTLFLAG_RW,
112     &VNET_NAME(nd6_ignore_ipv6_only_ra), 0,
113     "Ignore the 'IPv6-Only flag' in RA messages in compliance with "
114     "draft-ietf-6man-ipv6only-flag");
115 #endif
116 
117 /* RTPREF_MEDIUM has to be 0! */
118 #define RTPREF_HIGH	1
119 #define RTPREF_MEDIUM	0
120 #define RTPREF_LOW	(-1)
121 #define RTPREF_RESERVED	(-2)
122 #define RTPREF_INVALID	(-3)	/* internal */
123 
124 static void
defrouter_ref(struct nd_defrouter * dr)125 defrouter_ref(struct nd_defrouter *dr)
126 {
127 
128 	refcount_acquire(&dr->refcnt);
129 }
130 
131 void
defrouter_rele(struct nd_defrouter * dr)132 defrouter_rele(struct nd_defrouter *dr)
133 {
134 
135 	if (refcount_release(&dr->refcnt))
136 		free(dr, M_IP6NDP);
137 }
138 
139 /*
140  * Remove a router from the global list and optionally stash it in a
141  * caller-supplied queue.
142  */
143 static void
defrouter_unlink(struct nd_defrouter * dr,struct nd6_drhead * drq)144 defrouter_unlink(struct nd_defrouter *dr, struct nd6_drhead *drq)
145 {
146 
147 	ND6_WLOCK_ASSERT();
148 
149 	TAILQ_REMOVE(&V_nd6_defrouter, dr, dr_entry);
150 	V_nd6_list_genid++;
151 	if (drq != NULL)
152 		TAILQ_INSERT_TAIL(drq, dr, dr_entry);
153 }
154 
155 /*
156  * Receive Router Solicitation Message - just for routers.
157  * Router solicitation/advertisement is mostly managed by userland program
158  * (rtadvd) so here we have no function like nd6_ra_output().
159  *
160  * Based on RFC 2461
161  */
162 void
nd6_rs_input(struct mbuf * m,int off,int icmp6len)163 nd6_rs_input(struct mbuf *m, int off, int icmp6len)
164 {
165 	struct ifnet *ifp;
166 	struct ip6_hdr *ip6;
167 	struct nd_router_solicit *nd_rs;
168 	struct in6_addr saddr6;
169 	union nd_opts ndopts;
170 	char ip6bufs[INET6_ADDRSTRLEN], ip6bufd[INET6_ADDRSTRLEN];
171 	char *lladdr;
172 	int lladdrlen;
173 
174 	ifp = m->m_pkthdr.rcvif;
175 
176 	/*
177 	 * Accept RS only when V_ip6_forwarding=1 and the interface has
178 	 * no ND6_IFF_ACCEPT_RTADV.
179 	 */
180 	if (!V_ip6_forwarding || ifp->if_inet6->nd_flags & ND6_IFF_ACCEPT_RTADV)
181 		goto freeit;
182 
183 	/* RFC 6980: Nodes MUST silently ignore fragments */
184 	if(m->m_flags & M_FRAGMENTED)
185 		goto freeit;
186 
187 	/* Sanity checks */
188 	ip6 = mtod(m, struct ip6_hdr *);
189 	if (__predict_false(ip6->ip6_hlim != 255)) {
190 		ICMP6STAT_INC(icp6s_invlhlim);
191 		nd6log((LOG_ERR,
192 		    "%s: invalid hlim (%d) from %s to %s on %s\n", __func__,
193 		    ip6->ip6_hlim, ip6_sprintf(ip6bufs, &ip6->ip6_src),
194 		    ip6_sprintf(ip6bufd, &ip6->ip6_dst), if_name(ifp)));
195 		goto bad;
196 	}
197 
198 	/*
199 	 * Don't update the neighbor cache, if src = ::.
200 	 * This indicates that the src has no IP address assigned yet.
201 	 */
202 	saddr6 = ip6->ip6_src;
203 	if (IN6_IS_ADDR_UNSPECIFIED(&saddr6))
204 		goto freeit;
205 
206 	if (m->m_len < off + icmp6len) {
207 		m = m_pullup(m, off + icmp6len);
208 		if (m == NULL) {
209 			IP6STAT_INC(ip6s_exthdrtoolong);
210 			return;
211 		}
212 	}
213 	ip6 = mtod(m, struct ip6_hdr *);
214 	nd_rs = (struct nd_router_solicit *)((caddr_t)ip6 + off);
215 
216 	icmp6len -= sizeof(*nd_rs);
217 	nd6_option_init(nd_rs + 1, icmp6len, &ndopts);
218 	if (nd6_options(&ndopts) < 0) {
219 		nd6log((LOG_INFO,
220 		    "%s: invalid ND option, ignored\n", __func__));
221 		/* nd6_options have incremented stats */
222 		goto freeit;
223 	}
224 
225 	lladdr = NULL;
226 	lladdrlen = 0;
227 	if (ndopts.nd_opts_src_lladdr) {
228 		lladdr = (char *)(ndopts.nd_opts_src_lladdr + 1);
229 		lladdrlen = ndopts.nd_opts_src_lladdr->nd_opt_len << 3;
230 	}
231 
232 	if (lladdr && ((ifp->if_addrlen + 2 + 7) & ~7) != lladdrlen) {
233 		nd6log((LOG_INFO,
234 		    "%s: lladdrlen mismatch for %s (if %d, RS packet %d)\n",
235 		    __func__, ip6_sprintf(ip6bufs, &saddr6),
236 		    ifp->if_addrlen, lladdrlen - 2));
237 		goto bad;
238 	}
239 
240 	nd6_cache_lladdr(ifp, &saddr6, lladdr, lladdrlen, ND_ROUTER_SOLICIT, 0);
241 
242  freeit:
243 	m_freem(m);
244 	return;
245 
246  bad:
247 	ICMP6STAT_INC(icp6s_badrs);
248 	m_freem(m);
249 }
250 
251 #ifdef EXPERIMENTAL
252 /*
253  * An initial update routine for draft-ietf-6man-ipv6only-flag.
254  * We need to iterate over all default routers for the given
255  * interface to see whether they are all advertising the "S"
256  * (IPv6-Only) flag.  If they do set, otherwise unset, the
257  * interface flag we later use to filter on.
258  *
259  * XXXGL: The use of IF_ADDR_WLOCK (previously it was IF_AFDATA_LOCK) in this
260  * function is quite strange.
261  */
262 static void
defrtr_ipv6_only_ifp(struct ifnet * ifp)263 defrtr_ipv6_only_ifp(struct ifnet *ifp)
264 {
265 	struct nd_defrouter *dr;
266 	bool ipv6_only, ipv6_only_old;
267 #ifdef INET
268 	struct epoch_tracker et;
269 	struct ifaddr *ifa;
270 	bool has_ipv4_addr;
271 #endif
272 
273 	if (V_nd6_ignore_ipv6_only_ra != 0)
274 		return;
275 
276 	ipv6_only = true;
277 	ND6_RLOCK();
278 	TAILQ_FOREACH(dr, &V_nd6_defrouter, dr_entry)
279 		if (dr->ifp == ifp &&
280 		    (dr->raflags & ND_RA_FLAG_IPV6_ONLY) == 0)
281 			ipv6_only = false;
282 	ND6_RUNLOCK();
283 
284 	IF_ADDR_WLOCK(ifp);
285 	ipv6_only_old = ifp->if_inet6->nd_flags & ND6_IFF_IPV6_ONLY;
286 	IF_ADDR_WUNLOCK(ifp);
287 
288 	/* If nothing changed, we have an early exit. */
289 	if (ipv6_only == ipv6_only_old)
290 		return;
291 
292 #ifdef INET
293 	/*
294 	 * Should we want to set the IPV6-ONLY flag, check if the
295 	 * interface has a non-0/0 and non-link-local IPv4 address
296 	 * configured on it.  If it has we will assume working
297 	 * IPv4 operations and will clear the interface flag.
298 	 */
299 	has_ipv4_addr = false;
300 	if (ipv6_only) {
301 		NET_EPOCH_ENTER(et);
302 		CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
303 			if (ifa->ifa_addr->sa_family != AF_INET)
304 				continue;
305 			if (in_canforward(
306 			    satosin(ifa->ifa_addr)->sin_addr)) {
307 				has_ipv4_addr = true;
308 				break;
309 			}
310 		}
311 		NET_EPOCH_EXIT(et);
312 	}
313 	if (ipv6_only && has_ipv4_addr) {
314 		log(LOG_NOTICE, "%s rcvd RA w/ IPv6-Only flag set but has IPv4 "
315 		    "configured, ignoring IPv6-Only flag.\n", ifp->if_xname);
316 		ipv6_only = false;
317 	}
318 #endif
319 
320 	IF_ADDR_WLOCK(ifp);
321 	if (ipv6_only)
322 		ifp->if_inet6->nd_flags |= ND6_IFF_IPV6_ONLY;
323 	else
324 		ifp->if_inet6->nd_flags &= ~ND6_IFF_IPV6_ONLY;
325 	IF_ADDR_WUNLOCK(ifp);
326 
327 #ifdef notyet
328 	/* Send notification of flag change. */
329 #endif
330 }
331 
332 static void
defrtr_ipv6_only_ipf_down(struct ifnet * ifp)333 defrtr_ipv6_only_ipf_down(struct ifnet *ifp)
334 {
335 
336 	IF_ADDR_WLOCK(ifp);
337 	ifp->if_inet6->nd_flags &= ~ND6_IFF_IPV6_ONLY;
338 	IF_ADDR_WUNLOCK(ifp);
339 }
340 #endif	/* EXPERIMENTAL */
341 
342 void
nd6_ifnet_link_event(void * arg __unused,struct ifnet * ifp,int linkstate)343 nd6_ifnet_link_event(void *arg __unused, struct ifnet *ifp, int linkstate)
344 {
345 
346 	/*
347 	 * XXX-BZ we might want to trigger re-evaluation of our default router
348 	 * availability. E.g., on link down the default router might be
349 	 * unreachable but a different interface might still have connectivity.
350 	 */
351 
352 #ifdef EXPERIMENTAL
353 	if (linkstate == LINK_STATE_DOWN)
354 		defrtr_ipv6_only_ipf_down(ifp);
355 #endif
356 }
357 
358 static void
nd6_ra_opt_pi(struct nd_opt_hdr * pt,struct ifnet * ifp,struct nd_router_advert * nd_ra,struct nd_defrouter * dr,bool auth,bool mcast)359 nd6_ra_opt_pi(struct nd_opt_hdr *pt, struct ifnet *ifp,
360     struct nd_router_advert *nd_ra, struct nd_defrouter *dr,
361     bool auth, bool mcast)
362 {
363 	struct nd_opt_prefix_info *pi = NULL;
364 	struct nd_prefixctl pr;
365 	char ip6bufs[INET6_ADDRSTRLEN];
366 
367 	if (pt->nd_opt_type != ND_OPT_PREFIX_INFORMATION)
368 		return;
369 
370 	pi = (struct nd_opt_prefix_info *)pt;
371 	if (pi->nd_opt_pi_len != 4) {
372 		nd6log((LOG_INFO,
373 		    "%s: invalid option len %d for prefix "
374 		    "information option, ignored\n", __func__,
375 		    pi->nd_opt_pi_len));
376 		return;
377 	}
378 
379 	if (pi->nd_opt_pi_prefix_len > 128) {
380 		nd6log((LOG_INFO,
381 		    "%s: invalid prefix len %d for prefix "
382 		    "information option, ignored\n", __func__,
383 		    pi->nd_opt_pi_prefix_len));
384 		return;
385 	}
386 
387 	if (IN6_IS_ADDR_MULTICAST(&pi->nd_opt_pi_prefix)
388 	    || IN6_IS_ADDR_LINKLOCAL(&pi->nd_opt_pi_prefix)) {
389 		nd6log((LOG_INFO,
390 		    "%s: invalid prefix %s, ignored\n",
391 		    __func__, ip6_sprintf(ip6bufs,
392 			&pi->nd_opt_pi_prefix)));
393 		return;
394 	}
395 
396 	bzero(&pr, sizeof(pr));
397 	pr.ndpr_prefix.sin6_family = AF_INET6;
398 	pr.ndpr_prefix.sin6_len = sizeof(pr.ndpr_prefix);
399 	pr.ndpr_prefix.sin6_addr = pi->nd_opt_pi_prefix;
400 	pr.ndpr_ifp = ifp;
401 
402 	pr.ndpr_raf_onlink = (pi->nd_opt_pi_flags_reserved &
403 	    ND_OPT_PI_FLAG_ONLINK) ? 1 : 0;
404 	pr.ndpr_raf_auto = (pi->nd_opt_pi_flags_reserved &
405 	    ND_OPT_PI_FLAG_AUTO) ? 1 : 0;
406 	pr.ndpr_plen = pi->nd_opt_pi_prefix_len;
407 	pr.ndpr_vltime = ntohl(pi->nd_opt_pi_valid_time);
408 	pr.ndpr_pltime = ntohl(pi->nd_opt_pi_preferred_time);
409 	(void)prelist_update(&pr, dr, auth, mcast);
410 }
411 
412 static void
nd6_ra_opt_mtu(struct nd_opt_mtu * optmtu,struct ifnet * ifp,struct in6_addr saddr6)413 nd6_ra_opt_mtu(struct nd_opt_mtu *optmtu, struct ifnet *ifp,
414     struct in6_addr saddr6)
415 {
416 	struct in6_ifextra *ndi;
417 	char ip6bufs[INET6_ADDRSTRLEN];
418 	uint32_t mtu, maxmtu;
419 
420 	ndi = ifp->if_inet6;
421 
422 	if (optmtu->nd_opt_mtu_len != 1)
423 		return;
424 	mtu = (uint32_t)ntohl(optmtu->nd_opt_mtu_mtu);
425 	/* lower bound */
426 	if (mtu < IPV6_MMTU) {
427 		nd6log((LOG_INFO, "%s: bogus mtu option mtu=%u sent from %s, "
428 		    "ignoring\n", __func__, mtu, ip6_sprintf(ip6bufs, &saddr6)));
429 		return;
430 	}
431 
432 	/* upper bound */
433 	maxmtu = (ndi->nd_maxmtu && ndi->nd_maxmtu < ifp->if_mtu)
434 	    ? ndi->nd_maxmtu : ifp->if_mtu;
435 	if (mtu <= maxmtu) {
436 		if (ndi->nd_linkmtu != mtu) {
437 			ndi->nd_linkmtu = mtu;
438 			rt_updatemtu(ifp);
439 		}
440 	} else {
441 		nd6log((LOG_INFO, "%s: bogus mtu=%u sent from %s; "
442 		    "exceeds maxmtu %u, ignoring\n", __func__,
443 		    mtu, ip6_sprintf(ip6bufs, &saddr6), maxmtu));
444 	}
445 }
446 
447 static int
nd6_ra_opt_src_lladdr(struct nd_opt_hdr * opthdr,struct ifnet * ifp,struct in6_addr saddr6)448 nd6_ra_opt_src_lladdr(struct nd_opt_hdr *opthdr, struct ifnet *ifp,
449     struct in6_addr saddr6)
450 {
451 	char ip6bufs[INET6_ADDRSTRLEN];
452 	char *lladdr = NULL;
453 	int lladdrlen = 0;
454 
455 	if (opthdr != NULL) {
456 		lladdr = (char *)(opthdr + 1);
457 		lladdrlen = opthdr->nd_opt_len << 3;
458 	}
459 
460 	if (lladdr && ((ifp->if_addrlen + 2 + 7) & ~7) != lladdrlen) {
461 		nd6log((LOG_INFO,
462 		    "%s: lladdrlen mismatch for %s (if %d, RA packet %d)\n",
463 		    __func__, ip6_sprintf(ip6bufs, &saddr6),
464 		    ifp->if_addrlen, lladdrlen - 2));
465 		return (-1);
466 	}
467 
468 	nd6_cache_lladdr(ifp, &saddr6, lladdr, lladdrlen, ND_ROUTER_ADVERT, 0);
469 
470 	/*
471 	 * Installing a link-layer address might change the state of the
472 	 * router's neighbor cache, which might also affect our on-link
473 	 * detection of adveritsed prefixes.
474 	 */
475 	pfxlist_onlink_check();
476 	return (0);
477 }
478 
479 /*
480  * Receive Router Advertisement Message.
481  *
482  * Based on RFC 2461
483  * TODO: on-link bit on prefix information
484  * TODO: ND_RA_FLAG_{OTHER,MANAGED} processing
485  */
486 void
nd6_ra_input(struct mbuf * m,int off,int icmp6len)487 nd6_ra_input(struct mbuf *m, int off, int icmp6len)
488 {
489 	struct ifnet *ifp;
490 	struct in6_ifextra *ndi;
491 	struct ip6_hdr *ip6;
492 	struct nd_router_advert *nd_ra;
493 	struct nd_opt_hdr *pt;
494 	struct in6_addr saddr6;
495 	struct nd_defrouter dr0, *dr;
496 	union nd_opts ndopts;
497 	char ip6bufs[INET6_ADDRSTRLEN], ip6bufd[INET6_ADDRSTRLEN];
498 	uint32_t advreachable;
499 	bool mcast, auth;
500 
501 	/*
502 	 * We only accept RAs only when the per-interface flag
503 	 * ND6_IFF_ACCEPT_RTADV is on the receiving interface.
504 	 */
505 	ifp = m->m_pkthdr.rcvif;
506 	ndi = ifp->if_inet6;
507 	if (!(ndi->nd_flags & ND6_IFF_ACCEPT_RTADV))
508 		goto freeit;
509 
510 	/* RFC 6980: Nodes MUST silently ignore fragments */
511 	if(m->m_flags & M_FRAGMENTED)
512 		goto freeit;
513 
514 	ip6 = mtod(m, struct ip6_hdr *);
515 	/* RFC 4861 section 6.1.2: hlim must be 255 */
516 	if (__predict_false(ip6->ip6_hlim != 255)) {
517 		ICMP6STAT_INC(icp6s_invlhlim);
518 		nd6log((LOG_ERR,
519 		    "%s: invalid hlim (%d) from %s to %s on %s\n", __func__,
520 		    ip6->ip6_hlim, ip6_sprintf(ip6bufs, &ip6->ip6_src),
521 		    ip6_sprintf(ip6bufd, &ip6->ip6_dst), if_name(ifp)));
522 		goto bad;
523 	}
524 
525 	saddr6 = ip6->ip6_src;
526 	/* RFC 4861 section 6.1.2: source address must be link-local */
527 	if (!IN6_IS_ADDR_LINKLOCAL(&saddr6)) {
528 		nd6log((LOG_ERR,
529 		    "%s: src %s is not link-local\n", __func__,
530 		    ip6_sprintf(ip6bufs, &saddr6)));
531 		goto bad;
532 	}
533 
534 	if (m->m_len < off + icmp6len) {
535 		m = m_pullup(m, off + icmp6len);
536 		if (m == NULL) {
537 			IP6STAT_INC(ip6s_exthdrtoolong);
538 			return;
539 		}
540 	}
541 	nd_ra = (struct nd_router_advert *)((caddr_t)ip6 + off);
542 
543 	icmp6len -= sizeof(*nd_ra);
544 	nd6_option_init(nd_ra + 1, icmp6len, &ndopts);
545 	if (nd6_options(&ndopts) < 0) {
546 		nd6log((LOG_INFO,
547 		    "%s: invalid ND option, ignored\n", __func__));
548 		/* nd6_options have incremented stats */
549 		goto freeit;
550 	}
551 
552 	dr = NULL;
553 	mcast = false;
554 	/* remember if this is a multicasted advertisement */
555 	if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst))
556 		mcast = true;
557 
558 	bzero(&dr0, sizeof(dr0));
559 	dr0.rtaddr = saddr6;
560 	dr0.raflags = nd_ra->nd_ra_flags_reserved;
561 	/*
562 	 * Effectively-disable routes from RA messages when
563 	 * ND6_IFF_NO_RADR enabled on the receiving interface or
564 	 * (ip6.forwarding == 1 && ip6.rfc6204w3 != 1).
565 	 */
566 	if ((ndi->nd_flags & ND6_IFF_NO_RADR) ||
567 	    (V_ip6_forwarding && !V_ip6_rfc6204w3))
568 		dr0.rtlifetime = 0;
569 	else
570 		dr0.rtlifetime = ntohs(nd_ra->nd_ra_router_lifetime);
571 	dr0.expire = time_uptime + dr0.rtlifetime;
572 	dr0.ifp = ifp;
573 	/*
574 	 * RFC 4861 6.3.4: RA fields such as Cur Hop Limit,
575 	 * Reachable Time, and Retrans Timer may be unspecified.
576 	 * In such cases, the parameter should be ignored.
577 	 */
578 	if (nd_ra->nd_ra_reachable) {
579 		advreachable = ntohl(nd_ra->nd_ra_reachable);
580 		if (advreachable <= MAX_REACHABLE_TIME &&
581 		    ndi->nd_basereachable != advreachable) {
582 			ndi->nd_basereachable = advreachable;
583 			ndi->nd_reachable =
584 			    ND_COMPUTE_RTIME(ndi->nd_basereachable);
585 			ndi->nd_recalc_timer = V_nd6_recalc_reachtm_interval;
586 		}
587 	}
588 	if (nd_ra->nd_ra_retransmit)
589 		ndi->nd_retrans = ntohl(nd_ra->nd_ra_retransmit);
590 	if (nd_ra->nd_ra_curhoplimit) {
591 		if (ndi->nd_curhoplimit < nd_ra->nd_ra_curhoplimit)
592 			ndi->nd_curhoplimit = nd_ra->nd_ra_curhoplimit;
593 		else if (ndi->nd_curhoplimit != nd_ra->nd_ra_curhoplimit) {
594 			log(LOG_ERR, "RA with a lower CurHopLimit sent from "
595 			    "%s on %s (current = %d, received = %d). "
596 			    "Ignored.\n", ip6_sprintf(ip6bufs, &ip6->ip6_src),
597 			    if_name(ifp), ndi->nd_curhoplimit,
598 			    nd_ra->nd_ra_curhoplimit);
599 		}
600 	}
601 	dr = defrtrlist_update(&dr0);
602 #ifdef EXPERIMENTAL
603 	defrtr_ipv6_only_ifp(ifp);
604 #endif
605 	/* Prefix Information */
606 	if (ndopts.nd_opts_pi != NULL) {
607 		/*
608 		 * Authenticity for NA consists authentication for
609 		 * both IP header and IP datagrams, doesn't it ?
610 		 */
611 		auth = ((m->m_flags & M_AUTHIPHDR) && (m->m_flags & M_AUTHIPDGM));
612 		for (pt = (struct nd_opt_hdr *)ndopts.nd_opts_pi;
613 		     pt <= (struct nd_opt_hdr *)ndopts.nd_opts_pi_end;
614 		     pt = (struct nd_opt_hdr *)((caddr_t)pt +
615 						(pt->nd_opt_len << 3))) {
616 			nd6_ra_opt_pi(pt, ifp, nd_ra, dr, auth, mcast);
617 		}
618 	}
619 	if (dr != NULL) {
620 		defrouter_rele(dr);
621 		dr = NULL;
622 	}
623 
624 	/* MTU */
625 	if (ndopts.nd_opts_mtu != NULL)
626 		nd6_ra_opt_mtu(ndopts.nd_opts_mtu, ifp, saddr6);
627 
628 	/* Source link layer address */
629 	if (nd6_ra_opt_src_lladdr(ndopts.nd_opts_src_lladdr, ifp, saddr6) != 0)
630 		goto bad;
631 
632  freeit:
633 	m_freem(m);
634 	return;
635 
636  bad:
637 	ICMP6STAT_INC(icp6s_badra);
638 	m_freem(m);
639 }
640 
641 /* PFXRTR */
642 static struct nd_pfxrouter *
pfxrtr_lookup(struct nd_prefix * pr,struct nd_defrouter * dr)643 pfxrtr_lookup(struct nd_prefix *pr, struct nd_defrouter *dr)
644 {
645 	struct nd_pfxrouter *search;
646 
647 	ND6_LOCK_ASSERT();
648 
649 	LIST_FOREACH(search, &pr->ndpr_advrtrs, pfr_entry) {
650 		if (search->router == dr)
651 			break;
652 	}
653 	return (search);
654 }
655 
656 static void
pfxrtr_add(struct nd_prefix * pr,struct nd_defrouter * dr)657 pfxrtr_add(struct nd_prefix *pr, struct nd_defrouter *dr)
658 {
659 	struct nd_pfxrouter *new;
660 	bool update;
661 
662 	ND6_UNLOCK_ASSERT();
663 
664 	ND6_RLOCK();
665 	if (pfxrtr_lookup(pr, dr) != NULL) {
666 		ND6_RUNLOCK();
667 		return;
668 	}
669 	ND6_RUNLOCK();
670 
671 	new = malloc(sizeof(*new), M_IP6NDP, M_NOWAIT | M_ZERO);
672 	if (new == NULL)
673 		return;
674 	defrouter_ref(dr);
675 	new->router = dr;
676 
677 	ND6_WLOCK();
678 	if (pfxrtr_lookup(pr, dr) == NULL) {
679 		LIST_INSERT_HEAD(&pr->ndpr_advrtrs, new, pfr_entry);
680 		update = true;
681 	} else {
682 		/* We lost a race to add the reference. */
683 		defrouter_rele(dr);
684 		free(new, M_IP6NDP);
685 		update = false;
686 	}
687 	ND6_WUNLOCK();
688 
689 	if (update)
690 		pfxlist_onlink_check();
691 }
692 
693 static void
pfxrtr_del(struct nd_pfxrouter * pfr)694 pfxrtr_del(struct nd_pfxrouter *pfr)
695 {
696 
697 	ND6_WLOCK_ASSERT();
698 
699 	LIST_REMOVE(pfr, pfr_entry);
700 	defrouter_rele(pfr->router);
701 	free(pfr, M_IP6NDP);
702 }
703 
704 /* Default router list processing sub routines. */
705 static void
defrouter_addreq(struct nd_defrouter * new)706 defrouter_addreq(struct nd_defrouter *new)
707 {
708 	uint32_t fibnum = new->ifp->if_fib;
709 	struct rib_cmd_info rc = {};
710 	int error = 0;
711 
712 	NET_EPOCH_ASSERT();
713 
714 	struct sockaddr_in6 gw = {
715 		.sin6_family = AF_INET6,
716 		.sin6_len = sizeof(struct sockaddr_in6),
717 		.sin6_addr = new->rtaddr,
718 	};
719 
720 	error = rib_add_default_route(fibnum, AF_INET6, new->ifp,
721 	    (struct sockaddr *)&gw, &rc);
722 
723 	if (error == 0) {
724 		struct nhop_object *nh = nhop_select_func(rc.rc_nh_new, 0);
725 		rt_routemsg(RTM_ADD, rc.rc_rt, nh, fibnum);
726 		new->installed = 1;
727 	}
728 }
729 
730 /*
731  * Remove the default route for a given router.
732  * This is just a subroutine function for defrouter_select_fib(), and
733  * should not be called from anywhere else.
734  */
735 static void
defrouter_delreq(struct nd_defrouter * dr)736 defrouter_delreq(struct nd_defrouter *dr)
737 {
738 	uint32_t fibnum = dr->ifp->if_fib;
739 	struct epoch_tracker et;
740 	struct rib_cmd_info rc;
741 	int error;
742 
743 	struct sockaddr_in6 dst = {
744 		.sin6_family = AF_INET6,
745 		.sin6_len = sizeof(struct sockaddr_in6),
746 	};
747 
748 	struct sockaddr_in6 gw = {
749 		.sin6_family = AF_INET6,
750 		.sin6_len = sizeof(struct sockaddr_in6),
751 		.sin6_addr = dr->rtaddr,
752 	};
753 
754 	NET_EPOCH_ENTER(et);
755 	error = rib_del_route_px(fibnum, (struct sockaddr *)&dst, 0,
756 		    rib_match_gw, (struct sockaddr *)&gw, 0, &rc);
757 	if (error == 0) {
758 		struct nhop_object *nh = nhop_select_func(rc.rc_nh_old, 0);
759 		rt_routemsg(RTM_DELETE, rc.rc_rt, nh, fibnum);
760 	}
761 	NET_EPOCH_EXIT(et);
762 
763 	dr->installed = 0;
764 }
765 
766 static void
defrouter_del(struct nd_defrouter * dr)767 defrouter_del(struct nd_defrouter *dr)
768 {
769 	struct nd_defrouter *deldr = NULL;
770 	struct nd_prefix *pr;
771 	struct nd_pfxrouter *pfxrtr;
772 
773 	ND6_UNLOCK_ASSERT();
774 
775 	/*
776 	 * Flush all the routing table entries that use the router
777 	 * as a next hop.
778 	 */
779 	if (dr->ifp->if_inet6->nd_flags & ND6_IFF_ACCEPT_RTADV)
780 		rt6_flush(&dr->rtaddr, dr->ifp);
781 
782 #ifdef EXPERIMENTAL
783 	defrtr_ipv6_only_ifp(dr->ifp);
784 #endif
785 
786 	if (dr->installed) {
787 		deldr = dr;
788 		defrouter_delreq(dr);
789 	}
790 
791 	/*
792 	 * Also delete all the pointers to the router in each prefix lists.
793 	 */
794 	ND6_WLOCK();
795 	LIST_FOREACH(pr, &V_nd_prefix, ndpr_entry) {
796 		if ((pfxrtr = pfxrtr_lookup(pr, dr)) != NULL)
797 			pfxrtr_del(pfxrtr);
798 	}
799 	ND6_WUNLOCK();
800 
801 	pfxlist_onlink_check();
802 
803 	/*
804 	 * If the router is the primary one, choose a new one.
805 	 * Note that defrouter_select_fib() will remove the current
806          * gateway from the routing table.
807 	 */
808 	if (deldr)
809 		defrouter_select_fib(deldr->ifp->if_fib);
810 
811 	/*
812 	 * Release the list reference.
813 	 */
814 	defrouter_rele(dr);
815 }
816 
817 struct nd_defrouter *
defrouter_lookup_locked(const struct in6_addr * addr,struct ifnet * ifp)818 defrouter_lookup_locked(const struct in6_addr *addr, struct ifnet *ifp)
819 {
820 	struct nd_defrouter *dr;
821 
822 	ND6_LOCK_ASSERT();
823 	TAILQ_FOREACH(dr, &V_nd6_defrouter, dr_entry)
824 		if (dr->ifp == ifp && IN6_ARE_ADDR_EQUAL(addr, &dr->rtaddr)) {
825 			defrouter_ref(dr);
826 			return (dr);
827 		}
828 	return (NULL);
829 }
830 
831 struct nd_defrouter *
defrouter_lookup(const struct in6_addr * addr,struct ifnet * ifp)832 defrouter_lookup(const struct in6_addr *addr, struct ifnet *ifp)
833 {
834 	struct nd_defrouter *dr;
835 
836 	ND6_RLOCK();
837 	dr = defrouter_lookup_locked(addr, ifp);
838 	ND6_RUNLOCK();
839 	return (dr);
840 }
841 
842 /*
843  * Remove all default routes from default router list.
844  */
845 void
defrouter_reset(void)846 defrouter_reset(void)
847 {
848 	struct nd_defrouter *dr, **dra;
849 	int count, i;
850 
851 	count = i = 0;
852 
853 	/*
854 	 * We can't delete routes with the ND lock held, so make a copy of the
855 	 * current default router list and use that when deleting routes.
856 	 */
857 	ND6_RLOCK();
858 	TAILQ_FOREACH(dr, &V_nd6_defrouter, dr_entry)
859 		count++;
860 	ND6_RUNLOCK();
861 
862 	dra = malloc(count * sizeof(*dra), M_TEMP, M_WAITOK | M_ZERO);
863 
864 	ND6_RLOCK();
865 	TAILQ_FOREACH(dr, &V_nd6_defrouter, dr_entry) {
866 		if (i == count)
867 			break;
868 		defrouter_ref(dr);
869 		dra[i++] = dr;
870 	}
871 	ND6_RUNLOCK();
872 
873 	for (i = 0; i < count && dra[i] != NULL; i++) {
874 		defrouter_delreq(dra[i]);
875 		defrouter_rele(dra[i]);
876 	}
877 	free(dra, M_TEMP);
878 
879 	/*
880 	 * XXX should we also nuke any default routers in the kernel, by
881 	 * going through them by rtalloc1()?
882 	 */
883 }
884 
885 /*
886  * Look up a matching default router list entry and remove it. Returns true if a
887  * matching entry was found, false otherwise.
888  */
889 bool
defrouter_remove(struct in6_addr * addr,struct ifnet * ifp)890 defrouter_remove(struct in6_addr *addr, struct ifnet *ifp)
891 {
892 	struct nd_defrouter *dr;
893 
894 	ND6_WLOCK();
895 	dr = defrouter_lookup_locked(addr, ifp);
896 	if (dr == NULL) {
897 		ND6_WUNLOCK();
898 		return (false);
899 	}
900 
901 	defrouter_unlink(dr, NULL);
902 	ND6_WUNLOCK();
903 	defrouter_del(dr);
904 	defrouter_rele(dr);
905 	return (true);
906 }
907 
908 /*
909  * for default router selection
910  * regards router-preference field as a 2-bit signed integer
911  */
912 static int
rtpref(struct nd_defrouter * dr)913 rtpref(struct nd_defrouter *dr)
914 {
915 	switch (dr->raflags & ND_RA_FLAG_RTPREF_MASK) {
916 	case ND_RA_FLAG_RTPREF_HIGH:
917 		return (RTPREF_HIGH);
918 	case ND_RA_FLAG_RTPREF_MEDIUM:
919 	case ND_RA_FLAG_RTPREF_RSV:
920 		return (RTPREF_MEDIUM);
921 	case ND_RA_FLAG_RTPREF_LOW:
922 		return (RTPREF_LOW);
923 	default:
924 		/*
925 		 * This case should never happen.  If it did, it would mean a
926 		 * serious bug of kernel internal.  We thus always bark here.
927 		 * Or, can we even panic?
928 		 */
929 		log(LOG_ERR, "rtpref: impossible RA flag %x\n", dr->raflags);
930 		return (RTPREF_INVALID);
931 	}
932 	/* NOTREACHED */
933 }
934 
935 static bool
is_dr_reachable(const struct nd_defrouter * dr)936 is_dr_reachable(const struct nd_defrouter *dr) {
937 	struct llentry *ln = NULL;
938 
939 	ln = nd6_lookup(&dr->rtaddr, LLE_SF(AF_INET6, 0), dr->ifp);
940 	if (ln == NULL)
941 		return (false);
942 	bool reachable = ND6_IS_LLINFO_PROBREACH(ln);
943 	LLE_RUNLOCK(ln);
944 	return reachable;
945 }
946 
947 /*
948  * Default Router Selection according to Section 6.3.6 of RFC 2461 and
949  * draft-ietf-ipngwg-router-selection:
950  * 1) Routers that are reachable or probably reachable should be preferred.
951  *    If we have more than one (probably) reachable router, prefer ones
952  *    with the highest router preference.
953  * 2) When no routers on the list are known to be reachable or
954  *    probably reachable, routers SHOULD be selected in a round-robin
955  *    fashion, regardless of router preference values.
956  * 3) If the Default Router List is empty, assume that all
957  *    destinations are on-link.
958  *
959  * We assume nd_defrouter is sorted by router preference value.
960  * Since the code below covers both with and without router preference cases,
961  * we do not need to classify the cases by ifdef.
962  *
963  * At this moment, we do not try to install more than one default router,
964  * even when the multipath routing is available, because we're not sure about
965  * the benefits for stub hosts comparing to the risk of making the code
966  * complicated and the possibility of introducing bugs.
967  *
968  * We maintain a single list of routers for multiple FIBs, only considering one
969  * at a time based on the receiving interface's FIB. If @fibnum is RT_ALL_FIBS,
970  * we do the whole thing multiple times.
971  */
972 void
defrouter_select_fib(int fibnum)973 defrouter_select_fib(int fibnum)
974 {
975 	struct epoch_tracker et;
976 	struct nd_defrouter *dr, *selected_dr, *installed_dr;
977 
978 	if (fibnum == RT_ALL_FIBS) {
979 		for (fibnum = 0; fibnum < rt_numfibs; fibnum++) {
980 			defrouter_select_fib(fibnum);
981 		}
982 		return;
983 	}
984 
985 	ND6_RLOCK();
986 	/*
987 	 * Let's handle easy case (3) first:
988 	 * If default router list is empty, there's nothing to be done.
989 	 */
990 	if (TAILQ_EMPTY(&V_nd6_defrouter)) {
991 		ND6_RUNLOCK();
992 		return;
993 	}
994 
995 	/*
996 	 * Search for a (probably) reachable router from the list.
997 	 * We just pick up the first reachable one (if any), assuming that
998 	 * the ordering rule of the list described in defrtrlist_update().
999 	 */
1000 	selected_dr = installed_dr = NULL;
1001 	NET_EPOCH_ENTER(et);
1002 	TAILQ_FOREACH(dr, &V_nd6_defrouter, dr_entry) {
1003 		if (dr->ifp->if_fib != fibnum)
1004 			continue;
1005 
1006 		if (selected_dr == NULL && is_dr_reachable(dr)) {
1007 			selected_dr = dr;
1008 			defrouter_ref(selected_dr);
1009 		}
1010 
1011 		if (dr->installed) {
1012 			if (installed_dr == NULL) {
1013 				installed_dr = dr;
1014 				defrouter_ref(installed_dr);
1015 			} else {
1016 				/*
1017 				 * this should not happen.
1018 				 * warn for diagnosis.
1019 				 */
1020 				log(LOG_ERR, "defrouter_select_fib: more than "
1021 				             "one router is installed\n");
1022 			}
1023 		}
1024 	}
1025 
1026 	/*
1027 	 * If none of the default routers was found to be reachable,
1028 	 * round-robin the list regardless of preference.
1029 	 * Otherwise, if we have an installed router, check if the selected
1030 	 * (reachable) router should really be preferred to the installed one.
1031 	 * We only prefer the new router when the old one is not reachable
1032 	 * or when the new one has a really higher preference value.
1033 	 */
1034 	if (selected_dr == NULL) {
1035 		if (installed_dr == NULL ||
1036 		    TAILQ_NEXT(installed_dr, dr_entry) == NULL)
1037 			dr = TAILQ_FIRST(&V_nd6_defrouter);
1038 		else
1039 			dr = TAILQ_NEXT(installed_dr, dr_entry);
1040 
1041 		/* Ensure we select a router for this FIB. */
1042 		TAILQ_FOREACH_FROM(dr, &V_nd6_defrouter, dr_entry) {
1043 			if (dr->ifp->if_fib == fibnum) {
1044 				selected_dr = dr;
1045 				defrouter_ref(selected_dr);
1046 				break;
1047 			}
1048 		}
1049 	} else if (installed_dr != NULL) {
1050 		if (is_dr_reachable(installed_dr) &&
1051 		    rtpref(selected_dr) <= rtpref(installed_dr)) {
1052 			defrouter_rele(selected_dr);
1053 			selected_dr = installed_dr;
1054 		}
1055 	}
1056 	ND6_RUNLOCK();
1057 
1058 	/*
1059 	 * If we selected a router for this FIB and it's different
1060 	 * than the installed one, remove the installed router and
1061 	 * install the selected one in its place.
1062 	 */
1063 	if (installed_dr != selected_dr) {
1064 		if (installed_dr != NULL) {
1065 			defrouter_delreq(installed_dr);
1066 			defrouter_rele(installed_dr);
1067 		}
1068 		if (selected_dr != NULL)
1069 			defrouter_addreq(selected_dr);
1070 	}
1071 	if (selected_dr != NULL)
1072 		defrouter_rele(selected_dr);
1073 	NET_EPOCH_EXIT(et);
1074 }
1075 
1076 static struct nd_defrouter *
defrtrlist_update(struct nd_defrouter * new)1077 defrtrlist_update(struct nd_defrouter *new)
1078 {
1079 	struct nd_defrouter *dr, *n;
1080 	uint64_t genid;
1081 	int oldpref;
1082 	bool writelocked;
1083 
1084 	if (new->rtlifetime == 0) {
1085 		defrouter_remove(&new->rtaddr, new->ifp);
1086 		return (NULL);
1087 	}
1088 
1089 	ND6_RLOCK();
1090 	writelocked = false;
1091 restart:
1092 	dr = defrouter_lookup_locked(&new->rtaddr, new->ifp);
1093 	if (dr != NULL) {
1094 		oldpref = rtpref(dr);
1095 
1096 		/* override */
1097 		dr->raflags = new->raflags; /* XXX flag check */
1098 		dr->rtlifetime = new->rtlifetime;
1099 		dr->expire = new->expire;
1100 
1101 		/*
1102 		 * If the preference does not change, there's no need
1103 		 * to sort the entries. Also make sure the selected
1104 		 * router is still installed in the kernel.
1105 		 */
1106 		if (dr->installed && rtpref(new) == oldpref) {
1107 			if (writelocked)
1108 				ND6_WUNLOCK();
1109 			else
1110 				ND6_RUNLOCK();
1111 			return (dr);
1112 		}
1113 	}
1114 
1115 	/*
1116 	 * The router needs to be reinserted into the default router
1117 	 * list, so upgrade to a write lock. If that fails and the list
1118 	 * has potentially changed while the lock was dropped, we'll
1119 	 * redo the lookup with the write lock held.
1120 	 */
1121 	if (!writelocked) {
1122 		writelocked = true;
1123 		if (!ND6_TRY_UPGRADE()) {
1124 			genid = V_nd6_list_genid;
1125 			ND6_RUNLOCK();
1126 			ND6_WLOCK();
1127 			if (genid != V_nd6_list_genid)
1128 				goto restart;
1129 		}
1130 	}
1131 
1132 	if (dr != NULL) {
1133 		/*
1134 		 * The preferred router may have changed, so relocate this
1135 		 * router.
1136 		 */
1137 		TAILQ_REMOVE(&V_nd6_defrouter, dr, dr_entry);
1138 		n = dr;
1139 	} else {
1140 		n = malloc(sizeof(*n), M_IP6NDP, M_NOWAIT | M_ZERO);
1141 		if (n == NULL) {
1142 			ND6_WUNLOCK();
1143 			return (NULL);
1144 		}
1145 		memcpy(n, new, sizeof(*n));
1146 		/* Initialize with an extra reference for the caller. */
1147 		refcount_init(&n->refcnt, 2);
1148 	}
1149 
1150 	/*
1151 	 * Insert the new router in the Default Router List;
1152 	 * The Default Router List should be in the descending order
1153 	 * of router-preferece.  Routers with the same preference are
1154 	 * sorted in the arriving time order.
1155 	 */
1156 
1157 	/* insert at the end of the group */
1158 	TAILQ_FOREACH(dr, &V_nd6_defrouter, dr_entry) {
1159 		if (rtpref(n) > rtpref(dr))
1160 			break;
1161 	}
1162 	if (dr != NULL)
1163 		TAILQ_INSERT_BEFORE(dr, n, dr_entry);
1164 	else
1165 		TAILQ_INSERT_TAIL(&V_nd6_defrouter, n, dr_entry);
1166 	V_nd6_list_genid++;
1167 	ND6_WUNLOCK();
1168 
1169 	defrouter_select_fib(new->ifp->if_fib);
1170 
1171 	return (n);
1172 }
1173 
1174 static void
in6_init_prefix_ltimes(struct nd_prefix * ndpr)1175 in6_init_prefix_ltimes(struct nd_prefix *ndpr)
1176 {
1177 	ndpr->ndpr_preferred = in6_expire_time(ndpr->ndpr_pltime);
1178 	ndpr->ndpr_expire = in6_expire_time(ndpr->ndpr_vltime);
1179 }
1180 
1181 static void
in6_init_address_ltimes(struct nd_prefix * new,struct in6_addrlifetime * lt6)1182 in6_init_address_ltimes(struct nd_prefix *new, struct in6_addrlifetime *lt6)
1183 {
1184 	lt6->ia6t_preferred = in6_expire_time(lt6->ia6t_pltime);
1185 	lt6->ia6t_expire = in6_expire_time(lt6->ia6t_vltime);
1186 }
1187 
1188 static struct in6_ifaddr *
in6_ifadd(struct nd_prefixctl * pr,int mcast)1189 in6_ifadd(struct nd_prefixctl *pr, int mcast)
1190 {
1191 	struct ifnet *ifp = pr->ndpr_ifp;
1192 	struct ifaddr *ifa;
1193 	struct in6_aliasreq ifra;
1194 	struct in6_ifaddr *ia = NULL, *ib = NULL;
1195 	int error, plen0;
1196 	struct in6_addr *ifid_addr = NULL, mask, newaddr;
1197 	int prefixlen = pr->ndpr_plen;
1198 	int updateflags;
1199 	char ip6buf[INET6_ADDRSTRLEN];
1200 
1201 	in6_prefixlen2mask(&mask, prefixlen);
1202 
1203 	/*
1204 	 * find a link-local address (will be interface ID).
1205 	 * Is it really mandatory? Theoretically, a global or a site-local
1206 	 * address can be configured without a link-local address, if we
1207 	 * have a unique interface identifier...
1208 	 *
1209 	 * it is not mandatory to have a link-local address, we can generate
1210 	 * interface identifier on the fly.  we do this because:
1211 	 * (1) it should be the easiest way to find interface identifier.
1212 	 * (2) RFC2462 5.4 suggesting the use of the same interface identifier
1213 	 * for multiple addresses on a single interface, and possible shortcut
1214 	 * of DAD.  we omitted DAD for this reason in the past.
1215 	 * (3) a user can prevent autoconfiguration of global address
1216 	 * by removing link-local address by hand (this is partly because we
1217 	 * don't have other way to control the use of IPv6 on an interface.
1218 	 * this has been our design choice - cf. NRL's "ifconfig auto").
1219 	 * (4) it is easier to manage when an interface has addresses
1220 	 * with the same interface identifier, than to have multiple addresses
1221 	 * with different interface identifiers.
1222 	 *
1223 	 * If using stable privacy generation, generate a new address with
1224 	 * the algorithm specified in RFC 7217 section 5
1225 	 */
1226 
1227 	/* make ifaddr */
1228 	in6_prepare_ifra(&ifra, &pr->ndpr_prefix.sin6_addr, &mask);
1229 
1230 	if (ifp->if_inet6->nd_flags & ND6_IFF_STABLEADDR) {
1231 		memcpy(&newaddr, &pr->ndpr_prefix.sin6_addr,  sizeof(pr->ndpr_prefix.sin6_addr));
1232 
1233 		if(!in6_get_stableifid(ifp, &newaddr, prefixlen))
1234 			return NULL;
1235 	} else {
1236 		ifa = (struct ifaddr *)in6ifa_ifpforlinklocal(ifp, 0); /* 0 is OK? */
1237 		if (ifa) {
1238 			ib = (struct in6_ifaddr *)ifa;
1239 			ifid_addr = &ib->ia_addr.sin6_addr;
1240 
1241 			/* prefixlen + ifidlen must be equal to 128 */
1242 			plen0 = in6_mask2len(&ib->ia_prefixmask.sin6_addr, NULL);
1243 			if (prefixlen != plen0) {
1244 				ifa_free(ifa);
1245 				ifid_addr = NULL;
1246 				nd6log((LOG_DEBUG,
1247 				    "%s: wrong prefixlen for %s (prefix=%d ifid=%d)\n",
1248 				    __func__, if_name(ifp), prefixlen, 128 - plen0));
1249 			}
1250 		}
1251 
1252 		/* No suitable LL address, get the ifid directly */
1253 		if (ifid_addr == NULL) {
1254 			ifa = ifa_alloc(sizeof(struct in6_ifaddr), M_NOWAIT);
1255 			if (ifa != NULL) {
1256 				ib = (struct in6_ifaddr *)ifa;
1257 				ifid_addr = &ib->ia_addr.sin6_addr;
1258 				if(in6_get_ifid(ifp, NULL, ifid_addr) != 0) {
1259 					nd6log((LOG_DEBUG,
1260 					    "%s: failed to get ifid for %s\n",
1261 					    __func__, if_name(ifp)));
1262 					ifa_free(ifa);
1263 					ifid_addr = NULL;
1264 				}
1265 			}
1266 		}
1267 
1268 		if (ifid_addr == NULL) {
1269 			nd6log((LOG_INFO,
1270 			    "%s: could not determine ifid for %s\n",
1271 			    __func__, if_name(ifp)));
1272 			return NULL;
1273 		}
1274 
1275 		memcpy(&newaddr, &ib->ia_addr.sin6_addr, sizeof(ib->ia_addr.sin6_addr));
1276 		ifa_free(ifa);
1277 	}
1278 
1279 	IN6_MASK_ADDR(&ifra.ifra_addr.sin6_addr, &mask);
1280 	/* interface ID */
1281 	ifra.ifra_addr.sin6_addr.s6_addr32[0] |= (newaddr.s6_addr32[0] & ~mask.s6_addr32[0]);
1282 	ifra.ifra_addr.sin6_addr.s6_addr32[1] |= (newaddr.s6_addr32[1] & ~mask.s6_addr32[1]);
1283 	ifra.ifra_addr.sin6_addr.s6_addr32[2] |= (newaddr.s6_addr32[2] & ~mask.s6_addr32[2]);
1284 	ifra.ifra_addr.sin6_addr.s6_addr32[3] |= (newaddr.s6_addr32[3] & ~mask.s6_addr32[3]);
1285 
1286 	/* lifetimes. */
1287 	ifra.ifra_lifetime.ia6t_vltime = pr->ndpr_vltime;
1288 	ifra.ifra_lifetime.ia6t_pltime = pr->ndpr_pltime;
1289 
1290 	/* XXX: scope zone ID? */
1291 
1292 	ifra.ifra_flags |= IN6_IFF_AUTOCONF; /* obey autoconf */
1293 
1294 	/*
1295 	 * Make sure that we do not have this address already.  This should
1296 	 * usually not happen, but we can still see this case, e.g., if we
1297 	 * have manually configured the exact address to be configured.
1298 	 */
1299 	ifa = (struct ifaddr *)in6ifa_ifpwithaddr(ifp,
1300 	    &ifra.ifra_addr.sin6_addr);
1301 	if (ifa != NULL) {
1302 		ifa_free(ifa);
1303 		/* this should be rare enough to make an explicit log */
1304 		log(LOG_INFO, "in6_ifadd: %s is already configured\n",
1305 		    ip6_sprintf(ip6buf, &ifra.ifra_addr.sin6_addr));
1306 		return (NULL);
1307 	}
1308 
1309 	/*
1310 	 * Allocate ifaddr structure, link into chain, etc.
1311 	 * If we are going to create a new address upon receiving a multicasted
1312 	 * RA, we need to impose a random delay before starting DAD.
1313 	 * [draft-ietf-ipv6-rfc2462bis-02.txt, Section 5.4.2]
1314 	 */
1315 	updateflags = 0;
1316 	if (mcast)
1317 		updateflags |= IN6_IFAUPDATE_DADDELAY;
1318 	if ((error = in6_update_ifa(ifp, &ifra, NULL, updateflags)) != 0) {
1319 		nd6log((LOG_ERR,
1320 		    "%s: failed to make ifaddr %s on %s (errno=%d)\n", __func__,
1321 		    ip6_sprintf(ip6buf, &ifra.ifra_addr.sin6_addr),
1322 		    if_name(ifp), error));
1323 		return (NULL);	/* ifaddr must not have been allocated. */
1324 	}
1325 
1326 	ia = in6ifa_ifpwithaddr(ifp, &ifra.ifra_addr.sin6_addr);
1327 	/*
1328 	 * XXXRW: Assumption of non-NULLness here might not be true with
1329 	 * fine-grained locking -- should we validate it?  Or just return
1330 	 * earlier ifa rather than looking it up again?
1331 	 */
1332 	return (ia);		/* this is always non-NULL  and referenced. */
1333 }
1334 
1335 static struct nd_prefix *
nd6_prefix_lookup_locked(struct nd_prefixctl * key)1336 nd6_prefix_lookup_locked(struct nd_prefixctl *key)
1337 {
1338 	struct nd_prefix *search;
1339 
1340 	ND6_LOCK_ASSERT();
1341 
1342 	LIST_FOREACH(search, &V_nd_prefix, ndpr_entry) {
1343 		if (key->ndpr_ifp == search->ndpr_ifp &&
1344 		    key->ndpr_plen == search->ndpr_plen &&
1345 		    in6_are_prefix_equal(&key->ndpr_prefix.sin6_addr,
1346 		    &search->ndpr_prefix.sin6_addr, key->ndpr_plen)) {
1347 			nd6_prefix_ref(search);
1348 			break;
1349 		}
1350 	}
1351 	return (search);
1352 }
1353 
1354 struct nd_prefix *
nd6_prefix_lookup(struct nd_prefixctl * key)1355 nd6_prefix_lookup(struct nd_prefixctl *key)
1356 {
1357 	struct nd_prefix *search;
1358 
1359 	ND6_RLOCK();
1360 	search = nd6_prefix_lookup_locked(key);
1361 	ND6_RUNLOCK();
1362 	return (search);
1363 }
1364 
1365 void
nd6_prefix_ref(struct nd_prefix * pr)1366 nd6_prefix_ref(struct nd_prefix *pr)
1367 {
1368 
1369 	refcount_acquire(&pr->ndpr_refcnt);
1370 }
1371 
1372 void
nd6_prefix_rele(struct nd_prefix * pr)1373 nd6_prefix_rele(struct nd_prefix *pr)
1374 {
1375 
1376 	if (refcount_release(&pr->ndpr_refcnt)) {
1377 		KASSERT(LIST_EMPTY(&pr->ndpr_advrtrs),
1378 		    ("prefix %p has advertising routers", pr));
1379 		free(pr, M_IP6NDP);
1380 	}
1381 }
1382 
1383 int
nd6_prelist_add(struct nd_prefixctl * pr,struct nd_defrouter * dr,struct nd_prefix ** newp)1384 nd6_prelist_add(struct nd_prefixctl *pr, struct nd_defrouter *dr,
1385     struct nd_prefix **newp)
1386 {
1387 	struct nd_prefix *new;
1388 	char ip6buf[INET6_ADDRSTRLEN];
1389 	int error;
1390 
1391 	new = malloc(sizeof(*new), M_IP6NDP, M_NOWAIT | M_ZERO);
1392 	if (new == NULL)
1393 		return (ENOMEM);
1394 	refcount_init(&new->ndpr_refcnt, newp != NULL ? 2 : 1);
1395 	new->ndpr_ifp = pr->ndpr_ifp;
1396 	new->ndpr_prefix = pr->ndpr_prefix;
1397 	new->ndpr_plen = pr->ndpr_plen;
1398 	new->ndpr_vltime = pr->ndpr_vltime;
1399 	new->ndpr_pltime = pr->ndpr_pltime;
1400 	new->ndpr_flags = pr->ndpr_flags;
1401 	new->ndpr_lastupdate = time_uptime;
1402 	in6_init_prefix_ltimes(new);
1403 
1404 	/* initialization */
1405 	LIST_INIT(&new->ndpr_advrtrs);
1406 	in6_prefixlen2mask(&new->ndpr_mask, new->ndpr_plen);
1407 	/* make prefix in the canonical form */
1408 	IN6_MASK_ADDR(&new->ndpr_prefix.sin6_addr, &new->ndpr_mask);
1409 
1410 	ND6_WLOCK();
1411 	LIST_INSERT_HEAD(&V_nd_prefix, new, ndpr_entry);
1412 	V_nd6_list_genid++;
1413 	ND6_WUNLOCK();
1414 
1415 	/* ND_OPT_PI_FLAG_ONLINK processing */
1416 	if (new->ndpr_raf_onlink) {
1417 		struct epoch_tracker et;
1418 
1419 		ND6_ONLINK_LOCK();
1420 		NET_EPOCH_ENTER(et);
1421 		if ((error = nd6_prefix_onlink(new)) != 0) {
1422 			nd6log((LOG_ERR, "%s: failed to make the prefix %s/%d "
1423 			    "on-link on %s (errno=%d)\n", __func__,
1424 			    ip6_sprintf(ip6buf, &pr->ndpr_prefix.sin6_addr),
1425 			    pr->ndpr_plen, if_name(pr->ndpr_ifp), error));
1426 			/* proceed anyway. XXX: is it correct? */
1427 		}
1428 		NET_EPOCH_EXIT(et);
1429 		ND6_ONLINK_UNLOCK();
1430 	}
1431 
1432 	if (dr != NULL)
1433 		pfxrtr_add(new, dr);
1434 	if (newp != NULL)
1435 		*newp = new;
1436 	return (0);
1437 }
1438 
1439 /*
1440  * Remove a prefix from the prefix list and optionally stash it in a
1441  * caller-provided list.
1442  *
1443  * The ND6 lock must be held.
1444  */
1445 void
nd6_prefix_unlink(struct nd_prefix * pr,struct nd_prhead * list)1446 nd6_prefix_unlink(struct nd_prefix *pr, struct nd_prhead *list)
1447 {
1448 
1449 	ND6_WLOCK_ASSERT();
1450 
1451 	LIST_REMOVE(pr, ndpr_entry);
1452 	V_nd6_list_genid++;
1453 	if (list != NULL)
1454 		LIST_INSERT_HEAD(list, pr, ndpr_entry);
1455 }
1456 
1457 /*
1458  * Free an unlinked prefix, first marking it off-link if necessary.
1459  */
1460 void
nd6_prefix_del(struct nd_prefix * pr)1461 nd6_prefix_del(struct nd_prefix *pr)
1462 {
1463 	struct nd_pfxrouter *pfr, *next;
1464 	int e;
1465 	char ip6buf[INET6_ADDRSTRLEN];
1466 
1467 	KASSERT(pr->ndpr_addrcnt == 0,
1468 	    ("prefix %p has referencing addresses", pr));
1469 	ND6_UNLOCK_ASSERT();
1470 
1471 	/*
1472 	 * Though these flags are now meaningless, we'd rather keep the value
1473 	 * of pr->ndpr_raf_onlink and pr->ndpr_raf_auto not to confuse users
1474 	 * when executing "ndp -p".
1475 	 */
1476 	if ((pr->ndpr_stateflags & NDPRF_ONLINK) != 0) {
1477 		ND6_ONLINK_LOCK();
1478 		if ((e = nd6_prefix_offlink(pr)) != 0) {
1479 			nd6log((LOG_ERR,
1480 			    "%s: failed to make the prefix %s/%d offlink on %s "
1481 			    "(errno=%d)\n", __func__,
1482 			    ip6_sprintf(ip6buf, &pr->ndpr_prefix.sin6_addr),
1483 			    pr->ndpr_plen, if_name(pr->ndpr_ifp), e));
1484 			/* what should we do? */
1485 		}
1486 		ND6_ONLINK_UNLOCK();
1487 	}
1488 
1489 	/* Release references to routers that have advertised this prefix. */
1490 	ND6_WLOCK();
1491 	LIST_FOREACH_SAFE(pfr, &pr->ndpr_advrtrs, pfr_entry, next)
1492 		pfxrtr_del(pfr);
1493 	ND6_WUNLOCK();
1494 
1495 	nd6_prefix_rele(pr);
1496 
1497 	pfxlist_onlink_check();
1498 }
1499 
1500 static int
prelist_update(struct nd_prefixctl * new,struct nd_defrouter * dr,bool auth,int mcast)1501 prelist_update(struct nd_prefixctl *new, struct nd_defrouter *dr,
1502     bool auth, int mcast)
1503 {
1504 	struct in6_ifaddr *ia6 = NULL, *ia6_match = NULL;
1505 	struct ifaddr *ifa;
1506 	struct ifnet *ifp = new->ndpr_ifp;
1507 	struct nd_prefix *pr;
1508 	int error = 0;
1509 	struct in6_addrlifetime lt6_tmp;
1510 	char ip6buf[INET6_ADDRSTRLEN];
1511 	bool has_temporary = false;
1512 
1513 	NET_EPOCH_ASSERT();
1514 
1515 	if ((pr = nd6_prefix_lookup(new)) != NULL) {
1516 		/*
1517 		 * nd6_prefix_lookup() ensures that pr and new have the same
1518 		 * prefix on a same interface.
1519 		 */
1520 
1521 		/*
1522 		 * Update prefix information.  Note that the on-link (L) bit
1523 		 * and the autonomous (A) bit should NOT be changed from 1
1524 		 * to 0.
1525 		 */
1526 		if (new->ndpr_raf_onlink == 1)
1527 			pr->ndpr_raf_onlink = 1;
1528 		if (new->ndpr_raf_auto == 1)
1529 			pr->ndpr_raf_auto = 1;
1530 		if (new->ndpr_raf_onlink) {
1531 			pr->ndpr_vltime = new->ndpr_vltime;
1532 			pr->ndpr_pltime = new->ndpr_pltime;
1533 			in6_init_prefix_ltimes(pr);
1534 			pr->ndpr_lastupdate = time_uptime;
1535 		}
1536 
1537 		if (new->ndpr_raf_onlink &&
1538 		    (pr->ndpr_stateflags & NDPRF_ONLINK) == 0) {
1539 			ND6_ONLINK_LOCK();
1540 			if ((error = nd6_prefix_onlink(pr)) != 0) {
1541 				nd6log((LOG_ERR,
1542 				    "%s: failed to make the prefix %s/%d "
1543 				    "on-link on %s (errno=%d)\n", __func__,
1544 				    ip6_sprintf(ip6buf,
1545 				        &pr->ndpr_prefix.sin6_addr),
1546 				    pr->ndpr_plen, if_name(pr->ndpr_ifp),
1547 				    error));
1548 				/* proceed anyway. XXX: is it correct? */
1549 			}
1550 			ND6_ONLINK_UNLOCK();
1551 		}
1552 
1553 		if (dr != NULL)
1554 			pfxrtr_add(pr, dr);
1555 	} else {
1556 		if (new->ndpr_vltime == 0)
1557 			goto end;
1558 		if (new->ndpr_raf_onlink == 0 && new->ndpr_raf_auto == 0)
1559 			goto end;
1560 
1561 		error = nd6_prelist_add(new, dr, &pr);
1562 		if (error != 0) {
1563 			nd6log((LOG_NOTICE, "%s: nd6_prelist_add() failed for "
1564 			    "the prefix %s/%d on %s (errno=%d)\n", __func__,
1565 			    ip6_sprintf(ip6buf, &new->ndpr_prefix.sin6_addr),
1566 			    new->ndpr_plen, if_name(new->ndpr_ifp), error));
1567 			goto end; /* we should just give up in this case. */
1568 		}
1569 
1570 		/*
1571 		 * XXX: from the ND point of view, we can ignore a prefix
1572 		 * with the on-link bit being zero.  However, we need a
1573 		 * prefix structure for references from autoconfigured
1574 		 * addresses.  Thus, we explicitly make sure that the prefix
1575 		 * itself expires now.
1576 		 */
1577 		if (pr->ndpr_raf_onlink == 0) {
1578 			pr->ndpr_vltime = 0;
1579 			pr->ndpr_pltime = 0;
1580 			in6_init_prefix_ltimes(pr);
1581 		}
1582 	}
1583 
1584 	/*
1585 	 * Address autoconfiguration based on Section 5.5.3 of RFC 2462.
1586 	 * Note that pr must be non NULL at this point.
1587 	 */
1588 
1589 	/* 5.5.3 (a). Ignore the prefix without the A bit set. */
1590 	if (!new->ndpr_raf_auto)
1591 		goto end;
1592 
1593 	/*
1594 	 * 5.5.3 (b). the link-local prefix should have been ignored in
1595 	 * nd6_ra_input.
1596 	 */
1597 
1598 	/* 5.5.3 (c). Consistency check on lifetimes: pltime <= vltime. */
1599 	if (new->ndpr_pltime > new->ndpr_vltime) {
1600 		error = EINVAL;	/* XXX: won't be used */
1601 		goto end;
1602 	}
1603 
1604 	/*
1605 	 * 5.5.3 (d).  If the prefix advertised is not equal to the prefix of
1606 	 * an address configured by stateless autoconfiguration already in the
1607 	 * list of addresses associated with the interface, and the Valid
1608 	 * Lifetime is not 0, form an address.  We first check if we have
1609 	 * a matching prefix.
1610 	 * Note: we apply a clarification in rfc2462bis-02 here.  We only
1611 	 * consider autoconfigured addresses while RFC2462 simply said
1612 	 * "address".
1613 	 */
1614 	CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1615 		struct in6_ifaddr *ifa6;
1616 		u_int32_t remaininglifetime;
1617 
1618 		if (ifa->ifa_addr->sa_family != AF_INET6)
1619 			continue;
1620 
1621 		ifa6 = (struct in6_ifaddr *)ifa;
1622 
1623 		/*
1624 		 * We only consider autoconfigured addresses as per rfc2462bis.
1625 		 */
1626 		if (!(ifa6->ia6_flags & IN6_IFF_AUTOCONF))
1627 			continue;
1628 
1629 		/*
1630 		 * Spec is not clear here, but I believe we should concentrate
1631 		 * on unicast (i.e. not anycast) addresses.
1632 		 * XXX: other ia6_flags? detached or duplicated?
1633 		 */
1634 		if ((ifa6->ia6_flags & IN6_IFF_ANYCAST) != 0)
1635 			continue;
1636 
1637 		/*
1638 		 * Ignore the address if it is not associated with a prefix
1639 		 * or is associated with a prefix that is different from this
1640 		 * one.  (pr is never NULL here)
1641 		 */
1642 		if (ifa6->ia6_ndpr != pr)
1643 			continue;
1644 
1645 		/*
1646 		 * An already autoconfigured address matched.  Now that we
1647 		 * are sure there is at least one matched address, we can
1648 		 * proceed to 5.5.3. (e): update the lifetimes according to the
1649 		 * "two hours" rule and the privacy extension.
1650 		 * We apply some clarifications in rfc2462bis:
1651 		 * - use remaininglifetime instead of storedlifetime as a
1652 		 *   variable name
1653 		 * - remove the dead code in the "two-hour" rule
1654 		 */
1655 #define TWOHOUR		(120*60)
1656 		lt6_tmp = ifa6->ia6_lifetime;
1657 
1658 		if (lt6_tmp.ia6t_vltime == ND6_INFINITE_LIFETIME)
1659 			remaininglifetime = ND6_INFINITE_LIFETIME;
1660 		else if (time_uptime - ifa6->ia6_updatetime >
1661 			 lt6_tmp.ia6t_vltime) {
1662 			/*
1663 			 * The case of "invalid" address.  We should usually
1664 			 * not see this case.
1665 			 */
1666 			remaininglifetime = 0;
1667 		} else
1668 			remaininglifetime = lt6_tmp.ia6t_vltime -
1669 			    (time_uptime - ifa6->ia6_updatetime);
1670 
1671 		/* when not updating, keep the current stored lifetime. */
1672 		lt6_tmp.ia6t_vltime = remaininglifetime;
1673 
1674 		if (TWOHOUR < new->ndpr_vltime ||
1675 		    remaininglifetime < new->ndpr_vltime) {
1676 			lt6_tmp.ia6t_vltime = new->ndpr_vltime;
1677 		} else if (remaininglifetime <= TWOHOUR) {
1678 			if (auth) {
1679 				lt6_tmp.ia6t_vltime = new->ndpr_vltime;
1680 			}
1681 		} else {
1682 			/*
1683 			 * new->ndpr_vltime <= TWOHOUR &&
1684 			 * TWOHOUR < remaininglifetime
1685 			 */
1686 			lt6_tmp.ia6t_vltime = TWOHOUR;
1687 		}
1688 
1689 		/* The 2 hour rule is not imposed for preferred lifetime. */
1690 		lt6_tmp.ia6t_pltime = new->ndpr_pltime;
1691 
1692 		in6_init_address_ltimes(pr, &lt6_tmp);
1693 
1694 		/*
1695 		 * We need to treat lifetimes for temporary addresses
1696 		 * differently, according to
1697 		 * draft-ietf-ipv6-privacy-addrs-v2-01.txt 3.3 (1);
1698 		 * we only update the lifetimes when they are in the maximum
1699 		 * intervals.
1700 		 */
1701 		if ((ifa6->ia6_flags & IN6_IFF_TEMPORARY) != 0) {
1702 			u_int32_t maxvltime, maxpltime;
1703 
1704 			/*
1705 			 * if stable addresses (RFC 7217) are enabled, mark that a temporary address has been found
1706 			 * to avoid generating uneeded extra ones.
1707 			 */
1708 			if (ifp->if_inet6->nd_flags & ND6_IFF_STABLEADDR)
1709 				has_temporary = true;
1710 
1711 			if (V_ip6_temp_valid_lifetime >
1712 			    (u_int32_t)((time_uptime - ifa6->ia6_createtime) +
1713 			    V_ip6_desync_factor)) {
1714 				maxvltime = V_ip6_temp_valid_lifetime -
1715 				    (time_uptime - ifa6->ia6_createtime) -
1716 				    V_ip6_desync_factor;
1717 			} else
1718 				maxvltime = 0;
1719 			if (V_ip6_temp_preferred_lifetime >
1720 			    (u_int32_t)((time_uptime - ifa6->ia6_createtime) +
1721 			    V_ip6_desync_factor)) {
1722 				maxpltime = V_ip6_temp_preferred_lifetime -
1723 				    (time_uptime - ifa6->ia6_createtime) -
1724 				    V_ip6_desync_factor;
1725 			} else
1726 				maxpltime = 0;
1727 
1728 			if (lt6_tmp.ia6t_vltime == ND6_INFINITE_LIFETIME ||
1729 			    lt6_tmp.ia6t_vltime > maxvltime) {
1730 				lt6_tmp.ia6t_vltime = maxvltime;
1731 			}
1732 			if (lt6_tmp.ia6t_pltime == ND6_INFINITE_LIFETIME ||
1733 			    lt6_tmp.ia6t_pltime > maxpltime) {
1734 				lt6_tmp.ia6t_pltime = maxpltime;
1735 			}
1736 		}
1737 		ifa6->ia6_lifetime = lt6_tmp;
1738 		ifa6->ia6_updatetime = time_uptime;
1739 
1740 		/*
1741 		 * If using stable addresses (RFC 7217) and we still have retries to perform, ignore
1742 		 * addresses already marked as duplicated, since a new one will be generated.
1743 		 * Also ignore addresses marked as temporary, since their generation is orthogonal to
1744 		 * opaque stable ones.
1745 		 *
1746 		 * There is a small race condition, in that the dad_counter could be incremented
1747 		 * between here and when a new address is generated, but this will cause that generation
1748 		 * to fail and no further retries should happen.
1749 		 */
1750 		if (ifp->if_inet6->nd_flags & ND6_IFF_STABLEADDR &&
1751 		    atomic_load_int(&DAD_FAILURES(ifp)) <= V_ip6_stableaddr_maxretries &&
1752 		    ifa6->ia6_flags & (IN6_IFF_DUPLICATED | IN6_IFF_TEMPORARY))
1753 			continue;
1754 
1755 		if (ia6_match == NULL) /* remember the first one */
1756 			ia6_match = ifa6;
1757 	}
1758 	if (ia6_match == NULL && new->ndpr_vltime) {
1759 		int ifidlen;
1760 
1761 		/*
1762 		 * 5.5.3 (d) (continued)
1763 		 * No address matched and the valid lifetime is non-zero.
1764 		 * Create a new address.
1765 		 */
1766 
1767 		/*
1768 		 * Prefix Length check:
1769 		 * If the sum of the prefix length and interface identifier
1770 		 * length does not equal 128 bits, the Prefix Information
1771 		 * option MUST be ignored.  The length of the interface
1772 		 * identifier is defined in a separate link-type specific
1773 		 * document.
1774 		 */
1775 		ifidlen = in6_if2idlen(ifp);
1776 		if (ifidlen < 0) {
1777 			/* this should not happen, so we always log it. */
1778 			log(LOG_ERR, "prelist_update: IFID undefined (%s)\n",
1779 			    if_name(ifp));
1780 			goto end;
1781 		}
1782 		if (ifidlen + pr->ndpr_plen != 128) {
1783 			nd6log((LOG_INFO,
1784 			    "%s: invalid prefixlen %d for %s, ignored\n",
1785 			    __func__, pr->ndpr_plen, if_name(ifp)));
1786 			goto end;
1787 		}
1788 
1789 		if ((ia6 = in6_ifadd(new, mcast)) != NULL) {
1790 			/*
1791 			 * note that we should use pr (not new) for reference.
1792 			 */
1793 			pr->ndpr_addrcnt++;
1794 			ia6->ia6_ndpr = pr;
1795 
1796 			/*
1797 			 * RFC 3041 3.3 (2).
1798 			 * When a new public address is created as described
1799 			 * in RFC2462, also create a new temporary address.
1800 			 *
1801 			 * RFC 3041 3.5.
1802 			 * When an interface connects to a new link, a new
1803 			 * randomized interface identifier should be generated
1804 			 * immediately together with a new set of temporary
1805 			 * addresses.  Thus, we specifiy 1 as the 2nd arg of
1806 			 * in6_tmpifadd().
1807 			 *
1808 			 * Skip this if a temporary address has been marked as
1809 			 * found (happens only if stable addresses (RFC 7217) is in use)
1810 			 */
1811 			if (V_ip6_use_tempaddr && !has_temporary) {
1812 				int e;
1813 				if ((e = in6_tmpifadd(ia6, 1, 1)) != 0) {
1814 					nd6log((LOG_NOTICE, "%s: failed to "
1815 					    "create a temporary address "
1816 					    "(errno=%d)\n", __func__, e));
1817 				}
1818 			}
1819 			ifa_free(&ia6->ia_ifa);
1820 
1821 			/*
1822 			 * A newly added address might affect the status
1823 			 * of other addresses, so we check and update it.
1824 			 * XXX: what if address duplication happens?
1825 			 */
1826 			pfxlist_onlink_check();
1827 		} else {
1828 			/* just set an error. do not bark here. */
1829 			error = EADDRNOTAVAIL; /* XXX: might be unused. */
1830 		}
1831 	}
1832 
1833 end:
1834 	if (pr != NULL)
1835 		nd6_prefix_rele(pr);
1836 	return (error);
1837 }
1838 
1839 /*
1840  * A supplement function used in the on-link detection below;
1841  * detect if a given prefix has a (probably) reachable advertising router.
1842  * XXX: lengthy function name...
1843  */
1844 static struct nd_pfxrouter *
find_pfxlist_reachable_router(struct nd_prefix * pr)1845 find_pfxlist_reachable_router(struct nd_prefix *pr)
1846 {
1847 	struct epoch_tracker et;
1848 	struct nd_pfxrouter *pfxrtr;
1849 
1850 	ND6_LOCK_ASSERT();
1851 
1852 	NET_EPOCH_ENTER(et);
1853 	LIST_FOREACH(pfxrtr, &pr->ndpr_advrtrs, pfr_entry) {
1854 		if (is_dr_reachable(pfxrtr->router))
1855 			break;
1856 	}
1857 	NET_EPOCH_EXIT(et);
1858 	return (pfxrtr);
1859 }
1860 
1861 /*
1862  * Check if each prefix in the prefix list has at least one available router
1863  * that advertised the prefix (a router is "available" if its neighbor cache
1864  * entry is reachable or probably reachable).
1865  * If the check fails, the prefix may be off-link, because, for example,
1866  * we have moved from the network but the lifetime of the prefix has not
1867  * expired yet.  So we should not use the prefix if there is another prefix
1868  * that has an available router.
1869  * But, if there is no prefix that has an available router, we still regard
1870  * all the prefixes as on-link.  This is because we can't tell if all the
1871  * routers are simply dead or if we really moved from the network and there
1872  * is no router around us.
1873  */
1874 void
pfxlist_onlink_check(void)1875 pfxlist_onlink_check(void)
1876 {
1877 	struct nd_prefix *pr;
1878 	struct in6_ifaddr *ifa;
1879 	struct nd_defrouter *dr;
1880 	struct nd_pfxrouter *pfxrtr = NULL;
1881 	struct rm_priotracker in6_ifa_tracker;
1882 	uint64_t genid;
1883 	uint32_t flags;
1884 
1885 	ND6_ONLINK_LOCK();
1886 	ND6_RLOCK();
1887 
1888 	/*
1889 	 * Check if there is a prefix that has a reachable advertising
1890 	 * router.
1891 	 */
1892 	LIST_FOREACH(pr, &V_nd_prefix, ndpr_entry) {
1893 		if (pr->ndpr_raf_onlink && find_pfxlist_reachable_router(pr))
1894 			break;
1895 	}
1896 
1897 	/*
1898 	 * If we have no such prefix, check whether we still have a router
1899 	 * that does not advertise any prefixes.
1900 	 */
1901 	if (pr == NULL) {
1902 		TAILQ_FOREACH(dr, &V_nd6_defrouter, dr_entry) {
1903 			struct nd_prefix *pr0;
1904 
1905 			LIST_FOREACH(pr0, &V_nd_prefix, ndpr_entry) {
1906 				if ((pfxrtr = pfxrtr_lookup(pr0, dr)) != NULL)
1907 					break;
1908 			}
1909 			if (pfxrtr != NULL)
1910 				break;
1911 		}
1912 	}
1913 	if (pr != NULL || (!TAILQ_EMPTY(&V_nd6_defrouter) && pfxrtr == NULL)) {
1914 		/*
1915 		 * There is at least one prefix that has a reachable router,
1916 		 * or at least a router which probably does not advertise
1917 		 * any prefixes.  The latter would be the case when we move
1918 		 * to a new link where we have a router that does not provide
1919 		 * prefixes and we configure an address by hand.
1920 		 * Detach prefixes which have no reachable advertising
1921 		 * router, and attach other prefixes.
1922 		 */
1923 		LIST_FOREACH(pr, &V_nd_prefix, ndpr_entry) {
1924 			/* XXX: a link-local prefix should never be detached */
1925 			if (IN6_IS_ADDR_LINKLOCAL(&pr->ndpr_prefix.sin6_addr) ||
1926 			    pr->ndpr_raf_onlink == 0 ||
1927 			    pr->ndpr_raf_auto == 0)
1928 				continue;
1929 
1930 			if ((pr->ndpr_stateflags & NDPRF_DETACHED) == 0 &&
1931 			    find_pfxlist_reachable_router(pr) == NULL)
1932 				pr->ndpr_stateflags |= NDPRF_DETACHED;
1933 			else if ((pr->ndpr_stateflags & NDPRF_DETACHED) != 0 &&
1934 			    find_pfxlist_reachable_router(pr) != NULL)
1935 				pr->ndpr_stateflags &= ~NDPRF_DETACHED;
1936 		}
1937 	} else {
1938 		/* there is no prefix that has a reachable router */
1939 		LIST_FOREACH(pr, &V_nd_prefix, ndpr_entry) {
1940 			if (IN6_IS_ADDR_LINKLOCAL(&pr->ndpr_prefix.sin6_addr) ||
1941 			    pr->ndpr_raf_onlink == 0 ||
1942 			    pr->ndpr_raf_auto == 0)
1943 				continue;
1944 			pr->ndpr_stateflags &= ~NDPRF_DETACHED;
1945 		}
1946 	}
1947 
1948 	/*
1949 	 * Remove each interface route associated with a (just) detached
1950 	 * prefix, and reinstall the interface route for a (just) attached
1951 	 * prefix.  Note that all attempt of reinstallation does not
1952 	 * necessarily success, when a same prefix is shared among multiple
1953 	 * interfaces.  Such cases will be handled in nd6_prefix_onlink,
1954 	 * so we don't have to care about them.
1955 	 */
1956 restart:
1957 	LIST_FOREACH(pr, &V_nd_prefix, ndpr_entry) {
1958 		char ip6buf[INET6_ADDRSTRLEN];
1959 		int e;
1960 
1961 		if (IN6_IS_ADDR_LINKLOCAL(&pr->ndpr_prefix.sin6_addr) ||
1962 		    pr->ndpr_raf_onlink == 0 ||
1963 		    pr->ndpr_raf_auto == 0)
1964 			continue;
1965 
1966 		flags = pr->ndpr_stateflags & (NDPRF_DETACHED | NDPRF_ONLINK);
1967 		if (flags == 0 || flags == (NDPRF_DETACHED | NDPRF_ONLINK)) {
1968 			genid = V_nd6_list_genid;
1969 			ND6_RUNLOCK();
1970 			if ((flags & NDPRF_ONLINK) != 0 &&
1971 			    (e = nd6_prefix_offlink(pr)) != 0) {
1972 				nd6log((LOG_ERR,
1973 				    "%s: failed to make %s/%d offlink "
1974 				    "(errno=%d)\n", __func__,
1975 				    ip6_sprintf(ip6buf,
1976 					    &pr->ndpr_prefix.sin6_addr),
1977 					    pr->ndpr_plen, e));
1978 			} else if ((flags & NDPRF_ONLINK) == 0 &&
1979 			    (e = nd6_prefix_onlink(pr)) != 0) {
1980 				nd6log((LOG_ERR,
1981 				    "%s: failed to make %s/%d onlink "
1982 				    "(errno=%d)\n", __func__,
1983 				    ip6_sprintf(ip6buf,
1984 					    &pr->ndpr_prefix.sin6_addr),
1985 					    pr->ndpr_plen, e));
1986 			}
1987 			ND6_RLOCK();
1988 			if (genid != V_nd6_list_genid)
1989 				goto restart;
1990 		}
1991 	}
1992 
1993 	/*
1994 	 * Changes on the prefix status might affect address status as well.
1995 	 * Make sure that all addresses derived from an attached prefix are
1996 	 * attached, and that all addresses derived from a detached prefix are
1997 	 * detached.  Note, however, that a manually configured address should
1998 	 * always be attached.
1999 	 * The precise detection logic is same as the one for prefixes.
2000 	 */
2001 	IN6_IFADDR_RLOCK(&in6_ifa_tracker);
2002 	CK_STAILQ_FOREACH(ifa, &V_in6_ifaddrhead, ia_link) {
2003 		if (!(ifa->ia6_flags & IN6_IFF_AUTOCONF))
2004 			continue;
2005 
2006 		if (ifa->ia6_ndpr == NULL) {
2007 			/*
2008 			 * This can happen when we first configure the address
2009 			 * (i.e. the address exists, but the prefix does not).
2010 			 * XXX: complicated relationships...
2011 			 */
2012 			continue;
2013 		}
2014 
2015 		if (find_pfxlist_reachable_router(ifa->ia6_ndpr))
2016 			break;
2017 	}
2018 	if (ifa) {
2019 		CK_STAILQ_FOREACH(ifa, &V_in6_ifaddrhead, ia_link) {
2020 			if ((ifa->ia6_flags & IN6_IFF_AUTOCONF) == 0)
2021 				continue;
2022 
2023 			if (ifa->ia6_ndpr == NULL) /* XXX: see above. */
2024 				continue;
2025 
2026 			if (find_pfxlist_reachable_router(ifa->ia6_ndpr)) {
2027 				if (ifa->ia6_flags & IN6_IFF_DETACHED) {
2028 					ifa->ia6_flags &= ~IN6_IFF_DETACHED;
2029 					ifa->ia6_flags |= IN6_IFF_TENTATIVE;
2030 					nd6_dad_start((struct ifaddr *)ifa, 0);
2031 				}
2032 			} else {
2033 				ifa->ia6_flags |= IN6_IFF_DETACHED;
2034 			}
2035 		}
2036 	} else {
2037 		CK_STAILQ_FOREACH(ifa, &V_in6_ifaddrhead, ia_link) {
2038 			if ((ifa->ia6_flags & IN6_IFF_AUTOCONF) == 0)
2039 				continue;
2040 
2041 			if (ifa->ia6_flags & IN6_IFF_DETACHED) {
2042 				ifa->ia6_flags &= ~IN6_IFF_DETACHED;
2043 				ifa->ia6_flags |= IN6_IFF_TENTATIVE;
2044 				/* Do we need a delay in this case? */
2045 				nd6_dad_start((struct ifaddr *)ifa, 0);
2046 			}
2047 		}
2048 	}
2049 	IN6_IFADDR_RUNLOCK(&in6_ifa_tracker);
2050 	ND6_RUNLOCK();
2051 	ND6_ONLINK_UNLOCK();
2052 }
2053 
2054 /*
2055  * Add or remove interface route specified by @dst, @netmask and @ifp.
2056  * ifa can be NULL.
2057  * Returns 0 on success
2058  */
2059 static int
nd6_prefix_rtrequest(uint32_t fibnum,int cmd,struct sockaddr_in6 * dst,struct sockaddr_in6 * netmask,struct ifnet * ifp,struct ifaddr * ifa)2060 nd6_prefix_rtrequest(uint32_t fibnum, int cmd, struct sockaddr_in6 *dst,
2061     struct sockaddr_in6 *netmask, struct ifnet *ifp, struct ifaddr *ifa)
2062 {
2063 	struct epoch_tracker et;
2064 	int error;
2065 
2066 	/* Prepare gateway */
2067 	struct sockaddr_dl_short sdl = {
2068 		.sdl_family = AF_LINK,
2069 		.sdl_len = sizeof(struct sockaddr_dl_short),
2070 		.sdl_type = ifp->if_type,
2071 		.sdl_index = ifp->if_index,
2072 	};
2073 
2074 	struct rt_addrinfo info = {
2075 		.rti_ifa = ifa,
2076 		.rti_ifp = ifp,
2077 		.rti_flags = RTF_PINNED | ((netmask != NULL) ? 0 : RTF_HOST),
2078 		.rti_info = {
2079 			[RTAX_DST] = (struct sockaddr *)dst,
2080 			[RTAX_NETMASK] = (struct sockaddr *)netmask,
2081 			[RTAX_GATEWAY] = (struct sockaddr *)&sdl,
2082 		},
2083 	};
2084 	/* Don't set additional per-gw filters on removal */
2085 
2086 	NET_EPOCH_ENTER(et);
2087 	error = rib_handle_ifaddr_info(fibnum, cmd, &info);
2088 	NET_EPOCH_EXIT(et);
2089 	return (error);
2090 }
2091 
2092 static int
nd6_prefix_onlink_rtrequest(struct nd_prefix * pr,struct ifaddr * ifa)2093 nd6_prefix_onlink_rtrequest(struct nd_prefix *pr, struct ifaddr *ifa)
2094 {
2095 	int error;
2096 
2097 	struct sockaddr_in6 mask6 = {
2098 		.sin6_family = AF_INET6,
2099 		.sin6_len = sizeof(struct sockaddr_in6),
2100 		.sin6_addr = pr->ndpr_mask,
2101 	};
2102 	struct sockaddr_in6 *pmask6 = (pr->ndpr_plen != 128) ? &mask6 : NULL;
2103 
2104 	error = nd6_prefix_rtrequest(pr->ndpr_ifp->if_fib, RTM_ADD,
2105 	    &pr->ndpr_prefix, pmask6, pr->ndpr_ifp, ifa);
2106 	if (error == 0)
2107 		pr->ndpr_stateflags |= NDPRF_ONLINK;
2108 
2109 	return (error);
2110 }
2111 
2112 static int
nd6_prefix_onlink(struct nd_prefix * pr)2113 nd6_prefix_onlink(struct nd_prefix *pr)
2114 {
2115 	struct epoch_tracker et;
2116 	struct ifaddr *ifa;
2117 	struct ifnet *ifp = pr->ndpr_ifp;
2118 	struct nd_prefix *opr;
2119 	char ip6buf[INET6_ADDRSTRLEN];
2120 	int error;
2121 
2122 	ND6_ONLINK_LOCK_ASSERT();
2123 	ND6_UNLOCK_ASSERT();
2124 
2125 	if ((pr->ndpr_stateflags & NDPRF_ONLINK) != 0)
2126 		return (EEXIST);
2127 
2128 	/*
2129 	 * Add the interface route associated with the prefix.  Before
2130 	 * installing the route, check if there's the same prefix on another
2131 	 * interface, and the prefix has already installed the interface route.
2132 	 * Although such a configuration is expected to be rare, we explicitly
2133 	 * allow it.
2134 	 */
2135 	ND6_RLOCK();
2136 	LIST_FOREACH(opr, &V_nd_prefix, ndpr_entry) {
2137 		if (opr == pr)
2138 			continue;
2139 
2140 		if ((opr->ndpr_stateflags & NDPRF_ONLINK) == 0)
2141 			continue;
2142 
2143 		if (!V_rt_add_addr_allfibs &&
2144 		    opr->ndpr_ifp->if_fib != pr->ndpr_ifp->if_fib)
2145 			continue;
2146 
2147 		if (opr->ndpr_plen == pr->ndpr_plen &&
2148 		    in6_are_prefix_equal(&pr->ndpr_prefix.sin6_addr,
2149 		    &opr->ndpr_prefix.sin6_addr, pr->ndpr_plen)) {
2150 			ND6_RUNLOCK();
2151 			return (0);
2152 		}
2153 	}
2154 	ND6_RUNLOCK();
2155 
2156 	/*
2157 	 * We prefer link-local addresses as the associated interface address.
2158 	 */
2159 	/* search for a link-local addr */
2160 	NET_EPOCH_ENTER(et);
2161 	ifa = (struct ifaddr *)in6ifa_ifpforlinklocal(ifp,
2162 	    IN6_IFF_NOTREADY | IN6_IFF_ANYCAST);
2163 	if (ifa == NULL) {
2164 		/* XXX: freebsd does not have ifa_ifwithaf */
2165 		CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
2166 			if (ifa->ifa_addr->sa_family == AF_INET6) {
2167 				ifa_ref(ifa);
2168 				break;
2169 			}
2170 		}
2171 		/* should we care about ia6_flags? */
2172 	}
2173 	if (ifa == NULL) {
2174 		/*
2175 		 * This can still happen, when, for example, we receive an RA
2176 		 * containing a prefix with the L bit set and the A bit clear,
2177 		 * after removing all IPv6 addresses on the receiving
2178 		 * interface.  This should, of course, be rare though.
2179 		 */
2180 		nd6log((LOG_NOTICE,
2181 		    "%s: failed to find any ifaddr to add route for a "
2182 		    "prefix(%s/%d) on %s\n", __func__,
2183 		    ip6_sprintf(ip6buf, &pr->ndpr_prefix.sin6_addr),
2184 		    pr->ndpr_plen, if_name(ifp)));
2185 		error = 0;
2186 	} else {
2187 		error = nd6_prefix_onlink_rtrequest(pr, ifa);
2188 		ifa_free(ifa);
2189 	}
2190 	NET_EPOCH_EXIT(et);
2191 
2192 	return (error);
2193 }
2194 
2195 int
nd6_prefix_offlink(struct nd_prefix * pr)2196 nd6_prefix_offlink(struct nd_prefix *pr)
2197 {
2198 	int error = 0;
2199 	struct ifnet *ifp = pr->ndpr_ifp;
2200 	struct nd_prefix *opr;
2201 	char ip6buf[INET6_ADDRSTRLEN];
2202 	uint64_t genid;
2203 	int a_failure;
2204 
2205 	ND6_ONLINK_LOCK_ASSERT();
2206 	ND6_UNLOCK_ASSERT();
2207 
2208 	if ((pr->ndpr_stateflags & NDPRF_ONLINK) == 0)
2209 		return (EEXIST);
2210 
2211 	struct sockaddr_in6 mask6 = {
2212 		.sin6_family = AF_INET6,
2213 		.sin6_len = sizeof(struct sockaddr_in6),
2214 		.sin6_addr = pr->ndpr_mask,
2215 	};
2216 	struct sockaddr_in6 *pmask6 = (pr->ndpr_plen != 128) ? &mask6 : NULL;
2217 
2218 	error = nd6_prefix_rtrequest(ifp->if_fib, RTM_DELETE,
2219 	    &pr->ndpr_prefix, pmask6, ifp, NULL);
2220 
2221 	a_failure = 1;
2222 	if (error == 0) {
2223 		pr->ndpr_stateflags &= ~NDPRF_ONLINK;
2224 
2225 		/*
2226 		 * There might be the same prefix on another interface,
2227 		 * the prefix which could not be on-link just because we have
2228 		 * the interface route (see comments in nd6_prefix_onlink).
2229 		 * If there's one, try to make the prefix on-link on the
2230 		 * interface.
2231 		 */
2232 		ND6_RLOCK();
2233 restart:
2234 		LIST_FOREACH(opr, &V_nd_prefix, ndpr_entry) {
2235 			/*
2236 			 * KAME specific: detached prefixes should not be
2237 			 * on-link.
2238 			 */
2239 			if (opr == pr || (opr->ndpr_stateflags &
2240 			    (NDPRF_ONLINK | NDPRF_DETACHED)) != 0)
2241 				continue;
2242 
2243 			if (opr->ndpr_plen == pr->ndpr_plen &&
2244 			    in6_are_prefix_equal(&pr->ndpr_prefix.sin6_addr,
2245 			    &opr->ndpr_prefix.sin6_addr, pr->ndpr_plen)) {
2246 				int e;
2247 
2248 				genid = V_nd6_list_genid;
2249 				ND6_RUNLOCK();
2250 				if ((e = nd6_prefix_onlink(opr)) != 0) {
2251 					nd6log((LOG_ERR,
2252 					    "%s: failed to recover a prefix "
2253 					    "%s/%d from %s to %s (errno=%d)\n",
2254 					    __func__, ip6_sprintf(ip6buf,
2255 						&opr->ndpr_prefix.sin6_addr),
2256 					    opr->ndpr_plen, if_name(ifp),
2257 					    if_name(opr->ndpr_ifp), e));
2258 				} else
2259 					a_failure = 0;
2260 				ND6_RLOCK();
2261 				if (genid != V_nd6_list_genid)
2262 					goto restart;
2263 			}
2264 		}
2265 		ND6_RUNLOCK();
2266 	} else {
2267 		/* XXX: can we still set the NDPRF_ONLINK flag? */
2268 		nd6log((LOG_ERR,
2269 		    "%s: failed to delete route: %s/%d on %s (errno=%d)\n",
2270 		    __func__, ip6_sprintf(ip6buf, &pr->ndpr_prefix.sin6_addr),
2271 		    pr->ndpr_plen, if_name(ifp), error));
2272 	}
2273 
2274 	if (a_failure)
2275 		lltable_prefix_free(AF_INET6,
2276 		    (struct sockaddr *)&pr->ndpr_prefix,
2277 		    (struct sockaddr *)&mask6, LLE_STATIC);
2278 
2279 	return (error);
2280 }
2281 
2282 /*
2283  * Get a randomized interface identifier for a temporary address
2284  * Based on RFC 8981, Section 3.3.1.
2285  */
2286 static int
in6_get_tmp_ifid(struct in6_aliasreq * ifra)2287 in6_get_tmp_ifid(struct in6_aliasreq *ifra)
2288 {
2289 	struct in6_addr *addr;
2290 
2291 	if(!is_random_seeded()){
2292 		return 1;
2293 	}
2294 
2295 	addr = &(ifra->ifra_addr.sin6_addr);
2296 regen:
2297 	ifra->ifra_addr.sin6_addr.s6_addr32[2] |=
2298 	    (arc4random() & ~(ifra->ifra_prefixmask.sin6_addr.s6_addr32[2]));
2299 	ifra->ifra_addr.sin6_addr.s6_addr32[3] |=
2300 	    (arc4random() & ~(ifra->ifra_prefixmask.sin6_addr.s6_addr32[3]));
2301 
2302 	/*
2303 	 * Check if generated address is not inappropriate:
2304 	 *
2305 	 * - Reserved IPv6 Interface Identifiers
2306 	 *   (https://www.iana.org/assignments/ipv6-interface-ids/)
2307 	 */
2308 
2309 	/* Subnet-router anycast: 0000:0000:0000:0000 */
2310 	if (!(addr->s6_addr32[2] | addr->s6_addr32[3]))
2311 		goto regen;
2312 
2313 	/*
2314 	 * IANA Ethernet block: 0200:5EFF:FE00:0000-0200:5EFF:FE00:5212
2315 	 * Proxy Mobile IPv6:   0200:5EFF:FE00:5213
2316 	 * IANA Ethernet block: 0200:5EFF:FE00:5214-0200:5EFF:FEFF:FFFF
2317 	 */
2318 	if (ntohl(addr->s6_addr32[2]) == 0x02005eff &&
2319 	    (ntohl(addr->s6_addr32[3]) & 0Xff000000) == 0xfe000000)
2320 		goto regen;
2321 
2322 	/* Reserved subnet anycast addresses */
2323 	if (ntohl(addr->s6_addr32[2]) == 0xfdffffff &&
2324 	    ntohl(addr->s6_addr32[3]) >= 0Xffffff80)
2325 		goto regen;
2326 
2327 	return 0;
2328 }
2329 
2330 /*
2331  * ia0 - corresponding public address
2332  */
2333 int
in6_tmpifadd(const struct in6_ifaddr * ia0,int forcegen,int delay)2334 in6_tmpifadd(const struct in6_ifaddr *ia0, int forcegen, int delay)
2335 {
2336 	struct ifnet *ifp = ia0->ia_ifa.ifa_ifp;
2337 	struct in6_ifaddr *newia;
2338 	struct in6_aliasreq ifra;
2339 	int error;
2340 	int trylimit = 3;	/* XXX: adhoc value */
2341 	int updateflags;
2342 	time_t vltime0, pltime0;
2343 
2344 	in6_prepare_ifra(&ifra, &ia0->ia_addr.sin6_addr,
2345 	    &ia0->ia_prefixmask.sin6_addr);
2346 
2347 	ifra.ifra_addr = ia0->ia_addr;	/* XXX: do we need this ? */
2348 	/* clear the old IFID */
2349 	IN6_MASK_ADDR(&ifra.ifra_addr.sin6_addr,
2350 	    &ifra.ifra_prefixmask.sin6_addr);
2351 
2352   again:
2353 	if (in6_get_tmp_ifid(&ifra) != 0) {
2354 		nd6log((LOG_NOTICE, "%s: failed to find a good random IFID\n",
2355 		    __func__));
2356 		return (EINVAL);
2357 	}
2358 
2359 	/*
2360 	 * in6_get_tmpifid() quite likely provided a unique interface ID.
2361 	 * However, we may still have a chance to see collision, because
2362 	 * there may be a time lag between generation of the ID and generation
2363 	 * of the address.  So, we'll do one more sanity check.
2364 	 */
2365 
2366 	if (in6_localip(&ifra.ifra_addr.sin6_addr) != 0) {
2367 		if (trylimit-- > 0) {
2368 			forcegen = 1;
2369 			goto again;
2370 		}
2371 
2372 		/* Give up.  Something strange should have happened.  */
2373 		nd6log((LOG_NOTICE, "%s: failed to find a unique random IFID\n",
2374 		    __func__));
2375 		return (EEXIST);
2376 	}
2377 
2378 	/*
2379 	 * The Valid Lifetime is the lower of the Valid Lifetime of the
2380          * public address or TEMP_VALID_LIFETIME.
2381 	 * The Preferred Lifetime is the lower of the Preferred Lifetime
2382          * of the public address or TEMP_PREFERRED_LIFETIME -
2383          * DESYNC_FACTOR.
2384 	 */
2385 	if (ia0->ia6_lifetime.ia6t_vltime != ND6_INFINITE_LIFETIME) {
2386 		vltime0 = IFA6_IS_INVALID(ia0) ? 0 :
2387 		    (ia0->ia6_lifetime.ia6t_vltime -
2388 		    (time_uptime - ia0->ia6_updatetime));
2389 		if (vltime0 > V_ip6_temp_valid_lifetime)
2390 			vltime0 = V_ip6_temp_valid_lifetime;
2391 	} else
2392 		vltime0 = V_ip6_temp_valid_lifetime;
2393 	if (ia0->ia6_lifetime.ia6t_pltime != ND6_INFINITE_LIFETIME) {
2394 		pltime0 = IFA6_IS_DEPRECATED(ia0) ? 0 :
2395 		    (ia0->ia6_lifetime.ia6t_pltime -
2396 		    (time_uptime - ia0->ia6_updatetime));
2397 		if (pltime0 > V_ip6_temp_preferred_lifetime - V_ip6_desync_factor){
2398 			pltime0 = V_ip6_temp_preferred_lifetime -
2399 			    V_ip6_desync_factor;
2400 		}
2401 	} else
2402 		pltime0 = V_ip6_temp_preferred_lifetime - V_ip6_desync_factor;
2403 	ifra.ifra_lifetime.ia6t_vltime = vltime0;
2404 	ifra.ifra_lifetime.ia6t_pltime = pltime0;
2405 
2406 	/*
2407 	 * A temporary address is created only if this calculated Preferred
2408 	 * Lifetime is greater than REGEN_ADVANCE time units.
2409 	 */
2410 	if (ifra.ifra_lifetime.ia6t_pltime <= V_ip6_temp_regen_advance)
2411 		return (0);
2412 
2413 	/* XXX: scope zone ID? */
2414 
2415 	ifra.ifra_flags |= (IN6_IFF_AUTOCONF|IN6_IFF_TEMPORARY);
2416 
2417 	/* allocate ifaddr structure, link into chain, etc. */
2418 	updateflags = 0;
2419 	if (delay)
2420 		updateflags |= IN6_IFAUPDATE_DADDELAY;
2421 	if ((error = in6_update_ifa(ifp, &ifra, NULL, updateflags)) != 0)
2422 		return (error);
2423 
2424 	newia = in6ifa_ifpwithaddr(ifp, &ifra.ifra_addr.sin6_addr);
2425 	if (newia == NULL) {	/* XXX: can it happen? */
2426 		nd6log((LOG_ERR,
2427 		    "%s: ifa update succeeded, but we got no ifaddr\n",
2428 		    __func__));
2429 		return (EINVAL); /* XXX */
2430 	}
2431 	newia->ia6_ndpr = ia0->ia6_ndpr;
2432 	newia->ia6_ndpr->ndpr_addrcnt++;
2433 	ifa_free(&newia->ia_ifa);
2434 
2435 	/*
2436 	 * A newly added address might affect the status of other addresses.
2437 	 * XXX: when the temporary address is generated with a new public
2438 	 * address, the onlink check is redundant.  However, it would be safe
2439 	 * to do the check explicitly everywhere a new address is generated,
2440 	 * and, in fact, we surely need the check when we create a new
2441 	 * temporary address due to deprecation of an old temporary address.
2442 	 */
2443 	pfxlist_onlink_check();
2444 
2445 	return (0);
2446 }
2447 
2448 static int
rt6_deleteroute(const struct rtentry * rt,const struct nhop_object * nh,void * arg)2449 rt6_deleteroute(const struct rtentry *rt, const struct nhop_object *nh,
2450     void *arg)
2451 {
2452 	struct in6_addr *gate = (struct in6_addr *)arg;
2453 	int nh_rt_flags;
2454 
2455 	if (nh->gw_sa.sa_family != AF_INET6)
2456 		return (0);
2457 
2458 	if (!IN6_ARE_ADDR_EQUAL(gate, &nh->gw6_sa.sin6_addr)) {
2459 		return (0);
2460 	}
2461 
2462 	/*
2463 	 * Do not delete a static route.
2464 	 * XXX: this seems to be a bit ad-hoc. Should we consider the
2465 	 * 'cloned' bit instead?
2466 	 */
2467 	nh_rt_flags = nhop_get_rtflags(nh);
2468 	if ((nh_rt_flags & RTF_STATIC) != 0)
2469 		return (0);
2470 
2471 	/*
2472 	 * We delete only host route. This means, in particular, we don't
2473 	 * delete default route.
2474 	 */
2475 	if ((nh_rt_flags & RTF_HOST) == 0)
2476 		return (0);
2477 
2478 	return (1);
2479 #undef SIN6
2480 }
2481 
2482 /*
2483  * Delete all the routing table entries that use the specified gateway.
2484  * XXX: this function causes search through all entries of routing table, so
2485  * it shouldn't be called when acting as a router.
2486  */
2487 void
rt6_flush(struct in6_addr * gateway,struct ifnet * ifp)2488 rt6_flush(struct in6_addr *gateway, struct ifnet *ifp)
2489 {
2490 
2491 	/* We'll care only link-local addresses */
2492 	if (!IN6_IS_ADDR_LINKLOCAL(gateway))
2493 		return;
2494 
2495 	/* XXX Do we really need to walk any but the default FIB? */
2496 	rib_foreach_table_walk_del(AF_INET6, rt6_deleteroute, (void *)gateway);
2497 }
2498 
2499 int
nd6_setdefaultiface(int ifindex)2500 nd6_setdefaultiface(int ifindex)
2501 {
2502 
2503 	if (V_nd6_defifindex != ifindex) {
2504 		V_nd6_defifindex = ifindex;
2505 		if (V_nd6_defifindex != 0) {
2506 			struct epoch_tracker et;
2507 
2508 			/*
2509 			 * XXXGL: this function should use ifnet_byindex_ref!
2510 			 */
2511 			NET_EPOCH_ENTER(et);
2512 			V_nd6_defifp = ifnet_byindex(V_nd6_defifindex);
2513 			NET_EPOCH_EXIT(et);
2514 			if (V_nd6_defifp == NULL)
2515 				return (EINVAL);
2516 		} else
2517 			V_nd6_defifp = NULL;
2518 
2519 		/*
2520 		 * Our current implementation assumes one-to-one mapping between
2521 		 * interfaces and links, so it would be natural to use the
2522 		 * default interface as the default link.
2523 		 */
2524 		scope6_setdefault(V_nd6_defifp);
2525 	}
2526 
2527 	return (0);
2528 }
2529 
2530 bool
nd6_defrouter_list_empty(void)2531 nd6_defrouter_list_empty(void)
2532 {
2533 
2534 	return (TAILQ_EMPTY(&V_nd6_defrouter));
2535 }
2536 
2537 void
nd6_defrouter_timer(void)2538 nd6_defrouter_timer(void)
2539 {
2540 	struct nd_defrouter *dr, *ndr;
2541 	struct nd6_drhead drq;
2542 
2543 	TAILQ_INIT(&drq);
2544 
2545 	ND6_WLOCK();
2546 	TAILQ_FOREACH_SAFE(dr, &V_nd6_defrouter, dr_entry, ndr)
2547 		if (dr->expire && dr->expire < time_uptime)
2548 			defrouter_unlink(dr, &drq);
2549 	ND6_WUNLOCK();
2550 
2551 	while ((dr = TAILQ_FIRST(&drq)) != NULL) {
2552 		TAILQ_REMOVE(&drq, dr, dr_entry);
2553 		defrouter_del(dr);
2554 	}
2555 }
2556 
2557 /*
2558  * Nuke default router list entries toward ifp.
2559  * We defer removal of default router list entries that is installed in the
2560  * routing table, in order to keep additional side effects as small as possible.
2561  */
2562 void
nd6_defrouter_purge(struct ifnet * ifp)2563 nd6_defrouter_purge(struct ifnet *ifp)
2564 {
2565 	struct nd_defrouter *dr, *ndr;
2566 	struct nd6_drhead drq;
2567 
2568 	TAILQ_INIT(&drq);
2569 
2570 	ND6_WLOCK();
2571 	TAILQ_FOREACH_SAFE(dr, &V_nd6_defrouter, dr_entry, ndr) {
2572 		if (dr->installed)
2573 			continue;
2574 		if (dr->ifp == ifp)
2575 			defrouter_unlink(dr, &drq);
2576 	}
2577 	TAILQ_FOREACH_SAFE(dr, &V_nd6_defrouter, dr_entry, ndr) {
2578 		if (!dr->installed)
2579 			continue;
2580 		if (dr->ifp == ifp)
2581 			defrouter_unlink(dr, &drq);
2582 	}
2583 	ND6_WUNLOCK();
2584 
2585 	/* Delete the unlinked router objects. */
2586 	while ((dr = TAILQ_FIRST(&drq)) != NULL) {
2587 		TAILQ_REMOVE(&drq, dr, dr_entry);
2588 		defrouter_del(dr);
2589 	}
2590 }
2591 
2592 void
nd6_defrouter_flush_all(void)2593 nd6_defrouter_flush_all(void)
2594 {
2595 	struct nd_defrouter *dr;
2596 	struct nd6_drhead drq;
2597 
2598 	TAILQ_INIT(&drq);
2599 
2600 	ND6_WLOCK();
2601 	while ((dr = TAILQ_FIRST(&V_nd6_defrouter)) != NULL)
2602 		defrouter_unlink(dr, &drq);
2603 	ND6_WUNLOCK();
2604 
2605 	while ((dr = TAILQ_FIRST(&drq)) != NULL) {
2606 		TAILQ_REMOVE(&drq, dr, dr_entry);
2607 		defrouter_del(dr);
2608 	}
2609 }
2610 
2611 void
nd6_defrouter_init(void)2612 nd6_defrouter_init(void)
2613 {
2614 
2615 	TAILQ_INIT(&V_nd6_defrouter);
2616 }
2617 
2618 static int
nd6_sysctl_drlist(SYSCTL_HANDLER_ARGS)2619 nd6_sysctl_drlist(SYSCTL_HANDLER_ARGS)
2620 {
2621 	struct in6_defrouter d;
2622 	struct nd_defrouter *dr;
2623 	int error;
2624 
2625 	if (req->newptr != NULL)
2626 		return (EPERM);
2627 
2628 	error = sysctl_wire_old_buffer(req, 0);
2629 	if (error != 0)
2630 		return (error);
2631 
2632 	bzero(&d, sizeof(d));
2633 	d.rtaddr.sin6_family = AF_INET6;
2634 	d.rtaddr.sin6_len = sizeof(d.rtaddr);
2635 
2636 	ND6_RLOCK();
2637 	TAILQ_FOREACH(dr, &V_nd6_defrouter, dr_entry) {
2638 		d.rtaddr.sin6_addr = dr->rtaddr;
2639 		error = sa6_recoverscope(&d.rtaddr);
2640 		if (error != 0)
2641 			break;
2642 		d.flags = dr->raflags;
2643 		d.rtlifetime = dr->rtlifetime;
2644 		d.expire = dr->expire + (time_second - time_uptime);
2645 		d.if_index = dr->ifp->if_index;
2646 		error = SYSCTL_OUT(req, &d, sizeof(d));
2647 		if (error != 0)
2648 			break;
2649 	}
2650 	ND6_RUNLOCK();
2651 	return (error);
2652 }
2653 SYSCTL_PROC(_net_inet6_icmp6, ICMPV6CTL_ND6_DRLIST, nd6_drlist,
2654 	CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_MPSAFE,
2655 	NULL, 0, nd6_sysctl_drlist, "S,in6_defrouter",
2656 	"NDP default router list");
2657