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