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