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