xref: /linux/net/ipv6/addrconf.c (revision 91ec2035134982b98fab0609a9fd8480e8217dc1)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  *	IPv6 Address [auto]configuration
4  *	Linux INET6 implementation
5  *
6  *	Authors:
7  *	Pedro Roque		<roque@di.fc.ul.pt>
8  *	Alexey Kuznetsov	<kuznet@ms2.inr.ac.ru>
9  */
10 
11 /*
12  *	Changes:
13  *
14  *	Janos Farkas			:	delete timer on ifdown
15  *	<chexum@bankinf.banki.hu>
16  *	Andi Kleen			:	kill double kfree on module
17  *						unload.
18  *	Maciej W. Rozycki		:	FDDI support
19  *	sekiya@USAGI			:	Don't send too many RS
20  *						packets.
21  *	yoshfuji@USAGI			:       Fixed interval between DAD
22  *						packets.
23  *	YOSHIFUJI Hideaki @USAGI	:	improved accuracy of
24  *						address validation timer.
25  *	YOSHIFUJI Hideaki @USAGI	:	Privacy Extensions (RFC3041)
26  *						support.
27  *	Yuji SEKIYA @USAGI		:	Don't assign a same IPv6
28  *						address on a same interface.
29  *	YOSHIFUJI Hideaki @USAGI	:	ARCnet support
30  *	YOSHIFUJI Hideaki @USAGI	:	convert /proc/net/if_inet6 to
31  *						seq_file.
32  *	YOSHIFUJI Hideaki @USAGI	:	improved source address
33  *						selection; consider scope,
34  *						status etc.
35  */
36 
37 #define pr_fmt(fmt) "IPv6: " fmt
38 
39 #include <crypto/sha1.h>
40 #include <linux/errno.h>
41 #include <linux/types.h>
42 #include <linux/kernel.h>
43 #include <linux/sched/signal.h>
44 #include <linux/socket.h>
45 #include <linux/sockios.h>
46 #include <linux/net.h>
47 #include <linux/inet.h>
48 #include <linux/in6.h>
49 #include <linux/netdevice.h>
50 #include <linux/if_addr.h>
51 #include <linux/if_arp.h>
52 #include <linux/if_arcnet.h>
53 #include <linux/if_infiniband.h>
54 #include <linux/route.h>
55 #include <linux/inetdevice.h>
56 #include <linux/init.h>
57 #include <linux/slab.h>
58 #ifdef CONFIG_SYSCTL
59 #include <linux/sysctl.h>
60 #endif
61 #include <linux/capability.h>
62 #include <linux/delay.h>
63 #include <linux/notifier.h>
64 #include <linux/string.h>
65 #include <linux/hash.h>
66 
67 #include <net/ip_tunnels.h>
68 #include <net/net_namespace.h>
69 #include <net/sock.h>
70 #include <net/snmp.h>
71 
72 #include <net/6lowpan.h>
73 #include <net/firewire.h>
74 #include <net/ipv6.h>
75 #include <net/protocol.h>
76 #include <net/ndisc.h>
77 #include <net/ip6_route.h>
78 #include <net/addrconf.h>
79 #include <net/tcp.h>
80 #include <net/ip.h>
81 #include <net/netlink.h>
82 #include <net/pkt_sched.h>
83 #include <net/l3mdev.h>
84 #include <net/netdev_lock.h>
85 #include <linux/if_tunnel.h>
86 #include <linux/rtnetlink.h>
87 #include <linux/netconf.h>
88 #include <linux/random.h>
89 #include <linux/uaccess.h>
90 #include <linux/unaligned.h>
91 
92 #include <linux/proc_fs.h>
93 #include <linux/seq_file.h>
94 #include <linux/export.h>
95 #include <linux/ioam6.h>
96 
97 #define IPV6_MAX_STRLEN \
98 	sizeof("ffff:ffff:ffff:ffff:ffff:ffff:255.255.255.255")
99 
cstamp_delta(unsigned long cstamp)100 static inline u32 cstamp_delta(unsigned long cstamp)
101 {
102 	return (cstamp - INITIAL_JIFFIES) * 100UL / HZ;
103 }
104 
rfc3315_s14_backoff_init(s32 irt)105 static inline s32 rfc3315_s14_backoff_init(s32 irt)
106 {
107 	/* multiply 'initial retransmission time' by 0.9 .. 1.1 */
108 	u64 tmp = get_random_u32_inclusive(900000, 1100000) * (u64)irt;
109 	do_div(tmp, 1000000);
110 	return (s32)tmp;
111 }
112 
rfc3315_s14_backoff_update(s32 rt,s32 mrt)113 static inline s32 rfc3315_s14_backoff_update(s32 rt, s32 mrt)
114 {
115 	/* multiply 'retransmission timeout' by 1.9 .. 2.1 */
116 	u64 tmp = get_random_u32_inclusive(1900000, 2100000) * (u64)rt;
117 	do_div(tmp, 1000000);
118 	if ((s32)tmp > mrt) {
119 		/* multiply 'maximum retransmission time' by 0.9 .. 1.1 */
120 		tmp = get_random_u32_inclusive(900000, 1100000) * (u64)mrt;
121 		do_div(tmp, 1000000);
122 	}
123 	return (s32)tmp;
124 }
125 
126 #ifdef CONFIG_SYSCTL
127 static int addrconf_sysctl_register(struct inet6_dev *idev);
128 static void addrconf_sysctl_unregister(struct inet6_dev *idev);
129 #else
addrconf_sysctl_register(struct inet6_dev * idev)130 static inline int addrconf_sysctl_register(struct inet6_dev *idev)
131 {
132 	return 0;
133 }
134 
addrconf_sysctl_unregister(struct inet6_dev * idev)135 static inline void addrconf_sysctl_unregister(struct inet6_dev *idev)
136 {
137 }
138 #endif
139 
140 static void ipv6_gen_rnd_iid(struct in6_addr *addr);
141 
142 static int ipv6_generate_eui64(u8 *eui, struct net_device *dev);
143 static int ipv6_count_addresses(const struct inet6_dev *idev);
144 static int ipv6_generate_stable_address(struct in6_addr *addr,
145 					u8 dad_count,
146 					const struct inet6_dev *idev);
147 
148 #define IN6_ADDR_HSIZE_SHIFT	8
149 #define IN6_ADDR_HSIZE		(1 << IN6_ADDR_HSIZE_SHIFT)
150 
151 static void addrconf_verify(struct net *net);
152 static void addrconf_verify_rtnl(struct net *net);
153 
154 static struct workqueue_struct *addrconf_wq;
155 
156 static void addrconf_join_anycast(struct inet6_ifaddr *ifp);
157 static void addrconf_leave_anycast(struct inet6_ifaddr *ifp);
158 
159 static void addrconf_type_change(struct net_device *dev,
160 				 unsigned long event);
161 static int addrconf_ifdown(struct net_device *dev, bool unregister);
162 
163 static struct fib6_info *addrconf_get_prefix_route(const struct in6_addr *pfx,
164 						  int plen,
165 						  const struct net_device *dev,
166 						  u32 flags, u32 noflags,
167 						  bool no_gw);
168 
169 static void addrconf_dad_start(struct inet6_ifaddr *ifp);
170 static void addrconf_dad_work(struct work_struct *w);
171 static void addrconf_dad_completed(struct inet6_ifaddr *ifp, bool bump_id,
172 				   bool send_na);
173 static void addrconf_dad_run(struct inet6_dev *idev, bool restart);
174 static void addrconf_rs_timer(struct timer_list *t);
175 static void __ipv6_ifa_notify(int event, struct inet6_ifaddr *ifa);
176 static void ipv6_ifa_notify(int event, struct inet6_ifaddr *ifa);
177 
178 static void inet6_prefix_notify(int event, struct inet6_dev *idev,
179 				struct prefix_info *pinfo);
180 
181 static struct ipv6_devconf ipv6_devconf __read_mostly = {
182 	.forwarding		= 0,
183 	.hop_limit		= IPV6_DEFAULT_HOPLIMIT,
184 	.mtu6			= IPV6_MIN_MTU,
185 	.accept_ra		= 1,
186 	.accept_redirects	= 1,
187 	.autoconf		= 1,
188 	.force_mld_version	= 0,
189 	.mldv1_unsolicited_report_interval = 10 * HZ,
190 	.mldv2_unsolicited_report_interval = HZ,
191 	.dad_transmits		= 1,
192 	.rtr_solicits		= MAX_RTR_SOLICITATIONS,
193 	.rtr_solicit_interval	= RTR_SOLICITATION_INTERVAL,
194 	.rtr_solicit_max_interval = RTR_SOLICITATION_MAX_INTERVAL,
195 	.rtr_solicit_delay	= MAX_RTR_SOLICITATION_DELAY,
196 	.use_tempaddr		= 0,
197 	.temp_valid_lft		= TEMP_VALID_LIFETIME,
198 	.temp_prefered_lft	= TEMP_PREFERRED_LIFETIME,
199 	.regen_min_advance	= REGEN_MIN_ADVANCE,
200 	.regen_max_retry	= REGEN_MAX_RETRY,
201 	.max_desync_factor	= MAX_DESYNC_FACTOR,
202 	.max_addresses		= IPV6_MAX_ADDRESSES,
203 	.accept_ra_defrtr	= 1,
204 	.ra_defrtr_metric	= IP6_RT_PRIO_USER,
205 	.accept_ra_from_local	= 0,
206 	.accept_ra_min_hop_limit= 1,
207 	.accept_ra_min_lft	= 0,
208 	.accept_ra_pinfo	= 1,
209 #ifdef CONFIG_IPV6_ROUTER_PREF
210 	.accept_ra_rtr_pref	= 1,
211 	.rtr_probe_interval	= 60 * HZ,
212 #ifdef CONFIG_IPV6_ROUTE_INFO
213 	.accept_ra_rt_info_min_plen = 0,
214 	.accept_ra_rt_info_max_plen = 0,
215 #endif
216 #endif
217 	.proxy_ndp		= 0,
218 	.accept_source_route	= 0,	/* we do not accept RH0 by default. */
219 	.disable_ipv6		= 0,
220 	.accept_dad		= 0,
221 	.suppress_frag_ndisc	= 1,
222 	.accept_ra_mtu		= 1,
223 	.stable_secret		= {
224 		.initialized = false,
225 	},
226 	.use_oif_addrs_only	= 0,
227 	.ignore_routes_with_linkdown = 0,
228 	.keep_addr_on_down	= 0,
229 	.seg6_enabled		= 0,
230 #ifdef CONFIG_IPV6_SEG6_HMAC
231 	.seg6_require_hmac	= 0,
232 #endif
233 	.enhanced_dad           = 1,
234 	.addr_gen_mode		= IN6_ADDR_GEN_MODE_EUI64,
235 	.disable_policy		= 0,
236 	.rpl_seg_enabled	= 0,
237 	.ioam6_enabled		= 0,
238 	.ioam6_id               = IOAM6_DEFAULT_IF_ID,
239 	.ioam6_id_wide		= IOAM6_DEFAULT_IF_ID_WIDE,
240 	.ndisc_evict_nocarrier	= 1,
241 	.ra_honor_pio_life	= 0,
242 	.ra_honor_pio_pflag	= 0,
243 	.force_forwarding	= 0,
244 };
245 
246 static struct ipv6_devconf ipv6_devconf_dflt __read_mostly = {
247 	.forwarding		= 0,
248 	.hop_limit		= IPV6_DEFAULT_HOPLIMIT,
249 	.mtu6			= IPV6_MIN_MTU,
250 	.accept_ra		= 1,
251 	.accept_redirects	= 1,
252 	.autoconf		= 1,
253 	.force_mld_version	= 0,
254 	.mldv1_unsolicited_report_interval = 10 * HZ,
255 	.mldv2_unsolicited_report_interval = HZ,
256 	.dad_transmits		= 1,
257 	.rtr_solicits		= MAX_RTR_SOLICITATIONS,
258 	.rtr_solicit_interval	= RTR_SOLICITATION_INTERVAL,
259 	.rtr_solicit_max_interval = RTR_SOLICITATION_MAX_INTERVAL,
260 	.rtr_solicit_delay	= MAX_RTR_SOLICITATION_DELAY,
261 	.use_tempaddr		= 0,
262 	.temp_valid_lft		= TEMP_VALID_LIFETIME,
263 	.temp_prefered_lft	= TEMP_PREFERRED_LIFETIME,
264 	.regen_min_advance	= REGEN_MIN_ADVANCE,
265 	.regen_max_retry	= REGEN_MAX_RETRY,
266 	.max_desync_factor	= MAX_DESYNC_FACTOR,
267 	.max_addresses		= IPV6_MAX_ADDRESSES,
268 	.accept_ra_defrtr	= 1,
269 	.ra_defrtr_metric	= IP6_RT_PRIO_USER,
270 	.accept_ra_from_local	= 0,
271 	.accept_ra_min_hop_limit= 1,
272 	.accept_ra_min_lft	= 0,
273 	.accept_ra_pinfo	= 1,
274 #ifdef CONFIG_IPV6_ROUTER_PREF
275 	.accept_ra_rtr_pref	= 1,
276 	.rtr_probe_interval	= 60 * HZ,
277 #ifdef CONFIG_IPV6_ROUTE_INFO
278 	.accept_ra_rt_info_min_plen = 0,
279 	.accept_ra_rt_info_max_plen = 0,
280 #endif
281 #endif
282 	.proxy_ndp		= 0,
283 	.accept_source_route	= 0,	/* we do not accept RH0 by default. */
284 	.disable_ipv6		= 0,
285 	.accept_dad		= 1,
286 	.suppress_frag_ndisc	= 1,
287 	.accept_ra_mtu		= 1,
288 	.stable_secret		= {
289 		.initialized = false,
290 	},
291 	.use_oif_addrs_only	= 0,
292 	.ignore_routes_with_linkdown = 0,
293 	.keep_addr_on_down	= 0,
294 	.seg6_enabled		= 0,
295 #ifdef CONFIG_IPV6_SEG6_HMAC
296 	.seg6_require_hmac	= 0,
297 #endif
298 	.enhanced_dad           = 1,
299 	.addr_gen_mode		= IN6_ADDR_GEN_MODE_EUI64,
300 	.disable_policy		= 0,
301 	.rpl_seg_enabled	= 0,
302 	.ioam6_enabled		= 0,
303 	.ioam6_id               = IOAM6_DEFAULT_IF_ID,
304 	.ioam6_id_wide		= IOAM6_DEFAULT_IF_ID_WIDE,
305 	.ndisc_evict_nocarrier	= 1,
306 	.ra_honor_pio_life	= 0,
307 	.ra_honor_pio_pflag	= 0,
308 	.force_forwarding	= 0,
309 };
310 
311 /* Check if link is ready: is it up and is a valid qdisc available */
addrconf_link_ready(const struct net_device * dev)312 static inline bool addrconf_link_ready(const struct net_device *dev)
313 {
314 	return netif_oper_up(dev) && !qdisc_tx_is_noop(dev);
315 }
316 
addrconf_del_rs_timer(struct inet6_dev * idev)317 static void addrconf_del_rs_timer(struct inet6_dev *idev)
318 {
319 	if (timer_delete(&idev->rs_timer))
320 		__in6_dev_put(idev);
321 }
322 
addrconf_del_dad_work(struct inet6_ifaddr * ifp)323 static void addrconf_del_dad_work(struct inet6_ifaddr *ifp)
324 {
325 	if (cancel_delayed_work(&ifp->dad_work))
326 		__in6_ifa_put(ifp);
327 }
328 
addrconf_mod_rs_timer(struct inet6_dev * idev,unsigned long when)329 static void addrconf_mod_rs_timer(struct inet6_dev *idev,
330 				  unsigned long when)
331 {
332 	if (!mod_timer(&idev->rs_timer, jiffies + when))
333 		in6_dev_hold(idev);
334 }
335 
addrconf_mod_dad_work(struct inet6_ifaddr * ifp,unsigned long delay)336 static void addrconf_mod_dad_work(struct inet6_ifaddr *ifp,
337 				   unsigned long delay)
338 {
339 	in6_ifa_hold(ifp);
340 	if (mod_delayed_work(addrconf_wq, &ifp->dad_work, delay))
341 		in6_ifa_put(ifp);
342 }
343 
snmp6_alloc_dev(struct inet6_dev * idev)344 static int snmp6_alloc_dev(struct inet6_dev *idev)
345 {
346 	int i;
347 
348 	idev->stats.ipv6 = alloc_percpu_gfp(struct ipstats_mib, GFP_KERNEL_ACCOUNT);
349 	if (!idev->stats.ipv6)
350 		goto err_ip;
351 
352 	for_each_possible_cpu(i) {
353 		struct ipstats_mib *addrconf_stats;
354 		addrconf_stats = per_cpu_ptr(idev->stats.ipv6, i);
355 		u64_stats_init(&addrconf_stats->syncp);
356 	}
357 
358 
359 	idev->stats.icmpv6dev = kzalloc_obj(struct icmpv6_mib_device);
360 	if (!idev->stats.icmpv6dev)
361 		goto err_icmp;
362 	idev->stats.icmpv6msgdev = kzalloc_obj(struct icmpv6msg_mib_device,
363 					       GFP_KERNEL_ACCOUNT);
364 	if (!idev->stats.icmpv6msgdev)
365 		goto err_icmpmsg;
366 
367 	return 0;
368 
369 err_icmpmsg:
370 	kfree(idev->stats.icmpv6dev);
371 err_icmp:
372 	free_percpu(idev->stats.ipv6);
373 err_ip:
374 	return -ENOMEM;
375 }
376 
ipv6_add_dev(struct net_device * dev)377 static struct inet6_dev *ipv6_add_dev(struct net_device *dev)
378 {
379 	struct inet6_dev *ndev;
380 	int err = -ENOMEM;
381 
382 	ASSERT_RTNL();
383 	netdev_assert_locked_ops_compat(dev);
384 
385 	if (dev->mtu < IPV6_MIN_MTU && dev != blackhole_netdev)
386 		return ERR_PTR(-EINVAL);
387 
388 	ndev = kzalloc_obj(*ndev, GFP_KERNEL_ACCOUNT);
389 	if (!ndev)
390 		return ERR_PTR(err);
391 
392 	rwlock_init(&ndev->lock);
393 	ndev->dev = dev;
394 	INIT_LIST_HEAD(&ndev->addr_list);
395 	timer_setup(&ndev->rs_timer, addrconf_rs_timer, 0);
396 	memcpy(&ndev->cnf, dev_net(dev)->ipv6.devconf_dflt, sizeof(ndev->cnf));
397 
398 	if (ndev->cnf.stable_secret.initialized)
399 		ndev->cnf.addr_gen_mode = IN6_ADDR_GEN_MODE_STABLE_PRIVACY;
400 
401 	ndev->cnf.mtu6 = dev->mtu;
402 	ndev->ra_mtu = 0;
403 	ndev->nd_parms = neigh_parms_alloc(dev, &nd_tbl);
404 	if (!ndev->nd_parms) {
405 		kfree(ndev);
406 		return ERR_PTR(err);
407 	}
408 	if (ndev->cnf.forwarding)
409 		netif_disable_lro(dev);
410 	/* We refer to the device */
411 	netdev_hold(dev, &ndev->dev_tracker, GFP_KERNEL);
412 
413 	if (snmp6_alloc_dev(ndev) < 0) {
414 		netdev_dbg(dev, "%s: cannot allocate memory for statistics\n",
415 			   __func__);
416 		neigh_parms_release(&nd_tbl, ndev->nd_parms);
417 		netdev_put(dev, &ndev->dev_tracker);
418 		kfree(ndev);
419 		return ERR_PTR(err);
420 	}
421 
422 	if (dev != blackhole_netdev) {
423 		if (snmp6_register_dev(ndev) < 0) {
424 			netdev_dbg(dev, "%s: cannot create /proc/net/dev_snmp6/%s\n",
425 				   __func__, dev->name);
426 			goto err_release;
427 		}
428 	}
429 	/* One reference from device. */
430 	refcount_set(&ndev->refcnt, 1);
431 
432 	if (dev->flags & (IFF_NOARP | IFF_LOOPBACK))
433 		ndev->cnf.accept_dad = -1;
434 
435 #if IS_ENABLED(CONFIG_IPV6_SIT)
436 	if (dev->type == ARPHRD_SIT && (dev->priv_flags & IFF_ISATAP)) {
437 		pr_info("%s: Disabled Multicast RS\n", dev->name);
438 		ndev->cnf.rtr_solicits = 0;
439 	}
440 #endif
441 
442 	INIT_LIST_HEAD(&ndev->tempaddr_list);
443 	ndev->desync_factor = U32_MAX;
444 	if ((dev->flags&IFF_LOOPBACK) ||
445 	    dev->type == ARPHRD_TUNNEL ||
446 	    dev->type == ARPHRD_TUNNEL6 ||
447 	    dev->type == ARPHRD_SIT ||
448 	    dev->type == ARPHRD_NONE) {
449 		ndev->cnf.use_tempaddr = -1;
450 	}
451 
452 	ndev->token = in6addr_any;
453 
454 	if (netif_running(dev) && addrconf_link_ready(dev))
455 		ndev->if_flags |= IF_READY;
456 
457 	ipv6_mc_init_dev(ndev);
458 	ndev->tstamp = jiffies;
459 	if (dev != blackhole_netdev) {
460 		err = addrconf_sysctl_register(ndev);
461 		if (err) {
462 			ipv6_mc_destroy_dev(ndev);
463 			snmp6_unregister_dev(ndev);
464 			goto err_release;
465 		}
466 	}
467 	/* protected by rtnl_lock */
468 	rcu_assign_pointer(dev->ip6_ptr, ndev);
469 
470 	if (dev != blackhole_netdev) {
471 		/* Join interface-local all-node multicast group */
472 		ipv6_dev_mc_inc(dev, &in6addr_interfacelocal_allnodes);
473 
474 		/* Join all-node multicast group */
475 		ipv6_dev_mc_inc(dev, &in6addr_linklocal_allnodes);
476 
477 		/* Join all-router multicast group if forwarding is set */
478 		if (ndev->cnf.forwarding && (dev->flags & IFF_MULTICAST))
479 			ipv6_dev_mc_inc(dev, &in6addr_linklocal_allrouters);
480 	}
481 	return ndev;
482 
483 err_release:
484 	neigh_parms_release(&nd_tbl, ndev->nd_parms);
485 	ndev->dead = 1;
486 	in6_dev_finish_destroy(ndev);
487 	return ERR_PTR(err);
488 }
489 
ipv6_find_idev(struct net_device * dev)490 static struct inet6_dev *ipv6_find_idev(struct net_device *dev)
491 {
492 	struct inet6_dev *idev;
493 
494 	ASSERT_RTNL();
495 
496 	idev = __in6_dev_get(dev);
497 	if (!idev) {
498 		idev = ipv6_add_dev(dev);
499 		if (IS_ERR(idev))
500 			return idev;
501 	}
502 
503 	if (dev->flags&IFF_UP)
504 		ipv6_mc_up(idev);
505 	return idev;
506 }
507 
inet6_netconf_msgsize_devconf(int type)508 static int inet6_netconf_msgsize_devconf(int type)
509 {
510 	int size =  NLMSG_ALIGN(sizeof(struct netconfmsg))
511 		    + nla_total_size(4);	/* NETCONFA_IFINDEX */
512 	bool all = false;
513 
514 	if (type == NETCONFA_ALL)
515 		all = true;
516 
517 	if (all || type == NETCONFA_FORWARDING)
518 		size += nla_total_size(4);
519 #ifdef CONFIG_IPV6_MROUTE
520 	if (all || type == NETCONFA_MC_FORWARDING)
521 		size += nla_total_size(4);
522 #endif
523 	if (all || type == NETCONFA_PROXY_NEIGH)
524 		size += nla_total_size(4);
525 
526 	if (all || type == NETCONFA_IGNORE_ROUTES_WITH_LINKDOWN)
527 		size += nla_total_size(4);
528 
529 	return size;
530 }
531 
inet6_netconf_fill_devconf(struct sk_buff * skb,int ifindex,struct ipv6_devconf * devconf,u32 portid,u32 seq,int event,unsigned int flags,int type)532 static int inet6_netconf_fill_devconf(struct sk_buff *skb, int ifindex,
533 				      struct ipv6_devconf *devconf, u32 portid,
534 				      u32 seq, int event, unsigned int flags,
535 				      int type)
536 {
537 	struct nlmsghdr  *nlh;
538 	struct netconfmsg *ncm;
539 	bool all = false;
540 
541 	nlh = nlmsg_put(skb, portid, seq, event, sizeof(struct netconfmsg),
542 			flags);
543 	if (!nlh)
544 		return -EMSGSIZE;
545 
546 	if (type == NETCONFA_ALL)
547 		all = true;
548 
549 	ncm = nlmsg_data(nlh);
550 	ncm->ncm_family = AF_INET6;
551 
552 	if (nla_put_s32(skb, NETCONFA_IFINDEX, ifindex) < 0)
553 		goto nla_put_failure;
554 
555 	if (!devconf)
556 		goto out;
557 
558 	if ((all || type == NETCONFA_FORWARDING) &&
559 	    nla_put_s32(skb, NETCONFA_FORWARDING,
560 			READ_ONCE(devconf->forwarding)) < 0)
561 		goto nla_put_failure;
562 #ifdef CONFIG_IPV6_MROUTE
563 	if ((all || type == NETCONFA_MC_FORWARDING) &&
564 	    nla_put_s32(skb, NETCONFA_MC_FORWARDING,
565 			atomic_read(&devconf->mc_forwarding)) < 0)
566 		goto nla_put_failure;
567 #endif
568 	if ((all || type == NETCONFA_PROXY_NEIGH) &&
569 	    nla_put_s32(skb, NETCONFA_PROXY_NEIGH,
570 			READ_ONCE(devconf->proxy_ndp)) < 0)
571 		goto nla_put_failure;
572 
573 	if ((all || type == NETCONFA_IGNORE_ROUTES_WITH_LINKDOWN) &&
574 	    nla_put_s32(skb, NETCONFA_IGNORE_ROUTES_WITH_LINKDOWN,
575 			READ_ONCE(devconf->ignore_routes_with_linkdown)) < 0)
576 		goto nla_put_failure;
577 
578 out:
579 	nlmsg_end(skb, nlh);
580 	return 0;
581 
582 nla_put_failure:
583 	nlmsg_cancel(skb, nlh);
584 	return -EMSGSIZE;
585 }
586 
inet6_netconf_notify_devconf(struct net * net,int event,int type,int ifindex,struct ipv6_devconf * devconf)587 void inet6_netconf_notify_devconf(struct net *net, int event, int type,
588 				  int ifindex, struct ipv6_devconf *devconf)
589 {
590 	struct sk_buff *skb;
591 	int err = -ENOBUFS;
592 
593 	skb = nlmsg_new(inet6_netconf_msgsize_devconf(type), GFP_KERNEL);
594 	if (!skb)
595 		goto errout;
596 
597 	err = inet6_netconf_fill_devconf(skb, ifindex, devconf, 0, 0,
598 					 event, 0, type);
599 	if (err < 0) {
600 		/* -EMSGSIZE implies BUG in inet6_netconf_msgsize_devconf() */
601 		WARN_ON(err == -EMSGSIZE);
602 		kfree_skb(skb);
603 		goto errout;
604 	}
605 	rtnl_notify(skb, net, 0, RTNLGRP_IPV6_NETCONF, NULL, GFP_KERNEL);
606 	return;
607 errout:
608 	rtnl_set_sk_err(net, RTNLGRP_IPV6_NETCONF, err);
609 }
610 
611 static const struct nla_policy devconf_ipv6_policy[NETCONFA_MAX+1] = {
612 	[NETCONFA_IFINDEX]	= { .len = sizeof(int) },
613 	[NETCONFA_FORWARDING]	= { .len = sizeof(int) },
614 	[NETCONFA_PROXY_NEIGH]	= { .len = sizeof(int) },
615 	[NETCONFA_IGNORE_ROUTES_WITH_LINKDOWN]	= { .len = sizeof(int) },
616 };
617 
inet6_netconf_valid_get_req(struct sk_buff * skb,const struct nlmsghdr * nlh,struct nlattr ** tb,struct netlink_ext_ack * extack)618 static int inet6_netconf_valid_get_req(struct sk_buff *skb,
619 				       const struct nlmsghdr *nlh,
620 				       struct nlattr **tb,
621 				       struct netlink_ext_ack *extack)
622 {
623 	int i, err;
624 
625 	if (nlh->nlmsg_len < nlmsg_msg_size(sizeof(struct netconfmsg))) {
626 		NL_SET_ERR_MSG_MOD(extack, "Invalid header for netconf get request");
627 		return -EINVAL;
628 	}
629 
630 	if (!netlink_strict_get_check(skb))
631 		return nlmsg_parse_deprecated(nlh, sizeof(struct netconfmsg),
632 					      tb, NETCONFA_MAX,
633 					      devconf_ipv6_policy, extack);
634 
635 	err = nlmsg_parse_deprecated_strict(nlh, sizeof(struct netconfmsg),
636 					    tb, NETCONFA_MAX,
637 					    devconf_ipv6_policy, extack);
638 	if (err)
639 		return err;
640 
641 	for (i = 0; i <= NETCONFA_MAX; i++) {
642 		if (!tb[i])
643 			continue;
644 
645 		switch (i) {
646 		case NETCONFA_IFINDEX:
647 			break;
648 		default:
649 			NL_SET_ERR_MSG_MOD(extack, "Unsupported attribute in netconf get request");
650 			return -EINVAL;
651 		}
652 	}
653 
654 	return 0;
655 }
656 
inet6_netconf_get_devconf(struct sk_buff * in_skb,struct nlmsghdr * nlh,struct netlink_ext_ack * extack)657 static int inet6_netconf_get_devconf(struct sk_buff *in_skb,
658 				     struct nlmsghdr *nlh,
659 				     struct netlink_ext_ack *extack)
660 {
661 	struct net *net = sock_net(in_skb->sk);
662 	struct nlattr *tb[NETCONFA_MAX+1];
663 	struct inet6_dev *in6_dev = NULL;
664 	struct net_device *dev = NULL;
665 	struct sk_buff *skb;
666 	struct ipv6_devconf *devconf;
667 	int ifindex;
668 	int err;
669 
670 	err = inet6_netconf_valid_get_req(in_skb, nlh, tb, extack);
671 	if (err < 0)
672 		return err;
673 
674 	if (!tb[NETCONFA_IFINDEX])
675 		return -EINVAL;
676 
677 	err = -EINVAL;
678 	ifindex = nla_get_s32(tb[NETCONFA_IFINDEX]);
679 	switch (ifindex) {
680 	case NETCONFA_IFINDEX_ALL:
681 		devconf = net->ipv6.devconf_all;
682 		break;
683 	case NETCONFA_IFINDEX_DEFAULT:
684 		devconf = net->ipv6.devconf_dflt;
685 		break;
686 	default:
687 		dev = dev_get_by_index(net, ifindex);
688 		if (!dev)
689 			return -EINVAL;
690 		in6_dev = in6_dev_get(dev);
691 		if (!in6_dev)
692 			goto errout;
693 		devconf = &in6_dev->cnf;
694 		break;
695 	}
696 
697 	err = -ENOBUFS;
698 	skb = nlmsg_new(inet6_netconf_msgsize_devconf(NETCONFA_ALL), GFP_KERNEL);
699 	if (!skb)
700 		goto errout;
701 
702 	err = inet6_netconf_fill_devconf(skb, ifindex, devconf,
703 					 NETLINK_CB(in_skb).portid,
704 					 nlh->nlmsg_seq, RTM_NEWNETCONF, 0,
705 					 NETCONFA_ALL);
706 	if (err < 0) {
707 		/* -EMSGSIZE implies BUG in inet6_netconf_msgsize_devconf() */
708 		WARN_ON(err == -EMSGSIZE);
709 		kfree_skb(skb);
710 		goto errout;
711 	}
712 	err = rtnl_unicast(skb, net, NETLINK_CB(in_skb).portid);
713 errout:
714 	if (in6_dev)
715 		in6_dev_put(in6_dev);
716 	dev_put(dev);
717 	return err;
718 }
719 
720 /* Combine dev_addr_genid and dev_base_seq to detect changes.
721  */
inet6_base_seq(const struct net * net)722 static u32 inet6_base_seq(const struct net *net)
723 {
724 	u32 res = atomic_read(&net->ipv6.dev_addr_genid) +
725 		  READ_ONCE(net->dev_base_seq);
726 
727 	/* Must not return 0 (see nl_dump_check_consistent()).
728 	 * Chose a value far away from 0.
729 	 */
730 	if (!res)
731 		res = 0x80000000;
732 	return res;
733 }
734 
inet6_netconf_dump_devconf(struct sk_buff * skb,struct netlink_callback * cb)735 static int inet6_netconf_dump_devconf(struct sk_buff *skb,
736 				      struct netlink_callback *cb)
737 {
738 	const struct nlmsghdr *nlh = cb->nlh;
739 	struct net *net = sock_net(skb->sk);
740 	struct {
741 		unsigned long ifindex;
742 		unsigned int all_default;
743 	} *ctx = (void *)cb->ctx;
744 	struct net_device *dev;
745 	struct inet6_dev *idev;
746 	int err = 0;
747 
748 	if (cb->strict_check) {
749 		struct netlink_ext_ack *extack = cb->extack;
750 		struct netconfmsg *ncm;
751 
752 		if (nlh->nlmsg_len < nlmsg_msg_size(sizeof(*ncm))) {
753 			NL_SET_ERR_MSG_MOD(extack, "Invalid header for netconf dump request");
754 			return -EINVAL;
755 		}
756 
757 		if (nlmsg_attrlen(nlh, sizeof(*ncm))) {
758 			NL_SET_ERR_MSG_MOD(extack, "Invalid data after header in netconf dump request");
759 			return -EINVAL;
760 		}
761 	}
762 
763 	rcu_read_lock();
764 	for_each_netdev_dump(net, dev, ctx->ifindex) {
765 		idev = __in6_dev_get(dev);
766 		if (!idev)
767 			continue;
768 		err = inet6_netconf_fill_devconf(skb, dev->ifindex,
769 					         &idev->cnf,
770 						 NETLINK_CB(cb->skb).portid,
771 						 nlh->nlmsg_seq,
772 						 RTM_NEWNETCONF,
773 						 NLM_F_MULTI,
774 						 NETCONFA_ALL);
775 		if (err < 0)
776 			goto done;
777 	}
778 	if (ctx->all_default == 0) {
779 		err = inet6_netconf_fill_devconf(skb, NETCONFA_IFINDEX_ALL,
780 						 net->ipv6.devconf_all,
781 						 NETLINK_CB(cb->skb).portid,
782 						 nlh->nlmsg_seq,
783 						 RTM_NEWNETCONF, NLM_F_MULTI,
784 						 NETCONFA_ALL);
785 		if (err < 0)
786 			goto done;
787 		ctx->all_default++;
788 	}
789 	if (ctx->all_default == 1) {
790 		err = inet6_netconf_fill_devconf(skb, NETCONFA_IFINDEX_DEFAULT,
791 						 net->ipv6.devconf_dflt,
792 						 NETLINK_CB(cb->skb).portid,
793 						 nlh->nlmsg_seq,
794 						 RTM_NEWNETCONF, NLM_F_MULTI,
795 						 NETCONFA_ALL);
796 		if (err < 0)
797 			goto done;
798 		ctx->all_default++;
799 	}
800 done:
801 	rcu_read_unlock();
802 	return err;
803 }
804 
805 #ifdef CONFIG_SYSCTL
dev_forward_change(struct inet6_dev * idev)806 static void dev_forward_change(struct inet6_dev *idev)
807 {
808 	struct net_device *dev;
809 	struct inet6_ifaddr *ifa;
810 	LIST_HEAD(tmp_addr_list);
811 
812 	if (!idev)
813 		return;
814 	dev = idev->dev;
815 	if (idev->cnf.forwarding)
816 		dev_disable_lro(dev);
817 	if (dev->flags & IFF_MULTICAST) {
818 		if (idev->cnf.forwarding) {
819 			ipv6_dev_mc_inc(dev, &in6addr_linklocal_allrouters);
820 			ipv6_dev_mc_inc(dev, &in6addr_interfacelocal_allrouters);
821 			ipv6_dev_mc_inc(dev, &in6addr_sitelocal_allrouters);
822 		} else {
823 			ipv6_dev_mc_dec(dev, &in6addr_linklocal_allrouters);
824 			ipv6_dev_mc_dec(dev, &in6addr_interfacelocal_allrouters);
825 			ipv6_dev_mc_dec(dev, &in6addr_sitelocal_allrouters);
826 		}
827 	}
828 
829 	read_lock_bh(&idev->lock);
830 	list_for_each_entry(ifa, &idev->addr_list, if_list) {
831 		if (ifa->flags&IFA_F_TENTATIVE)
832 			continue;
833 		list_add_tail(&ifa->if_list_aux, &tmp_addr_list);
834 	}
835 	read_unlock_bh(&idev->lock);
836 
837 	while (!list_empty(&tmp_addr_list)) {
838 		ifa = list_first_entry(&tmp_addr_list,
839 				       struct inet6_ifaddr, if_list_aux);
840 		list_del(&ifa->if_list_aux);
841 		if (idev->cnf.forwarding)
842 			addrconf_join_anycast(ifa);
843 		else
844 			addrconf_leave_anycast(ifa);
845 	}
846 
847 	inet6_netconf_notify_devconf(dev_net(dev), RTM_NEWNETCONF,
848 				     NETCONFA_FORWARDING,
849 				     dev->ifindex, &idev->cnf);
850 }
851 
852 
addrconf_forward_change(struct net * net,__s32 newf)853 static void addrconf_forward_change(struct net *net, __s32 newf)
854 {
855 	struct net_device *dev;
856 	struct inet6_dev *idev;
857 
858 	for_each_netdev(net, dev) {
859 		idev = __in6_dev_get_rtnl_net(dev);
860 		if (idev) {
861 			int changed = (!idev->cnf.forwarding) ^ (!newf);
862 			/* Disabling all.forwarding sets 0 to force_forwarding for all interfaces */
863 			if (newf == 0)
864 				WRITE_ONCE(idev->cnf.force_forwarding, 0);
865 
866 			WRITE_ONCE(idev->cnf.forwarding, newf);
867 			if (changed)
868 				dev_forward_change(idev);
869 		}
870 	}
871 }
872 
addrconf_fixup_forwarding(const struct ctl_table * table,int * p,int newf)873 static int addrconf_fixup_forwarding(const struct ctl_table *table, int *p, int newf)
874 {
875 	struct net *net = (struct net *)table->extra2;
876 	int old;
877 
878 	if (!rtnl_net_trylock(net))
879 		return restart_syscall();
880 
881 	old = *p;
882 	WRITE_ONCE(*p, newf);
883 
884 	if (p == &net->ipv6.devconf_dflt->forwarding) {
885 		if ((!newf) ^ (!old))
886 			inet6_netconf_notify_devconf(net, RTM_NEWNETCONF,
887 						     NETCONFA_FORWARDING,
888 						     NETCONFA_IFINDEX_DEFAULT,
889 						     net->ipv6.devconf_dflt);
890 		rtnl_net_unlock(net);
891 		return 0;
892 	}
893 
894 	if (p == &net->ipv6.devconf_all->forwarding) {
895 		int old_dflt = net->ipv6.devconf_dflt->forwarding;
896 
897 		WRITE_ONCE(net->ipv6.devconf_dflt->forwarding, newf);
898 		if ((!newf) ^ (!old_dflt))
899 			inet6_netconf_notify_devconf(net, RTM_NEWNETCONF,
900 						     NETCONFA_FORWARDING,
901 						     NETCONFA_IFINDEX_DEFAULT,
902 						     net->ipv6.devconf_dflt);
903 
904 		addrconf_forward_change(net, newf);
905 		if ((!newf) ^ (!old))
906 			inet6_netconf_notify_devconf(net, RTM_NEWNETCONF,
907 						     NETCONFA_FORWARDING,
908 						     NETCONFA_IFINDEX_ALL,
909 						     net->ipv6.devconf_all);
910 	} else if ((!newf) ^ (!old))
911 		dev_forward_change((struct inet6_dev *)table->extra1);
912 	rtnl_net_unlock(net);
913 
914 	if (newf)
915 		rt6_purge_dflt_routers(net);
916 	return 0;
917 }
918 
addrconf_linkdown_change(struct net * net,__s32 newf)919 static void addrconf_linkdown_change(struct net *net, __s32 newf)
920 {
921 	struct net_device *dev;
922 	struct inet6_dev *idev;
923 
924 	for_each_netdev(net, dev) {
925 		idev = __in6_dev_get_rtnl_net(dev);
926 		if (idev) {
927 			int changed = (!idev->cnf.ignore_routes_with_linkdown) ^ (!newf);
928 
929 			WRITE_ONCE(idev->cnf.ignore_routes_with_linkdown, newf);
930 			if (changed)
931 				inet6_netconf_notify_devconf(dev_net(dev),
932 							     RTM_NEWNETCONF,
933 							     NETCONFA_IGNORE_ROUTES_WITH_LINKDOWN,
934 							     dev->ifindex,
935 							     &idev->cnf);
936 		}
937 	}
938 }
939 
addrconf_fixup_linkdown(const struct ctl_table * table,int * p,int newf)940 static int addrconf_fixup_linkdown(const struct ctl_table *table, int *p, int newf)
941 {
942 	struct net *net = (struct net *)table->extra2;
943 	int old;
944 
945 	if (!rtnl_net_trylock(net))
946 		return restart_syscall();
947 
948 	old = *p;
949 	WRITE_ONCE(*p, newf);
950 
951 	if (p == &net->ipv6.devconf_dflt->ignore_routes_with_linkdown) {
952 		if ((!newf) ^ (!old))
953 			inet6_netconf_notify_devconf(net,
954 						     RTM_NEWNETCONF,
955 						     NETCONFA_IGNORE_ROUTES_WITH_LINKDOWN,
956 						     NETCONFA_IFINDEX_DEFAULT,
957 						     net->ipv6.devconf_dflt);
958 	} else if (p == &net->ipv6.devconf_all->ignore_routes_with_linkdown) {
959 		WRITE_ONCE(net->ipv6.devconf_dflt->ignore_routes_with_linkdown, newf);
960 		addrconf_linkdown_change(net, newf);
961 		if ((!newf) ^ (!old))
962 			inet6_netconf_notify_devconf(net,
963 						     RTM_NEWNETCONF,
964 						     NETCONFA_IGNORE_ROUTES_WITH_LINKDOWN,
965 						     NETCONFA_IFINDEX_ALL,
966 						     net->ipv6.devconf_all);
967 	} else {
968 		if (!newf ^ !old) {
969 			struct inet6_dev *idev = table->extra1;
970 
971 			inet6_netconf_notify_devconf(net,
972 						     RTM_NEWNETCONF,
973 						     NETCONFA_IGNORE_ROUTES_WITH_LINKDOWN,
974 						     idev->dev->ifindex,
975 						     &idev->cnf);
976 		}
977 	}
978 
979 	rtnl_net_unlock(net);
980 
981 	return 0;
982 }
983 
984 #endif
985 
986 /* Nobody refers to this ifaddr, destroy it */
inet6_ifa_finish_destroy(struct inet6_ifaddr * ifp)987 void inet6_ifa_finish_destroy(struct inet6_ifaddr *ifp)
988 {
989 	WARN_ON(!hlist_unhashed(&ifp->addr_lst));
990 
991 #ifdef NET_REFCNT_DEBUG
992 	pr_debug("%s\n", __func__);
993 #endif
994 
995 	in6_dev_put(ifp->idev);
996 
997 	if (cancel_delayed_work(&ifp->dad_work))
998 		pr_notice("delayed DAD work was pending while freeing ifa=%p\n",
999 			  ifp);
1000 
1001 	if (ifp->state != INET6_IFADDR_STATE_DEAD) {
1002 		pr_warn("Freeing alive inet6 address %p\n", ifp);
1003 		return;
1004 	}
1005 
1006 	kfree_rcu(ifp, rcu);
1007 }
1008 
1009 static void
ipv6_link_dev_addr(struct inet6_dev * idev,struct inet6_ifaddr * ifp)1010 ipv6_link_dev_addr(struct inet6_dev *idev, struct inet6_ifaddr *ifp)
1011 {
1012 	struct list_head *p;
1013 	int ifp_scope = ipv6_addr_src_scope(&ifp->addr);
1014 
1015 	/*
1016 	 * Each device address list is sorted in order of scope -
1017 	 * global before linklocal.
1018 	 */
1019 	list_for_each(p, &idev->addr_list) {
1020 		struct inet6_ifaddr *ifa
1021 			= list_entry(p, struct inet6_ifaddr, if_list);
1022 		if (ifp_scope >= ipv6_addr_src_scope(&ifa->addr))
1023 			break;
1024 	}
1025 
1026 	list_add_tail_rcu(&ifp->if_list, p);
1027 }
1028 
inet6_addr_hash(const struct net * net,const struct in6_addr * addr)1029 static u32 inet6_addr_hash(const struct net *net, const struct in6_addr *addr)
1030 {
1031 	u32 val = __ipv6_addr_jhash(addr, net_hash_mix(net));
1032 
1033 	return hash_32(val, IN6_ADDR_HSIZE_SHIFT);
1034 }
1035 
ipv6_chk_same_addr(struct net * net,const struct in6_addr * addr,struct net_device * dev,unsigned int hash)1036 static bool ipv6_chk_same_addr(struct net *net, const struct in6_addr *addr,
1037 			       struct net_device *dev, unsigned int hash)
1038 {
1039 	struct inet6_ifaddr *ifp;
1040 
1041 	hlist_for_each_entry(ifp, &net->ipv6.inet6_addr_lst[hash], addr_lst) {
1042 		if (ipv6_addr_equal(&ifp->addr, addr)) {
1043 			if (!dev || ifp->idev->dev == dev)
1044 				return true;
1045 		}
1046 	}
1047 	return false;
1048 }
1049 
ipv6_add_addr_hash(struct net_device * dev,struct inet6_ifaddr * ifa)1050 static int ipv6_add_addr_hash(struct net_device *dev, struct inet6_ifaddr *ifa)
1051 {
1052 	struct net *net = dev_net(dev);
1053 	unsigned int hash = inet6_addr_hash(net, &ifa->addr);
1054 	int err = 0;
1055 
1056 	spin_lock_bh(&net->ipv6.addrconf_hash_lock);
1057 
1058 	/* Ignore adding duplicate addresses on an interface */
1059 	if (ipv6_chk_same_addr(net, &ifa->addr, dev, hash)) {
1060 		netdev_dbg(dev, "ipv6_add_addr: already assigned\n");
1061 		err = -EEXIST;
1062 	} else {
1063 		hlist_add_head_rcu(&ifa->addr_lst, &net->ipv6.inet6_addr_lst[hash]);
1064 	}
1065 
1066 	spin_unlock_bh(&net->ipv6.addrconf_hash_lock);
1067 
1068 	return err;
1069 }
1070 
1071 /* On success it returns ifp with increased reference count */
1072 
1073 static struct inet6_ifaddr *
ipv6_add_addr(struct inet6_dev * idev,struct ifa6_config * cfg,bool can_block,struct netlink_ext_ack * extack)1074 ipv6_add_addr(struct inet6_dev *idev, struct ifa6_config *cfg,
1075 	      bool can_block, struct netlink_ext_ack *extack)
1076 {
1077 	gfp_t gfp_flags = can_block ? GFP_KERNEL : GFP_ATOMIC;
1078 	int addr_type = ipv6_addr_type(cfg->pfx);
1079 	struct net *net = dev_net(idev->dev);
1080 	struct inet6_ifaddr *ifa = NULL;
1081 	struct fib6_info *f6i = NULL;
1082 	int err = 0;
1083 
1084 	if (addr_type == IPV6_ADDR_ANY) {
1085 		NL_SET_ERR_MSG_MOD(extack, "Invalid address");
1086 		return ERR_PTR(-EADDRNOTAVAIL);
1087 	} else if (addr_type & IPV6_ADDR_MULTICAST &&
1088 		   !(cfg->ifa_flags & IFA_F_MCAUTOJOIN)) {
1089 		NL_SET_ERR_MSG_MOD(extack, "Cannot assign multicast address without \"IFA_F_MCAUTOJOIN\" flag");
1090 		return ERR_PTR(-EADDRNOTAVAIL);
1091 	} else if (!(idev->dev->flags & IFF_LOOPBACK) &&
1092 		   !netif_is_l3_master(idev->dev) &&
1093 		   addr_type & IPV6_ADDR_LOOPBACK) {
1094 		NL_SET_ERR_MSG_MOD(extack, "Cannot assign loopback address on this device");
1095 		return ERR_PTR(-EADDRNOTAVAIL);
1096 	}
1097 
1098 	if (idev->dead) {
1099 		NL_SET_ERR_MSG_MOD(extack, "device is going away");
1100 		err = -ENODEV;
1101 		goto out;
1102 	}
1103 
1104 	if (idev->cnf.disable_ipv6) {
1105 		NL_SET_ERR_MSG_MOD(extack, "IPv6 is disabled on this device");
1106 		err = -EACCES;
1107 		goto out;
1108 	}
1109 
1110 	/* validator notifier needs to be blocking;
1111 	 * do not call in atomic context
1112 	 */
1113 	if (can_block) {
1114 		struct in6_validator_info i6vi = {
1115 			.i6vi_addr = *cfg->pfx,
1116 			.i6vi_dev = idev,
1117 			.extack = extack,
1118 		};
1119 
1120 		err = inet6addr_validator_notifier_call_chain(NETDEV_UP, &i6vi);
1121 		err = notifier_to_errno(err);
1122 		if (err < 0)
1123 			goto out;
1124 	}
1125 
1126 	ifa = kzalloc_obj(*ifa, gfp_flags | __GFP_ACCOUNT);
1127 	if (!ifa) {
1128 		err = -ENOBUFS;
1129 		goto out;
1130 	}
1131 
1132 	f6i = addrconf_f6i_alloc(net, idev, cfg->pfx, false, gfp_flags, extack);
1133 	if (IS_ERR(f6i)) {
1134 		err = PTR_ERR(f6i);
1135 		f6i = NULL;
1136 		goto out;
1137 	}
1138 
1139 	neigh_parms_data_state_setall(idev->nd_parms);
1140 
1141 	ifa->addr = *cfg->pfx;
1142 	if (cfg->peer_pfx)
1143 		ifa->peer_addr = *cfg->peer_pfx;
1144 
1145 	spin_lock_init(&ifa->lock);
1146 	INIT_DELAYED_WORK(&ifa->dad_work, addrconf_dad_work);
1147 	INIT_HLIST_NODE(&ifa->addr_lst);
1148 	ifa->scope = cfg->scope;
1149 	ifa->prefix_len = cfg->plen;
1150 	ifa->rt_priority = cfg->rt_priority;
1151 	ifa->flags = cfg->ifa_flags;
1152 	ifa->ifa_proto = cfg->ifa_proto;
1153 	/* No need to add the TENTATIVE flag for addresses with NODAD */
1154 	if (!(cfg->ifa_flags & IFA_F_NODAD))
1155 		ifa->flags |= IFA_F_TENTATIVE;
1156 	ifa->valid_lft = cfg->valid_lft;
1157 	ifa->prefered_lft = cfg->preferred_lft;
1158 	ifa->cstamp = ifa->tstamp = jiffies;
1159 	ifa->tokenized = false;
1160 
1161 	ifa->rt = f6i;
1162 
1163 	ifa->idev = idev;
1164 	in6_dev_hold(idev);
1165 
1166 	/* For caller */
1167 	refcount_set(&ifa->refcnt, 1);
1168 
1169 	rcu_read_lock();
1170 
1171 	err = ipv6_add_addr_hash(idev->dev, ifa);
1172 	if (err < 0) {
1173 		rcu_read_unlock();
1174 		goto out;
1175 	}
1176 
1177 	write_lock_bh(&idev->lock);
1178 
1179 	/* Add to inet6_dev unicast addr list. */
1180 	ipv6_link_dev_addr(idev, ifa);
1181 
1182 	if (ifa->flags&IFA_F_TEMPORARY) {
1183 		/* manage_tempaddrs() relies on addresses being added to the head */
1184 		list_add(&ifa->tmp_list, &idev->tempaddr_list);
1185 		in6_ifa_hold(ifa);
1186 	}
1187 
1188 	in6_ifa_hold(ifa);
1189 	write_unlock_bh(&idev->lock);
1190 
1191 	rcu_read_unlock();
1192 
1193 	inet6addr_notifier_call_chain(NETDEV_UP, ifa);
1194 out:
1195 	if (unlikely(err < 0)) {
1196 		fib6_info_release(f6i);
1197 
1198 		if (ifa) {
1199 			if (ifa->idev)
1200 				in6_dev_put(ifa->idev);
1201 			kfree(ifa);
1202 		}
1203 		ifa = ERR_PTR(err);
1204 	}
1205 
1206 	return ifa;
1207 }
1208 
1209 enum cleanup_prefix_rt_t {
1210 	CLEANUP_PREFIX_RT_NOP,    /* no cleanup action for prefix route */
1211 	CLEANUP_PREFIX_RT_DEL,    /* delete the prefix route */
1212 	CLEANUP_PREFIX_RT_EXPIRE, /* update the lifetime of the prefix route */
1213 };
1214 
1215 /*
1216  * Check, whether the prefix for ifp would still need a prefix route
1217  * after deleting ifp. The function returns one of the CLEANUP_PREFIX_RT_*
1218  * constants.
1219  *
1220  * 1) we don't purge prefix if address was not permanent.
1221  *    prefix is managed by its own lifetime.
1222  * 2) we also don't purge, if the address was IFA_F_NOPREFIXROUTE.
1223  * 3) if there are no addresses, delete prefix.
1224  * 4) if there are still other permanent address(es),
1225  *    corresponding prefix is still permanent.
1226  * 5) if there are still other addresses with IFA_F_NOPREFIXROUTE,
1227  *    don't purge the prefix, assume user space is managing it.
1228  * 6) otherwise, update prefix lifetime to the
1229  *    longest valid lifetime among the corresponding
1230  *    addresses on the device.
1231  *    Note: subsequent RA will update lifetime.
1232  **/
1233 static enum cleanup_prefix_rt_t
check_cleanup_prefix_route(struct inet6_ifaddr * ifp,unsigned long * expires)1234 check_cleanup_prefix_route(struct inet6_ifaddr *ifp, unsigned long *expires)
1235 {
1236 	struct inet6_ifaddr *ifa;
1237 	struct inet6_dev *idev = ifp->idev;
1238 	unsigned long lifetime;
1239 	enum cleanup_prefix_rt_t action = CLEANUP_PREFIX_RT_DEL;
1240 
1241 	*expires = jiffies;
1242 
1243 	list_for_each_entry(ifa, &idev->addr_list, if_list) {
1244 		if (ifa == ifp)
1245 			continue;
1246 		if (ifa->prefix_len != ifp->prefix_len ||
1247 		    !ipv6_prefix_equal(&ifa->addr, &ifp->addr,
1248 				       ifp->prefix_len))
1249 			continue;
1250 		if (ifa->flags & (IFA_F_PERMANENT | IFA_F_NOPREFIXROUTE))
1251 			return CLEANUP_PREFIX_RT_NOP;
1252 
1253 		action = CLEANUP_PREFIX_RT_EXPIRE;
1254 
1255 		spin_lock(&ifa->lock);
1256 
1257 		lifetime = addrconf_timeout_fixup(ifa->valid_lft, HZ);
1258 		/*
1259 		 * Note: Because this address is
1260 		 * not permanent, lifetime <
1261 		 * LONG_MAX / HZ here.
1262 		 */
1263 		if (time_before(*expires, ifa->tstamp + lifetime * HZ))
1264 			*expires = ifa->tstamp + lifetime * HZ;
1265 		spin_unlock(&ifa->lock);
1266 	}
1267 
1268 	return action;
1269 }
1270 
1271 static void
cleanup_prefix_route(struct inet6_ifaddr * ifp,unsigned long expires,bool del_rt,bool del_peer)1272 cleanup_prefix_route(struct inet6_ifaddr *ifp, unsigned long expires,
1273 		     bool del_rt, bool del_peer)
1274 {
1275 	struct net *net = dev_net(ifp->idev->dev);
1276 	struct fib6_table *table;
1277 	struct fib6_info *f6i;
1278 
1279 	f6i = addrconf_get_prefix_route(del_peer ? &ifp->peer_addr : &ifp->addr,
1280 					ifp->prefix_len,
1281 					ifp->idev->dev, 0, RTF_DEFAULT, true);
1282 	if (f6i) {
1283 		if (del_rt)
1284 			ip6_del_rt(net, f6i, false);
1285 		else {
1286 			if (f6i != net->ipv6.fib6_null_entry &&
1287 			    !(f6i->fib6_flags & RTF_EXPIRES)) {
1288 				table = f6i->fib6_table;
1289 				spin_lock_bh(&table->tb6_lock);
1290 
1291 				fib6_set_expires(f6i, expires);
1292 				fib6_add_gc_list(f6i);
1293 
1294 				spin_unlock_bh(&table->tb6_lock);
1295 			}
1296 			fib6_info_release(f6i);
1297 		}
1298 	}
1299 }
1300 
1301 
1302 /* This function wants to get referenced ifp and releases it before return */
1303 
ipv6_del_addr(struct inet6_ifaddr * ifp)1304 static void ipv6_del_addr(struct inet6_ifaddr *ifp)
1305 {
1306 	enum cleanup_prefix_rt_t action = CLEANUP_PREFIX_RT_NOP;
1307 	struct net *net = dev_net(ifp->idev->dev);
1308 	unsigned long expires;
1309 	int state;
1310 
1311 	ASSERT_RTNL();
1312 
1313 	spin_lock_bh(&ifp->lock);
1314 	state = ifp->state;
1315 	ifp->state = INET6_IFADDR_STATE_DEAD;
1316 	spin_unlock_bh(&ifp->lock);
1317 
1318 	if (state == INET6_IFADDR_STATE_DEAD)
1319 		goto out;
1320 
1321 	spin_lock_bh(&net->ipv6.addrconf_hash_lock);
1322 	hlist_del_init_rcu(&ifp->addr_lst);
1323 	spin_unlock_bh(&net->ipv6.addrconf_hash_lock);
1324 
1325 	write_lock_bh(&ifp->idev->lock);
1326 
1327 	if (ifp->flags&IFA_F_TEMPORARY) {
1328 		list_del(&ifp->tmp_list);
1329 		if (ifp->ifpub) {
1330 			in6_ifa_put(ifp->ifpub);
1331 			ifp->ifpub = NULL;
1332 		}
1333 		__in6_ifa_put(ifp);
1334 	}
1335 
1336 	if (!(ifp->flags & IFA_F_NOPREFIXROUTE))
1337 		action = check_cleanup_prefix_route(ifp, &expires);
1338 
1339 	list_del_rcu(&ifp->if_list);
1340 	__in6_ifa_put(ifp);
1341 
1342 	write_unlock_bh(&ifp->idev->lock);
1343 
1344 	addrconf_del_dad_work(ifp);
1345 
1346 	ipv6_ifa_notify(RTM_DELADDR, ifp);
1347 
1348 	inet6addr_notifier_call_chain(NETDEV_DOWN, ifp);
1349 
1350 	if (action != CLEANUP_PREFIX_RT_NOP) {
1351 		cleanup_prefix_route(ifp, expires,
1352 			action == CLEANUP_PREFIX_RT_DEL, false);
1353 	}
1354 
1355 	/* clean up prefsrc entries */
1356 	rt6_remove_prefsrc(ifp);
1357 out:
1358 	in6_ifa_put(ifp);
1359 }
1360 
ipv6_get_regen_advance(const struct inet6_dev * idev)1361 static unsigned long ipv6_get_regen_advance(const struct inet6_dev *idev)
1362 {
1363 	return READ_ONCE(idev->cnf.regen_min_advance) +
1364 		READ_ONCE(idev->cnf.regen_max_retry) *
1365 		READ_ONCE(idev->cnf.dad_transmits) *
1366 		max(NEIGH_VAR(idev->nd_parms, RETRANS_TIME), HZ/100) / HZ;
1367 }
1368 
ipv6_create_tempaddr(struct inet6_ifaddr * ifp,bool block)1369 static int ipv6_create_tempaddr(struct inet6_ifaddr *ifp, bool block)
1370 {
1371 	struct inet6_dev *idev = ifp->idev;
1372 	unsigned long tmp_tstamp, age;
1373 	unsigned long regen_advance;
1374 	unsigned long now = jiffies;
1375 	u32 if_public_preferred_lft;
1376 	s32 cnf_temp_preferred_lft;
1377 	struct inet6_ifaddr *ift;
1378 	struct ifa6_config cfg;
1379 	long max_desync_factor;
1380 	struct in6_addr addr;
1381 	int ret = 0;
1382 
1383 	write_lock_bh(&idev->lock);
1384 
1385 retry:
1386 	in6_dev_hold(idev);
1387 	if (READ_ONCE(idev->cnf.use_tempaddr) <= 0) {
1388 		write_unlock_bh(&idev->lock);
1389 		pr_info("%s: use_tempaddr is disabled\n", __func__);
1390 		in6_dev_put(idev);
1391 		ret = -1;
1392 		goto out;
1393 	}
1394 	spin_lock_bh(&ifp->lock);
1395 	if (ifp->regen_count++ >= READ_ONCE(idev->cnf.regen_max_retry)) {
1396 		WRITE_ONCE(idev->cnf.use_tempaddr, -1);	/*XXX*/
1397 		spin_unlock_bh(&ifp->lock);
1398 		write_unlock_bh(&idev->lock);
1399 		pr_warn("%s: regeneration time exceeded - disabled temporary address support\n",
1400 			__func__);
1401 		in6_dev_put(idev);
1402 		ret = -1;
1403 		goto out;
1404 	}
1405 	in6_ifa_hold(ifp);
1406 	memcpy(addr.s6_addr, ifp->addr.s6_addr, 8);
1407 	ipv6_gen_rnd_iid(&addr);
1408 
1409 	age = (now - ifp->tstamp) / HZ;
1410 
1411 	regen_advance = ipv6_get_regen_advance(idev);
1412 
1413 	/* recalculate max_desync_factor each time and update
1414 	 * idev->desync_factor if it's larger
1415 	 */
1416 	cnf_temp_preferred_lft = READ_ONCE(idev->cnf.temp_prefered_lft);
1417 	max_desync_factor = min_t(long,
1418 				  READ_ONCE(idev->cnf.max_desync_factor),
1419 				  cnf_temp_preferred_lft - regen_advance);
1420 
1421 	if (unlikely(idev->desync_factor > max_desync_factor)) {
1422 		if (max_desync_factor > 0) {
1423 			get_random_bytes(&idev->desync_factor,
1424 					 sizeof(idev->desync_factor));
1425 			idev->desync_factor %= max_desync_factor;
1426 		} else {
1427 			idev->desync_factor = 0;
1428 		}
1429 	}
1430 
1431 	if_public_preferred_lft = ifp->prefered_lft;
1432 
1433 	memset(&cfg, 0, sizeof(cfg));
1434 	cfg.valid_lft = min_t(__u32, ifp->valid_lft,
1435 			      READ_ONCE(idev->cnf.temp_valid_lft) + age);
1436 	cfg.preferred_lft = cnf_temp_preferred_lft + age - idev->desync_factor;
1437 	cfg.preferred_lft = min_t(__u32, if_public_preferred_lft, cfg.preferred_lft);
1438 	cfg.preferred_lft = min_t(__u32, cfg.valid_lft, cfg.preferred_lft);
1439 
1440 	cfg.plen = ifp->prefix_len;
1441 	tmp_tstamp = ifp->tstamp;
1442 	spin_unlock_bh(&ifp->lock);
1443 
1444 	write_unlock_bh(&idev->lock);
1445 
1446 	/* From RFC 4941:
1447 	 *
1448 	 *     A temporary address is created only if this calculated Preferred
1449 	 *     Lifetime is greater than REGEN_ADVANCE time units.  In
1450 	 *     particular, an implementation must not create a temporary address
1451 	 *     with a zero Preferred Lifetime.
1452 	 *
1453 	 *     ...
1454 	 *
1455 	 *     When creating a temporary address, the lifetime values MUST be
1456 	 *     derived from the corresponding prefix as follows:
1457 	 *
1458 	 *     ...
1459 	 *
1460 	 *     *  Its Preferred Lifetime is the lower of the Preferred Lifetime
1461 	 *        of the public address or TEMP_PREFERRED_LIFETIME -
1462 	 *        DESYNC_FACTOR.
1463 	 *
1464 	 * To comply with the RFC's requirements, clamp the preferred lifetime
1465 	 * to a minimum of regen_advance, unless that would exceed valid_lft or
1466 	 * ifp->prefered_lft.
1467 	 *
1468 	 * Use age calculation as in addrconf_verify to avoid unnecessary
1469 	 * temporary addresses being generated.
1470 	 */
1471 	age = (now - tmp_tstamp + ADDRCONF_TIMER_FUZZ_MINUS) / HZ;
1472 	if (cfg.preferred_lft <= regen_advance + age) {
1473 		cfg.preferred_lft = regen_advance + age + 1;
1474 		if (cfg.preferred_lft > cfg.valid_lft ||
1475 		    cfg.preferred_lft > if_public_preferred_lft) {
1476 			in6_ifa_put(ifp);
1477 			in6_dev_put(idev);
1478 			ret = -1;
1479 			goto out;
1480 		}
1481 	}
1482 
1483 	cfg.ifa_flags = IFA_F_TEMPORARY;
1484 	/* set in addrconf_prefix_rcv() */
1485 	if (ifp->flags & IFA_F_OPTIMISTIC)
1486 		cfg.ifa_flags |= IFA_F_OPTIMISTIC;
1487 
1488 	cfg.pfx = &addr;
1489 	cfg.scope = ipv6_addr_scope(cfg.pfx);
1490 
1491 	ift = ipv6_add_addr(idev, &cfg, block, NULL);
1492 	if (IS_ERR(ift)) {
1493 		in6_ifa_put(ifp);
1494 		in6_dev_put(idev);
1495 		pr_info("%s: retry temporary address regeneration\n", __func__);
1496 		write_lock_bh(&idev->lock);
1497 		goto retry;
1498 	}
1499 
1500 	spin_lock_bh(&ift->lock);
1501 	ift->ifpub = ifp;
1502 	ift->cstamp = now;
1503 	ift->tstamp = tmp_tstamp;
1504 	spin_unlock_bh(&ift->lock);
1505 
1506 	addrconf_dad_start(ift);
1507 	in6_ifa_put(ift);
1508 	in6_dev_put(idev);
1509 out:
1510 	return ret;
1511 }
1512 
1513 /*
1514  *	Choose an appropriate source address (RFC3484)
1515  */
1516 enum {
1517 	IPV6_SADDR_RULE_INIT = 0,
1518 	IPV6_SADDR_RULE_LOCAL,
1519 	IPV6_SADDR_RULE_SCOPE,
1520 	IPV6_SADDR_RULE_PREFERRED,
1521 #ifdef CONFIG_IPV6_MIP6
1522 	IPV6_SADDR_RULE_HOA,
1523 #endif
1524 	IPV6_SADDR_RULE_OIF,
1525 	IPV6_SADDR_RULE_LABEL,
1526 	IPV6_SADDR_RULE_PRIVACY,
1527 	IPV6_SADDR_RULE_ORCHID,
1528 	IPV6_SADDR_RULE_PREFIX,
1529 #ifdef CONFIG_IPV6_OPTIMISTIC_DAD
1530 	IPV6_SADDR_RULE_NOT_OPTIMISTIC,
1531 #endif
1532 	IPV6_SADDR_RULE_MAX
1533 };
1534 
1535 struct ipv6_saddr_score {
1536 	int			rule;
1537 	int			addr_type;
1538 	struct inet6_ifaddr	*ifa;
1539 	DECLARE_BITMAP(scorebits, IPV6_SADDR_RULE_MAX);
1540 	int			scopedist;
1541 	int			matchlen;
1542 };
1543 
1544 struct ipv6_saddr_dst {
1545 	const struct in6_addr *addr;
1546 	int ifindex;
1547 	int scope;
1548 	int label;
1549 	unsigned int prefs;
1550 };
1551 
ipv6_saddr_preferred(int type)1552 static inline int ipv6_saddr_preferred(int type)
1553 {
1554 	if (type & (IPV6_ADDR_MAPPED|IPV6_ADDR_COMPATv4|IPV6_ADDR_LOOPBACK))
1555 		return 1;
1556 	return 0;
1557 }
1558 
ipv6_use_optimistic_addr(const struct net * net,const struct inet6_dev * idev)1559 static bool ipv6_use_optimistic_addr(const struct net *net,
1560 				     const struct inet6_dev *idev)
1561 {
1562 #ifdef CONFIG_IPV6_OPTIMISTIC_DAD
1563 	if (!idev)
1564 		return false;
1565 	if (!READ_ONCE(net->ipv6.devconf_all->optimistic_dad) &&
1566 	    !READ_ONCE(idev->cnf.optimistic_dad))
1567 		return false;
1568 	if (!READ_ONCE(net->ipv6.devconf_all->use_optimistic) &&
1569 	    !READ_ONCE(idev->cnf.use_optimistic))
1570 		return false;
1571 
1572 	return true;
1573 #else
1574 	return false;
1575 #endif
1576 }
1577 
ipv6_allow_optimistic_dad(const struct net * net,const struct inet6_dev * idev)1578 static bool ipv6_allow_optimistic_dad(const struct net *net,
1579 				      const struct inet6_dev *idev)
1580 {
1581 #ifdef CONFIG_IPV6_OPTIMISTIC_DAD
1582 	if (!idev)
1583 		return false;
1584 	if (!READ_ONCE(net->ipv6.devconf_all->optimistic_dad) &&
1585 	    !READ_ONCE(idev->cnf.optimistic_dad))
1586 		return false;
1587 
1588 	return true;
1589 #else
1590 	return false;
1591 #endif
1592 }
1593 
ipv6_get_saddr_eval(struct net * net,struct ipv6_saddr_score * score,struct ipv6_saddr_dst * dst,int i)1594 static int ipv6_get_saddr_eval(struct net *net,
1595 			       struct ipv6_saddr_score *score,
1596 			       struct ipv6_saddr_dst *dst,
1597 			       int i)
1598 {
1599 	int ret;
1600 
1601 	if (i <= score->rule) {
1602 		switch (i) {
1603 		case IPV6_SADDR_RULE_SCOPE:
1604 			ret = score->scopedist;
1605 			break;
1606 		case IPV6_SADDR_RULE_PREFIX:
1607 			ret = score->matchlen;
1608 			break;
1609 		default:
1610 			ret = !!test_bit(i, score->scorebits);
1611 		}
1612 		goto out;
1613 	}
1614 
1615 	switch (i) {
1616 	case IPV6_SADDR_RULE_INIT:
1617 		/* Rule 0: remember if hiscore is not ready yet */
1618 		ret = !!score->ifa;
1619 		break;
1620 	case IPV6_SADDR_RULE_LOCAL:
1621 		/* Rule 1: Prefer same address */
1622 		ret = ipv6_addr_equal(&score->ifa->addr, dst->addr);
1623 		break;
1624 	case IPV6_SADDR_RULE_SCOPE:
1625 		/* Rule 2: Prefer appropriate scope
1626 		 *
1627 		 *      ret
1628 		 *       ^
1629 		 *    -1 |  d 15
1630 		 *    ---+--+-+---> scope
1631 		 *       |
1632 		 *       |             d is scope of the destination.
1633 		 *  B-d  |  \
1634 		 *       |   \      <- smaller scope is better if
1635 		 *  B-15 |    \        if scope is enough for destination.
1636 		 *       |             ret = B - scope (-1 <= scope >= d <= 15).
1637 		 * d-C-1 | /
1638 		 *       |/         <- greater is better
1639 		 *   -C  /             if scope is not enough for destination.
1640 		 *      /|             ret = scope - C (-1 <= d < scope <= 15).
1641 		 *
1642 		 * d - C - 1 < B -15 (for all -1 <= d <= 15).
1643 		 * C > d + 14 - B >= 15 + 14 - B = 29 - B.
1644 		 * Assume B = 0 and we get C > 29.
1645 		 */
1646 		ret = __ipv6_addr_src_scope(score->addr_type);
1647 		if (ret >= dst->scope)
1648 			ret = -ret;
1649 		else
1650 			ret -= 128;	/* 30 is enough */
1651 		score->scopedist = ret;
1652 		break;
1653 	case IPV6_SADDR_RULE_PREFERRED:
1654 	    {
1655 		/* Rule 3: Avoid deprecated and optimistic addresses */
1656 		u8 avoid = IFA_F_DEPRECATED;
1657 
1658 		if (!ipv6_use_optimistic_addr(net, score->ifa->idev))
1659 			avoid |= IFA_F_OPTIMISTIC;
1660 		ret = ipv6_saddr_preferred(score->addr_type) ||
1661 		      !(score->ifa->flags & avoid);
1662 		break;
1663 	    }
1664 #ifdef CONFIG_IPV6_MIP6
1665 	case IPV6_SADDR_RULE_HOA:
1666 	    {
1667 		/* Rule 4: Prefer home address */
1668 		int prefhome = !(dst->prefs & IPV6_PREFER_SRC_COA);
1669 		ret = !(score->ifa->flags & IFA_F_HOMEADDRESS) ^ prefhome;
1670 		break;
1671 	    }
1672 #endif
1673 	case IPV6_SADDR_RULE_OIF:
1674 		/* Rule 5: Prefer outgoing interface */
1675 		ret = (!dst->ifindex ||
1676 		       dst->ifindex == score->ifa->idev->dev->ifindex);
1677 		break;
1678 	case IPV6_SADDR_RULE_LABEL:
1679 		/* Rule 6: Prefer matching label */
1680 		ret = ipv6_addr_label(net,
1681 				      &score->ifa->addr, score->addr_type,
1682 				      score->ifa->idev->dev->ifindex) == dst->label;
1683 		break;
1684 	case IPV6_SADDR_RULE_PRIVACY:
1685 	    {
1686 		/* Rule 7: Prefer public address
1687 		 * Note: prefer temporary address if use_tempaddr >= 2
1688 		 */
1689 		int preftmp = dst->prefs & (IPV6_PREFER_SRC_PUBLIC|IPV6_PREFER_SRC_TMP) ?
1690 				!!(dst->prefs & IPV6_PREFER_SRC_TMP) :
1691 				READ_ONCE(score->ifa->idev->cnf.use_tempaddr) >= 2;
1692 		ret = (!(score->ifa->flags & IFA_F_TEMPORARY)) ^ preftmp;
1693 		break;
1694 	    }
1695 	case IPV6_SADDR_RULE_ORCHID:
1696 		/* Rule 8-: Prefer ORCHID vs ORCHID or
1697 		 *	    non-ORCHID vs non-ORCHID
1698 		 */
1699 		ret = !(ipv6_addr_orchid(&score->ifa->addr) ^
1700 			ipv6_addr_orchid(dst->addr));
1701 		break;
1702 	case IPV6_SADDR_RULE_PREFIX:
1703 		/* Rule 8: Use longest matching prefix */
1704 		ret = ipv6_addr_diff(&score->ifa->addr, dst->addr);
1705 		if (ret > score->ifa->prefix_len)
1706 			ret = score->ifa->prefix_len;
1707 		score->matchlen = ret;
1708 		break;
1709 #ifdef CONFIG_IPV6_OPTIMISTIC_DAD
1710 	case IPV6_SADDR_RULE_NOT_OPTIMISTIC:
1711 		/* Optimistic addresses still have lower precedence than other
1712 		 * preferred addresses.
1713 		 */
1714 		ret = !(score->ifa->flags & IFA_F_OPTIMISTIC);
1715 		break;
1716 #endif
1717 	default:
1718 		ret = 0;
1719 	}
1720 
1721 	if (ret)
1722 		__set_bit(i, score->scorebits);
1723 	score->rule = i;
1724 out:
1725 	return ret;
1726 }
1727 
__ipv6_dev_get_saddr(struct net * net,struct ipv6_saddr_dst * dst,struct inet6_dev * idev,struct ipv6_saddr_score * scores,int hiscore_idx)1728 static int __ipv6_dev_get_saddr(struct net *net,
1729 				struct ipv6_saddr_dst *dst,
1730 				struct inet6_dev *idev,
1731 				struct ipv6_saddr_score *scores,
1732 				int hiscore_idx)
1733 {
1734 	struct ipv6_saddr_score *score = &scores[1 - hiscore_idx], *hiscore = &scores[hiscore_idx];
1735 
1736 	list_for_each_entry_rcu(score->ifa, &idev->addr_list, if_list) {
1737 		int i;
1738 
1739 		/*
1740 		 * - Tentative Address (RFC2462 section 5.4)
1741 		 *  - A tentative address is not considered
1742 		 *    "assigned to an interface" in the traditional
1743 		 *    sense, unless it is also flagged as optimistic.
1744 		 * - Candidate Source Address (section 4)
1745 		 *  - In any case, anycast addresses, multicast
1746 		 *    addresses, and the unspecified address MUST
1747 		 *    NOT be included in a candidate set.
1748 		 */
1749 		if ((score->ifa->flags & IFA_F_TENTATIVE) &&
1750 		    (!(score->ifa->flags & IFA_F_OPTIMISTIC)))
1751 			continue;
1752 
1753 		score->addr_type = __ipv6_addr_type(&score->ifa->addr);
1754 
1755 		if (unlikely(score->addr_type == IPV6_ADDR_ANY ||
1756 			     score->addr_type & IPV6_ADDR_MULTICAST)) {
1757 			net_dbg_ratelimited("ADDRCONF: unspecified / multicast address assigned as unicast address on %s",
1758 					    idev->dev->name);
1759 			continue;
1760 		}
1761 
1762 		score->rule = -1;
1763 		bitmap_zero(score->scorebits, IPV6_SADDR_RULE_MAX);
1764 
1765 		for (i = 0; i < IPV6_SADDR_RULE_MAX; i++) {
1766 			int minihiscore, miniscore;
1767 
1768 			minihiscore = ipv6_get_saddr_eval(net, hiscore, dst, i);
1769 			miniscore = ipv6_get_saddr_eval(net, score, dst, i);
1770 
1771 			if (minihiscore > miniscore) {
1772 				if (i == IPV6_SADDR_RULE_SCOPE &&
1773 				    score->scopedist > 0) {
1774 					/*
1775 					 * special case:
1776 					 * each remaining entry
1777 					 * has too small (not enough)
1778 					 * scope, because ifa entries
1779 					 * are sorted by their scope
1780 					 * values.
1781 					 */
1782 					goto out;
1783 				}
1784 				break;
1785 			} else if (minihiscore < miniscore) {
1786 				swap(hiscore, score);
1787 				hiscore_idx = 1 - hiscore_idx;
1788 
1789 				/* restore our iterator */
1790 				score->ifa = hiscore->ifa;
1791 
1792 				break;
1793 			}
1794 		}
1795 	}
1796 out:
1797 	return hiscore_idx;
1798 }
1799 
ipv6_get_saddr_master(struct net * net,const struct net_device * dst_dev,const struct net_device * master,struct ipv6_saddr_dst * dst,struct ipv6_saddr_score * scores,int hiscore_idx)1800 static int ipv6_get_saddr_master(struct net *net,
1801 				 const struct net_device *dst_dev,
1802 				 const struct net_device *master,
1803 				 struct ipv6_saddr_dst *dst,
1804 				 struct ipv6_saddr_score *scores,
1805 				 int hiscore_idx)
1806 {
1807 	struct inet6_dev *idev;
1808 
1809 	idev = __in6_dev_get(dst_dev);
1810 	if (idev)
1811 		hiscore_idx = __ipv6_dev_get_saddr(net, dst, idev,
1812 						   scores, hiscore_idx);
1813 
1814 	idev = __in6_dev_get(master);
1815 	if (idev)
1816 		hiscore_idx = __ipv6_dev_get_saddr(net, dst, idev,
1817 						   scores, hiscore_idx);
1818 
1819 	return hiscore_idx;
1820 }
1821 
ipv6_dev_get_saddr(struct net * net,const struct net_device * dst_dev,const struct in6_addr * daddr,unsigned int prefs,struct in6_addr * saddr)1822 int ipv6_dev_get_saddr(struct net *net, const struct net_device *dst_dev,
1823 		       const struct in6_addr *daddr, unsigned int prefs,
1824 		       struct in6_addr *saddr)
1825 {
1826 	struct ipv6_saddr_score scores[2], *hiscore;
1827 	struct ipv6_saddr_dst dst;
1828 	struct inet6_dev *idev;
1829 	struct net_device *dev;
1830 	int dst_type;
1831 	bool use_oif_addr = false;
1832 	int hiscore_idx = 0;
1833 	int ret = 0;
1834 
1835 	dst_type = __ipv6_addr_type(daddr);
1836 	dst.addr = daddr;
1837 	dst.ifindex = dst_dev ? dst_dev->ifindex : 0;
1838 	dst.scope = __ipv6_addr_src_scope(dst_type);
1839 	dst.label = ipv6_addr_label(net, daddr, dst_type, dst.ifindex);
1840 	dst.prefs = prefs;
1841 
1842 	scores[hiscore_idx].rule = -1;
1843 	scores[hiscore_idx].ifa = NULL;
1844 
1845 	rcu_read_lock();
1846 
1847 	/* Candidate Source Address (section 4)
1848 	 *  - multicast and link-local destination address,
1849 	 *    the set of candidate source address MUST only
1850 	 *    include addresses assigned to interfaces
1851 	 *    belonging to the same link as the outgoing
1852 	 *    interface.
1853 	 * (- For site-local destination addresses, the
1854 	 *    set of candidate source addresses MUST only
1855 	 *    include addresses assigned to interfaces
1856 	 *    belonging to the same site as the outgoing
1857 	 *    interface.)
1858 	 *  - "It is RECOMMENDED that the candidate source addresses
1859 	 *    be the set of unicast addresses assigned to the
1860 	 *    interface that will be used to send to the destination
1861 	 *    (the 'outgoing' interface)." (RFC 6724)
1862 	 */
1863 	if (dst_dev) {
1864 		idev = __in6_dev_get(dst_dev);
1865 		if ((dst_type & IPV6_ADDR_MULTICAST) ||
1866 		    dst.scope <= IPV6_ADDR_SCOPE_LINKLOCAL ||
1867 		    (idev && READ_ONCE(idev->cnf.use_oif_addrs_only))) {
1868 			use_oif_addr = true;
1869 		}
1870 	}
1871 
1872 	if (use_oif_addr) {
1873 		if (idev)
1874 			hiscore_idx = __ipv6_dev_get_saddr(net, &dst, idev, scores, hiscore_idx);
1875 	} else {
1876 		const struct net_device *master;
1877 		int master_idx = 0;
1878 
1879 		/* if dst_dev exists and is enslaved to an L3 device, then
1880 		 * prefer addresses from dst_dev and then the master over
1881 		 * any other enslaved devices in the L3 domain.
1882 		 */
1883 		master = l3mdev_master_dev_rcu(dst_dev);
1884 		if (master) {
1885 			master_idx = master->ifindex;
1886 
1887 			hiscore_idx = ipv6_get_saddr_master(net, dst_dev,
1888 							    master, &dst,
1889 							    scores, hiscore_idx);
1890 
1891 			if (scores[hiscore_idx].ifa &&
1892 			    scores[hiscore_idx].scopedist >= 0)
1893 				goto out;
1894 		}
1895 
1896 		for_each_netdev_rcu(net, dev) {
1897 			/* only consider addresses on devices in the
1898 			 * same L3 domain
1899 			 */
1900 			if (l3mdev_master_ifindex_rcu(dev) != master_idx)
1901 				continue;
1902 			idev = __in6_dev_get(dev);
1903 			if (!idev)
1904 				continue;
1905 			hiscore_idx = __ipv6_dev_get_saddr(net, &dst, idev, scores, hiscore_idx);
1906 		}
1907 	}
1908 
1909 out:
1910 	hiscore = &scores[hiscore_idx];
1911 	if (!hiscore->ifa)
1912 		ret = -EADDRNOTAVAIL;
1913 	else
1914 		*saddr = hiscore->ifa->addr;
1915 
1916 	rcu_read_unlock();
1917 	return ret;
1918 }
1919 EXPORT_SYMBOL(ipv6_dev_get_saddr);
1920 
__ipv6_get_lladdr(struct inet6_dev * idev,struct in6_addr * addr,u32 banned_flags)1921 static int __ipv6_get_lladdr(struct inet6_dev *idev, struct in6_addr *addr,
1922 			      u32 banned_flags)
1923 {
1924 	struct inet6_ifaddr *ifp;
1925 	int err = -EADDRNOTAVAIL;
1926 
1927 	list_for_each_entry_reverse(ifp, &idev->addr_list, if_list) {
1928 		if (ifp->scope > IFA_LINK)
1929 			break;
1930 		if (ifp->scope == IFA_LINK &&
1931 		    !(ifp->flags & banned_flags)) {
1932 			*addr = ifp->addr;
1933 			err = 0;
1934 			break;
1935 		}
1936 	}
1937 	return err;
1938 }
1939 
ipv6_get_lladdr(struct net_device * dev,struct in6_addr * addr,u32 banned_flags)1940 int ipv6_get_lladdr(struct net_device *dev, struct in6_addr *addr,
1941 		    u32 banned_flags)
1942 {
1943 	struct inet6_dev *idev;
1944 	int err = -EADDRNOTAVAIL;
1945 
1946 	rcu_read_lock();
1947 	idev = __in6_dev_get(dev);
1948 	if (idev) {
1949 		read_lock_bh(&idev->lock);
1950 		err = __ipv6_get_lladdr(idev, addr, banned_flags);
1951 		read_unlock_bh(&idev->lock);
1952 	}
1953 	rcu_read_unlock();
1954 	return err;
1955 }
1956 
ipv6_count_addresses(const struct inet6_dev * idev)1957 static int ipv6_count_addresses(const struct inet6_dev *idev)
1958 {
1959 	const struct inet6_ifaddr *ifp;
1960 	int cnt = 0;
1961 
1962 	rcu_read_lock();
1963 	list_for_each_entry_rcu(ifp, &idev->addr_list, if_list)
1964 		cnt++;
1965 	rcu_read_unlock();
1966 	return cnt;
1967 }
1968 
ipv6_chk_addr(struct net * net,const struct in6_addr * addr,const struct net_device * dev,int strict)1969 int ipv6_chk_addr(struct net *net, const struct in6_addr *addr,
1970 		  const struct net_device *dev, int strict)
1971 {
1972 	return ipv6_chk_addr_and_flags(net, addr, dev, !dev,
1973 				       strict, IFA_F_TENTATIVE);
1974 }
1975 EXPORT_SYMBOL(ipv6_chk_addr);
1976 
1977 /* device argument is used to find the L3 domain of interest. If
1978  * skip_dev_check is set, then the ifp device is not checked against
1979  * the passed in dev argument. So the 2 cases for addresses checks are:
1980  *   1. does the address exist in the L3 domain that dev is part of
1981  *      (skip_dev_check = true), or
1982  *
1983  *   2. does the address exist on the specific device
1984  *      (skip_dev_check = false)
1985  */
1986 static struct net_device *
__ipv6_chk_addr_and_flags(struct net * net,const struct in6_addr * addr,const struct net_device * dev,bool skip_dev_check,int strict,u32 banned_flags)1987 __ipv6_chk_addr_and_flags(struct net *net, const struct in6_addr *addr,
1988 			  const struct net_device *dev, bool skip_dev_check,
1989 			  int strict, u32 banned_flags)
1990 {
1991 	unsigned int hash = inet6_addr_hash(net, addr);
1992 	struct net_device *l3mdev, *ndev;
1993 	struct inet6_ifaddr *ifp;
1994 	u32 ifp_flags;
1995 
1996 	rcu_read_lock();
1997 
1998 	l3mdev = l3mdev_master_dev_rcu(dev);
1999 	if (skip_dev_check)
2000 		dev = NULL;
2001 
2002 	hlist_for_each_entry_rcu(ifp, &net->ipv6.inet6_addr_lst[hash], addr_lst) {
2003 		ndev = ifp->idev->dev;
2004 
2005 		if (l3mdev_master_dev_rcu(ndev) != l3mdev)
2006 			continue;
2007 
2008 		/* Decouple optimistic from tentative for evaluation here.
2009 		 * Ban optimistic addresses explicitly, when required.
2010 		 */
2011 		ifp_flags = (ifp->flags&IFA_F_OPTIMISTIC)
2012 			    ? (ifp->flags&~IFA_F_TENTATIVE)
2013 			    : ifp->flags;
2014 		if (ipv6_addr_equal(&ifp->addr, addr) &&
2015 		    !(ifp_flags&banned_flags) &&
2016 		    (!dev || ndev == dev ||
2017 		     !(ifp->scope&(IFA_LINK|IFA_HOST) || strict))) {
2018 			rcu_read_unlock();
2019 			return ndev;
2020 		}
2021 	}
2022 
2023 	rcu_read_unlock();
2024 	return NULL;
2025 }
2026 
ipv6_chk_addr_and_flags(struct net * net,const struct in6_addr * addr,const struct net_device * dev,bool skip_dev_check,int strict,u32 banned_flags)2027 int ipv6_chk_addr_and_flags(struct net *net, const struct in6_addr *addr,
2028 			    const struct net_device *dev, bool skip_dev_check,
2029 			    int strict, u32 banned_flags)
2030 {
2031 	return __ipv6_chk_addr_and_flags(net, addr, dev, skip_dev_check,
2032 					 strict, banned_flags) ? 1 : 0;
2033 }
2034 EXPORT_SYMBOL(ipv6_chk_addr_and_flags);
2035 
2036 
2037 /* Compares an address/prefix_len with addresses on device @dev.
2038  * If one is found it returns true.
2039  */
ipv6_chk_custom_prefix(const struct in6_addr * addr,const unsigned int prefix_len,struct net_device * dev)2040 bool ipv6_chk_custom_prefix(const struct in6_addr *addr,
2041 	const unsigned int prefix_len, struct net_device *dev)
2042 {
2043 	const struct inet6_ifaddr *ifa;
2044 	const struct inet6_dev *idev;
2045 	bool ret = false;
2046 
2047 	rcu_read_lock();
2048 	idev = __in6_dev_get(dev);
2049 	if (idev) {
2050 		list_for_each_entry_rcu(ifa, &idev->addr_list, if_list) {
2051 			ret = ipv6_prefix_equal(addr, &ifa->addr, prefix_len);
2052 			if (ret)
2053 				break;
2054 		}
2055 	}
2056 	rcu_read_unlock();
2057 
2058 	return ret;
2059 }
2060 EXPORT_SYMBOL(ipv6_chk_custom_prefix);
2061 
ipv6_chk_prefix(const struct in6_addr * addr,struct net_device * dev)2062 int ipv6_chk_prefix(const struct in6_addr *addr, struct net_device *dev)
2063 {
2064 	const struct inet6_ifaddr *ifa;
2065 	const struct inet6_dev *idev;
2066 	int	onlink;
2067 
2068 	onlink = 0;
2069 	rcu_read_lock();
2070 	idev = __in6_dev_get(dev);
2071 	if (idev) {
2072 		list_for_each_entry_rcu(ifa, &idev->addr_list, if_list) {
2073 			onlink = ipv6_prefix_equal(addr, &ifa->addr,
2074 						   ifa->prefix_len);
2075 			if (onlink)
2076 				break;
2077 		}
2078 	}
2079 	rcu_read_unlock();
2080 	return onlink;
2081 }
2082 EXPORT_SYMBOL(ipv6_chk_prefix);
2083 
2084 /**
2085  * ipv6_dev_find - find the first device with a given source address.
2086  * @net: the net namespace
2087  * @addr: the source address
2088  * @dev: used to find the L3 domain of interest
2089  *
2090  * The caller should be protected by RCU, or RTNL.
2091  */
ipv6_dev_find(struct net * net,const struct in6_addr * addr,struct net_device * dev)2092 struct net_device *ipv6_dev_find(struct net *net, const struct in6_addr *addr,
2093 				 struct net_device *dev)
2094 {
2095 	return __ipv6_chk_addr_and_flags(net, addr, dev, !dev, 1,
2096 					 IFA_F_TENTATIVE);
2097 }
2098 EXPORT_SYMBOL(ipv6_dev_find);
2099 
ipv6_get_ifaddr(struct net * net,const struct in6_addr * addr,struct net_device * dev,int strict)2100 struct inet6_ifaddr *ipv6_get_ifaddr(struct net *net, const struct in6_addr *addr,
2101 				     struct net_device *dev, int strict)
2102 {
2103 	unsigned int hash = inet6_addr_hash(net, addr);
2104 	struct inet6_ifaddr *ifp, *result = NULL;
2105 
2106 	rcu_read_lock();
2107 	hlist_for_each_entry_rcu(ifp, &net->ipv6.inet6_addr_lst[hash], addr_lst) {
2108 		if (ipv6_addr_equal(&ifp->addr, addr)) {
2109 			if (!dev || ifp->idev->dev == dev ||
2110 			    !(ifp->scope&(IFA_LINK|IFA_HOST) || strict)) {
2111 				if (in6_ifa_hold_safe(ifp)) {
2112 					result = ifp;
2113 					break;
2114 				}
2115 			}
2116 		}
2117 	}
2118 	rcu_read_unlock();
2119 
2120 	return result;
2121 }
2122 
2123 /* Gets referenced address, destroys ifaddr */
2124 
addrconf_dad_stop(struct inet6_ifaddr * ifp,int dad_failed)2125 static void addrconf_dad_stop(struct inet6_ifaddr *ifp, int dad_failed)
2126 {
2127 	if (dad_failed)
2128 		ifp->flags |= IFA_F_DADFAILED;
2129 
2130 	if (ifp->flags&IFA_F_TEMPORARY) {
2131 		struct inet6_ifaddr *ifpub;
2132 		spin_lock_bh(&ifp->lock);
2133 		ifpub = ifp->ifpub;
2134 		if (ifpub) {
2135 			in6_ifa_hold(ifpub);
2136 			spin_unlock_bh(&ifp->lock);
2137 			ipv6_create_tempaddr(ifpub, true);
2138 			in6_ifa_put(ifpub);
2139 		} else {
2140 			spin_unlock_bh(&ifp->lock);
2141 		}
2142 		ipv6_del_addr(ifp);
2143 	} else if (ifp->flags&IFA_F_PERMANENT || !dad_failed) {
2144 		spin_lock_bh(&ifp->lock);
2145 		addrconf_del_dad_work(ifp);
2146 		ifp->flags |= IFA_F_TENTATIVE;
2147 		if (dad_failed)
2148 			ifp->flags &= ~IFA_F_OPTIMISTIC;
2149 		spin_unlock_bh(&ifp->lock);
2150 		if (dad_failed)
2151 			ipv6_ifa_notify(0, ifp);
2152 		in6_ifa_put(ifp);
2153 	} else {
2154 		ipv6_del_addr(ifp);
2155 	}
2156 }
2157 
addrconf_dad_end(struct inet6_ifaddr * ifp)2158 static int addrconf_dad_end(struct inet6_ifaddr *ifp)
2159 {
2160 	int err = -ENOENT;
2161 
2162 	spin_lock_bh(&ifp->lock);
2163 	if (ifp->state == INET6_IFADDR_STATE_DAD) {
2164 		ifp->state = INET6_IFADDR_STATE_POSTDAD;
2165 		err = 0;
2166 	}
2167 	spin_unlock_bh(&ifp->lock);
2168 
2169 	return err;
2170 }
2171 
addrconf_dad_failure(struct sk_buff * skb,struct inet6_ifaddr * ifp)2172 void addrconf_dad_failure(struct sk_buff *skb, struct inet6_ifaddr *ifp)
2173 {
2174 	struct inet6_dev *idev = ifp->idev;
2175 	struct net *net = dev_net(idev->dev);
2176 	int max_addresses;
2177 
2178 	spin_lock_bh(&ifp->lock);
2179 
2180 	if (ifp->state != INET6_IFADDR_STATE_DAD) {
2181 		spin_unlock_bh(&ifp->lock);
2182 		in6_ifa_put(ifp);
2183 		return;
2184 	}
2185 	ifp->state = INET6_IFADDR_STATE_POSTDAD;
2186 
2187 	net_info_ratelimited("%s: IPv6 duplicate address %pI6c used by %pM detected!\n",
2188 			     ifp->idev->dev->name, &ifp->addr, eth_hdr(skb)->h_source);
2189 
2190 	if (ifp->flags & IFA_F_STABLE_PRIVACY) {
2191 		struct in6_addr new_addr;
2192 		struct inet6_ifaddr *ifp2;
2193 		int retries = ifp->stable_privacy_retry + 1;
2194 		struct ifa6_config cfg = {
2195 			.pfx = &new_addr,
2196 			.plen = ifp->prefix_len,
2197 			.ifa_flags = ifp->flags,
2198 			.valid_lft = ifp->valid_lft,
2199 			.preferred_lft = ifp->prefered_lft,
2200 			.scope = ifp->scope,
2201 		};
2202 
2203 		if (retries > net->ipv6.sysctl.idgen_retries) {
2204 			net_info_ratelimited("%s: privacy stable address generation failed because of DAD conflicts!\n",
2205 					     ifp->idev->dev->name);
2206 			goto errdad;
2207 		}
2208 
2209 		new_addr = ifp->addr;
2210 		if (ipv6_generate_stable_address(&new_addr, retries,
2211 						 idev))
2212 			goto errdad;
2213 
2214 		spin_unlock_bh(&ifp->lock);
2215 
2216 		max_addresses = READ_ONCE(idev->cnf.max_addresses);
2217 		if (max_addresses &&
2218 		    ipv6_count_addresses(idev) >= max_addresses)
2219 			goto lock_errdad;
2220 
2221 		net_info_ratelimited("%s: generating new stable privacy address because of DAD conflict\n",
2222 				     ifp->idev->dev->name);
2223 
2224 		ifp2 = ipv6_add_addr(idev, &cfg, false, NULL);
2225 		if (IS_ERR(ifp2))
2226 			goto lock_errdad;
2227 
2228 		spin_lock_bh(&ifp2->lock);
2229 		ifp2->stable_privacy_retry = retries;
2230 		ifp2->state = INET6_IFADDR_STATE_PREDAD;
2231 		spin_unlock_bh(&ifp2->lock);
2232 
2233 		addrconf_mod_dad_work(ifp2, net->ipv6.sysctl.idgen_delay);
2234 		in6_ifa_put(ifp2);
2235 lock_errdad:
2236 		spin_lock_bh(&ifp->lock);
2237 		if (ifp->state != INET6_IFADDR_STATE_POSTDAD) {
2238 			spin_unlock_bh(&ifp->lock);
2239 			in6_ifa_put(ifp);
2240 			return;
2241 		}
2242 	}
2243 
2244 errdad:
2245 	/* transition from _POSTDAD to _ERRDAD */
2246 	ifp->state = INET6_IFADDR_STATE_ERRDAD;
2247 	spin_unlock_bh(&ifp->lock);
2248 
2249 	addrconf_mod_dad_work(ifp, 0);
2250 	in6_ifa_put(ifp);
2251 }
2252 
2253 /* Join to solicited addr multicast group. */
addrconf_join_solict(struct net_device * dev,const struct in6_addr * addr)2254 void addrconf_join_solict(struct net_device *dev, const struct in6_addr *addr)
2255 {
2256 	struct in6_addr maddr;
2257 
2258 	if (READ_ONCE(dev->flags) & (IFF_LOOPBACK | IFF_NOARP))
2259 		return;
2260 
2261 	addrconf_addr_solict_mult(addr, &maddr);
2262 	ipv6_dev_mc_inc(dev, &maddr);
2263 }
2264 
addrconf_leave_solict(struct inet6_dev * idev,const struct in6_addr * addr)2265 void addrconf_leave_solict(struct inet6_dev *idev, const struct in6_addr *addr)
2266 {
2267 	struct in6_addr maddr;
2268 
2269 	if (READ_ONCE(idev->dev->flags) & (IFF_LOOPBACK | IFF_NOARP))
2270 		return;
2271 
2272 	addrconf_addr_solict_mult(addr, &maddr);
2273 	__ipv6_dev_mc_dec(idev, &maddr);
2274 }
2275 
addrconf_join_anycast(struct inet6_ifaddr * ifp)2276 static void addrconf_join_anycast(struct inet6_ifaddr *ifp)
2277 {
2278 	struct in6_addr addr;
2279 
2280 	if (ifp->prefix_len >= 127) /* RFC 6164 */
2281 		return;
2282 	ipv6_addr_prefix(&addr, &ifp->addr, ifp->prefix_len);
2283 	if (ipv6_addr_any(&addr))
2284 		return;
2285 	__ipv6_dev_ac_inc(ifp->idev, &addr);
2286 }
2287 
addrconf_leave_anycast(struct inet6_ifaddr * ifp)2288 static void addrconf_leave_anycast(struct inet6_ifaddr *ifp)
2289 {
2290 	struct in6_addr addr;
2291 
2292 	if (ifp->prefix_len >= 127) /* RFC 6164 */
2293 		return;
2294 	ipv6_addr_prefix(&addr, &ifp->addr, ifp->prefix_len);
2295 	if (ipv6_addr_any(&addr))
2296 		return;
2297 	__ipv6_dev_ac_dec(ifp->idev, &addr);
2298 }
2299 
addrconf_ifid_6lowpan(u8 * eui,struct net_device * dev)2300 static int addrconf_ifid_6lowpan(u8 *eui, struct net_device *dev)
2301 {
2302 	switch (dev->addr_len) {
2303 	case ETH_ALEN:
2304 		memcpy(eui, dev->dev_addr, 3);
2305 		eui[3] = 0xFF;
2306 		eui[4] = 0xFE;
2307 		memcpy(eui + 5, dev->dev_addr + 3, 3);
2308 		break;
2309 	case EUI64_ADDR_LEN:
2310 		memcpy(eui, dev->dev_addr, EUI64_ADDR_LEN);
2311 		eui[0] ^= 2;
2312 		break;
2313 	default:
2314 		return -1;
2315 	}
2316 
2317 	return 0;
2318 }
2319 
addrconf_ifid_ieee1394(u8 * eui,struct net_device * dev)2320 static int addrconf_ifid_ieee1394(u8 *eui, struct net_device *dev)
2321 {
2322 	const union fwnet_hwaddr *ha;
2323 
2324 	if (dev->addr_len != FWNET_ALEN)
2325 		return -1;
2326 
2327 	ha = (const union fwnet_hwaddr *)dev->dev_addr;
2328 
2329 	memcpy(eui, &ha->uc.uniq_id, sizeof(ha->uc.uniq_id));
2330 	eui[0] ^= 2;
2331 	return 0;
2332 }
2333 
addrconf_ifid_arcnet(u8 * eui,struct net_device * dev)2334 static int addrconf_ifid_arcnet(u8 *eui, struct net_device *dev)
2335 {
2336 	/* XXX: inherit EUI-64 from other interface -- yoshfuji */
2337 	if (dev->addr_len != ARCNET_ALEN)
2338 		return -1;
2339 	memset(eui, 0, 7);
2340 	eui[7] = *(u8 *)dev->dev_addr;
2341 	return 0;
2342 }
2343 
addrconf_ifid_infiniband(u8 * eui,struct net_device * dev)2344 static int addrconf_ifid_infiniband(u8 *eui, struct net_device *dev)
2345 {
2346 	if (dev->addr_len != INFINIBAND_ALEN)
2347 		return -1;
2348 	memcpy(eui, dev->dev_addr + 12, 8);
2349 	eui[0] |= 2;
2350 	return 0;
2351 }
2352 
__ipv6_isatap_ifid(u8 * eui,__be32 addr)2353 static int __ipv6_isatap_ifid(u8 *eui, __be32 addr)
2354 {
2355 	if (addr == 0)
2356 		return -1;
2357 	eui[0] = (ipv4_is_zeronet(addr) || ipv4_is_private_10(addr) ||
2358 		  ipv4_is_loopback(addr) || ipv4_is_linklocal_169(addr) ||
2359 		  ipv4_is_private_172(addr) || ipv4_is_test_192(addr) ||
2360 		  ipv4_is_anycast_6to4(addr) || ipv4_is_private_192(addr) ||
2361 		  ipv4_is_test_198(addr) || ipv4_is_multicast(addr) ||
2362 		  ipv4_is_lbcast(addr)) ? 0x00 : 0x02;
2363 	eui[1] = 0;
2364 	eui[2] = 0x5E;
2365 	eui[3] = 0xFE;
2366 	memcpy(eui + 4, &addr, 4);
2367 	return 0;
2368 }
2369 
addrconf_ifid_sit(u8 * eui,struct net_device * dev)2370 static int addrconf_ifid_sit(u8 *eui, struct net_device *dev)
2371 {
2372 	if (dev->priv_flags & IFF_ISATAP)
2373 		return __ipv6_isatap_ifid(eui, *(__be32 *)dev->dev_addr);
2374 	return -1;
2375 }
2376 
addrconf_ifid_gre(u8 * eui,struct net_device * dev)2377 static int addrconf_ifid_gre(u8 *eui, struct net_device *dev)
2378 {
2379 	return __ipv6_isatap_ifid(eui, *(__be32 *)dev->dev_addr);
2380 }
2381 
addrconf_ifid_ip6tnl(u8 * eui,struct net_device * dev)2382 static int addrconf_ifid_ip6tnl(u8 *eui, struct net_device *dev)
2383 {
2384 	memcpy(eui, dev->perm_addr, 3);
2385 	memcpy(eui + 5, dev->perm_addr + 3, 3);
2386 	eui[3] = 0xFF;
2387 	eui[4] = 0xFE;
2388 	eui[0] ^= 2;
2389 	return 0;
2390 }
2391 
ipv6_generate_eui64(u8 * eui,struct net_device * dev)2392 static int ipv6_generate_eui64(u8 *eui, struct net_device *dev)
2393 {
2394 	switch (dev->type) {
2395 	case ARPHRD_ETHER:
2396 	case ARPHRD_FDDI:
2397 		return addrconf_ifid_eui48(eui, dev);
2398 	case ARPHRD_ARCNET:
2399 		return addrconf_ifid_arcnet(eui, dev);
2400 	case ARPHRD_INFINIBAND:
2401 		return addrconf_ifid_infiniband(eui, dev);
2402 	case ARPHRD_SIT:
2403 		return addrconf_ifid_sit(eui, dev);
2404 	case ARPHRD_IPGRE:
2405 	case ARPHRD_TUNNEL:
2406 		return addrconf_ifid_gre(eui, dev);
2407 	case ARPHRD_6LOWPAN:
2408 		return addrconf_ifid_6lowpan(eui, dev);
2409 	case ARPHRD_IEEE1394:
2410 		return addrconf_ifid_ieee1394(eui, dev);
2411 	case ARPHRD_TUNNEL6:
2412 	case ARPHRD_IP6GRE:
2413 	case ARPHRD_RAWIP:
2414 		return addrconf_ifid_ip6tnl(eui, dev);
2415 	}
2416 	return -1;
2417 }
2418 
ipv6_inherit_eui64(u8 * eui,struct inet6_dev * idev)2419 static int ipv6_inherit_eui64(u8 *eui, struct inet6_dev *idev)
2420 {
2421 	int err = -1;
2422 	struct inet6_ifaddr *ifp;
2423 
2424 	read_lock_bh(&idev->lock);
2425 	list_for_each_entry_reverse(ifp, &idev->addr_list, if_list) {
2426 		if (ifp->scope > IFA_LINK)
2427 			break;
2428 		if (ifp->scope == IFA_LINK && !(ifp->flags&IFA_F_TENTATIVE)) {
2429 			memcpy(eui, ifp->addr.s6_addr+8, 8);
2430 			err = 0;
2431 			break;
2432 		}
2433 	}
2434 	read_unlock_bh(&idev->lock);
2435 	return err;
2436 }
2437 
2438 /* Generation of a randomized Interface Identifier
2439  * draft-ietf-6man-rfc4941bis, Section 3.3.1
2440  */
2441 
ipv6_gen_rnd_iid(struct in6_addr * addr)2442 static void ipv6_gen_rnd_iid(struct in6_addr *addr)
2443 {
2444 regen:
2445 	get_random_bytes(&addr->s6_addr[8], 8);
2446 
2447 	/* <draft-ietf-6man-rfc4941bis-08.txt>, Section 3.3.1:
2448 	 * check if generated address is not inappropriate:
2449 	 *
2450 	 * - Reserved IPv6 Interface Identifiers
2451 	 * - XXX: already assigned to an address on the device
2452 	 */
2453 
2454 	/* Subnet-router anycast: 0000:0000:0000:0000 */
2455 	if (!(addr->s6_addr32[2] | addr->s6_addr32[3]))
2456 		goto regen;
2457 
2458 	/* IANA Ethernet block: 0200:5EFF:FE00:0000-0200:5EFF:FE00:5212
2459 	 * Proxy Mobile IPv6:   0200:5EFF:FE00:5213
2460 	 * IANA Ethernet block: 0200:5EFF:FE00:5214-0200:5EFF:FEFF:FFFF
2461 	 */
2462 	if (ntohl(addr->s6_addr32[2]) == 0x02005eff &&
2463 	    (ntohl(addr->s6_addr32[3]) & 0Xff000000) == 0xfe000000)
2464 		goto regen;
2465 
2466 	/* Reserved subnet anycast addresses */
2467 	if (ntohl(addr->s6_addr32[2]) == 0xfdffffff &&
2468 	    ntohl(addr->s6_addr32[3]) >= 0Xffffff80)
2469 		goto regen;
2470 }
2471 
2472 /*
2473  *	Add prefix route.
2474  */
2475 
2476 static void
addrconf_prefix_route(struct in6_addr * pfx,int plen,u32 metric,struct net_device * dev,unsigned long expires,u32 flags,gfp_t gfp_flags)2477 addrconf_prefix_route(struct in6_addr *pfx, int plen, u32 metric,
2478 		      struct net_device *dev, unsigned long expires,
2479 		      u32 flags, gfp_t gfp_flags)
2480 {
2481 	struct fib6_config cfg = {
2482 		.fc_table = l3mdev_fib_table(dev) ? : RT6_TABLE_PREFIX,
2483 		.fc_metric = metric ? : IP6_RT_PRIO_ADDRCONF,
2484 		.fc_ifindex = dev->ifindex,
2485 		.fc_expires = expires,
2486 		.fc_dst_len = plen,
2487 		.fc_flags = RTF_UP | flags,
2488 		.fc_nlinfo.nl_net = dev_net(dev),
2489 		.fc_protocol = RTPROT_KERNEL,
2490 		.fc_type = RTN_UNICAST,
2491 	};
2492 
2493 	cfg.fc_dst = *pfx;
2494 
2495 	/* Prevent useless cloning on PtP SIT.
2496 	   This thing is done here expecting that the whole
2497 	   class of non-broadcast devices need not cloning.
2498 	 */
2499 #if IS_ENABLED(CONFIG_IPV6_SIT)
2500 	if (dev->type == ARPHRD_SIT && (dev->flags & IFF_POINTOPOINT))
2501 		cfg.fc_flags |= RTF_NONEXTHOP;
2502 #endif
2503 
2504 	ip6_route_add(&cfg, gfp_flags, NULL);
2505 }
2506 
2507 
addrconf_get_prefix_route(const struct in6_addr * pfx,int plen,const struct net_device * dev,u32 flags,u32 noflags,bool no_gw)2508 static struct fib6_info *addrconf_get_prefix_route(const struct in6_addr *pfx,
2509 						  int plen,
2510 						  const struct net_device *dev,
2511 						  u32 flags, u32 noflags,
2512 						  bool no_gw)
2513 {
2514 	struct fib6_node *fn;
2515 	struct fib6_info *rt = NULL;
2516 	struct fib6_table *table;
2517 	u32 tb_id = l3mdev_fib_table(dev) ? : RT6_TABLE_PREFIX;
2518 
2519 	table = fib6_get_table(dev_net(dev), tb_id);
2520 	if (!table)
2521 		return NULL;
2522 
2523 	rcu_read_lock();
2524 	fn = fib6_locate(&table->tb6_root, pfx, plen, NULL, 0, true);
2525 	if (!fn)
2526 		goto out;
2527 
2528 	for_each_fib6_node_rt_rcu(fn) {
2529 		/* prefix routes only use builtin fib6_nh */
2530 		if (rt->nh)
2531 			continue;
2532 
2533 		if (rt->fib6_nh->fib_nh_dev->ifindex != dev->ifindex)
2534 			continue;
2535 		if (no_gw && rt->fib6_nh->fib_nh_gw_family)
2536 			continue;
2537 		if ((rt->fib6_flags & flags) != flags)
2538 			continue;
2539 		if ((rt->fib6_flags & noflags) != 0)
2540 			continue;
2541 		if (!fib6_info_hold_safe(rt))
2542 			continue;
2543 		break;
2544 	}
2545 out:
2546 	rcu_read_unlock();
2547 	return rt;
2548 }
2549 
2550 
2551 /* Create "default" multicast route to the interface */
2552 
addrconf_add_mroute(struct net_device * dev)2553 static void addrconf_add_mroute(struct net_device *dev)
2554 {
2555 	struct fib6_config cfg = {
2556 		.fc_table = l3mdev_fib_table(dev) ? : RT6_TABLE_LOCAL,
2557 		.fc_metric = IP6_RT_PRIO_ADDRCONF,
2558 		.fc_ifindex = dev->ifindex,
2559 		.fc_dst_len = 8,
2560 		.fc_flags = RTF_UP,
2561 		.fc_type = RTN_MULTICAST,
2562 		.fc_nlinfo.nl_net = dev_net(dev),
2563 		.fc_protocol = RTPROT_KERNEL,
2564 	};
2565 
2566 	ipv6_addr_set(&cfg.fc_dst, htonl(0xFF000000), 0, 0, 0);
2567 
2568 	ip6_route_add(&cfg, GFP_KERNEL, NULL);
2569 }
2570 
addrconf_add_dev(struct net_device * dev)2571 static struct inet6_dev *addrconf_add_dev(struct net_device *dev)
2572 {
2573 	struct inet6_dev *idev;
2574 
2575 	ASSERT_RTNL();
2576 
2577 	idev = ipv6_find_idev(dev);
2578 	if (IS_ERR(idev))
2579 		return idev;
2580 
2581 	if (idev->cnf.disable_ipv6)
2582 		return ERR_PTR(-EACCES);
2583 
2584 	/* Add default multicast route */
2585 	if (!(dev->flags & IFF_LOOPBACK) && !netif_is_l3_master(dev))
2586 		addrconf_add_mroute(dev);
2587 
2588 	return idev;
2589 }
2590 
delete_tempaddrs(struct inet6_dev * idev,struct inet6_ifaddr * ifp)2591 static void delete_tempaddrs(struct inet6_dev *idev,
2592 			     struct inet6_ifaddr *ifp)
2593 {
2594 	struct inet6_ifaddr *ift, *tmp;
2595 
2596 	write_lock_bh(&idev->lock);
2597 	list_for_each_entry_safe(ift, tmp, &idev->tempaddr_list, tmp_list) {
2598 		if (ift->ifpub != ifp)
2599 			continue;
2600 
2601 		in6_ifa_hold(ift);
2602 		write_unlock_bh(&idev->lock);
2603 		ipv6_del_addr(ift);
2604 		write_lock_bh(&idev->lock);
2605 	}
2606 	write_unlock_bh(&idev->lock);
2607 }
2608 
manage_tempaddrs(struct inet6_dev * idev,struct inet6_ifaddr * ifp,__u32 valid_lft,__u32 prefered_lft,bool create,unsigned long now)2609 static void manage_tempaddrs(struct inet6_dev *idev,
2610 			     struct inet6_ifaddr *ifp,
2611 			     __u32 valid_lft, __u32 prefered_lft,
2612 			     bool create, unsigned long now)
2613 {
2614 	u32 orig_prefered_lft = prefered_lft;
2615 	struct inet6_ifaddr *ift;
2616 	bool reset_done = false;
2617 	u32 flags;
2618 
2619 	read_lock_bh(&idev->lock);
2620 	/* update all temporary addresses in the list */
2621 	list_for_each_entry(ift, &idev->tempaddr_list, tmp_list) {
2622 		int age, max_valid, max_prefered;
2623 
2624 		if (ifp != ift->ifpub)
2625 			continue;
2626 
2627 		/* RFC 4941 section 3.3:
2628 		 * If a received option will extend the lifetime of a public
2629 		 * address, the lifetimes of temporary addresses should
2630 		 * be extended, subject to the overall constraint that no
2631 		 * temporary addresses should ever remain "valid" or "preferred"
2632 		 * for a time longer than (TEMP_VALID_LIFETIME) or
2633 		 * (TEMP_PREFERRED_LIFETIME - DESYNC_FACTOR), respectively.
2634 		 */
2635 		age = (now - ift->cstamp) / HZ;
2636 		max_valid = READ_ONCE(idev->cnf.temp_valid_lft) - age;
2637 		if (max_valid < 0)
2638 			max_valid = 0;
2639 
2640 		max_prefered = READ_ONCE(idev->cnf.temp_prefered_lft) -
2641 			       idev->desync_factor - age;
2642 		if (max_prefered < 0)
2643 			max_prefered = 0;
2644 
2645 		if (valid_lft > max_valid)
2646 			valid_lft = max_valid;
2647 
2648 		if (prefered_lft > max_prefered)
2649 			prefered_lft = max_prefered;
2650 
2651 		spin_lock(&ift->lock);
2652 		/* the first match is the most recent temp address */
2653 		if (!reset_done && orig_prefered_lft > 0) {
2654 			ift->regen_count = 0;
2655 			reset_done = true;
2656 		}
2657 		flags = ift->flags;
2658 		ift->valid_lft = valid_lft;
2659 		ift->prefered_lft = prefered_lft;
2660 		ift->tstamp = now;
2661 		if (prefered_lft > 0)
2662 			ift->flags &= ~IFA_F_DEPRECATED;
2663 
2664 		spin_unlock(&ift->lock);
2665 		if (!(flags&IFA_F_TENTATIVE))
2666 			ipv6_ifa_notify(0, ift);
2667 	}
2668 
2669 	/* Also create a temporary address if it's enabled but no temporary
2670 	 * address currently exists.
2671 	 * However, we get called with valid_lft == 0, prefered_lft == 0, create == false
2672 	 * as part of cleanup (ie. deleting the mngtmpaddr).
2673 	 * We don't want that to result in creating a new temporary ip address.
2674 	 */
2675 	if (list_empty(&idev->tempaddr_list) && (valid_lft || prefered_lft))
2676 		create = true;
2677 
2678 	if (create && READ_ONCE(idev->cnf.use_tempaddr) > 0) {
2679 		/* When a new public address is created as described
2680 		 * in [ADDRCONF], also create a new temporary address.
2681 		 */
2682 		read_unlock_bh(&idev->lock);
2683 		ipv6_create_tempaddr(ifp, false);
2684 	} else {
2685 		read_unlock_bh(&idev->lock);
2686 	}
2687 }
2688 
is_addr_mode_generate_stable(struct inet6_dev * idev)2689 static bool is_addr_mode_generate_stable(struct inet6_dev *idev)
2690 {
2691 	return idev->cnf.addr_gen_mode == IN6_ADDR_GEN_MODE_STABLE_PRIVACY ||
2692 	       idev->cnf.addr_gen_mode == IN6_ADDR_GEN_MODE_RANDOM;
2693 }
2694 
addrconf_prefix_rcv_add_addr(struct net * net,struct net_device * dev,const struct prefix_info * pinfo,struct inet6_dev * in6_dev,const struct in6_addr * addr,int addr_type,u32 addr_flags,bool sllao,bool tokenized,__u32 valid_lft,u32 prefered_lft)2695 int addrconf_prefix_rcv_add_addr(struct net *net, struct net_device *dev,
2696 				 const struct prefix_info *pinfo,
2697 				 struct inet6_dev *in6_dev,
2698 				 const struct in6_addr *addr, int addr_type,
2699 				 u32 addr_flags, bool sllao, bool tokenized,
2700 				 __u32 valid_lft, u32 prefered_lft)
2701 {
2702 	struct inet6_ifaddr *ifp = ipv6_get_ifaddr(net, addr, dev, 1);
2703 	int create = 0, update_lft = 0;
2704 
2705 	if (!ifp && valid_lft) {
2706 		int max_addresses = READ_ONCE(in6_dev->cnf.max_addresses);
2707 		struct ifa6_config cfg = {
2708 			.pfx = addr,
2709 			.plen = pinfo->prefix_len,
2710 			.ifa_flags = addr_flags,
2711 			.valid_lft = valid_lft,
2712 			.preferred_lft = prefered_lft,
2713 			.scope = addr_type & IPV6_ADDR_SCOPE_MASK,
2714 			.ifa_proto = IFAPROT_KERNEL_RA
2715 		};
2716 
2717 #ifdef CONFIG_IPV6_OPTIMISTIC_DAD
2718 		if ((READ_ONCE(net->ipv6.devconf_all->optimistic_dad) ||
2719 		     READ_ONCE(in6_dev->cnf.optimistic_dad)) &&
2720 		    !net->ipv6.devconf_all->forwarding && sllao)
2721 			cfg.ifa_flags |= IFA_F_OPTIMISTIC;
2722 #endif
2723 
2724 		/* Do not allow to create too much of autoconfigured
2725 		 * addresses; this would be too easy way to crash kernel.
2726 		 */
2727 		if (!max_addresses ||
2728 		    ipv6_count_addresses(in6_dev) < max_addresses)
2729 			ifp = ipv6_add_addr(in6_dev, &cfg, false, NULL);
2730 
2731 		if (IS_ERR_OR_NULL(ifp))
2732 			return -1;
2733 
2734 		create = 1;
2735 		spin_lock_bh(&ifp->lock);
2736 		ifp->flags |= IFA_F_MANAGETEMPADDR;
2737 		ifp->cstamp = jiffies;
2738 		ifp->tokenized = tokenized;
2739 		spin_unlock_bh(&ifp->lock);
2740 		addrconf_dad_start(ifp);
2741 	}
2742 
2743 	if (ifp) {
2744 		u32 flags;
2745 		unsigned long now;
2746 		u32 stored_lft;
2747 
2748 		/* update lifetime (RFC2462 5.5.3 e) */
2749 		spin_lock_bh(&ifp->lock);
2750 		now = jiffies;
2751 		if (ifp->valid_lft > (now - ifp->tstamp) / HZ)
2752 			stored_lft = ifp->valid_lft - (now - ifp->tstamp) / HZ;
2753 		else
2754 			stored_lft = 0;
2755 
2756 		/* RFC4862 Section 5.5.3e:
2757 		 * "Note that the preferred lifetime of the
2758 		 *  corresponding address is always reset to
2759 		 *  the Preferred Lifetime in the received
2760 		 *  Prefix Information option, regardless of
2761 		 *  whether the valid lifetime is also reset or
2762 		 *  ignored."
2763 		 *
2764 		 * So we should always update prefered_lft here.
2765 		 */
2766 		update_lft = !create && stored_lft;
2767 
2768 		if (update_lft && !READ_ONCE(in6_dev->cnf.ra_honor_pio_life)) {
2769 			const u32 minimum_lft = min_t(u32,
2770 				stored_lft, MIN_VALID_LIFETIME);
2771 			valid_lft = max(valid_lft, minimum_lft);
2772 		}
2773 
2774 		if (update_lft) {
2775 			ifp->valid_lft = valid_lft;
2776 			ifp->prefered_lft = prefered_lft;
2777 			WRITE_ONCE(ifp->tstamp, now);
2778 			flags = ifp->flags;
2779 			ifp->flags &= ~IFA_F_DEPRECATED;
2780 			spin_unlock_bh(&ifp->lock);
2781 
2782 			if (!(flags&IFA_F_TENTATIVE))
2783 				ipv6_ifa_notify(0, ifp);
2784 		} else
2785 			spin_unlock_bh(&ifp->lock);
2786 
2787 		manage_tempaddrs(in6_dev, ifp, valid_lft, prefered_lft,
2788 				 create, now);
2789 
2790 		in6_ifa_put(ifp);
2791 		addrconf_verify(net);
2792 	}
2793 
2794 	return 0;
2795 }
2796 EXPORT_SYMBOL_GPL(addrconf_prefix_rcv_add_addr);
2797 
addrconf_prefix_rcv(struct net_device * dev,u8 * opt,int len,bool sllao)2798 void addrconf_prefix_rcv(struct net_device *dev, u8 *opt, int len, bool sllao)
2799 {
2800 	struct prefix_info *pinfo;
2801 	struct fib6_table *table;
2802 	__u32 valid_lft;
2803 	__u32 prefered_lft;
2804 	int addr_type, err;
2805 	u32 addr_flags = 0;
2806 	struct inet6_dev *in6_dev;
2807 	struct net *net = dev_net(dev);
2808 	bool ignore_autoconf = false;
2809 
2810 	pinfo = (struct prefix_info *) opt;
2811 
2812 	if (len < sizeof(struct prefix_info)) {
2813 		netdev_dbg(dev, "addrconf: prefix option too short\n");
2814 		return;
2815 	}
2816 
2817 	/*
2818 	 *	Validation checks ([ADDRCONF], page 19)
2819 	 */
2820 
2821 	addr_type = ipv6_addr_type(&pinfo->prefix);
2822 
2823 	if (addr_type & (IPV6_ADDR_MULTICAST|IPV6_ADDR_LINKLOCAL))
2824 		return;
2825 
2826 	valid_lft = ntohl(pinfo->valid);
2827 	prefered_lft = ntohl(pinfo->prefered);
2828 
2829 	if (prefered_lft > valid_lft) {
2830 		net_warn_ratelimited("addrconf: prefix option has invalid lifetime\n");
2831 		return;
2832 	}
2833 
2834 	in6_dev = in6_dev_get(dev);
2835 
2836 	if (!in6_dev) {
2837 		net_dbg_ratelimited("addrconf: device %s not configured\n",
2838 				    dev->name);
2839 		return;
2840 	}
2841 
2842 	if (valid_lft != 0 && valid_lft < in6_dev->cnf.accept_ra_min_lft)
2843 		goto put;
2844 
2845 	/*
2846 	 *	Two things going on here:
2847 	 *	1) Add routes for on-link prefixes
2848 	 *	2) Configure prefixes with the auto flag set
2849 	 */
2850 
2851 	if (pinfo->onlink) {
2852 		struct fib6_info *rt;
2853 		unsigned long rt_expires;
2854 
2855 		/* Avoid arithmetic overflow. Really, we could
2856 		 * save rt_expires in seconds, likely valid_lft,
2857 		 * but it would require division in fib gc, that it
2858 		 * not good.
2859 		 */
2860 		if (HZ > USER_HZ)
2861 			rt_expires = addrconf_timeout_fixup(valid_lft, HZ);
2862 		else
2863 			rt_expires = addrconf_timeout_fixup(valid_lft, USER_HZ);
2864 
2865 		if (addrconf_finite_timeout(rt_expires))
2866 			rt_expires *= HZ;
2867 
2868 		rt = addrconf_get_prefix_route(&pinfo->prefix,
2869 					       pinfo->prefix_len,
2870 					       dev,
2871 					       RTF_ADDRCONF | RTF_PREFIX_RT,
2872 					       RTF_DEFAULT, true);
2873 
2874 		if (rt) {
2875 			/* Autoconf prefix route */
2876 			if (valid_lft == 0) {
2877 				ip6_del_rt_reason(net, rt,
2878 						  RT_DEL_REASON_RA_WITHDRAWN);
2879 				rt = NULL;
2880 			} else {
2881 				table = rt->fib6_table;
2882 				spin_lock_bh(&table->tb6_lock);
2883 
2884 				if (addrconf_finite_timeout(rt_expires)) {
2885 					/* not infinity */
2886 					fib6_set_expires(rt, jiffies + rt_expires);
2887 					fib6_add_gc_list(rt);
2888 				} else {
2889 					fib6_clean_expires(rt);
2890 					fib6_may_remove_gc_list(net, rt);
2891 				}
2892 
2893 				spin_unlock_bh(&table->tb6_lock);
2894 			}
2895 		} else if (valid_lft) {
2896 			clock_t expires = 0;
2897 			int flags = RTF_ADDRCONF | RTF_PREFIX_RT;
2898 			if (addrconf_finite_timeout(rt_expires)) {
2899 				/* not infinity */
2900 				flags |= RTF_EXPIRES;
2901 				expires = jiffies_to_clock_t(rt_expires);
2902 			}
2903 			addrconf_prefix_route(&pinfo->prefix, pinfo->prefix_len,
2904 					      0, dev, expires, flags,
2905 					      GFP_ATOMIC);
2906 		}
2907 		fib6_info_release(rt);
2908 	}
2909 
2910 	/* Try to figure out our local address for this prefix */
2911 
2912 	ignore_autoconf = READ_ONCE(in6_dev->cnf.ra_honor_pio_pflag) && pinfo->preferpd;
2913 	if (pinfo->autoconf && in6_dev->cnf.autoconf && !ignore_autoconf) {
2914 		struct in6_addr addr;
2915 		bool tokenized = false, dev_addr_generated = false;
2916 
2917 		if (pinfo->prefix_len == 64) {
2918 			memcpy(&addr, &pinfo->prefix, 8);
2919 
2920 			if (!ipv6_addr_any(&in6_dev->token)) {
2921 				read_lock_bh(&in6_dev->lock);
2922 				memcpy(addr.s6_addr + 8,
2923 				       in6_dev->token.s6_addr + 8, 8);
2924 				read_unlock_bh(&in6_dev->lock);
2925 				tokenized = true;
2926 			} else if (is_addr_mode_generate_stable(in6_dev) &&
2927 				   !ipv6_generate_stable_address(&addr, 0,
2928 								 in6_dev)) {
2929 				addr_flags |= IFA_F_STABLE_PRIVACY;
2930 				goto ok;
2931 			} else if (ipv6_generate_eui64(addr.s6_addr + 8, dev) &&
2932 				   ipv6_inherit_eui64(addr.s6_addr + 8, in6_dev)) {
2933 				goto put;
2934 			} else {
2935 				dev_addr_generated = true;
2936 			}
2937 			goto ok;
2938 		}
2939 		net_dbg_ratelimited("IPv6 addrconf: prefix with wrong length %d\n",
2940 				    pinfo->prefix_len);
2941 		goto put;
2942 
2943 ok:
2944 		err = addrconf_prefix_rcv_add_addr(net, dev, pinfo, in6_dev,
2945 						   &addr, addr_type,
2946 						   addr_flags, sllao,
2947 						   tokenized, valid_lft,
2948 						   prefered_lft);
2949 		if (err)
2950 			goto put;
2951 
2952 		/* Ignore error case here because previous prefix add addr was
2953 		 * successful which will be notified.
2954 		 */
2955 		ndisc_ops_prefix_rcv_add_addr(net, dev, pinfo, in6_dev, &addr,
2956 					      addr_type, addr_flags, sllao,
2957 					      tokenized, valid_lft,
2958 					      prefered_lft,
2959 					      dev_addr_generated);
2960 	}
2961 	inet6_prefix_notify(RTM_NEWPREFIX, in6_dev, pinfo);
2962 put:
2963 	in6_dev_put(in6_dev);
2964 }
2965 
addrconf_set_sit_dstaddr(struct net * net,struct net_device * dev,struct in6_ifreq * ireq)2966 static int addrconf_set_sit_dstaddr(struct net *net, struct net_device *dev,
2967 		struct in6_ifreq *ireq)
2968 {
2969 	struct ip_tunnel_parm_kern p = { };
2970 	int err;
2971 
2972 	if (!(ipv6_addr_type(&ireq->ifr6_addr) & IPV6_ADDR_COMPATv4))
2973 		return -EADDRNOTAVAIL;
2974 
2975 	p.iph.daddr = ireq->ifr6_addr.s6_addr32[3];
2976 	p.iph.version = 4;
2977 	p.iph.ihl = 5;
2978 	p.iph.protocol = IPPROTO_IPV6;
2979 	p.iph.ttl = 64;
2980 
2981 	if (!dev->netdev_ops->ndo_tunnel_ctl)
2982 		return -EOPNOTSUPP;
2983 	err = dev->netdev_ops->ndo_tunnel_ctl(dev, &p, SIOCADDTUNNEL);
2984 	if (err)
2985 		return err;
2986 
2987 	dev = __dev_get_by_name(net, p.name);
2988 	if (!dev)
2989 		return -ENOBUFS;
2990 	return dev_open(dev, NULL);
2991 }
2992 
2993 /*
2994  *	Set destination address.
2995  *	Special case for SIT interfaces where we create a new "virtual"
2996  *	device.
2997  */
addrconf_set_dstaddr(struct net * net,void __user * arg)2998 int addrconf_set_dstaddr(struct net *net, void __user *arg)
2999 {
3000 	struct net_device *dev;
3001 	struct in6_ifreq ireq;
3002 	int err = -ENODEV;
3003 
3004 	if (!IS_ENABLED(CONFIG_IPV6_SIT))
3005 		return -ENODEV;
3006 	if (copy_from_user(&ireq, arg, sizeof(struct in6_ifreq)))
3007 		return -EFAULT;
3008 
3009 	rtnl_net_lock(net);
3010 	dev = __dev_get_by_index(net, ireq.ifr6_ifindex);
3011 	if (dev && dev->type == ARPHRD_SIT)
3012 		err = addrconf_set_sit_dstaddr(net, dev, &ireq);
3013 	rtnl_net_unlock(net);
3014 	return err;
3015 }
3016 
ipv6_mc_config(struct sock * sk,bool join,const struct in6_addr * addr,int ifindex)3017 static int ipv6_mc_config(struct sock *sk, bool join,
3018 			  const struct in6_addr *addr, int ifindex)
3019 {
3020 	int ret;
3021 
3022 	ASSERT_RTNL();
3023 
3024 	lock_sock(sk);
3025 	if (join)
3026 		ret = ipv6_sock_mc_join(sk, ifindex, addr);
3027 	else
3028 		ret = ipv6_sock_mc_drop(sk, ifindex, addr);
3029 	release_sock(sk);
3030 
3031 	return ret;
3032 }
3033 
3034 /*
3035  *	Manual configuration of address on an interface
3036  */
inet6_addr_add(struct net * net,struct net_device * dev,struct ifa6_config * cfg,clock_t expires,u32 flags,struct netlink_ext_ack * extack)3037 static int inet6_addr_add(struct net *net, struct net_device *dev,
3038 			  struct ifa6_config *cfg, clock_t expires, u32 flags,
3039 			  struct netlink_ext_ack *extack)
3040 {
3041 	struct inet6_ifaddr *ifp;
3042 	struct inet6_dev *idev;
3043 
3044 	ASSERT_RTNL_NET(net);
3045 
3046 	if (cfg->plen > 128) {
3047 		NL_SET_ERR_MSG_MOD(extack, "Invalid prefix length");
3048 		return -EINVAL;
3049 	}
3050 
3051 	if (cfg->ifa_flags & IFA_F_MANAGETEMPADDR && cfg->plen != 64) {
3052 		NL_SET_ERR_MSG_MOD(extack, "address with \"mngtmpaddr\" flag must have a prefix length of 64");
3053 		return -EINVAL;
3054 	}
3055 
3056 	idev = addrconf_add_dev(dev);
3057 	if (IS_ERR(idev)) {
3058 		NL_SET_ERR_MSG_MOD(extack, "IPv6 is disabled on this device");
3059 		return PTR_ERR(idev);
3060 	}
3061 
3062 	if (cfg->ifa_flags & IFA_F_MCAUTOJOIN) {
3063 		int ret = ipv6_mc_config(net->ipv6.mc_autojoin_sk,
3064 					 true, cfg->pfx, dev->ifindex);
3065 
3066 		if (ret < 0) {
3067 			NL_SET_ERR_MSG_MOD(extack, "Multicast auto join failed");
3068 			return ret;
3069 		}
3070 	}
3071 
3072 	cfg->scope = ipv6_addr_scope(cfg->pfx);
3073 
3074 	ifp = ipv6_add_addr(idev, cfg, true, extack);
3075 	if (!IS_ERR(ifp)) {
3076 		if (!(cfg->ifa_flags & IFA_F_NOPREFIXROUTE)) {
3077 			addrconf_prefix_route(&ifp->addr, ifp->prefix_len,
3078 					      ifp->rt_priority, dev, expires,
3079 					      flags, GFP_KERNEL);
3080 		}
3081 
3082 		/* Send a netlink notification if DAD is enabled and
3083 		 * optimistic flag is not set
3084 		 */
3085 		if (!(ifp->flags & (IFA_F_OPTIMISTIC | IFA_F_NODAD)))
3086 			ipv6_ifa_notify(0, ifp);
3087 		/*
3088 		 * Note that section 3.1 of RFC 4429 indicates
3089 		 * that the Optimistic flag should not be set for
3090 		 * manually configured addresses
3091 		 */
3092 		addrconf_dad_start(ifp);
3093 		if (cfg->ifa_flags & IFA_F_MANAGETEMPADDR)
3094 			manage_tempaddrs(idev, ifp, cfg->valid_lft,
3095 					 cfg->preferred_lft, true, jiffies);
3096 		in6_ifa_put(ifp);
3097 		addrconf_verify_rtnl(net);
3098 		return 0;
3099 	} else if (cfg->ifa_flags & IFA_F_MCAUTOJOIN) {
3100 		ipv6_mc_config(net->ipv6.mc_autojoin_sk, false,
3101 			       cfg->pfx, dev->ifindex);
3102 	}
3103 
3104 	return PTR_ERR(ifp);
3105 }
3106 
inet6_addr_del(struct net * net,int ifindex,u32 ifa_flags,const struct in6_addr * pfx,unsigned int plen,struct netlink_ext_ack * extack)3107 static int inet6_addr_del(struct net *net, int ifindex, u32 ifa_flags,
3108 			  const struct in6_addr *pfx, unsigned int plen,
3109 			  struct netlink_ext_ack *extack)
3110 {
3111 	struct inet6_ifaddr *ifp;
3112 	struct inet6_dev *idev;
3113 	struct net_device *dev;
3114 
3115 	if (plen > 128) {
3116 		NL_SET_ERR_MSG_MOD(extack, "Invalid prefix length");
3117 		return -EINVAL;
3118 	}
3119 
3120 	dev = __dev_get_by_index(net, ifindex);
3121 	if (!dev) {
3122 		NL_SET_ERR_MSG_MOD(extack, "Unable to find the interface");
3123 		return -ENODEV;
3124 	}
3125 
3126 	idev = __in6_dev_get_rtnl_net(dev);
3127 	if (!idev) {
3128 		NL_SET_ERR_MSG_MOD(extack, "IPv6 is disabled on this device");
3129 		return -ENXIO;
3130 	}
3131 
3132 	read_lock_bh(&idev->lock);
3133 	list_for_each_entry(ifp, &idev->addr_list, if_list) {
3134 		if (ifp->prefix_len == plen &&
3135 		    ipv6_addr_equal(pfx, &ifp->addr)) {
3136 			in6_ifa_hold(ifp);
3137 			read_unlock_bh(&idev->lock);
3138 
3139 			if (!(ifp->flags & IFA_F_TEMPORARY) &&
3140 			    (ifp->flags & IFA_F_MANAGETEMPADDR))
3141 				delete_tempaddrs(idev, ifp);
3142 
3143 			ipv6_del_addr(ifp);
3144 
3145 			addrconf_verify_rtnl(net);
3146 			if (ipv6_addr_is_multicast(pfx)) {
3147 				ipv6_mc_config(net->ipv6.mc_autojoin_sk,
3148 					       false, pfx, dev->ifindex);
3149 			}
3150 			return 0;
3151 		}
3152 	}
3153 	read_unlock_bh(&idev->lock);
3154 
3155 	NL_SET_ERR_MSG_MOD(extack, "address not found");
3156 	return -EADDRNOTAVAIL;
3157 }
3158 
3159 
addrconf_add_ifaddr(struct net * net,void __user * arg)3160 int addrconf_add_ifaddr(struct net *net, void __user *arg)
3161 {
3162 	struct ifa6_config cfg = {
3163 		.ifa_flags = IFA_F_PERMANENT,
3164 		.preferred_lft = INFINITY_LIFE_TIME,
3165 		.valid_lft = INFINITY_LIFE_TIME,
3166 	};
3167 	struct net_device *dev;
3168 	struct in6_ifreq ireq;
3169 	int err;
3170 
3171 	if (!ns_capable(net->user_ns, CAP_NET_ADMIN))
3172 		return -EPERM;
3173 
3174 	if (copy_from_user(&ireq, arg, sizeof(struct in6_ifreq)))
3175 		return -EFAULT;
3176 
3177 	cfg.pfx = &ireq.ifr6_addr;
3178 	cfg.plen = ireq.ifr6_prefixlen;
3179 
3180 	rtnl_net_lock(net);
3181 	dev = __dev_get_by_index(net, ireq.ifr6_ifindex);
3182 	if (dev) {
3183 		netdev_lock_ops(dev);
3184 		err = inet6_addr_add(net, dev, &cfg, 0, 0, NULL);
3185 		netdev_unlock_ops(dev);
3186 	} else {
3187 		err = -ENODEV;
3188 	}
3189 	rtnl_net_unlock(net);
3190 	return err;
3191 }
3192 
addrconf_del_ifaddr(struct net * net,void __user * arg)3193 int addrconf_del_ifaddr(struct net *net, void __user *arg)
3194 {
3195 	struct in6_ifreq ireq;
3196 	int err;
3197 
3198 	if (!ns_capable(net->user_ns, CAP_NET_ADMIN))
3199 		return -EPERM;
3200 
3201 	if (copy_from_user(&ireq, arg, sizeof(struct in6_ifreq)))
3202 		return -EFAULT;
3203 
3204 	rtnl_net_lock(net);
3205 	err = inet6_addr_del(net, ireq.ifr6_ifindex, 0, &ireq.ifr6_addr,
3206 			     ireq.ifr6_prefixlen, NULL);
3207 	rtnl_net_unlock(net);
3208 	return err;
3209 }
3210 
add_addr(struct inet6_dev * idev,const struct in6_addr * addr,int plen,int scope,u8 proto)3211 static void add_addr(struct inet6_dev *idev, const struct in6_addr *addr,
3212 		     int plen, int scope, u8 proto)
3213 {
3214 	struct inet6_ifaddr *ifp;
3215 	struct ifa6_config cfg = {
3216 		.pfx = addr,
3217 		.plen = plen,
3218 		.ifa_flags = IFA_F_PERMANENT,
3219 		.valid_lft = INFINITY_LIFE_TIME,
3220 		.preferred_lft = INFINITY_LIFE_TIME,
3221 		.scope = scope,
3222 		.ifa_proto = proto
3223 	};
3224 
3225 	ifp = ipv6_add_addr(idev, &cfg, true, NULL);
3226 	if (!IS_ERR(ifp)) {
3227 		spin_lock_bh(&ifp->lock);
3228 		ifp->flags &= ~IFA_F_TENTATIVE;
3229 		spin_unlock_bh(&ifp->lock);
3230 		rt_genid_bump_ipv6(dev_net(idev->dev));
3231 		ipv6_ifa_notify(RTM_NEWADDR, ifp);
3232 		in6_ifa_put(ifp);
3233 	}
3234 }
3235 
3236 #if IS_ENABLED(CONFIG_IPV6_SIT) || IS_ENABLED(CONFIG_NET_IPGRE)
add_v4_addrs(struct inet6_dev * idev)3237 static void add_v4_addrs(struct inet6_dev *idev)
3238 {
3239 	struct in6_addr addr;
3240 	struct net_device *dev;
3241 	struct net *net = dev_net(idev->dev);
3242 	int scope, plen;
3243 	u32 pflags = 0;
3244 
3245 	ASSERT_RTNL();
3246 
3247 	memset(&addr, 0, sizeof(struct in6_addr));
3248 	memcpy(&addr.s6_addr32[3], idev->dev->dev_addr, 4);
3249 
3250 	if (!(idev->dev->flags & IFF_POINTOPOINT) && idev->dev->type == ARPHRD_SIT) {
3251 		scope = IPV6_ADDR_COMPATv4;
3252 		plen = 96;
3253 		pflags |= RTF_NONEXTHOP;
3254 	} else {
3255 		if (idev->cnf.addr_gen_mode == IN6_ADDR_GEN_MODE_NONE)
3256 			return;
3257 
3258 		addr.s6_addr32[0] = htonl(0xfe800000);
3259 		scope = IFA_LINK;
3260 		plen = 64;
3261 	}
3262 
3263 	if (addr.s6_addr32[3]) {
3264 		add_addr(idev, &addr, plen, scope, IFAPROT_UNSPEC);
3265 		addrconf_prefix_route(&addr, plen, 0, idev->dev, 0, pflags,
3266 				      GFP_KERNEL);
3267 		return;
3268 	}
3269 
3270 	for_each_netdev(net, dev) {
3271 		struct in_device *in_dev = __in_dev_get_rtnl(dev);
3272 		if (in_dev && (dev->flags & IFF_UP)) {
3273 			struct in_ifaddr *ifa;
3274 			int flag = scope;
3275 
3276 			in_dev_for_each_ifa_rtnl(ifa, in_dev) {
3277 				addr.s6_addr32[3] = ifa->ifa_local;
3278 
3279 				if (ifa->ifa_scope == RT_SCOPE_LINK)
3280 					continue;
3281 				if (ifa->ifa_scope >= RT_SCOPE_HOST) {
3282 					if (idev->dev->flags&IFF_POINTOPOINT)
3283 						continue;
3284 					flag |= IFA_HOST;
3285 				}
3286 
3287 				add_addr(idev, &addr, plen, flag,
3288 					 IFAPROT_UNSPEC);
3289 				addrconf_prefix_route(&addr, plen, 0, idev->dev,
3290 						      0, pflags, GFP_KERNEL);
3291 			}
3292 		}
3293 	}
3294 }
3295 #endif
3296 
init_loopback(struct net_device * dev)3297 static void init_loopback(struct net_device *dev)
3298 {
3299 	struct inet6_dev  *idev;
3300 
3301 	/* ::1 */
3302 
3303 	ASSERT_RTNL();
3304 
3305 	idev = ipv6_find_idev(dev);
3306 	if (IS_ERR(idev)) {
3307 		pr_debug("%s: add_dev failed\n", __func__);
3308 		return;
3309 	}
3310 
3311 	add_addr(idev, &in6addr_loopback, 128, IFA_HOST, IFAPROT_KERNEL_LO);
3312 }
3313 
addrconf_add_linklocal(struct inet6_dev * idev,const struct in6_addr * addr,u32 flags)3314 void addrconf_add_linklocal(struct inet6_dev *idev,
3315 			    const struct in6_addr *addr, u32 flags)
3316 {
3317 	struct ifa6_config cfg = {
3318 		.pfx = addr,
3319 		.plen = 64,
3320 		.ifa_flags = flags | IFA_F_PERMANENT,
3321 		.valid_lft = INFINITY_LIFE_TIME,
3322 		.preferred_lft = INFINITY_LIFE_TIME,
3323 		.scope = IFA_LINK,
3324 		.ifa_proto = IFAPROT_KERNEL_LL
3325 	};
3326 	struct inet6_ifaddr *ifp;
3327 
3328 #ifdef CONFIG_IPV6_OPTIMISTIC_DAD
3329 	if ((READ_ONCE(dev_net(idev->dev)->ipv6.devconf_all->optimistic_dad) ||
3330 	     READ_ONCE(idev->cnf.optimistic_dad)) &&
3331 	    !dev_net(idev->dev)->ipv6.devconf_all->forwarding)
3332 		cfg.ifa_flags |= IFA_F_OPTIMISTIC;
3333 #endif
3334 
3335 	ifp = ipv6_add_addr(idev, &cfg, true, NULL);
3336 	if (!IS_ERR(ifp)) {
3337 		addrconf_prefix_route(&ifp->addr, ifp->prefix_len, 0, idev->dev,
3338 				      0, 0, GFP_ATOMIC);
3339 		addrconf_dad_start(ifp);
3340 		in6_ifa_put(ifp);
3341 	}
3342 }
3343 EXPORT_SYMBOL_GPL(addrconf_add_linklocal);
3344 
ipv6_reserved_interfaceid(struct in6_addr address)3345 static bool ipv6_reserved_interfaceid(struct in6_addr address)
3346 {
3347 	if ((address.s6_addr32[2] | address.s6_addr32[3]) == 0)
3348 		return true;
3349 
3350 	if (address.s6_addr32[2] == htonl(0x02005eff) &&
3351 	    ((address.s6_addr32[3] & htonl(0xfe000000)) == htonl(0xfe000000)))
3352 		return true;
3353 
3354 	if (address.s6_addr32[2] == htonl(0xfdffffff) &&
3355 	    ((address.s6_addr32[3] & htonl(0xffffff80)) == htonl(0xffffff80)))
3356 		return true;
3357 
3358 	return false;
3359 }
3360 
ipv6_generate_stable_address(struct in6_addr * address,u8 dad_count,const struct inet6_dev * idev)3361 static int ipv6_generate_stable_address(struct in6_addr *address,
3362 					u8 dad_count,
3363 					const struct inet6_dev *idev)
3364 {
3365 	static DEFINE_SPINLOCK(lock);
3366 	static struct sha1_ctx sha_ctx;
3367 
3368 	static union {
3369 		u8 __data[SHA1_BLOCK_SIZE];
3370 		struct {
3371 			struct in6_addr secret;
3372 			__be32 prefix[2];
3373 			unsigned char hwaddr[MAX_ADDR_LEN];
3374 			u8 dad_count;
3375 		} __packed;
3376 	} data;
3377 
3378 	struct in6_addr secret;
3379 	struct in6_addr temp;
3380 	struct net *net = dev_net(idev->dev);
3381 
3382 	BUILD_BUG_ON(sizeof(data.__data) != sizeof(data));
3383 
3384 	if (idev->cnf.stable_secret.initialized)
3385 		secret = idev->cnf.stable_secret.secret;
3386 	else if (net->ipv6.devconf_dflt->stable_secret.initialized)
3387 		secret = net->ipv6.devconf_dflt->stable_secret.secret;
3388 	else
3389 		return -1;
3390 
3391 retry:
3392 	spin_lock_bh(&lock);
3393 
3394 	sha1_init(&sha_ctx);
3395 
3396 	memset(&data, 0, sizeof(data));
3397 	memcpy(data.hwaddr, idev->dev->perm_addr, idev->dev->addr_len);
3398 	data.prefix[0] = address->s6_addr32[0];
3399 	data.prefix[1] = address->s6_addr32[1];
3400 	data.secret = secret;
3401 	data.dad_count = dad_count;
3402 
3403 	sha1_update(&sha_ctx, data.__data, sizeof(data));
3404 
3405 	/*
3406 	 * Note that the SHA-1 finalization is omitted here, and the digest is
3407 	 * pulled directly from the internal SHA-1 state (making it incompatible
3408 	 * with standard SHA-1).  Unusual, but technically okay since the data
3409 	 * length is fixed and is a multiple of the SHA-1 block size.
3410 	 */
3411 	temp = *address;
3412 	temp.s6_addr32[2] = (__force __be32)sha_ctx.state.h[0];
3413 	temp.s6_addr32[3] = (__force __be32)sha_ctx.state.h[1];
3414 
3415 	spin_unlock_bh(&lock);
3416 
3417 	if (ipv6_reserved_interfaceid(temp)) {
3418 		dad_count++;
3419 		if (dad_count > dev_net(idev->dev)->ipv6.sysctl.idgen_retries)
3420 			return -1;
3421 		goto retry;
3422 	}
3423 
3424 	*address = temp;
3425 	return 0;
3426 }
3427 
ipv6_gen_mode_random_init(struct inet6_dev * idev)3428 static void ipv6_gen_mode_random_init(struct inet6_dev *idev)
3429 {
3430 	struct ipv6_stable_secret *s = &idev->cnf.stable_secret;
3431 
3432 	if (s->initialized)
3433 		return;
3434 	s = &idev->cnf.stable_secret;
3435 	get_random_bytes(&s->secret, sizeof(s->secret));
3436 	s->initialized = true;
3437 }
3438 
addrconf_addr_gen(struct inet6_dev * idev,bool prefix_route)3439 static void addrconf_addr_gen(struct inet6_dev *idev, bool prefix_route)
3440 {
3441 	struct in6_addr addr;
3442 
3443 	/* no link local addresses on L3 master devices */
3444 	if (netif_is_l3_master(idev->dev))
3445 		return;
3446 
3447 	/* no link local addresses on devices flagged as slaves */
3448 	if (idev->dev->priv_flags & IFF_NO_ADDRCONF)
3449 		return;
3450 
3451 	ipv6_addr_set(&addr, htonl(0xFE800000), 0, 0, 0);
3452 
3453 	switch (idev->cnf.addr_gen_mode) {
3454 	case IN6_ADDR_GEN_MODE_RANDOM:
3455 		ipv6_gen_mode_random_init(idev);
3456 		fallthrough;
3457 	case IN6_ADDR_GEN_MODE_STABLE_PRIVACY:
3458 		if (!ipv6_generate_stable_address(&addr, 0, idev))
3459 			addrconf_add_linklocal(idev, &addr,
3460 					       IFA_F_STABLE_PRIVACY);
3461 		else if (prefix_route)
3462 			addrconf_prefix_route(&addr, 64, 0, idev->dev,
3463 					      0, 0, GFP_KERNEL);
3464 		break;
3465 	case IN6_ADDR_GEN_MODE_EUI64:
3466 		/* addrconf_add_linklocal also adds a prefix_route and we
3467 		 * only need to care about prefix routes if ipv6_generate_eui64
3468 		 * couldn't generate one.
3469 		 */
3470 		if (ipv6_generate_eui64(addr.s6_addr + 8, idev->dev) == 0)
3471 			addrconf_add_linklocal(idev, &addr, 0);
3472 		else if (prefix_route)
3473 			addrconf_prefix_route(&addr, 64, 0, idev->dev,
3474 					      0, 0, GFP_KERNEL);
3475 		break;
3476 	case IN6_ADDR_GEN_MODE_NONE:
3477 	default:
3478 		/* will not add any link local address */
3479 		break;
3480 	}
3481 }
3482 
addrconf_dev_config(struct net_device * dev)3483 static void addrconf_dev_config(struct net_device *dev)
3484 {
3485 	struct inet6_dev *idev;
3486 
3487 	ASSERT_RTNL();
3488 
3489 	if ((dev->type != ARPHRD_ETHER) &&
3490 	    (dev->type != ARPHRD_FDDI) &&
3491 	    (dev->type != ARPHRD_ARCNET) &&
3492 	    (dev->type != ARPHRD_INFINIBAND) &&
3493 	    (dev->type != ARPHRD_IEEE1394) &&
3494 	    (dev->type != ARPHRD_TUNNEL6) &&
3495 	    (dev->type != ARPHRD_6LOWPAN) &&
3496 	    (dev->type != ARPHRD_IP6GRE) &&
3497 	    (dev->type != ARPHRD_TUNNEL) &&
3498 	    (dev->type != ARPHRD_NONE) &&
3499 	    (dev->type != ARPHRD_RAWIP)) {
3500 		/* Alas, we support only Ethernet autoconfiguration. */
3501 		idev = __in6_dev_get(dev);
3502 		if (!IS_ERR_OR_NULL(idev) && dev->flags & IFF_UP &&
3503 		    dev->flags & IFF_MULTICAST)
3504 			ipv6_mc_up(idev);
3505 		return;
3506 	}
3507 
3508 	idev = addrconf_add_dev(dev);
3509 	if (IS_ERR(idev))
3510 		return;
3511 
3512 	/* this device type has no EUI support */
3513 	if (dev->type == ARPHRD_NONE &&
3514 	    idev->cnf.addr_gen_mode == IN6_ADDR_GEN_MODE_EUI64)
3515 		WRITE_ONCE(idev->cnf.addr_gen_mode,
3516 			   IN6_ADDR_GEN_MODE_RANDOM);
3517 
3518 	addrconf_addr_gen(idev, false);
3519 }
3520 
3521 #if IS_ENABLED(CONFIG_IPV6_SIT)
addrconf_sit_config(struct net_device * dev)3522 static void addrconf_sit_config(struct net_device *dev)
3523 {
3524 	struct inet6_dev *idev;
3525 
3526 	ASSERT_RTNL();
3527 
3528 	/*
3529 	 * Configure the tunnel with one of our IPv4
3530 	 * addresses... we should configure all of
3531 	 * our v4 addrs in the tunnel
3532 	 */
3533 
3534 	idev = ipv6_find_idev(dev);
3535 	if (IS_ERR(idev)) {
3536 		pr_debug("%s: add_dev failed\n", __func__);
3537 		return;
3538 	}
3539 
3540 	if (dev->priv_flags & IFF_ISATAP) {
3541 		addrconf_addr_gen(idev, false);
3542 		return;
3543 	}
3544 
3545 	add_v4_addrs(idev);
3546 
3547 	if (dev->flags&IFF_POINTOPOINT)
3548 		addrconf_add_mroute(dev);
3549 }
3550 #endif
3551 
3552 #if IS_ENABLED(CONFIG_NET_IPGRE)
addrconf_gre_config(struct net_device * dev)3553 static void addrconf_gre_config(struct net_device *dev)
3554 {
3555 	struct inet6_dev *idev;
3556 
3557 	ASSERT_RTNL();
3558 
3559 	idev = addrconf_add_dev(dev);
3560 	if (IS_ERR(idev))
3561 		return;
3562 
3563 	/* Generate the IPv6 link-local address using addrconf_addr_gen(),
3564 	 * unless we have an IPv4 GRE device not bound to an IP address and
3565 	 * which is in EUI64 mode (as __ipv6_isatap_ifid() would fail in this
3566 	 * case). Such devices fall back to add_v4_addrs() instead.
3567 	 */
3568 	if (!(*(__be32 *)dev->dev_addr == 0 &&
3569 	      idev->cnf.addr_gen_mode == IN6_ADDR_GEN_MODE_EUI64)) {
3570 		addrconf_addr_gen(idev, true);
3571 		return;
3572 	}
3573 
3574 	add_v4_addrs(idev);
3575 }
3576 #endif
3577 
addrconf_init_auto_addrs(struct net_device * dev)3578 static void addrconf_init_auto_addrs(struct net_device *dev)
3579 {
3580 	switch (dev->type) {
3581 #if IS_ENABLED(CONFIG_IPV6_SIT)
3582 	case ARPHRD_SIT:
3583 		addrconf_sit_config(dev);
3584 		break;
3585 #endif
3586 #if IS_ENABLED(CONFIG_NET_IPGRE)
3587 	case ARPHRD_IPGRE:
3588 		addrconf_gre_config(dev);
3589 		break;
3590 #endif
3591 	case ARPHRD_LOOPBACK:
3592 		init_loopback(dev);
3593 		break;
3594 
3595 	default:
3596 		addrconf_dev_config(dev);
3597 		break;
3598 	}
3599 }
3600 
fixup_permanent_addr(struct net * net,struct inet6_dev * idev,struct inet6_ifaddr * ifp)3601 static int fixup_permanent_addr(struct net *net,
3602 				struct inet6_dev *idev,
3603 				struct inet6_ifaddr *ifp)
3604 {
3605 	/* !fib6_node means the host route was removed from the
3606 	 * FIB, for example, if 'lo' device is taken down. In that
3607 	 * case regenerate the host route.
3608 	 */
3609 	if (!ifp->rt || !ifp->rt->fib6_node) {
3610 		struct fib6_info *f6i, *prev;
3611 
3612 		f6i = addrconf_f6i_alloc(net, idev, &ifp->addr, false,
3613 					 GFP_KERNEL, NULL);
3614 		if (IS_ERR(f6i))
3615 			return PTR_ERR(f6i);
3616 
3617 		/* ifp->rt can be accessed outside of rtnl */
3618 		spin_lock_bh(&ifp->lock);
3619 		prev = ifp->rt;
3620 		ifp->rt = f6i;
3621 		spin_unlock_bh(&ifp->lock);
3622 
3623 		fib6_info_release(prev);
3624 	}
3625 
3626 	if (!(ifp->flags & IFA_F_NOPREFIXROUTE)) {
3627 		addrconf_prefix_route(&ifp->addr, ifp->prefix_len,
3628 				      ifp->rt_priority, idev->dev, 0, 0,
3629 				      GFP_KERNEL);
3630 	}
3631 
3632 	if (ifp->state == INET6_IFADDR_STATE_PREDAD)
3633 		addrconf_dad_start(ifp);
3634 
3635 	return 0;
3636 }
3637 
addrconf_permanent_addr(struct net * net,struct net_device * dev)3638 static void addrconf_permanent_addr(struct net *net, struct net_device *dev)
3639 {
3640 	struct inet6_ifaddr *ifp;
3641 	LIST_HEAD(tmp_addr_list);
3642 	struct inet6_dev *idev;
3643 
3644 	/* Mutual exclusion with other if_list_aux users. */
3645 	ASSERT_RTNL();
3646 
3647 	idev = __in6_dev_get(dev);
3648 	if (!idev)
3649 		return;
3650 
3651 	write_lock_bh(&idev->lock);
3652 	list_for_each_entry(ifp, &idev->addr_list, if_list) {
3653 		if (ifp->flags & IFA_F_PERMANENT)
3654 			list_add_tail(&ifp->if_list_aux, &tmp_addr_list);
3655 	}
3656 	write_unlock_bh(&idev->lock);
3657 
3658 	while (!list_empty(&tmp_addr_list)) {
3659 		ifp = list_first_entry(&tmp_addr_list,
3660 				       struct inet6_ifaddr, if_list_aux);
3661 		list_del(&ifp->if_list_aux);
3662 
3663 		if (fixup_permanent_addr(net, idev, ifp) < 0) {
3664 			net_info_ratelimited("%s: Failed to add prefix route for address %pI6c; dropping\n",
3665 					     idev->dev->name, &ifp->addr);
3666 			in6_ifa_hold(ifp);
3667 			ipv6_del_addr(ifp);
3668 		}
3669 	}
3670 }
3671 
addrconf_notify(struct notifier_block * this,unsigned long event,void * ptr)3672 static int addrconf_notify(struct notifier_block *this, unsigned long event,
3673 			   void *ptr)
3674 {
3675 	struct net_device *dev = netdev_notifier_info_to_dev(ptr);
3676 	struct netdev_notifier_change_info *change_info;
3677 	struct netdev_notifier_changeupper_info *info;
3678 	struct inet6_dev *idev = __in6_dev_get(dev);
3679 	struct net *net = dev_net(dev);
3680 	int run_pending = 0;
3681 	int err;
3682 
3683 	switch (event) {
3684 	case NETDEV_REGISTER:
3685 		if (!idev && dev->mtu >= IPV6_MIN_MTU) {
3686 			idev = ipv6_add_dev(dev);
3687 			if (IS_ERR(idev))
3688 				return notifier_from_errno(PTR_ERR(idev));
3689 		}
3690 		break;
3691 
3692 	case NETDEV_CHANGEMTU:
3693 		/* if MTU under IPV6_MIN_MTU stop IPv6 on this interface. */
3694 		if (dev->mtu < IPV6_MIN_MTU) {
3695 			addrconf_ifdown(dev, dev != net->loopback_dev);
3696 			break;
3697 		}
3698 
3699 		if (idev) {
3700 			rt6_mtu_change(dev, dev->mtu);
3701 			WRITE_ONCE(idev->cnf.mtu6, dev->mtu);
3702 			break;
3703 		}
3704 
3705 		/* allocate new idev */
3706 		idev = ipv6_add_dev(dev);
3707 		if (IS_ERR(idev))
3708 			break;
3709 
3710 		/* device is still not ready */
3711 		if (!(idev->if_flags & IF_READY))
3712 			break;
3713 
3714 		run_pending = 1;
3715 		fallthrough;
3716 	case NETDEV_UP:
3717 	case NETDEV_CHANGE:
3718 		if (idev && idev->cnf.disable_ipv6)
3719 			break;
3720 
3721 		if (dev->priv_flags & IFF_NO_ADDRCONF) {
3722 			if (event == NETDEV_UP && !IS_ERR_OR_NULL(idev) &&
3723 			    dev->flags & IFF_UP && dev->flags & IFF_MULTICAST)
3724 				ipv6_mc_up(idev);
3725 			break;
3726 		}
3727 
3728 		if (event == NETDEV_UP) {
3729 			/* restore routes for permanent addresses */
3730 			addrconf_permanent_addr(net, dev);
3731 
3732 			if (!addrconf_link_ready(dev)) {
3733 				/* device is not ready yet. */
3734 				pr_debug("ADDRCONF(NETDEV_UP): %s: link is not ready\n",
3735 					 dev->name);
3736 				break;
3737 			}
3738 
3739 			if (!idev && dev->mtu >= IPV6_MIN_MTU)
3740 				idev = ipv6_add_dev(dev);
3741 
3742 			if (!IS_ERR_OR_NULL(idev)) {
3743 				idev->if_flags |= IF_READY;
3744 				run_pending = 1;
3745 			}
3746 		} else if (event == NETDEV_CHANGE) {
3747 			if (!addrconf_link_ready(dev)) {
3748 				/* device is still not ready. */
3749 				rt6_sync_down_dev(dev, event);
3750 				break;
3751 			}
3752 
3753 			if (!IS_ERR_OR_NULL(idev)) {
3754 				if (idev->if_flags & IF_READY) {
3755 					/* device is already configured -
3756 					 * but resend MLD reports, we might
3757 					 * have roamed and need to update
3758 					 * multicast snooping switches
3759 					 */
3760 					ipv6_mc_up(idev);
3761 					change_info = ptr;
3762 					if (change_info->flags_changed & IFF_NOARP)
3763 						addrconf_dad_run(idev, true);
3764 					rt6_sync_up(dev, RTNH_F_LINKDOWN);
3765 					break;
3766 				}
3767 				idev->if_flags |= IF_READY;
3768 			}
3769 
3770 			pr_debug("ADDRCONF(NETDEV_CHANGE): %s: link becomes ready\n",
3771 				 dev->name);
3772 
3773 			run_pending = 1;
3774 		}
3775 
3776 		addrconf_init_auto_addrs(dev);
3777 
3778 		if (!IS_ERR_OR_NULL(idev)) {
3779 			if (run_pending)
3780 				addrconf_dad_run(idev, false);
3781 
3782 			/* Device has an address by now */
3783 			rt6_sync_up(dev, RTNH_F_DEAD);
3784 
3785 			/*
3786 			 * If the MTU changed during the interface down,
3787 			 * when the interface up, the changed MTU must be
3788 			 * reflected in the idev as well as routers.
3789 			 */
3790 			if (idev->cnf.mtu6 != dev->mtu &&
3791 			    dev->mtu >= IPV6_MIN_MTU) {
3792 				rt6_mtu_change(dev, dev->mtu);
3793 				WRITE_ONCE(idev->cnf.mtu6, dev->mtu);
3794 			}
3795 			WRITE_ONCE(idev->tstamp, jiffies);
3796 			inet6_ifinfo_notify(RTM_NEWLINK, idev);
3797 
3798 			/*
3799 			 * If the changed mtu during down is lower than
3800 			 * IPV6_MIN_MTU stop IPv6 on this interface.
3801 			 */
3802 			if (dev->mtu < IPV6_MIN_MTU)
3803 				addrconf_ifdown(dev, dev != net->loopback_dev);
3804 		}
3805 		break;
3806 
3807 	case NETDEV_DOWN:
3808 	case NETDEV_UNREGISTER:
3809 		/*
3810 		 *	Remove all addresses from this interface.
3811 		 */
3812 		addrconf_ifdown(dev, event != NETDEV_DOWN);
3813 		break;
3814 
3815 	case NETDEV_CHANGENAME:
3816 		if (idev) {
3817 			snmp6_unregister_dev(idev);
3818 			addrconf_sysctl_unregister(idev);
3819 			err = addrconf_sysctl_register(idev);
3820 			if (err)
3821 				return notifier_from_errno(err);
3822 			err = snmp6_register_dev(idev);
3823 			if (err) {
3824 				addrconf_sysctl_unregister(idev);
3825 				return notifier_from_errno(err);
3826 			}
3827 		}
3828 		break;
3829 
3830 	case NETDEV_PRE_TYPE_CHANGE:
3831 	case NETDEV_POST_TYPE_CHANGE:
3832 		if (idev)
3833 			addrconf_type_change(dev, event);
3834 		break;
3835 
3836 	case NETDEV_CHANGEUPPER:
3837 		info = ptr;
3838 
3839 		/* flush all routes if dev is linked to or unlinked from
3840 		 * an L3 master device (e.g., VRF)
3841 		 */
3842 		if (info->upper_dev && netif_is_l3_master(info->upper_dev))
3843 			addrconf_ifdown(dev, false);
3844 	}
3845 
3846 	return NOTIFY_OK;
3847 }
3848 
3849 /*
3850  *	addrconf module should be notified of a device going up
3851  */
3852 static struct notifier_block ipv6_dev_notf = {
3853 	.notifier_call = addrconf_notify,
3854 	.priority = ADDRCONF_NOTIFY_PRIORITY,
3855 };
3856 
addrconf_type_change(struct net_device * dev,unsigned long event)3857 static void addrconf_type_change(struct net_device *dev, unsigned long event)
3858 {
3859 	struct inet6_dev *idev;
3860 	ASSERT_RTNL();
3861 
3862 	idev = __in6_dev_get(dev);
3863 
3864 	if (event == NETDEV_POST_TYPE_CHANGE)
3865 		ipv6_mc_remap(idev);
3866 	else if (event == NETDEV_PRE_TYPE_CHANGE)
3867 		ipv6_mc_unmap(idev);
3868 }
3869 
addr_is_local(const struct in6_addr * addr)3870 static bool addr_is_local(const struct in6_addr *addr)
3871 {
3872 	return ipv6_addr_type(addr) &
3873 		(IPV6_ADDR_LINKLOCAL | IPV6_ADDR_LOOPBACK);
3874 }
3875 
addrconf_ifdown(struct net_device * dev,bool unregister)3876 static int addrconf_ifdown(struct net_device *dev, bool unregister)
3877 {
3878 	unsigned long event = unregister ? NETDEV_UNREGISTER : NETDEV_DOWN;
3879 	struct net *net = dev_net(dev);
3880 	struct inet6_dev *idev;
3881 	struct inet6_ifaddr *ifa;
3882 	LIST_HEAD(tmp_addr_list);
3883 	bool keep_addr = false;
3884 	bool was_ready;
3885 	int state, i;
3886 
3887 	ASSERT_RTNL();
3888 
3889 	rt6_disable_ip(dev, event);
3890 
3891 	idev = __in6_dev_get(dev);
3892 	if (!idev)
3893 		return -ENODEV;
3894 
3895 	/*
3896 	 * Step 1: remove reference to ipv6 device from parent device.
3897 	 *	   Do not dev_put!
3898 	 */
3899 	if (unregister) {
3900 		WRITE_ONCE(idev->dead, 1);
3901 
3902 		/* protected by rtnl_lock */
3903 		RCU_INIT_POINTER(dev->ip6_ptr, NULL);
3904 
3905 		/* Step 1.5: remove snmp6 entry */
3906 		snmp6_unregister_dev(idev);
3907 
3908 	}
3909 
3910 	/* combine the user config with event to determine if permanent
3911 	 * addresses are to be removed from address hash table
3912 	 */
3913 	if (!unregister && !idev->cnf.disable_ipv6) {
3914 		/* aggregate the system setting and interface setting */
3915 		int _keep_addr = READ_ONCE(net->ipv6.devconf_all->keep_addr_on_down);
3916 
3917 		if (!_keep_addr)
3918 			_keep_addr = READ_ONCE(idev->cnf.keep_addr_on_down);
3919 
3920 		keep_addr = (_keep_addr > 0);
3921 	}
3922 
3923 	/* Step 2: clear hash table */
3924 	for (i = 0; i < IN6_ADDR_HSIZE; i++) {
3925 		struct hlist_head *h = &net->ipv6.inet6_addr_lst[i];
3926 
3927 		spin_lock_bh(&net->ipv6.addrconf_hash_lock);
3928 restart:
3929 		hlist_for_each_entry_rcu(ifa, h, addr_lst) {
3930 			if (ifa->idev == idev) {
3931 				addrconf_del_dad_work(ifa);
3932 				/* combined flag + permanent flag decide if
3933 				 * address is retained on a down event
3934 				 */
3935 				if (!keep_addr ||
3936 				    !(ifa->flags & IFA_F_PERMANENT) ||
3937 				    addr_is_local(&ifa->addr)) {
3938 					hlist_del_init_rcu(&ifa->addr_lst);
3939 					goto restart;
3940 				}
3941 			}
3942 		}
3943 		spin_unlock_bh(&net->ipv6.addrconf_hash_lock);
3944 	}
3945 
3946 	write_lock_bh(&idev->lock);
3947 
3948 	addrconf_del_rs_timer(idev);
3949 
3950 	/* Step 2: clear flags for stateless addrconf, repeated down
3951 	 *         detection
3952 	 */
3953 	was_ready = idev->if_flags & IF_READY;
3954 	if (!unregister)
3955 		idev->if_flags &= ~(IF_RS_SENT|IF_RA_RCVD|IF_READY);
3956 
3957 	/* Step 3: clear tempaddr list */
3958 	while (!list_empty(&idev->tempaddr_list)) {
3959 		ifa = list_first_entry(&idev->tempaddr_list,
3960 				       struct inet6_ifaddr, tmp_list);
3961 		list_del(&ifa->tmp_list);
3962 		write_unlock_bh(&idev->lock);
3963 		spin_lock_bh(&ifa->lock);
3964 
3965 		if (ifa->ifpub) {
3966 			in6_ifa_put(ifa->ifpub);
3967 			ifa->ifpub = NULL;
3968 		}
3969 		spin_unlock_bh(&ifa->lock);
3970 		in6_ifa_put(ifa);
3971 		write_lock_bh(&idev->lock);
3972 	}
3973 
3974 	list_for_each_entry(ifa, &idev->addr_list, if_list)
3975 		list_add_tail(&ifa->if_list_aux, &tmp_addr_list);
3976 	write_unlock_bh(&idev->lock);
3977 
3978 	while (!list_empty(&tmp_addr_list)) {
3979 		struct fib6_info *rt = NULL;
3980 		bool keep;
3981 
3982 		ifa = list_first_entry(&tmp_addr_list,
3983 				       struct inet6_ifaddr, if_list_aux);
3984 		list_del(&ifa->if_list_aux);
3985 
3986 		addrconf_del_dad_work(ifa);
3987 
3988 		keep = keep_addr && (ifa->flags & IFA_F_PERMANENT) &&
3989 			!addr_is_local(&ifa->addr);
3990 
3991 		spin_lock_bh(&ifa->lock);
3992 
3993 		if (keep) {
3994 			/* set state to skip the notifier below */
3995 			state = INET6_IFADDR_STATE_DEAD;
3996 			ifa->state = INET6_IFADDR_STATE_PREDAD;
3997 			if (!(ifa->flags & IFA_F_NODAD))
3998 				ifa->flags |= IFA_F_TENTATIVE;
3999 
4000 			rt = ifa->rt;
4001 			ifa->rt = NULL;
4002 		} else {
4003 			state = ifa->state;
4004 			ifa->state = INET6_IFADDR_STATE_DEAD;
4005 		}
4006 
4007 		spin_unlock_bh(&ifa->lock);
4008 
4009 		if (rt)
4010 			ip6_del_rt(net, rt, false);
4011 
4012 		if (state != INET6_IFADDR_STATE_DEAD) {
4013 			__ipv6_ifa_notify(RTM_DELADDR, ifa);
4014 			inet6addr_notifier_call_chain(NETDEV_DOWN, ifa);
4015 		} else {
4016 			if (idev->cnf.forwarding)
4017 				addrconf_leave_anycast(ifa);
4018 			addrconf_leave_solict(ifa->idev, &ifa->addr);
4019 		}
4020 
4021 		if (!keep) {
4022 			write_lock_bh(&idev->lock);
4023 			list_del_rcu(&ifa->if_list);
4024 			write_unlock_bh(&idev->lock);
4025 			in6_ifa_put(ifa);
4026 		}
4027 	}
4028 
4029 	/* Step 5: Discard anycast and multicast list */
4030 	if (unregister) {
4031 		ipv6_ac_destroy_dev(idev);
4032 		ipv6_mc_destroy_dev(idev);
4033 	} else if (was_ready) {
4034 		ipv6_mc_down(idev);
4035 	}
4036 
4037 	WRITE_ONCE(idev->tstamp, jiffies);
4038 	idev->ra_mtu = 0;
4039 
4040 	/* Last: Shot the device (if unregistered) */
4041 	if (unregister) {
4042 		addrconf_sysctl_unregister(idev);
4043 		neigh_parms_release(&nd_tbl, idev->nd_parms);
4044 		neigh_ifdown(&nd_tbl, dev);
4045 		in6_dev_put(idev);
4046 	}
4047 	return 0;
4048 }
4049 
addrconf_rs_timer(struct timer_list * t)4050 static void addrconf_rs_timer(struct timer_list *t)
4051 {
4052 	struct inet6_dev *idev = timer_container_of(idev, t, rs_timer);
4053 	struct net_device *dev = idev->dev;
4054 	struct in6_addr lladdr;
4055 	int rtr_solicits;
4056 
4057 	write_lock(&idev->lock);
4058 	if (idev->dead || !(idev->if_flags & IF_READY))
4059 		goto out;
4060 
4061 	if (!ipv6_accept_ra(idev))
4062 		goto out;
4063 
4064 	/* Announcement received after solicitation was sent */
4065 	if (idev->if_flags & IF_RA_RCVD)
4066 		goto out;
4067 
4068 	rtr_solicits = READ_ONCE(idev->cnf.rtr_solicits);
4069 
4070 	if (idev->rs_probes++ < rtr_solicits || rtr_solicits < 0) {
4071 		write_unlock(&idev->lock);
4072 		if (!ipv6_get_lladdr(dev, &lladdr, IFA_F_TENTATIVE))
4073 			ndisc_send_rs(dev, &lladdr,
4074 				      &in6addr_linklocal_allrouters);
4075 		else
4076 			goto put;
4077 
4078 		write_lock(&idev->lock);
4079 		idev->rs_interval = rfc3315_s14_backoff_update(
4080 				idev->rs_interval,
4081 				READ_ONCE(idev->cnf.rtr_solicit_max_interval));
4082 		/* The wait after the last probe can be shorter */
4083 		addrconf_mod_rs_timer(idev, (idev->rs_probes ==
4084 					     READ_ONCE(idev->cnf.rtr_solicits)) ?
4085 				      READ_ONCE(idev->cnf.rtr_solicit_delay) :
4086 				      idev->rs_interval);
4087 	} else {
4088 		/*
4089 		 * Note: we do not support deprecated "all on-link"
4090 		 * assumption any longer.
4091 		 */
4092 		pr_debug("%s: no IPv6 routers present\n", idev->dev->name);
4093 	}
4094 
4095 out:
4096 	write_unlock(&idev->lock);
4097 put:
4098 	in6_dev_put(idev);
4099 }
4100 
4101 /*
4102  *	Duplicate Address Detection
4103  */
addrconf_dad_kick(struct inet6_ifaddr * ifp)4104 static void addrconf_dad_kick(struct inet6_ifaddr *ifp)
4105 {
4106 	struct inet6_dev *idev = ifp->idev;
4107 	unsigned long rand_num;
4108 	u64 nonce;
4109 
4110 	if (ifp->flags & IFA_F_OPTIMISTIC)
4111 		rand_num = 0;
4112 	else
4113 		rand_num = get_random_u32_below(
4114 				READ_ONCE(idev->cnf.rtr_solicit_delay) ? : 1);
4115 
4116 	nonce = 0;
4117 	if (READ_ONCE(idev->cnf.enhanced_dad) ||
4118 	    READ_ONCE(dev_net(idev->dev)->ipv6.devconf_all->enhanced_dad)) {
4119 		do
4120 			get_random_bytes(&nonce, 6);
4121 		while (nonce == 0);
4122 	}
4123 	ifp->dad_nonce = nonce;
4124 	ifp->dad_probes = READ_ONCE(idev->cnf.dad_transmits);
4125 	addrconf_mod_dad_work(ifp, rand_num);
4126 }
4127 
addrconf_dad_begin(struct inet6_ifaddr * ifp)4128 static void addrconf_dad_begin(struct inet6_ifaddr *ifp)
4129 {
4130 	struct inet6_dev *idev = ifp->idev;
4131 	struct net_device *dev = idev->dev;
4132 	bool bump_id, notify = false;
4133 	struct net *net;
4134 
4135 	addrconf_join_solict(dev, &ifp->addr);
4136 
4137 	read_lock_bh(&idev->lock);
4138 	spin_lock(&ifp->lock);
4139 	if (ifp->state == INET6_IFADDR_STATE_DEAD)
4140 		goto out;
4141 
4142 	net = dev_net(dev);
4143 	if (dev->flags&(IFF_NOARP|IFF_LOOPBACK) ||
4144 	    (READ_ONCE(net->ipv6.devconf_all->accept_dad) < 1 &&
4145 	     READ_ONCE(idev->cnf.accept_dad) < 1) ||
4146 	    !(ifp->flags&IFA_F_TENTATIVE) ||
4147 	    ifp->flags & IFA_F_NODAD) {
4148 		bool send_na = false;
4149 
4150 		if (ifp->flags & IFA_F_TENTATIVE &&
4151 		    !(ifp->flags & IFA_F_OPTIMISTIC))
4152 			send_na = true;
4153 		bump_id = ifp->flags & IFA_F_TENTATIVE;
4154 		ifp->flags &= ~(IFA_F_TENTATIVE|IFA_F_OPTIMISTIC|IFA_F_DADFAILED);
4155 		spin_unlock(&ifp->lock);
4156 		read_unlock_bh(&idev->lock);
4157 
4158 		addrconf_dad_completed(ifp, bump_id, send_na);
4159 		return;
4160 	}
4161 
4162 	if (!(idev->if_flags & IF_READY)) {
4163 		spin_unlock(&ifp->lock);
4164 		read_unlock_bh(&idev->lock);
4165 		/*
4166 		 * If the device is not ready:
4167 		 * - keep it tentative if it is a permanent address.
4168 		 * - otherwise, kill it.
4169 		 */
4170 		in6_ifa_hold(ifp);
4171 		addrconf_dad_stop(ifp, 0);
4172 		return;
4173 	}
4174 
4175 	/*
4176 	 * Optimistic nodes can start receiving
4177 	 * Frames right away
4178 	 */
4179 	if (ifp->flags & IFA_F_OPTIMISTIC) {
4180 		ip6_ins_rt(net, ifp->rt);
4181 		if (ipv6_use_optimistic_addr(net, idev)) {
4182 			/* Because optimistic nodes can use this address,
4183 			 * notify listeners. If DAD fails, RTM_DELADDR is sent.
4184 			 */
4185 			notify = true;
4186 		}
4187 	}
4188 
4189 	addrconf_dad_kick(ifp);
4190 out:
4191 	spin_unlock(&ifp->lock);
4192 	read_unlock_bh(&idev->lock);
4193 	if (notify)
4194 		ipv6_ifa_notify(RTM_NEWADDR, ifp);
4195 }
4196 
addrconf_dad_start(struct inet6_ifaddr * ifp)4197 static void addrconf_dad_start(struct inet6_ifaddr *ifp)
4198 {
4199 	bool begin_dad = false;
4200 
4201 	spin_lock_bh(&ifp->lock);
4202 	if (ifp->state != INET6_IFADDR_STATE_DEAD) {
4203 		ifp->state = INET6_IFADDR_STATE_PREDAD;
4204 		begin_dad = true;
4205 	}
4206 	spin_unlock_bh(&ifp->lock);
4207 
4208 	if (begin_dad)
4209 		addrconf_mod_dad_work(ifp, 0);
4210 }
4211 
addrconf_dad_work(struct work_struct * w)4212 static void addrconf_dad_work(struct work_struct *w)
4213 {
4214 	struct inet6_ifaddr *ifp = container_of(to_delayed_work(w),
4215 						struct inet6_ifaddr,
4216 						dad_work);
4217 	struct inet6_dev *idev = ifp->idev;
4218 	bool bump_id, disable_ipv6 = false;
4219 	struct in6_addr mcaddr;
4220 	struct net *net;
4221 
4222 	enum {
4223 		DAD_PROCESS,
4224 		DAD_BEGIN,
4225 		DAD_ABORT,
4226 	} action = DAD_PROCESS;
4227 
4228 	net = dev_net(idev->dev);
4229 
4230 	rtnl_net_lock(net);
4231 
4232 	spin_lock_bh(&ifp->lock);
4233 	if (ifp->state == INET6_IFADDR_STATE_PREDAD) {
4234 		action = DAD_BEGIN;
4235 		ifp->state = INET6_IFADDR_STATE_DAD;
4236 	} else if (ifp->state == INET6_IFADDR_STATE_ERRDAD) {
4237 		action = DAD_ABORT;
4238 		ifp->state = INET6_IFADDR_STATE_POSTDAD;
4239 
4240 		if ((READ_ONCE(net->ipv6.devconf_all->accept_dad) > 1 ||
4241 		     READ_ONCE(idev->cnf.accept_dad) > 1) &&
4242 		    !idev->cnf.disable_ipv6 &&
4243 		    !(ifp->flags & IFA_F_STABLE_PRIVACY)) {
4244 			struct in6_addr addr;
4245 
4246 			addr.s6_addr32[0] = htonl(0xfe800000);
4247 			addr.s6_addr32[1] = 0;
4248 
4249 			if (!ipv6_generate_eui64(addr.s6_addr + 8, idev->dev) &&
4250 			    ipv6_addr_equal(&ifp->addr, &addr)) {
4251 				/* DAD failed for link-local based on MAC */
4252 				WRITE_ONCE(idev->cnf.disable_ipv6, 1);
4253 
4254 				pr_info("%s: IPv6 being disabled!\n",
4255 					ifp->idev->dev->name);
4256 				disable_ipv6 = true;
4257 			}
4258 		}
4259 	}
4260 	spin_unlock_bh(&ifp->lock);
4261 
4262 	if (action == DAD_BEGIN) {
4263 		addrconf_dad_begin(ifp);
4264 		goto out;
4265 	} else if (action == DAD_ABORT) {
4266 		in6_ifa_hold(ifp);
4267 		addrconf_dad_stop(ifp, 1);
4268 		if (disable_ipv6)
4269 			addrconf_ifdown(idev->dev, false);
4270 		goto out;
4271 	}
4272 
4273 	if (!ifp->dad_probes && addrconf_dad_end(ifp))
4274 		goto out;
4275 
4276 	write_lock_bh(&idev->lock);
4277 	if (idev->dead || !(idev->if_flags & IF_READY)) {
4278 		write_unlock_bh(&idev->lock);
4279 		goto out;
4280 	}
4281 
4282 	spin_lock(&ifp->lock);
4283 	if (ifp->state == INET6_IFADDR_STATE_DEAD) {
4284 		spin_unlock(&ifp->lock);
4285 		write_unlock_bh(&idev->lock);
4286 		goto out;
4287 	}
4288 
4289 	if (ifp->dad_probes == 0) {
4290 		bool send_na = false;
4291 
4292 		/*
4293 		 * DAD was successful
4294 		 */
4295 
4296 		if (ifp->flags & IFA_F_TENTATIVE &&
4297 		    !(ifp->flags & IFA_F_OPTIMISTIC))
4298 			send_na = true;
4299 		bump_id = ifp->flags & IFA_F_TENTATIVE;
4300 		ifp->flags &= ~(IFA_F_TENTATIVE|IFA_F_OPTIMISTIC|IFA_F_DADFAILED);
4301 		spin_unlock(&ifp->lock);
4302 		write_unlock_bh(&idev->lock);
4303 
4304 		addrconf_dad_completed(ifp, bump_id, send_na);
4305 
4306 		goto out;
4307 	}
4308 
4309 	ifp->dad_probes--;
4310 	addrconf_mod_dad_work(ifp,
4311 			      max(NEIGH_VAR(ifp->idev->nd_parms, RETRANS_TIME),
4312 				  HZ/100));
4313 	spin_unlock(&ifp->lock);
4314 	write_unlock_bh(&idev->lock);
4315 
4316 	/* send a neighbour solicitation for our addr */
4317 	addrconf_addr_solict_mult(&ifp->addr, &mcaddr);
4318 	ndisc_send_ns(ifp->idev->dev, &ifp->addr, &mcaddr, &in6addr_any,
4319 		      ifp->dad_nonce);
4320 out:
4321 	in6_ifa_put(ifp);
4322 	rtnl_net_unlock(net);
4323 }
4324 
4325 /* ifp->idev must be at least read locked */
ipv6_lonely_lladdr(struct inet6_ifaddr * ifp)4326 static bool ipv6_lonely_lladdr(struct inet6_ifaddr *ifp)
4327 {
4328 	struct inet6_ifaddr *ifpiter;
4329 	struct inet6_dev *idev = ifp->idev;
4330 
4331 	list_for_each_entry_reverse(ifpiter, &idev->addr_list, if_list) {
4332 		if (ifpiter->scope > IFA_LINK)
4333 			break;
4334 		if (ifp != ifpiter && ifpiter->scope == IFA_LINK &&
4335 		    (ifpiter->flags & (IFA_F_PERMANENT|IFA_F_TENTATIVE|
4336 				       IFA_F_OPTIMISTIC|IFA_F_DADFAILED)) ==
4337 		    IFA_F_PERMANENT)
4338 			return false;
4339 	}
4340 	return true;
4341 }
4342 
addrconf_dad_completed(struct inet6_ifaddr * ifp,bool bump_id,bool send_na)4343 static void addrconf_dad_completed(struct inet6_ifaddr *ifp, bool bump_id,
4344 				   bool send_na)
4345 {
4346 	struct net_device *dev = ifp->idev->dev;
4347 	struct in6_addr lladdr;
4348 	bool send_rs, send_mld;
4349 
4350 	addrconf_del_dad_work(ifp);
4351 
4352 	/*
4353 	 *	Configure the address for reception. Now it is valid.
4354 	 */
4355 
4356 	ipv6_ifa_notify(RTM_NEWADDR, ifp);
4357 
4358 	/* If added prefix is link local and we are prepared to process
4359 	   router advertisements, start sending router solicitations.
4360 	 */
4361 
4362 	read_lock_bh(&ifp->idev->lock);
4363 	send_mld = ifp->scope == IFA_LINK && ipv6_lonely_lladdr(ifp);
4364 	send_rs = send_mld &&
4365 		  ipv6_accept_ra(ifp->idev) &&
4366 		  READ_ONCE(ifp->idev->cnf.rtr_solicits) != 0 &&
4367 		  (dev->flags & IFF_LOOPBACK) == 0 &&
4368 		  (dev->type != ARPHRD_TUNNEL) &&
4369 		  !netif_is_team_port(dev);
4370 	read_unlock_bh(&ifp->idev->lock);
4371 
4372 	/* While dad is in progress mld report's source address is in6_addrany.
4373 	 * Resend with proper ll now.
4374 	 */
4375 	if (send_mld)
4376 		ipv6_mc_dad_complete(ifp->idev);
4377 
4378 	/* send unsolicited NA if enabled */
4379 	if (send_na &&
4380 	    (READ_ONCE(ifp->idev->cnf.ndisc_notify) ||
4381 	     READ_ONCE(dev_net(dev)->ipv6.devconf_all->ndisc_notify))) {
4382 		ndisc_send_na(dev, &in6addr_linklocal_allnodes, &ifp->addr,
4383 			      /*router=*/ !!ifp->idev->cnf.forwarding,
4384 			      /*solicited=*/ false, /*override=*/ true,
4385 			      /*inc_opt=*/ true);
4386 	}
4387 
4388 	if (send_rs) {
4389 		/*
4390 		 *	If a host as already performed a random delay
4391 		 *	[...] as part of DAD [...] there is no need
4392 		 *	to delay again before sending the first RS
4393 		 */
4394 		if (ipv6_get_lladdr(dev, &lladdr, IFA_F_TENTATIVE))
4395 			return;
4396 		ndisc_send_rs(dev, &lladdr, &in6addr_linklocal_allrouters);
4397 
4398 		write_lock_bh(&ifp->idev->lock);
4399 		spin_lock(&ifp->lock);
4400 		ifp->idev->rs_interval = rfc3315_s14_backoff_init(
4401 			READ_ONCE(ifp->idev->cnf.rtr_solicit_interval));
4402 		ifp->idev->rs_probes = 1;
4403 		ifp->idev->if_flags |= IF_RS_SENT;
4404 		addrconf_mod_rs_timer(ifp->idev, ifp->idev->rs_interval);
4405 		spin_unlock(&ifp->lock);
4406 		write_unlock_bh(&ifp->idev->lock);
4407 	}
4408 
4409 	if (bump_id)
4410 		rt_genid_bump_ipv6(dev_net(dev));
4411 
4412 	/* Make sure that a new temporary address will be created
4413 	 * before this temporary address becomes deprecated.
4414 	 */
4415 	if (ifp->flags & IFA_F_TEMPORARY)
4416 		addrconf_verify_rtnl(dev_net(dev));
4417 }
4418 
addrconf_dad_run(struct inet6_dev * idev,bool restart)4419 static void addrconf_dad_run(struct inet6_dev *idev, bool restart)
4420 {
4421 	struct inet6_ifaddr *ifp;
4422 
4423 	read_lock_bh(&idev->lock);
4424 	list_for_each_entry(ifp, &idev->addr_list, if_list) {
4425 		spin_lock(&ifp->lock);
4426 		if ((ifp->flags & IFA_F_TENTATIVE &&
4427 		     ifp->state == INET6_IFADDR_STATE_DAD) || restart) {
4428 			if (restart)
4429 				ifp->state = INET6_IFADDR_STATE_PREDAD;
4430 			addrconf_dad_kick(ifp);
4431 		}
4432 		spin_unlock(&ifp->lock);
4433 	}
4434 	read_unlock_bh(&idev->lock);
4435 }
4436 
4437 #ifdef CONFIG_PROC_FS
4438 struct if6_iter_state {
4439 	struct seq_net_private p;
4440 	int bucket;
4441 	int offset;
4442 };
4443 
if6_get_first(struct seq_file * seq,loff_t pos)4444 static struct inet6_ifaddr *if6_get_first(struct seq_file *seq, loff_t pos)
4445 {
4446 	struct if6_iter_state *state = seq->private;
4447 	struct net *net = seq_file_net(seq);
4448 	struct inet6_ifaddr *ifa = NULL;
4449 	int p = 0;
4450 
4451 	/* initial bucket if pos is 0 */
4452 	if (pos == 0) {
4453 		state->bucket = 0;
4454 		state->offset = 0;
4455 	}
4456 
4457 	for (; state->bucket < IN6_ADDR_HSIZE; ++state->bucket) {
4458 		hlist_for_each_entry_rcu(ifa, &net->ipv6.inet6_addr_lst[state->bucket],
4459 					 addr_lst) {
4460 			/* sync with offset */
4461 			if (p < state->offset) {
4462 				p++;
4463 				continue;
4464 			}
4465 			return ifa;
4466 		}
4467 
4468 		/* prepare for next bucket */
4469 		state->offset = 0;
4470 		p = 0;
4471 	}
4472 	return NULL;
4473 }
4474 
if6_get_next(struct seq_file * seq,struct inet6_ifaddr * ifa)4475 static struct inet6_ifaddr *if6_get_next(struct seq_file *seq,
4476 					 struct inet6_ifaddr *ifa)
4477 {
4478 	struct if6_iter_state *state = seq->private;
4479 	struct net *net = seq_file_net(seq);
4480 
4481 	hlist_for_each_entry_continue_rcu(ifa, addr_lst) {
4482 		state->offset++;
4483 		return ifa;
4484 	}
4485 
4486 	state->offset = 0;
4487 	while (++state->bucket < IN6_ADDR_HSIZE) {
4488 		hlist_for_each_entry_rcu(ifa,
4489 				     &net->ipv6.inet6_addr_lst[state->bucket], addr_lst) {
4490 			return ifa;
4491 		}
4492 	}
4493 
4494 	return NULL;
4495 }
4496 
if6_seq_start(struct seq_file * seq,loff_t * pos)4497 static void *if6_seq_start(struct seq_file *seq, loff_t *pos)
4498 	__acquires(rcu)
4499 {
4500 	rcu_read_lock();
4501 	return if6_get_first(seq, *pos);
4502 }
4503 
if6_seq_next(struct seq_file * seq,void * v,loff_t * pos)4504 static void *if6_seq_next(struct seq_file *seq, void *v, loff_t *pos)
4505 {
4506 	struct inet6_ifaddr *ifa;
4507 
4508 	ifa = if6_get_next(seq, v);
4509 	++*pos;
4510 	return ifa;
4511 }
4512 
if6_seq_stop(struct seq_file * seq,void * v)4513 static void if6_seq_stop(struct seq_file *seq, void *v)
4514 	__releases(rcu)
4515 {
4516 	rcu_read_unlock();
4517 }
4518 
if6_seq_show(struct seq_file * seq,void * v)4519 static int if6_seq_show(struct seq_file *seq, void *v)
4520 {
4521 	struct inet6_ifaddr *ifp = (struct inet6_ifaddr *)v;
4522 	seq_printf(seq, "%pi6 %02x %02x %02x %02x %8s\n",
4523 		   &ifp->addr,
4524 		   ifp->idev->dev->ifindex,
4525 		   ifp->prefix_len,
4526 		   ifp->scope,
4527 		   (u8) ifp->flags,
4528 		   ifp->idev->dev->name);
4529 	return 0;
4530 }
4531 
4532 static const struct seq_operations if6_seq_ops = {
4533 	.start	= if6_seq_start,
4534 	.next	= if6_seq_next,
4535 	.show	= if6_seq_show,
4536 	.stop	= if6_seq_stop,
4537 };
4538 
if6_proc_net_init(struct net * net)4539 static int __net_init if6_proc_net_init(struct net *net)
4540 {
4541 	if (!proc_create_net("if_inet6", 0444, net->proc_net, &if6_seq_ops,
4542 			sizeof(struct if6_iter_state)))
4543 		return -ENOMEM;
4544 	return 0;
4545 }
4546 
if6_proc_net_exit(struct net * net)4547 static void __net_exit if6_proc_net_exit(struct net *net)
4548 {
4549 	remove_proc_entry("if_inet6", net->proc_net);
4550 }
4551 
4552 static struct pernet_operations if6_proc_net_ops = {
4553 	.init = if6_proc_net_init,
4554 	.exit = if6_proc_net_exit,
4555 };
4556 
if6_proc_init(void)4557 int __init if6_proc_init(void)
4558 {
4559 	return register_pernet_subsys(&if6_proc_net_ops);
4560 }
4561 
if6_proc_exit(void)4562 void if6_proc_exit(void)
4563 {
4564 	unregister_pernet_subsys(&if6_proc_net_ops);
4565 }
4566 #endif	/* CONFIG_PROC_FS */
4567 
4568 #if IS_ENABLED(CONFIG_IPV6_MIP6)
4569 /* Check if address is a home address configured on any interface. */
ipv6_chk_home_addr(struct net * net,const struct in6_addr * addr)4570 int ipv6_chk_home_addr(struct net *net, const struct in6_addr *addr)
4571 {
4572 	unsigned int hash = inet6_addr_hash(net, addr);
4573 	struct inet6_ifaddr *ifp = NULL;
4574 	int ret = 0;
4575 
4576 	rcu_read_lock();
4577 	hlist_for_each_entry_rcu(ifp, &net->ipv6.inet6_addr_lst[hash], addr_lst) {
4578 		if (ipv6_addr_equal(&ifp->addr, addr) &&
4579 		    (ifp->flags & IFA_F_HOMEADDRESS)) {
4580 			ret = 1;
4581 			break;
4582 		}
4583 	}
4584 	rcu_read_unlock();
4585 	return ret;
4586 }
4587 #endif
4588 
4589 /* RFC6554 has some algorithm to avoid loops in segment routing by
4590  * checking if the segments contains any of a local interface address.
4591  *
4592  * Quote:
4593  *
4594  * To detect loops in the SRH, a router MUST determine if the SRH
4595  * includes multiple addresses assigned to any interface on that router.
4596  * If such addresses appear more than once and are separated by at least
4597  * one address not assigned to that router.
4598  */
ipv6_chk_rpl_srh_loop(struct net * net,const struct in6_addr * segs,unsigned char nsegs)4599 int ipv6_chk_rpl_srh_loop(struct net *net, const struct in6_addr *segs,
4600 			  unsigned char nsegs)
4601 {
4602 	const struct in6_addr *addr;
4603 	int i, ret = 0, found = 0;
4604 	struct inet6_ifaddr *ifp;
4605 	bool separated = false;
4606 	unsigned int hash;
4607 	bool hash_found;
4608 
4609 	rcu_read_lock();
4610 	for (i = 0; i < nsegs; i++) {
4611 		addr = &segs[i];
4612 		hash = inet6_addr_hash(net, addr);
4613 
4614 		hash_found = false;
4615 		hlist_for_each_entry_rcu(ifp, &net->ipv6.inet6_addr_lst[hash], addr_lst) {
4616 
4617 			if (ipv6_addr_equal(&ifp->addr, addr)) {
4618 				hash_found = true;
4619 				break;
4620 			}
4621 		}
4622 
4623 		if (hash_found) {
4624 			if (found > 1 && separated) {
4625 				ret = 1;
4626 				break;
4627 			}
4628 
4629 			separated = false;
4630 			found++;
4631 		} else {
4632 			separated = true;
4633 		}
4634 	}
4635 	rcu_read_unlock();
4636 
4637 	return ret;
4638 }
4639 
4640 /*
4641  *	Periodic address status verification
4642  */
4643 
addrconf_verify_rtnl(struct net * net)4644 static void addrconf_verify_rtnl(struct net *net)
4645 {
4646 	unsigned long now, next, next_sec, next_sched;
4647 	struct inet6_ifaddr *ifp;
4648 	int i;
4649 
4650 	ASSERT_RTNL();
4651 
4652 	rcu_read_lock_bh();
4653 	now = jiffies;
4654 	next = round_jiffies_up(now + ADDR_CHECK_FREQUENCY);
4655 
4656 	cancel_delayed_work(&net->ipv6.addr_chk_work);
4657 
4658 	for (i = 0; i < IN6_ADDR_HSIZE; i++) {
4659 restart:
4660 		hlist_for_each_entry_rcu_bh(ifp, &net->ipv6.inet6_addr_lst[i], addr_lst) {
4661 			unsigned long age;
4662 
4663 			/* When setting preferred_lft to a value not zero or
4664 			 * infinity, while valid_lft is infinity
4665 			 * IFA_F_PERMANENT has a non-infinity life time.
4666 			 */
4667 			if ((ifp->flags & IFA_F_PERMANENT) &&
4668 			    (ifp->prefered_lft == INFINITY_LIFE_TIME))
4669 				continue;
4670 
4671 			spin_lock(&ifp->lock);
4672 			/* We try to batch several events at once. */
4673 			age = (now - ifp->tstamp + ADDRCONF_TIMER_FUZZ_MINUS) / HZ;
4674 
4675 			if ((ifp->flags&IFA_F_TEMPORARY) &&
4676 			    !(ifp->flags&IFA_F_TENTATIVE) &&
4677 			    ifp->prefered_lft != INFINITY_LIFE_TIME &&
4678 			    !ifp->regen_count && ifp->ifpub) {
4679 				/* This is a non-regenerated temporary addr. */
4680 
4681 				unsigned long regen_advance = ipv6_get_regen_advance(ifp->idev);
4682 
4683 				if (age + regen_advance >= ifp->prefered_lft) {
4684 					struct inet6_ifaddr *ifpub = ifp->ifpub;
4685 					if (time_before(ifp->tstamp + ifp->prefered_lft * HZ, next))
4686 						next = ifp->tstamp + ifp->prefered_lft * HZ;
4687 
4688 					ifp->regen_count++;
4689 					in6_ifa_hold(ifp);
4690 					in6_ifa_hold(ifpub);
4691 					spin_unlock(&ifp->lock);
4692 
4693 					spin_lock(&ifpub->lock);
4694 					ifpub->regen_count = 0;
4695 					spin_unlock(&ifpub->lock);
4696 					rcu_read_unlock_bh();
4697 					ipv6_create_tempaddr(ifpub, true);
4698 					in6_ifa_put(ifpub);
4699 					in6_ifa_put(ifp);
4700 					rcu_read_lock_bh();
4701 					goto restart;
4702 				} else if (time_before(ifp->tstamp + ifp->prefered_lft * HZ - regen_advance * HZ, next))
4703 					next = ifp->tstamp + ifp->prefered_lft * HZ - regen_advance * HZ;
4704 			}
4705 
4706 			if (ifp->valid_lft != INFINITY_LIFE_TIME &&
4707 			    age >= ifp->valid_lft) {
4708 				spin_unlock(&ifp->lock);
4709 				in6_ifa_hold(ifp);
4710 				rcu_read_unlock_bh();
4711 				ipv6_del_addr(ifp);
4712 				rcu_read_lock_bh();
4713 				goto restart;
4714 			} else if (ifp->prefered_lft == INFINITY_LIFE_TIME) {
4715 				spin_unlock(&ifp->lock);
4716 				continue;
4717 			} else if (age >= ifp->prefered_lft) {
4718 				/* jiffies - ifp->tstamp > age >= ifp->prefered_lft */
4719 				int deprecate = 0;
4720 
4721 				if (!(ifp->flags&IFA_F_DEPRECATED)) {
4722 					deprecate = 1;
4723 					ifp->flags |= IFA_F_DEPRECATED;
4724 				}
4725 
4726 				if ((ifp->valid_lft != INFINITY_LIFE_TIME) &&
4727 				    (time_before(ifp->tstamp + ifp->valid_lft * HZ, next)))
4728 					next = ifp->tstamp + ifp->valid_lft * HZ;
4729 
4730 				spin_unlock(&ifp->lock);
4731 
4732 				if (deprecate) {
4733 					in6_ifa_hold(ifp);
4734 
4735 					ipv6_ifa_notify(0, ifp);
4736 					in6_ifa_put(ifp);
4737 					goto restart;
4738 				}
4739 			} else {
4740 				/* ifp->prefered_lft <= ifp->valid_lft */
4741 				if (time_before(ifp->tstamp + ifp->prefered_lft * HZ, next))
4742 					next = ifp->tstamp + ifp->prefered_lft * HZ;
4743 				spin_unlock(&ifp->lock);
4744 			}
4745 		}
4746 	}
4747 
4748 	next_sec = round_jiffies_up(next);
4749 	next_sched = next;
4750 
4751 	/* If rounded timeout is accurate enough, accept it. */
4752 	if (time_before(next_sec, next + ADDRCONF_TIMER_FUZZ))
4753 		next_sched = next_sec;
4754 
4755 	/* And minimum interval is ADDRCONF_TIMER_FUZZ_MAX. */
4756 	if (time_before(next_sched, jiffies + ADDRCONF_TIMER_FUZZ_MAX))
4757 		next_sched = jiffies + ADDRCONF_TIMER_FUZZ_MAX;
4758 
4759 	pr_debug("now = %lu, schedule = %lu, rounded schedule = %lu => %lu\n",
4760 		 now, next, next_sec, next_sched);
4761 	mod_delayed_work(addrconf_wq, &net->ipv6.addr_chk_work, next_sched - now);
4762 	rcu_read_unlock_bh();
4763 }
4764 
addrconf_verify_work(struct work_struct * w)4765 static void addrconf_verify_work(struct work_struct *w)
4766 {
4767 	struct net *net = container_of(to_delayed_work(w), struct net,
4768 				       ipv6.addr_chk_work);
4769 
4770 	rtnl_net_lock(net);
4771 	addrconf_verify_rtnl(net);
4772 	rtnl_net_unlock(net);
4773 }
4774 
addrconf_verify(struct net * net)4775 static void addrconf_verify(struct net *net)
4776 {
4777 	mod_delayed_work(addrconf_wq, &net->ipv6.addr_chk_work, 0);
4778 }
4779 
extract_addr(struct nlattr * addr,struct nlattr * local,struct in6_addr ** peer_pfx)4780 static struct in6_addr *extract_addr(struct nlattr *addr, struct nlattr *local,
4781 				     struct in6_addr **peer_pfx)
4782 {
4783 	struct in6_addr *pfx = NULL;
4784 
4785 	*peer_pfx = NULL;
4786 
4787 	if (addr)
4788 		pfx = nla_data(addr);
4789 
4790 	if (local) {
4791 		if (pfx && nla_memcmp(local, pfx, sizeof(*pfx)))
4792 			*peer_pfx = pfx;
4793 		pfx = nla_data(local);
4794 	}
4795 
4796 	return pfx;
4797 }
4798 
4799 static const struct nla_policy ifa_ipv6_policy[IFA_MAX+1] = {
4800 	[IFA_ADDRESS]		= { .len = sizeof(struct in6_addr) },
4801 	[IFA_LOCAL]		= { .len = sizeof(struct in6_addr) },
4802 	[IFA_CACHEINFO]		= { .len = sizeof(struct ifa_cacheinfo) },
4803 	[IFA_FLAGS]		= { .len = sizeof(u32) },
4804 	[IFA_RT_PRIORITY]	= { .len = sizeof(u32) },
4805 	[IFA_TARGET_NETNSID]	= { .type = NLA_S32 },
4806 	[IFA_PROTO]		= { .type = NLA_U8 },
4807 };
4808 
4809 static int
inet6_rtm_deladdr(struct sk_buff * skb,struct nlmsghdr * nlh,struct netlink_ext_ack * extack)4810 inet6_rtm_deladdr(struct sk_buff *skb, struct nlmsghdr *nlh,
4811 		  struct netlink_ext_ack *extack)
4812 {
4813 	struct net *net = sock_net(skb->sk);
4814 	struct ifaddrmsg *ifm;
4815 	struct nlattr *tb[IFA_MAX+1];
4816 	struct in6_addr *pfx, *peer_pfx;
4817 	u32 ifa_flags;
4818 	int err;
4819 
4820 	err = nlmsg_parse_deprecated(nlh, sizeof(*ifm), tb, IFA_MAX,
4821 				     ifa_ipv6_policy, extack);
4822 	if (err < 0)
4823 		return err;
4824 
4825 	ifm = nlmsg_data(nlh);
4826 	pfx = extract_addr(tb[IFA_ADDRESS], tb[IFA_LOCAL], &peer_pfx);
4827 	if (!pfx)
4828 		return -EINVAL;
4829 
4830 	ifa_flags = nla_get_u32_default(tb[IFA_FLAGS], ifm->ifa_flags);
4831 
4832 	/* We ignore other flags so far. */
4833 	ifa_flags &= IFA_F_MANAGETEMPADDR;
4834 
4835 	rtnl_net_lock(net);
4836 	err = inet6_addr_del(net, ifm->ifa_index, ifa_flags, pfx,
4837 			     ifm->ifa_prefixlen, extack);
4838 	rtnl_net_unlock(net);
4839 
4840 	return err;
4841 }
4842 
modify_prefix_route(struct net * net,struct inet6_ifaddr * ifp,unsigned long expires,u32 flags,bool modify_peer)4843 static int modify_prefix_route(struct net *net, struct inet6_ifaddr *ifp,
4844 			       unsigned long expires, u32 flags,
4845 			       bool modify_peer)
4846 {
4847 	struct fib6_table *table;
4848 	struct fib6_info *f6i;
4849 	u32 prio;
4850 
4851 	f6i = addrconf_get_prefix_route(modify_peer ? &ifp->peer_addr : &ifp->addr,
4852 					ifp->prefix_len,
4853 					ifp->idev->dev, 0, RTF_DEFAULT, true);
4854 	if (!f6i)
4855 		return -ENOENT;
4856 
4857 	prio = ifp->rt_priority ? : IP6_RT_PRIO_ADDRCONF;
4858 	if (f6i->fib6_metric != prio) {
4859 		/* delete old one */
4860 		ip6_del_rt(dev_net(ifp->idev->dev), f6i, false);
4861 
4862 		/* add new one */
4863 		addrconf_prefix_route(modify_peer ? &ifp->peer_addr : &ifp->addr,
4864 				      ifp->prefix_len,
4865 				      ifp->rt_priority, ifp->idev->dev,
4866 				      expires, flags, GFP_KERNEL);
4867 		return 0;
4868 	}
4869 	if (f6i != net->ipv6.fib6_null_entry) {
4870 		table = f6i->fib6_table;
4871 		spin_lock_bh(&table->tb6_lock);
4872 
4873 		if (!(flags & RTF_EXPIRES)) {
4874 			fib6_clean_expires(f6i);
4875 			fib6_may_remove_gc_list(net, f6i);
4876 		} else {
4877 			fib6_set_expires(f6i, expires);
4878 			fib6_add_gc_list(f6i);
4879 		}
4880 
4881 		spin_unlock_bh(&table->tb6_lock);
4882 	}
4883 	fib6_info_release(f6i);
4884 
4885 	return 0;
4886 }
4887 
inet6_addr_modify(struct net * net,struct inet6_ifaddr * ifp,struct ifa6_config * cfg,clock_t expires,u32 flags)4888 static int inet6_addr_modify(struct net *net, struct inet6_ifaddr *ifp,
4889 			     struct ifa6_config *cfg, clock_t expires,
4890 			     u32 flags)
4891 {
4892 	bool was_managetempaddr;
4893 	bool new_peer = false;
4894 	bool had_prefixroute;
4895 
4896 	ASSERT_RTNL_NET(net);
4897 
4898 	if (cfg->ifa_flags & IFA_F_MANAGETEMPADDR &&
4899 	    (ifp->flags & IFA_F_TEMPORARY || ifp->prefix_len != 64))
4900 		return -EINVAL;
4901 
4902 	if (!(ifp->flags & IFA_F_TENTATIVE) || ifp->flags & IFA_F_DADFAILED)
4903 		cfg->ifa_flags &= ~IFA_F_OPTIMISTIC;
4904 
4905 	if (cfg->peer_pfx &&
4906 	    memcmp(&ifp->peer_addr, cfg->peer_pfx, sizeof(struct in6_addr))) {
4907 		if (!ipv6_addr_any(&ifp->peer_addr))
4908 			cleanup_prefix_route(ifp, expires, true, true);
4909 		new_peer = true;
4910 	}
4911 
4912 	spin_lock_bh(&ifp->lock);
4913 	was_managetempaddr = ifp->flags & IFA_F_MANAGETEMPADDR;
4914 	had_prefixroute = ifp->flags & IFA_F_PERMANENT &&
4915 			  !(ifp->flags & IFA_F_NOPREFIXROUTE);
4916 	ifp->flags &= ~(IFA_F_DEPRECATED | IFA_F_PERMANENT | IFA_F_NODAD |
4917 			IFA_F_HOMEADDRESS | IFA_F_MANAGETEMPADDR |
4918 			IFA_F_NOPREFIXROUTE);
4919 	ifp->flags |= cfg->ifa_flags;
4920 	WRITE_ONCE(ifp->tstamp, jiffies);
4921 	WRITE_ONCE(ifp->valid_lft, cfg->valid_lft);
4922 	WRITE_ONCE(ifp->prefered_lft, cfg->preferred_lft);
4923 	WRITE_ONCE(ifp->ifa_proto, cfg->ifa_proto);
4924 
4925 	if (cfg->rt_priority && cfg->rt_priority != ifp->rt_priority)
4926 		WRITE_ONCE(ifp->rt_priority, cfg->rt_priority);
4927 
4928 	if (new_peer)
4929 		ifp->peer_addr = *cfg->peer_pfx;
4930 
4931 	spin_unlock_bh(&ifp->lock);
4932 	if (!(ifp->flags&IFA_F_TENTATIVE))
4933 		ipv6_ifa_notify(0, ifp);
4934 
4935 	if (!(cfg->ifa_flags & IFA_F_NOPREFIXROUTE)) {
4936 		int rc = -ENOENT;
4937 
4938 		if (had_prefixroute)
4939 			rc = modify_prefix_route(net, ifp, expires, flags, false);
4940 
4941 		/* prefix route could have been deleted; if so restore it */
4942 		if (rc == -ENOENT) {
4943 			addrconf_prefix_route(&ifp->addr, ifp->prefix_len,
4944 					      ifp->rt_priority, ifp->idev->dev,
4945 					      expires, flags, GFP_KERNEL);
4946 		}
4947 
4948 		if (had_prefixroute && !ipv6_addr_any(&ifp->peer_addr))
4949 			rc = modify_prefix_route(net, ifp, expires, flags, true);
4950 
4951 		if (rc == -ENOENT && !ipv6_addr_any(&ifp->peer_addr)) {
4952 			addrconf_prefix_route(&ifp->peer_addr, ifp->prefix_len,
4953 					      ifp->rt_priority, ifp->idev->dev,
4954 					      expires, flags, GFP_KERNEL);
4955 		}
4956 	} else if (had_prefixroute) {
4957 		enum cleanup_prefix_rt_t action;
4958 		unsigned long rt_expires;
4959 
4960 		write_lock_bh(&ifp->idev->lock);
4961 		action = check_cleanup_prefix_route(ifp, &rt_expires);
4962 		write_unlock_bh(&ifp->idev->lock);
4963 
4964 		if (action != CLEANUP_PREFIX_RT_NOP) {
4965 			cleanup_prefix_route(ifp, rt_expires,
4966 				action == CLEANUP_PREFIX_RT_DEL, false);
4967 		}
4968 	}
4969 
4970 	if (was_managetempaddr || ifp->flags & IFA_F_MANAGETEMPADDR) {
4971 		if (was_managetempaddr && !(ifp->flags & IFA_F_MANAGETEMPADDR))
4972 			delete_tempaddrs(ifp->idev, ifp);
4973 		else
4974 			manage_tempaddrs(ifp->idev, ifp, cfg->valid_lft,
4975 					 cfg->preferred_lft, !was_managetempaddr,
4976 					 jiffies);
4977 	}
4978 
4979 	addrconf_verify_rtnl(net);
4980 
4981 	return 0;
4982 }
4983 
4984 static int
inet6_rtm_newaddr(struct sk_buff * skb,struct nlmsghdr * nlh,struct netlink_ext_ack * extack)4985 inet6_rtm_newaddr(struct sk_buff *skb, struct nlmsghdr *nlh,
4986 		  struct netlink_ext_ack *extack)
4987 {
4988 	struct net *net = sock_net(skb->sk);
4989 	struct nlattr *tb[IFA_MAX+1];
4990 	struct in6_addr *peer_pfx;
4991 	struct inet6_ifaddr *ifa;
4992 	struct net_device *dev;
4993 	struct inet6_dev *idev;
4994 	struct ifa6_config cfg;
4995 	struct ifaddrmsg *ifm;
4996 	unsigned long timeout;
4997 	clock_t expires;
4998 	u32 flags;
4999 	int err;
5000 
5001 	err = nlmsg_parse_deprecated(nlh, sizeof(*ifm), tb, IFA_MAX,
5002 				     ifa_ipv6_policy, extack);
5003 	if (err < 0)
5004 		return err;
5005 
5006 	memset(&cfg, 0, sizeof(cfg));
5007 
5008 	ifm = nlmsg_data(nlh);
5009 	cfg.pfx = extract_addr(tb[IFA_ADDRESS], tb[IFA_LOCAL], &peer_pfx);
5010 	if (!cfg.pfx)
5011 		return -EINVAL;
5012 
5013 	cfg.peer_pfx = peer_pfx;
5014 	cfg.plen = ifm->ifa_prefixlen;
5015 	if (tb[IFA_RT_PRIORITY])
5016 		cfg.rt_priority = nla_get_u32(tb[IFA_RT_PRIORITY]);
5017 
5018 	if (tb[IFA_PROTO])
5019 		cfg.ifa_proto = nla_get_u8(tb[IFA_PROTO]);
5020 
5021 	cfg.ifa_flags = nla_get_u32_default(tb[IFA_FLAGS], ifm->ifa_flags);
5022 
5023 	/* We ignore other flags so far. */
5024 	cfg.ifa_flags &= IFA_F_NODAD | IFA_F_HOMEADDRESS |
5025 			 IFA_F_MANAGETEMPADDR | IFA_F_NOPREFIXROUTE |
5026 			 IFA_F_MCAUTOJOIN | IFA_F_OPTIMISTIC;
5027 
5028 	cfg.ifa_flags |= IFA_F_PERMANENT;
5029 	cfg.valid_lft = INFINITY_LIFE_TIME;
5030 	cfg.preferred_lft = INFINITY_LIFE_TIME;
5031 	expires = 0;
5032 	flags = 0;
5033 
5034 	if (tb[IFA_CACHEINFO]) {
5035 		struct ifa_cacheinfo *ci;
5036 
5037 		ci = nla_data(tb[IFA_CACHEINFO]);
5038 		cfg.valid_lft = ci->ifa_valid;
5039 		cfg.preferred_lft = ci->ifa_prefered;
5040 
5041 		if (!cfg.valid_lft || cfg.preferred_lft > cfg.valid_lft) {
5042 			NL_SET_ERR_MSG_MOD(extack, "address lifetime invalid");
5043 			return -EINVAL;
5044 		}
5045 
5046 		timeout = addrconf_timeout_fixup(cfg.valid_lft, HZ);
5047 		if (addrconf_finite_timeout(timeout)) {
5048 			cfg.ifa_flags &= ~IFA_F_PERMANENT;
5049 			cfg.valid_lft = timeout;
5050 			expires = jiffies_to_clock_t(timeout * HZ);
5051 			flags = RTF_EXPIRES;
5052 		}
5053 
5054 		timeout = addrconf_timeout_fixup(cfg.preferred_lft, HZ);
5055 		if (addrconf_finite_timeout(timeout)) {
5056 			if (timeout == 0)
5057 				cfg.ifa_flags |= IFA_F_DEPRECATED;
5058 
5059 			cfg.preferred_lft = timeout;
5060 		}
5061 	}
5062 
5063 	rtnl_net_lock(net);
5064 
5065 	dev =  __dev_get_by_index(net, ifm->ifa_index);
5066 	if (!dev) {
5067 		NL_SET_ERR_MSG_MOD(extack, "Unable to find the interface");
5068 		err = -ENODEV;
5069 		goto unlock_rtnl;
5070 	}
5071 
5072 	netdev_lock_ops(dev);
5073 	idev = ipv6_find_idev(dev);
5074 	if (IS_ERR(idev)) {
5075 		err = PTR_ERR(idev);
5076 		goto unlock;
5077 	}
5078 
5079 	if (!ipv6_allow_optimistic_dad(net, idev))
5080 		cfg.ifa_flags &= ~IFA_F_OPTIMISTIC;
5081 
5082 	if (cfg.ifa_flags & IFA_F_NODAD &&
5083 	    cfg.ifa_flags & IFA_F_OPTIMISTIC) {
5084 		NL_SET_ERR_MSG(extack, "IFA_F_NODAD and IFA_F_OPTIMISTIC are mutually exclusive");
5085 		err = -EINVAL;
5086 		goto unlock;
5087 	}
5088 
5089 	ifa = ipv6_get_ifaddr(net, cfg.pfx, dev, 1);
5090 	if (!ifa) {
5091 		/*
5092 		 * It would be best to check for !NLM_F_CREATE here but
5093 		 * userspace already relies on not having to provide this.
5094 		 */
5095 		err = inet6_addr_add(net, dev, &cfg, expires, flags, extack);
5096 		goto unlock;
5097 	}
5098 
5099 	if (nlh->nlmsg_flags & NLM_F_EXCL ||
5100 	    !(nlh->nlmsg_flags & NLM_F_REPLACE)) {
5101 		NL_SET_ERR_MSG_MOD(extack, "address already assigned");
5102 		err = -EEXIST;
5103 	} else {
5104 		err = inet6_addr_modify(net, ifa, &cfg, expires, flags);
5105 	}
5106 
5107 	in6_ifa_put(ifa);
5108 unlock:
5109 	netdev_unlock_ops(dev);
5110 unlock_rtnl:
5111 	rtnl_net_unlock(net);
5112 
5113 	return err;
5114 }
5115 
put_ifaddrmsg(struct nlmsghdr * nlh,u8 prefixlen,u32 flags,u8 scope,int ifindex)5116 static void put_ifaddrmsg(struct nlmsghdr *nlh, u8 prefixlen, u32 flags,
5117 			  u8 scope, int ifindex)
5118 {
5119 	struct ifaddrmsg *ifm;
5120 
5121 	ifm = nlmsg_data(nlh);
5122 	ifm->ifa_family = AF_INET6;
5123 	ifm->ifa_prefixlen = prefixlen;
5124 	ifm->ifa_flags = flags;
5125 	ifm->ifa_scope = scope;
5126 	ifm->ifa_index = ifindex;
5127 }
5128 
put_cacheinfo(struct sk_buff * skb,unsigned long cstamp,unsigned long tstamp,u32 preferred,u32 valid)5129 static int put_cacheinfo(struct sk_buff *skb, unsigned long cstamp,
5130 			 unsigned long tstamp, u32 preferred, u32 valid)
5131 {
5132 	struct ifa_cacheinfo ci;
5133 
5134 	ci.cstamp = cstamp_delta(cstamp);
5135 	ci.tstamp = cstamp_delta(tstamp);
5136 	ci.ifa_prefered = preferred;
5137 	ci.ifa_valid = valid;
5138 
5139 	return nla_put(skb, IFA_CACHEINFO, sizeof(ci), &ci);
5140 }
5141 
rt_scope(int ifa_scope)5142 static inline int rt_scope(int ifa_scope)
5143 {
5144 	if (ifa_scope & IFA_HOST)
5145 		return RT_SCOPE_HOST;
5146 	else if (ifa_scope & IFA_LINK)
5147 		return RT_SCOPE_LINK;
5148 	else if (ifa_scope & IFA_SITE)
5149 		return RT_SCOPE_SITE;
5150 	else
5151 		return RT_SCOPE_UNIVERSE;
5152 }
5153 
inet6_ifaddr_msgsize(void)5154 static inline int inet6_ifaddr_msgsize(void)
5155 {
5156 	return NLMSG_ALIGN(sizeof(struct ifaddrmsg))
5157 	       + nla_total_size(16) /* IFA_LOCAL */
5158 	       + nla_total_size(16) /* IFA_ADDRESS */
5159 	       + nla_total_size(sizeof(struct ifa_cacheinfo))
5160 	       + nla_total_size(4)  /* IFA_FLAGS */
5161 	       + nla_total_size(1)  /* IFA_PROTO */
5162 	       + nla_total_size(4)  /* IFA_RT_PRIORITY */;
5163 }
5164 
inet6_fill_ifaddr(struct sk_buff * skb,const struct inet6_ifaddr * ifa,struct inet6_fill_args * args)5165 static int inet6_fill_ifaddr(struct sk_buff *skb,
5166 			     const struct inet6_ifaddr *ifa,
5167 			     struct inet6_fill_args *args)
5168 {
5169 	struct nlmsghdr *nlh;
5170 	u32 preferred, valid;
5171 	u32 flags, priority;
5172 	u8 proto;
5173 
5174 	nlh = nlmsg_put(skb, args->portid, args->seq, args->event,
5175 			sizeof(struct ifaddrmsg), args->flags);
5176 	if (!nlh)
5177 		return -EMSGSIZE;
5178 
5179 	flags = READ_ONCE(ifa->flags);
5180 	put_ifaddrmsg(nlh, ifa->prefix_len, ifa->flags, rt_scope(ifa->scope),
5181 		      ifa->idev->dev->ifindex);
5182 
5183 	if (args->netnsid >= 0 &&
5184 	    nla_put_s32(skb, IFA_TARGET_NETNSID, args->netnsid))
5185 		goto error;
5186 
5187 	preferred = READ_ONCE(ifa->prefered_lft);
5188 	valid = READ_ONCE(ifa->valid_lft);
5189 
5190 	if (!((flags & IFA_F_PERMANENT) &&
5191 	      (preferred == INFINITY_LIFE_TIME))) {
5192 		if (preferred != INFINITY_LIFE_TIME) {
5193 			long tval = (jiffies - READ_ONCE(ifa->tstamp)) / HZ;
5194 
5195 			if (preferred > tval)
5196 				preferred -= tval;
5197 			else
5198 				preferred = 0;
5199 			if (valid != INFINITY_LIFE_TIME) {
5200 				if (valid > tval)
5201 					valid -= tval;
5202 				else
5203 					valid = 0;
5204 			}
5205 		}
5206 	} else {
5207 		preferred = INFINITY_LIFE_TIME;
5208 		valid = INFINITY_LIFE_TIME;
5209 	}
5210 
5211 	if (!ipv6_addr_any(&ifa->peer_addr)) {
5212 		if (nla_put_in6_addr(skb, IFA_LOCAL, &ifa->addr) < 0 ||
5213 		    nla_put_in6_addr(skb, IFA_ADDRESS, &ifa->peer_addr) < 0)
5214 			goto error;
5215 	} else {
5216 		if (nla_put_in6_addr(skb, IFA_ADDRESS, &ifa->addr) < 0)
5217 			goto error;
5218 	}
5219 
5220 	priority = READ_ONCE(ifa->rt_priority);
5221 	if (priority && nla_put_u32(skb, IFA_RT_PRIORITY, priority))
5222 		goto error;
5223 
5224 	if (put_cacheinfo(skb, ifa->cstamp, READ_ONCE(ifa->tstamp),
5225 			  preferred, valid) < 0)
5226 		goto error;
5227 
5228 	if (nla_put_u32(skb, IFA_FLAGS, flags) < 0)
5229 		goto error;
5230 
5231 	proto = READ_ONCE(ifa->ifa_proto);
5232 	if (proto && nla_put_u8(skb, IFA_PROTO, proto))
5233 		goto error;
5234 
5235 	nlmsg_end(skb, nlh);
5236 	return 0;
5237 
5238 error:
5239 	nlmsg_cancel(skb, nlh);
5240 	return -EMSGSIZE;
5241 }
5242 
inet6_fill_ifmcaddr(struct sk_buff * skb,const struct ifmcaddr6 * ifmca,struct inet6_fill_args * args)5243 int inet6_fill_ifmcaddr(struct sk_buff *skb,
5244 			const struct ifmcaddr6 *ifmca,
5245 			struct inet6_fill_args *args)
5246 {
5247 	int ifindex = ifmca->idev->dev->ifindex;
5248 	u8 scope = RT_SCOPE_UNIVERSE;
5249 	struct nlmsghdr *nlh;
5250 
5251 	if (!args->force_rt_scope_universe &&
5252 	    ipv6_addr_scope(&ifmca->mca_addr) & IFA_SITE)
5253 		scope = RT_SCOPE_SITE;
5254 
5255 	nlh = nlmsg_put(skb, args->portid, args->seq, args->event,
5256 			sizeof(struct ifaddrmsg), args->flags);
5257 	if (!nlh)
5258 		return -EMSGSIZE;
5259 
5260 	if (args->netnsid >= 0 &&
5261 	    nla_put_s32(skb, IFA_TARGET_NETNSID, args->netnsid)) {
5262 		nlmsg_cancel(skb, nlh);
5263 		return -EMSGSIZE;
5264 	}
5265 
5266 	put_ifaddrmsg(nlh, 128, IFA_F_PERMANENT, scope, ifindex);
5267 	if (nla_put_in6_addr(skb, IFA_MULTICAST, &ifmca->mca_addr) < 0 ||
5268 	    nla_put_u32(skb, IFA_MC_USERS, READ_ONCE(ifmca->mca_users)) < 0 ||
5269 	    put_cacheinfo(skb, ifmca->mca_cstamp, READ_ONCE(ifmca->mca_tstamp),
5270 			  INFINITY_LIFE_TIME, INFINITY_LIFE_TIME) < 0) {
5271 		nlmsg_cancel(skb, nlh);
5272 		return -EMSGSIZE;
5273 	}
5274 
5275 	nlmsg_end(skb, nlh);
5276 	return 0;
5277 }
5278 
inet6_fill_ifacaddr(struct sk_buff * skb,const struct ifacaddr6 * ifaca,struct inet6_fill_args * args)5279 int inet6_fill_ifacaddr(struct sk_buff *skb,
5280 			const struct ifacaddr6 *ifaca,
5281 			struct inet6_fill_args *args)
5282 {
5283 	struct net_device *dev = fib6_info_nh_dev(ifaca->aca_rt);
5284 	int ifindex = dev ? dev->ifindex : 1;
5285 	u8 scope = RT_SCOPE_UNIVERSE;
5286 	struct nlmsghdr *nlh;
5287 
5288 	if (ipv6_addr_scope(&ifaca->aca_addr) & IFA_SITE)
5289 		scope = RT_SCOPE_SITE;
5290 
5291 	nlh = nlmsg_put(skb, args->portid, args->seq, args->event,
5292 			sizeof(struct ifaddrmsg), args->flags);
5293 	if (!nlh)
5294 		return -EMSGSIZE;
5295 
5296 	if (args->netnsid >= 0 &&
5297 	    nla_put_s32(skb, IFA_TARGET_NETNSID, args->netnsid)) {
5298 		nlmsg_cancel(skb, nlh);
5299 		return -EMSGSIZE;
5300 	}
5301 
5302 	put_ifaddrmsg(nlh, 128, IFA_F_PERMANENT, scope, ifindex);
5303 	if (nla_put_in6_addr(skb, IFA_ANYCAST, &ifaca->aca_addr) < 0 ||
5304 	    put_cacheinfo(skb, ifaca->aca_cstamp, READ_ONCE(ifaca->aca_tstamp),
5305 			  INFINITY_LIFE_TIME, INFINITY_LIFE_TIME) < 0) {
5306 		nlmsg_cancel(skb, nlh);
5307 		return -EMSGSIZE;
5308 	}
5309 
5310 	nlmsg_end(skb, nlh);
5311 	return 0;
5312 }
5313 
5314 /* called with rcu_read_lock() */
in6_dump_addrs(const struct inet6_dev * idev,struct sk_buff * skb,struct netlink_callback * cb,int * s_ip_idx,struct inet6_fill_args * fillargs)5315 static int in6_dump_addrs(const struct inet6_dev *idev, struct sk_buff *skb,
5316 			  struct netlink_callback *cb, int *s_ip_idx,
5317 			  struct inet6_fill_args *fillargs)
5318 {
5319 	const struct ifmcaddr6 *ifmca;
5320 	const struct ifacaddr6 *ifaca;
5321 	int ip_idx = 0;
5322 	int err = 0;
5323 
5324 	switch (fillargs->type) {
5325 	case UNICAST_ADDR: {
5326 		const struct inet6_ifaddr *ifa;
5327 		fillargs->event = RTM_NEWADDR;
5328 
5329 		/* unicast address incl. temp addr */
5330 		list_for_each_entry_rcu(ifa, &idev->addr_list, if_list) {
5331 			if (ip_idx < *s_ip_idx)
5332 				goto next;
5333 			err = inet6_fill_ifaddr(skb, ifa, fillargs);
5334 			if (err < 0)
5335 				break;
5336 			nl_dump_check_consistent(cb, nlmsg_hdr(skb));
5337 next:
5338 			ip_idx++;
5339 		}
5340 		break;
5341 	}
5342 	case MULTICAST_ADDR:
5343 		fillargs->event = RTM_GETMULTICAST;
5344 
5345 		/* multicast address */
5346 		for (ifmca = rcu_dereference(idev->mc_list);
5347 		     ifmca;
5348 		     ifmca = rcu_dereference(ifmca->next), ip_idx++) {
5349 			if (ip_idx < *s_ip_idx)
5350 				continue;
5351 			err = inet6_fill_ifmcaddr(skb, ifmca, fillargs);
5352 			if (err < 0)
5353 				break;
5354 		}
5355 		break;
5356 	case ANYCAST_ADDR:
5357 		fillargs->event = RTM_GETANYCAST;
5358 		/* anycast address */
5359 		for (ifaca = rcu_dereference(idev->ac_list); ifaca;
5360 		     ifaca = rcu_dereference(ifaca->aca_next), ip_idx++) {
5361 			if (ip_idx < *s_ip_idx)
5362 				continue;
5363 			err = inet6_fill_ifacaddr(skb, ifaca, fillargs);
5364 			if (err < 0)
5365 				break;
5366 		}
5367 		break;
5368 	default:
5369 		break;
5370 	}
5371 	*s_ip_idx = err ? ip_idx : 0;
5372 	return err;
5373 }
5374 
inet6_valid_dump_ifaddr_req(const struct nlmsghdr * nlh,struct inet6_fill_args * fillargs,struct net ** tgt_net,struct sock * sk,struct netlink_callback * cb)5375 static int inet6_valid_dump_ifaddr_req(const struct nlmsghdr *nlh,
5376 				       struct inet6_fill_args *fillargs,
5377 				       struct net **tgt_net, struct sock *sk,
5378 				       struct netlink_callback *cb)
5379 {
5380 	struct netlink_ext_ack *extack = cb->extack;
5381 	struct nlattr *tb[IFA_MAX+1];
5382 	struct ifaddrmsg *ifm;
5383 	int err, i;
5384 
5385 	ifm = nlmsg_payload(nlh, sizeof(*ifm));
5386 	if (!ifm) {
5387 		NL_SET_ERR_MSG_MOD(extack, "Invalid header for address dump request");
5388 		return -EINVAL;
5389 	}
5390 
5391 	if (ifm->ifa_prefixlen || ifm->ifa_flags || ifm->ifa_scope) {
5392 		NL_SET_ERR_MSG_MOD(extack, "Invalid values in header for address dump request");
5393 		return -EINVAL;
5394 	}
5395 
5396 	fillargs->ifindex = ifm->ifa_index;
5397 	if (fillargs->ifindex) {
5398 		cb->answer_flags |= NLM_F_DUMP_FILTERED;
5399 		fillargs->flags |= NLM_F_DUMP_FILTERED;
5400 	}
5401 
5402 	err = nlmsg_parse_deprecated_strict(nlh, sizeof(*ifm), tb, IFA_MAX,
5403 					    ifa_ipv6_policy, extack);
5404 	if (err < 0)
5405 		return err;
5406 
5407 	for (i = 0; i <= IFA_MAX; ++i) {
5408 		if (!tb[i])
5409 			continue;
5410 
5411 		if (i == IFA_TARGET_NETNSID) {
5412 			struct net *net;
5413 
5414 			fillargs->netnsid = nla_get_s32(tb[i]);
5415 			net = rtnl_get_net_ns_capable(sk, fillargs->netnsid);
5416 			if (IS_ERR(net)) {
5417 				fillargs->netnsid = -1;
5418 				NL_SET_ERR_MSG_MOD(extack, "Invalid target network namespace id");
5419 				return PTR_ERR(net);
5420 			}
5421 			*tgt_net = net;
5422 		} else {
5423 			NL_SET_ERR_MSG_MOD(extack, "Unsupported attribute in dump request");
5424 			return -EINVAL;
5425 		}
5426 	}
5427 
5428 	return 0;
5429 }
5430 
inet6_dump_addr(struct sk_buff * skb,struct netlink_callback * cb,enum addr_type_t type)5431 static int inet6_dump_addr(struct sk_buff *skb, struct netlink_callback *cb,
5432 			   enum addr_type_t type)
5433 {
5434 	struct net *tgt_net = sock_net(skb->sk);
5435 	const struct nlmsghdr *nlh = cb->nlh;
5436 	struct inet6_fill_args fillargs = {
5437 		.portid = NETLINK_CB(cb->skb).portid,
5438 		.seq = cb->nlh->nlmsg_seq,
5439 		.flags = NLM_F_MULTI,
5440 		.netnsid = -1,
5441 		.type = type,
5442 		.force_rt_scope_universe = false,
5443 	};
5444 	struct {
5445 		unsigned long ifindex;
5446 		int ip_idx;
5447 	} *ctx = (void *)cb->ctx;
5448 	struct net_device *dev;
5449 	struct inet6_dev *idev;
5450 	int err = 0;
5451 
5452 	rcu_read_lock();
5453 	if (cb->strict_check) {
5454 		err = inet6_valid_dump_ifaddr_req(nlh, &fillargs, &tgt_net,
5455 						  skb->sk, cb);
5456 		if (err < 0)
5457 			goto done;
5458 
5459 		err = 0;
5460 		if (fillargs.ifindex) {
5461 			dev = dev_get_by_index_rcu(tgt_net, fillargs.ifindex);
5462 			if (!dev) {
5463 				err = -ENODEV;
5464 				goto done;
5465 			}
5466 			idev = __in6_dev_get(dev);
5467 			if (idev)
5468 				err = in6_dump_addrs(idev, skb, cb,
5469 						     &ctx->ip_idx,
5470 						     &fillargs);
5471 			goto done;
5472 		}
5473 	}
5474 
5475 	cb->seq = inet6_base_seq(tgt_net);
5476 	for_each_netdev_dump(tgt_net, dev, ctx->ifindex) {
5477 		idev = __in6_dev_get(dev);
5478 		if (!idev)
5479 			continue;
5480 		err = in6_dump_addrs(idev, skb, cb, &ctx->ip_idx,
5481 				     &fillargs);
5482 		if (err < 0)
5483 			goto done;
5484 	}
5485 done:
5486 	rcu_read_unlock();
5487 	if (fillargs.netnsid >= 0)
5488 		put_net(tgt_net);
5489 
5490 	return err;
5491 }
5492 
inet6_dump_ifaddr(struct sk_buff * skb,struct netlink_callback * cb)5493 static int inet6_dump_ifaddr(struct sk_buff *skb, struct netlink_callback *cb)
5494 {
5495 	enum addr_type_t type = UNICAST_ADDR;
5496 
5497 	return inet6_dump_addr(skb, cb, type);
5498 }
5499 
inet6_dump_ifmcaddr(struct sk_buff * skb,struct netlink_callback * cb)5500 static int inet6_dump_ifmcaddr(struct sk_buff *skb, struct netlink_callback *cb)
5501 {
5502 	enum addr_type_t type = MULTICAST_ADDR;
5503 
5504 	return inet6_dump_addr(skb, cb, type);
5505 }
5506 
5507 
inet6_dump_ifacaddr(struct sk_buff * skb,struct netlink_callback * cb)5508 static int inet6_dump_ifacaddr(struct sk_buff *skb, struct netlink_callback *cb)
5509 {
5510 	enum addr_type_t type = ANYCAST_ADDR;
5511 
5512 	return inet6_dump_addr(skb, cb, type);
5513 }
5514 
inet6_rtm_valid_getaddr_req(struct sk_buff * skb,const struct nlmsghdr * nlh,struct nlattr ** tb,struct netlink_ext_ack * extack)5515 static int inet6_rtm_valid_getaddr_req(struct sk_buff *skb,
5516 				       const struct nlmsghdr *nlh,
5517 				       struct nlattr **tb,
5518 				       struct netlink_ext_ack *extack)
5519 {
5520 	struct ifaddrmsg *ifm;
5521 	int i, err;
5522 
5523 	ifm = nlmsg_payload(nlh, sizeof(*ifm));
5524 	if (!ifm) {
5525 		NL_SET_ERR_MSG_MOD(extack, "Invalid header for get address request");
5526 		return -EINVAL;
5527 	}
5528 
5529 	if (!netlink_strict_get_check(skb))
5530 		return nlmsg_parse_deprecated(nlh, sizeof(*ifm), tb, IFA_MAX,
5531 					      ifa_ipv6_policy, extack);
5532 
5533 	if (ifm->ifa_prefixlen || ifm->ifa_flags || ifm->ifa_scope) {
5534 		NL_SET_ERR_MSG_MOD(extack, "Invalid values in header for get address request");
5535 		return -EINVAL;
5536 	}
5537 
5538 	err = nlmsg_parse_deprecated_strict(nlh, sizeof(*ifm), tb, IFA_MAX,
5539 					    ifa_ipv6_policy, extack);
5540 	if (err)
5541 		return err;
5542 
5543 	for (i = 0; i <= IFA_MAX; i++) {
5544 		if (!tb[i])
5545 			continue;
5546 
5547 		switch (i) {
5548 		case IFA_TARGET_NETNSID:
5549 		case IFA_ADDRESS:
5550 		case IFA_LOCAL:
5551 			break;
5552 		default:
5553 			NL_SET_ERR_MSG_MOD(extack, "Unsupported attribute in get address request");
5554 			return -EINVAL;
5555 		}
5556 	}
5557 
5558 	return 0;
5559 }
5560 
inet6_rtm_getaddr(struct sk_buff * in_skb,struct nlmsghdr * nlh,struct netlink_ext_ack * extack)5561 static int inet6_rtm_getaddr(struct sk_buff *in_skb, struct nlmsghdr *nlh,
5562 			     struct netlink_ext_ack *extack)
5563 {
5564 	struct net *tgt_net = sock_net(in_skb->sk);
5565 	struct inet6_fill_args fillargs = {
5566 		.portid = NETLINK_CB(in_skb).portid,
5567 		.seq = nlh->nlmsg_seq,
5568 		.event = RTM_NEWADDR,
5569 		.flags = 0,
5570 		.netnsid = -1,
5571 		.force_rt_scope_universe = false,
5572 	};
5573 	struct ifaddrmsg *ifm;
5574 	struct nlattr *tb[IFA_MAX+1];
5575 	struct in6_addr *addr = NULL, *peer;
5576 	struct net_device *dev = NULL;
5577 	struct inet6_ifaddr *ifa;
5578 	struct sk_buff *skb;
5579 	int err;
5580 
5581 	err = inet6_rtm_valid_getaddr_req(in_skb, nlh, tb, extack);
5582 	if (err < 0)
5583 		return err;
5584 
5585 	if (tb[IFA_TARGET_NETNSID]) {
5586 		fillargs.netnsid = nla_get_s32(tb[IFA_TARGET_NETNSID]);
5587 
5588 		tgt_net = rtnl_get_net_ns_capable(NETLINK_CB(in_skb).sk,
5589 						  fillargs.netnsid);
5590 		if (IS_ERR(tgt_net))
5591 			return PTR_ERR(tgt_net);
5592 	}
5593 
5594 	addr = extract_addr(tb[IFA_ADDRESS], tb[IFA_LOCAL], &peer);
5595 	if (!addr) {
5596 		err = -EINVAL;
5597 		goto errout;
5598 	}
5599 	ifm = nlmsg_data(nlh);
5600 	if (ifm->ifa_index)
5601 		dev = dev_get_by_index(tgt_net, ifm->ifa_index);
5602 
5603 	ifa = ipv6_get_ifaddr(tgt_net, addr, dev, 1);
5604 	if (!ifa) {
5605 		err = -EADDRNOTAVAIL;
5606 		goto errout;
5607 	}
5608 
5609 	skb = nlmsg_new(inet6_ifaddr_msgsize(), GFP_KERNEL);
5610 	if (!skb) {
5611 		err = -ENOBUFS;
5612 		goto errout_ifa;
5613 	}
5614 
5615 	err = inet6_fill_ifaddr(skb, ifa, &fillargs);
5616 	if (err < 0) {
5617 		/* -EMSGSIZE implies BUG in inet6_ifaddr_msgsize() */
5618 		WARN_ON(err == -EMSGSIZE);
5619 		kfree_skb(skb);
5620 		goto errout_ifa;
5621 	}
5622 	err = rtnl_unicast(skb, tgt_net, NETLINK_CB(in_skb).portid);
5623 errout_ifa:
5624 	in6_ifa_put(ifa);
5625 errout:
5626 	dev_put(dev);
5627 	if (fillargs.netnsid >= 0)
5628 		put_net(tgt_net);
5629 
5630 	return err;
5631 }
5632 
inet6_ifa_notify(int event,struct inet6_ifaddr * ifa)5633 static void inet6_ifa_notify(int event, struct inet6_ifaddr *ifa)
5634 {
5635 	struct sk_buff *skb;
5636 	struct net *net = dev_net(ifa->idev->dev);
5637 	struct inet6_fill_args fillargs = {
5638 		.portid = 0,
5639 		.seq = 0,
5640 		.event = event,
5641 		.flags = 0,
5642 		.netnsid = -1,
5643 		.force_rt_scope_universe = false,
5644 	};
5645 	int err = -ENOBUFS;
5646 
5647 	skb = nlmsg_new(inet6_ifaddr_msgsize(), GFP_ATOMIC);
5648 	if (!skb)
5649 		goto errout;
5650 
5651 	err = inet6_fill_ifaddr(skb, ifa, &fillargs);
5652 	if (err < 0) {
5653 		/* -EMSGSIZE implies BUG in inet6_ifaddr_msgsize() */
5654 		WARN_ON(err == -EMSGSIZE);
5655 		kfree_skb(skb);
5656 		goto errout;
5657 	}
5658 	rtnl_notify(skb, net, 0, RTNLGRP_IPV6_IFADDR, NULL, GFP_ATOMIC);
5659 	return;
5660 errout:
5661 	rtnl_set_sk_err(net, RTNLGRP_IPV6_IFADDR, err);
5662 }
5663 
ipv6_store_devconf(const struct ipv6_devconf * cnf,__s32 * array,int bytes)5664 static void ipv6_store_devconf(const struct ipv6_devconf *cnf,
5665 			       __s32 *array, int bytes)
5666 {
5667 	BUG_ON(bytes < (DEVCONF_MAX * 4));
5668 
5669 	memset(array, 0, bytes);
5670 	array[DEVCONF_FORWARDING] = READ_ONCE(cnf->forwarding);
5671 	array[DEVCONF_HOPLIMIT] = READ_ONCE(cnf->hop_limit);
5672 	array[DEVCONF_MTU6] = READ_ONCE(cnf->mtu6);
5673 	array[DEVCONF_ACCEPT_RA] = READ_ONCE(cnf->accept_ra);
5674 	array[DEVCONF_ACCEPT_REDIRECTS] = READ_ONCE(cnf->accept_redirects);
5675 	array[DEVCONF_AUTOCONF] = READ_ONCE(cnf->autoconf);
5676 	array[DEVCONF_DAD_TRANSMITS] = READ_ONCE(cnf->dad_transmits);
5677 	array[DEVCONF_RTR_SOLICITS] = READ_ONCE(cnf->rtr_solicits);
5678 	array[DEVCONF_RTR_SOLICIT_INTERVAL] =
5679 		jiffies_to_msecs(READ_ONCE(cnf->rtr_solicit_interval));
5680 	array[DEVCONF_RTR_SOLICIT_MAX_INTERVAL] =
5681 		jiffies_to_msecs(READ_ONCE(cnf->rtr_solicit_max_interval));
5682 	array[DEVCONF_RTR_SOLICIT_DELAY] =
5683 		jiffies_to_msecs(READ_ONCE(cnf->rtr_solicit_delay));
5684 	array[DEVCONF_FORCE_MLD_VERSION] = READ_ONCE(cnf->force_mld_version);
5685 	array[DEVCONF_MLDV1_UNSOLICITED_REPORT_INTERVAL] =
5686 		jiffies_to_msecs(READ_ONCE(cnf->mldv1_unsolicited_report_interval));
5687 	array[DEVCONF_MLDV2_UNSOLICITED_REPORT_INTERVAL] =
5688 		jiffies_to_msecs(READ_ONCE(cnf->mldv2_unsolicited_report_interval));
5689 	array[DEVCONF_USE_TEMPADDR] = READ_ONCE(cnf->use_tempaddr);
5690 	array[DEVCONF_TEMP_VALID_LFT] = READ_ONCE(cnf->temp_valid_lft);
5691 	array[DEVCONF_TEMP_PREFERED_LFT] = READ_ONCE(cnf->temp_prefered_lft);
5692 	array[DEVCONF_REGEN_MAX_RETRY] = READ_ONCE(cnf->regen_max_retry);
5693 	array[DEVCONF_MAX_DESYNC_FACTOR] = READ_ONCE(cnf->max_desync_factor);
5694 	array[DEVCONF_MAX_ADDRESSES] = READ_ONCE(cnf->max_addresses);
5695 	array[DEVCONF_ACCEPT_RA_DEFRTR] = READ_ONCE(cnf->accept_ra_defrtr);
5696 	array[DEVCONF_RA_DEFRTR_METRIC] = READ_ONCE(cnf->ra_defrtr_metric);
5697 	array[DEVCONF_ACCEPT_RA_MIN_HOP_LIMIT] =
5698 		READ_ONCE(cnf->accept_ra_min_hop_limit);
5699 	array[DEVCONF_ACCEPT_RA_PINFO] = READ_ONCE(cnf->accept_ra_pinfo);
5700 #ifdef CONFIG_IPV6_ROUTER_PREF
5701 	array[DEVCONF_ACCEPT_RA_RTR_PREF] = READ_ONCE(cnf->accept_ra_rtr_pref);
5702 	array[DEVCONF_RTR_PROBE_INTERVAL] =
5703 		jiffies_to_msecs(READ_ONCE(cnf->rtr_probe_interval));
5704 #ifdef CONFIG_IPV6_ROUTE_INFO
5705 	array[DEVCONF_ACCEPT_RA_RT_INFO_MIN_PLEN] =
5706 		READ_ONCE(cnf->accept_ra_rt_info_min_plen);
5707 	array[DEVCONF_ACCEPT_RA_RT_INFO_MAX_PLEN] =
5708 		READ_ONCE(cnf->accept_ra_rt_info_max_plen);
5709 #endif
5710 #endif
5711 	array[DEVCONF_PROXY_NDP] = READ_ONCE(cnf->proxy_ndp);
5712 	array[DEVCONF_ACCEPT_SOURCE_ROUTE] =
5713 		READ_ONCE(cnf->accept_source_route);
5714 #ifdef CONFIG_IPV6_OPTIMISTIC_DAD
5715 	array[DEVCONF_OPTIMISTIC_DAD] = READ_ONCE(cnf->optimistic_dad);
5716 	array[DEVCONF_USE_OPTIMISTIC] = READ_ONCE(cnf->use_optimistic);
5717 #endif
5718 #ifdef CONFIG_IPV6_MROUTE
5719 	array[DEVCONF_MC_FORWARDING] = atomic_read(&cnf->mc_forwarding);
5720 #endif
5721 	array[DEVCONF_DISABLE_IPV6] = READ_ONCE(cnf->disable_ipv6);
5722 	array[DEVCONF_ACCEPT_DAD] = READ_ONCE(cnf->accept_dad);
5723 	array[DEVCONF_FORCE_TLLAO] = READ_ONCE(cnf->force_tllao);
5724 	array[DEVCONF_NDISC_NOTIFY] = READ_ONCE(cnf->ndisc_notify);
5725 	array[DEVCONF_SUPPRESS_FRAG_NDISC] =
5726 		READ_ONCE(cnf->suppress_frag_ndisc);
5727 	array[DEVCONF_ACCEPT_RA_FROM_LOCAL] =
5728 		READ_ONCE(cnf->accept_ra_from_local);
5729 	array[DEVCONF_ACCEPT_RA_MTU] = READ_ONCE(cnf->accept_ra_mtu);
5730 	array[DEVCONF_IGNORE_ROUTES_WITH_LINKDOWN] =
5731 		READ_ONCE(cnf->ignore_routes_with_linkdown);
5732 	/* we omit DEVCONF_STABLE_SECRET for now */
5733 	array[DEVCONF_USE_OIF_ADDRS_ONLY] = READ_ONCE(cnf->use_oif_addrs_only);
5734 	array[DEVCONF_DROP_UNICAST_IN_L2_MULTICAST] =
5735 		READ_ONCE(cnf->drop_unicast_in_l2_multicast);
5736 	array[DEVCONF_DROP_UNSOLICITED_NA] = READ_ONCE(cnf->drop_unsolicited_na);
5737 	array[DEVCONF_KEEP_ADDR_ON_DOWN] = READ_ONCE(cnf->keep_addr_on_down);
5738 	array[DEVCONF_SEG6_ENABLED] = READ_ONCE(cnf->seg6_enabled);
5739 #ifdef CONFIG_IPV6_SEG6_HMAC
5740 	array[DEVCONF_SEG6_REQUIRE_HMAC] = READ_ONCE(cnf->seg6_require_hmac);
5741 #endif
5742 	array[DEVCONF_ENHANCED_DAD] = READ_ONCE(cnf->enhanced_dad);
5743 	array[DEVCONF_ADDR_GEN_MODE] = READ_ONCE(cnf->addr_gen_mode);
5744 	array[DEVCONF_DISABLE_POLICY] = READ_ONCE(cnf->disable_policy);
5745 	array[DEVCONF_NDISC_TCLASS] = READ_ONCE(cnf->ndisc_tclass);
5746 	array[DEVCONF_RPL_SEG_ENABLED] = READ_ONCE(cnf->rpl_seg_enabled);
5747 	array[DEVCONF_IOAM6_ENABLED] = READ_ONCE(cnf->ioam6_enabled);
5748 	array[DEVCONF_IOAM6_ID] = READ_ONCE(cnf->ioam6_id);
5749 	array[DEVCONF_IOAM6_ID_WIDE] = READ_ONCE(cnf->ioam6_id_wide);
5750 	array[DEVCONF_NDISC_EVICT_NOCARRIER] =
5751 		READ_ONCE(cnf->ndisc_evict_nocarrier);
5752 	array[DEVCONF_ACCEPT_UNTRACKED_NA] =
5753 		READ_ONCE(cnf->accept_untracked_na);
5754 	array[DEVCONF_ACCEPT_RA_MIN_LFT] = READ_ONCE(cnf->accept_ra_min_lft);
5755 	array[DEVCONF_FORCE_FORWARDING] = READ_ONCE(cnf->force_forwarding);
5756 }
5757 
inet6_ifla6_size(void)5758 static inline size_t inet6_ifla6_size(void)
5759 {
5760 	return nla_total_size(4) /* IFLA_INET6_FLAGS */
5761 	     + nla_total_size(sizeof(struct ifla_cacheinfo))
5762 	     + nla_total_size(DEVCONF_MAX * 4) /* IFLA_INET6_CONF */
5763 	     + nla_total_size(IPSTATS_MIB_MAX * 8) /* IFLA_INET6_STATS */
5764 	     + nla_total_size(ICMP6_MIB_MAX * 8) /* IFLA_INET6_ICMP6STATS */
5765 	     + nla_total_size(sizeof(struct in6_addr)) /* IFLA_INET6_TOKEN */
5766 	     + nla_total_size(1) /* IFLA_INET6_ADDR_GEN_MODE */
5767 	     + nla_total_size(4) /* IFLA_INET6_RA_MTU */
5768 	     + 0;
5769 }
5770 
inet6_if_nlmsg_size(void)5771 static inline size_t inet6_if_nlmsg_size(void)
5772 {
5773 	return NLMSG_ALIGN(sizeof(struct ifinfomsg))
5774 	       + nla_total_size(IFNAMSIZ) /* IFLA_IFNAME */
5775 	       + nla_total_size(MAX_ADDR_LEN) /* IFLA_ADDRESS */
5776 	       + nla_total_size(4) /* IFLA_MTU */
5777 	       + nla_total_size(4) /* IFLA_LINK */
5778 	       + nla_total_size(1) /* IFLA_OPERSTATE */
5779 	       + nla_total_size(inet6_ifla6_size()); /* IFLA_PROTINFO */
5780 }
5781 
__snmp6_fill_statsdev(u64 * stats,atomic_long_t * mib,int bytes)5782 static inline void __snmp6_fill_statsdev(u64 *stats, atomic_long_t *mib,
5783 					int bytes)
5784 {
5785 	int i;
5786 	int pad = bytes - sizeof(u64) * ICMP6_MIB_MAX;
5787 	BUG_ON(pad < 0);
5788 
5789 	/* Use put_unaligned() because stats may not be aligned for u64. */
5790 	put_unaligned(ICMP6_MIB_MAX, &stats[0]);
5791 	for (i = 1; i < ICMP6_MIB_MAX; i++)
5792 		put_unaligned(atomic_long_read(&mib[i]), &stats[i]);
5793 
5794 	memset(&stats[ICMP6_MIB_MAX], 0, pad);
5795 }
5796 
__snmp6_fill_stats64(u64 * stats,void __percpu * mib,int bytes,size_t syncpoff)5797 static inline void __snmp6_fill_stats64(u64 *stats, void __percpu *mib,
5798 					int bytes, size_t syncpoff)
5799 {
5800 	int i, c;
5801 	u64 buff[IPSTATS_MIB_MAX];
5802 	int pad = bytes - sizeof(u64) * IPSTATS_MIB_MAX;
5803 
5804 	BUG_ON(pad < 0);
5805 
5806 	memset(buff, 0, sizeof(buff));
5807 	buff[0] = IPSTATS_MIB_MAX;
5808 
5809 	for_each_possible_cpu(c) {
5810 		for (i = 1; i < IPSTATS_MIB_MAX; i++)
5811 			buff[i] += snmp_get_cpu_field64(mib, c, i, syncpoff);
5812 	}
5813 
5814 	memcpy(stats, buff, IPSTATS_MIB_MAX * sizeof(u64));
5815 	memset(&stats[IPSTATS_MIB_MAX], 0, pad);
5816 }
5817 
snmp6_fill_stats(u64 * stats,struct inet6_dev * idev,int attrtype,int bytes)5818 static void snmp6_fill_stats(u64 *stats, struct inet6_dev *idev, int attrtype,
5819 			     int bytes)
5820 {
5821 	switch (attrtype) {
5822 	case IFLA_INET6_STATS:
5823 		__snmp6_fill_stats64(stats, idev->stats.ipv6, bytes,
5824 				     offsetof(struct ipstats_mib, syncp));
5825 		break;
5826 	case IFLA_INET6_ICMP6STATS:
5827 		__snmp6_fill_statsdev(stats, idev->stats.icmpv6dev->mibs, bytes);
5828 		break;
5829 	}
5830 }
5831 
inet6_fill_ifla6_stats_attrs(struct sk_buff * skb,struct inet6_dev * idev)5832 static int inet6_fill_ifla6_stats_attrs(struct sk_buff *skb,
5833 					struct inet6_dev *idev)
5834 {
5835 	struct nlattr *nla;
5836 
5837 	nla = nla_reserve(skb, IFLA_INET6_STATS, IPSTATS_MIB_MAX * sizeof(u64));
5838 	if (!nla)
5839 		goto nla_put_failure;
5840 	snmp6_fill_stats(nla_data(nla), idev, IFLA_INET6_STATS, nla_len(nla));
5841 
5842 	nla = nla_reserve(skb, IFLA_INET6_ICMP6STATS, ICMP6_MIB_MAX * sizeof(u64));
5843 	if (!nla)
5844 		goto nla_put_failure;
5845 	snmp6_fill_stats(nla_data(nla), idev, IFLA_INET6_ICMP6STATS, nla_len(nla));
5846 
5847 	return 0;
5848 
5849 nla_put_failure:
5850 	return -EMSGSIZE;
5851 }
5852 
inet6_fill_ifla6_attrs(struct sk_buff * skb,struct inet6_dev * idev,u32 ext_filter_mask)5853 static int inet6_fill_ifla6_attrs(struct sk_buff *skb, struct inet6_dev *idev,
5854 				  u32 ext_filter_mask)
5855 {
5856 	struct ifla_cacheinfo ci;
5857 	struct nlattr *nla;
5858 	u32 ra_mtu;
5859 
5860 	if (nla_put_u32(skb, IFLA_INET6_FLAGS, READ_ONCE(idev->if_flags)))
5861 		goto nla_put_failure;
5862 	ci.max_reasm_len = IPV6_MAXPLEN;
5863 	ci.tstamp = cstamp_delta(READ_ONCE(idev->tstamp));
5864 	ci.reachable_time = jiffies_to_msecs(idev->nd_parms->reachable_time);
5865 	ci.retrans_time = jiffies_to_msecs(NEIGH_VAR(idev->nd_parms, RETRANS_TIME));
5866 	if (nla_put(skb, IFLA_INET6_CACHEINFO, sizeof(ci), &ci))
5867 		goto nla_put_failure;
5868 	nla = nla_reserve(skb, IFLA_INET6_CONF, DEVCONF_MAX * sizeof(s32));
5869 	if (!nla)
5870 		goto nla_put_failure;
5871 	ipv6_store_devconf(&idev->cnf, nla_data(nla), nla_len(nla));
5872 
5873 	/* XXX - MC not implemented */
5874 
5875 	if (!(ext_filter_mask & RTEXT_FILTER_SKIP_STATS)) {
5876 		if (inet6_fill_ifla6_stats_attrs(skb, idev) < 0)
5877 			goto nla_put_failure;
5878 	}
5879 
5880 	nla = nla_reserve(skb, IFLA_INET6_TOKEN, sizeof(struct in6_addr));
5881 	if (!nla)
5882 		goto nla_put_failure;
5883 	read_lock_bh(&idev->lock);
5884 	memcpy(nla_data(nla), idev->token.s6_addr, nla_len(nla));
5885 	read_unlock_bh(&idev->lock);
5886 
5887 	if (nla_put_u8(skb, IFLA_INET6_ADDR_GEN_MODE,
5888 		       READ_ONCE(idev->cnf.addr_gen_mode)))
5889 		goto nla_put_failure;
5890 
5891 	ra_mtu = READ_ONCE(idev->ra_mtu);
5892 	if (ra_mtu && nla_put_u32(skb, IFLA_INET6_RA_MTU, ra_mtu))
5893 		goto nla_put_failure;
5894 
5895 	return 0;
5896 
5897 nla_put_failure:
5898 	return -EMSGSIZE;
5899 }
5900 
inet6_get_link_af_size(const struct net_device * dev,u32 ext_filter_mask)5901 static size_t inet6_get_link_af_size(const struct net_device *dev,
5902 				     u32 ext_filter_mask)
5903 {
5904 	if (!__in6_dev_get(dev))
5905 		return 0;
5906 
5907 	return inet6_ifla6_size();
5908 }
5909 
inet6_fill_link_af(struct sk_buff * skb,const struct net_device * dev,u32 ext_filter_mask)5910 static int inet6_fill_link_af(struct sk_buff *skb, const struct net_device *dev,
5911 			      u32 ext_filter_mask)
5912 {
5913 	struct inet6_dev *idev = __in6_dev_get(dev);
5914 
5915 	if (!idev)
5916 		return -ENODATA;
5917 
5918 	if (inet6_fill_ifla6_attrs(skb, idev, ext_filter_mask) < 0)
5919 		return -EMSGSIZE;
5920 
5921 	return 0;
5922 }
5923 
inet6_set_iftoken(struct inet6_dev * idev,struct in6_addr * token,struct netlink_ext_ack * extack)5924 static int inet6_set_iftoken(struct inet6_dev *idev, struct in6_addr *token,
5925 			     struct netlink_ext_ack *extack)
5926 {
5927 	struct inet6_ifaddr *ifp;
5928 	struct net_device *dev = idev->dev;
5929 	bool clear_token, update_rs = false;
5930 	struct in6_addr ll_addr;
5931 
5932 	ASSERT_RTNL();
5933 
5934 	if (!token)
5935 		return -EINVAL;
5936 
5937 	if (dev->flags & IFF_LOOPBACK) {
5938 		NL_SET_ERR_MSG_MOD(extack, "Device is loopback");
5939 		return -EINVAL;
5940 	}
5941 
5942 	if (dev->flags & IFF_NOARP) {
5943 		NL_SET_ERR_MSG_MOD(extack,
5944 				   "Device does not do neighbour discovery");
5945 		return -EINVAL;
5946 	}
5947 
5948 	if (!ipv6_accept_ra(idev)) {
5949 		NL_SET_ERR_MSG_MOD(extack,
5950 				   "Router advertisement is disabled on device");
5951 		return -EINVAL;
5952 	}
5953 
5954 	if (READ_ONCE(idev->cnf.rtr_solicits) == 0) {
5955 		NL_SET_ERR_MSG(extack,
5956 			       "Router solicitation is disabled on device");
5957 		return -EINVAL;
5958 	}
5959 
5960 	write_lock_bh(&idev->lock);
5961 
5962 	BUILD_BUG_ON(sizeof(token->s6_addr) != 16);
5963 	memcpy(idev->token.s6_addr + 8, token->s6_addr + 8, 8);
5964 
5965 	write_unlock_bh(&idev->lock);
5966 
5967 	clear_token = ipv6_addr_any(token);
5968 	if (clear_token)
5969 		goto update_lft;
5970 
5971 	if (!idev->dead && (idev->if_flags & IF_READY) &&
5972 	    !ipv6_get_lladdr(dev, &ll_addr, IFA_F_TENTATIVE |
5973 			     IFA_F_OPTIMISTIC)) {
5974 		/* If we're not ready, then normal ifup will take care
5975 		 * of this. Otherwise, we need to request our rs here.
5976 		 */
5977 		ndisc_send_rs(dev, &ll_addr, &in6addr_linklocal_allrouters);
5978 		update_rs = true;
5979 	}
5980 
5981 update_lft:
5982 	write_lock_bh(&idev->lock);
5983 
5984 	if (update_rs) {
5985 		idev->if_flags |= IF_RS_SENT;
5986 		idev->rs_interval = rfc3315_s14_backoff_init(
5987 			READ_ONCE(idev->cnf.rtr_solicit_interval));
5988 		idev->rs_probes = 1;
5989 		addrconf_mod_rs_timer(idev, idev->rs_interval);
5990 	}
5991 
5992 	/* Well, that's kinda nasty ... */
5993 	list_for_each_entry(ifp, &idev->addr_list, if_list) {
5994 		spin_lock(&ifp->lock);
5995 		if (ifp->tokenized) {
5996 			ifp->valid_lft = 0;
5997 			ifp->prefered_lft = 0;
5998 		}
5999 		spin_unlock(&ifp->lock);
6000 	}
6001 
6002 	write_unlock_bh(&idev->lock);
6003 	inet6_ifinfo_notify(RTM_NEWLINK, idev);
6004 	addrconf_verify_rtnl(dev_net(dev));
6005 	return 0;
6006 }
6007 
6008 static const struct nla_policy inet6_af_policy[IFLA_INET6_MAX + 1] = {
6009 	[IFLA_INET6_ADDR_GEN_MODE]	= { .type = NLA_U8 },
6010 	[IFLA_INET6_TOKEN]		= { .len = sizeof(struct in6_addr) },
6011 	[IFLA_INET6_RA_MTU]		= { .type = NLA_REJECT,
6012 					    .reject_message =
6013 						"IFLA_INET6_RA_MTU can not be set" },
6014 };
6015 
check_addr_gen_mode(int mode)6016 static int check_addr_gen_mode(int mode)
6017 {
6018 	if (mode != IN6_ADDR_GEN_MODE_EUI64 &&
6019 	    mode != IN6_ADDR_GEN_MODE_NONE &&
6020 	    mode != IN6_ADDR_GEN_MODE_STABLE_PRIVACY &&
6021 	    mode != IN6_ADDR_GEN_MODE_RANDOM)
6022 		return -EINVAL;
6023 	return 1;
6024 }
6025 
check_stable_privacy(struct inet6_dev * idev,struct net * net,int mode)6026 static int check_stable_privacy(struct inet6_dev *idev, struct net *net,
6027 				int mode)
6028 {
6029 	if (mode == IN6_ADDR_GEN_MODE_STABLE_PRIVACY &&
6030 	    !idev->cnf.stable_secret.initialized &&
6031 	    !net->ipv6.devconf_dflt->stable_secret.initialized)
6032 		return -EINVAL;
6033 	return 1;
6034 }
6035 
inet6_validate_link_af(const struct net_device * dev,const struct nlattr * nla,struct netlink_ext_ack * extack)6036 static int inet6_validate_link_af(const struct net_device *dev,
6037 				  const struct nlattr *nla,
6038 				  struct netlink_ext_ack *extack)
6039 {
6040 	struct nlattr *tb[IFLA_INET6_MAX + 1];
6041 	struct inet6_dev *idev = NULL;
6042 	int err;
6043 
6044 	if (dev) {
6045 		idev = __in6_dev_get(dev);
6046 		if (!idev)
6047 			return -EAFNOSUPPORT;
6048 	}
6049 
6050 	err = nla_parse_nested_deprecated(tb, IFLA_INET6_MAX, nla,
6051 					  inet6_af_policy, extack);
6052 	if (err)
6053 		return err;
6054 
6055 	if (!tb[IFLA_INET6_TOKEN] && !tb[IFLA_INET6_ADDR_GEN_MODE])
6056 		return -EINVAL;
6057 
6058 	if (tb[IFLA_INET6_ADDR_GEN_MODE]) {
6059 		u8 mode = nla_get_u8(tb[IFLA_INET6_ADDR_GEN_MODE]);
6060 
6061 		if (check_addr_gen_mode(mode) < 0)
6062 			return -EINVAL;
6063 		if (dev && check_stable_privacy(idev, dev_net(dev), mode) < 0)
6064 			return -EINVAL;
6065 	}
6066 
6067 	return 0;
6068 }
6069 
inet6_set_link_af(struct net_device * dev,const struct nlattr * nla,struct netlink_ext_ack * extack)6070 static int inet6_set_link_af(struct net_device *dev, const struct nlattr *nla,
6071 			     struct netlink_ext_ack *extack)
6072 {
6073 	struct inet6_dev *idev = __in6_dev_get(dev);
6074 	struct nlattr *tb[IFLA_INET6_MAX + 1];
6075 	int err;
6076 
6077 	if (!idev)
6078 		return -EAFNOSUPPORT;
6079 
6080 	if (nla_parse_nested_deprecated(tb, IFLA_INET6_MAX, nla, NULL, NULL) < 0)
6081 		return -EINVAL;
6082 
6083 	if (tb[IFLA_INET6_TOKEN]) {
6084 		err = inet6_set_iftoken(idev, nla_data(tb[IFLA_INET6_TOKEN]),
6085 					extack);
6086 		if (err)
6087 			return err;
6088 	}
6089 
6090 	if (tb[IFLA_INET6_ADDR_GEN_MODE]) {
6091 		u8 mode = nla_get_u8(tb[IFLA_INET6_ADDR_GEN_MODE]);
6092 
6093 		WRITE_ONCE(idev->cnf.addr_gen_mode, mode);
6094 	}
6095 
6096 	return 0;
6097 }
6098 
inet6_fill_ifinfo(struct sk_buff * skb,struct inet6_dev * idev,u32 portid,u32 seq,int event,unsigned int flags)6099 static int inet6_fill_ifinfo(struct sk_buff *skb, struct inet6_dev *idev,
6100 			     u32 portid, u32 seq, int event, unsigned int flags)
6101 {
6102 	struct net_device *dev = idev->dev;
6103 	struct ifinfomsg *hdr;
6104 	struct nlmsghdr *nlh;
6105 	int ifindex, iflink;
6106 	void *protoinfo;
6107 
6108 	nlh = nlmsg_put(skb, portid, seq, event, sizeof(*hdr), flags);
6109 	if (!nlh)
6110 		return -EMSGSIZE;
6111 
6112 	hdr = nlmsg_data(nlh);
6113 	hdr->ifi_family = AF_INET6;
6114 	hdr->__ifi_pad = 0;
6115 	hdr->ifi_type = dev->type;
6116 	ifindex = READ_ONCE(dev->ifindex);
6117 	hdr->ifi_index = ifindex;
6118 	hdr->ifi_flags = netif_get_flags(dev);
6119 	hdr->ifi_change = 0;
6120 
6121 	iflink = dev_get_iflink(dev);
6122 	if (nla_put_string(skb, IFLA_IFNAME, dev->name) ||
6123 	    (dev->addr_len &&
6124 	     nla_put(skb, IFLA_ADDRESS, dev->addr_len, dev->dev_addr)) ||
6125 	    nla_put_u32(skb, IFLA_MTU, READ_ONCE(dev->mtu)) ||
6126 	    (ifindex != iflink &&
6127 	     nla_put_u32(skb, IFLA_LINK, iflink)) ||
6128 	    nla_put_u8(skb, IFLA_OPERSTATE,
6129 		       netif_running(dev) ? READ_ONCE(dev->operstate) : IF_OPER_DOWN))
6130 		goto nla_put_failure;
6131 	protoinfo = nla_nest_start_noflag(skb, IFLA_PROTINFO);
6132 	if (!protoinfo)
6133 		goto nla_put_failure;
6134 
6135 	if (inet6_fill_ifla6_attrs(skb, idev, 0) < 0)
6136 		goto nla_put_failure;
6137 
6138 	nla_nest_end(skb, protoinfo);
6139 	nlmsg_end(skb, nlh);
6140 	return 0;
6141 
6142 nla_put_failure:
6143 	nlmsg_cancel(skb, nlh);
6144 	return -EMSGSIZE;
6145 }
6146 
inet6_valid_dump_ifinfo(const struct nlmsghdr * nlh,struct netlink_ext_ack * extack)6147 static int inet6_valid_dump_ifinfo(const struct nlmsghdr *nlh,
6148 				   struct netlink_ext_ack *extack)
6149 {
6150 	struct ifinfomsg *ifm;
6151 
6152 	ifm = nlmsg_payload(nlh, sizeof(*ifm));
6153 	if (!ifm) {
6154 		NL_SET_ERR_MSG_MOD(extack, "Invalid header for link dump request");
6155 		return -EINVAL;
6156 	}
6157 
6158 	if (nlmsg_attrlen(nlh, sizeof(*ifm))) {
6159 		NL_SET_ERR_MSG_MOD(extack, "Invalid data after header");
6160 		return -EINVAL;
6161 	}
6162 
6163 	if (ifm->__ifi_pad || ifm->ifi_type || ifm->ifi_flags ||
6164 	    ifm->ifi_change || ifm->ifi_index) {
6165 		NL_SET_ERR_MSG_MOD(extack, "Invalid values in header for dump request");
6166 		return -EINVAL;
6167 	}
6168 
6169 	return 0;
6170 }
6171 
inet6_dump_ifinfo(struct sk_buff * skb,struct netlink_callback * cb)6172 static int inet6_dump_ifinfo(struct sk_buff *skb, struct netlink_callback *cb)
6173 {
6174 	struct net *net = sock_net(skb->sk);
6175 	struct {
6176 		unsigned long ifindex;
6177 	} *ctx = (void *)cb->ctx;
6178 	struct net_device *dev;
6179 	struct inet6_dev *idev;
6180 	int err;
6181 
6182 	/* only requests using strict checking can pass data to
6183 	 * influence the dump
6184 	 */
6185 	if (cb->strict_check) {
6186 		err = inet6_valid_dump_ifinfo(cb->nlh, cb->extack);
6187 
6188 		if (err < 0)
6189 			return err;
6190 	}
6191 
6192 	err = 0;
6193 	rcu_read_lock();
6194 	for_each_netdev_dump(net, dev, ctx->ifindex) {
6195 		idev = __in6_dev_get(dev);
6196 		if (!idev)
6197 			continue;
6198 		err = inet6_fill_ifinfo(skb, idev,
6199 					NETLINK_CB(cb->skb).portid,
6200 					cb->nlh->nlmsg_seq,
6201 					RTM_NEWLINK, NLM_F_MULTI);
6202 		if (err < 0)
6203 			break;
6204 	}
6205 	rcu_read_unlock();
6206 
6207 	return err;
6208 }
6209 
inet6_ifinfo_notify(int event,struct inet6_dev * idev)6210 void inet6_ifinfo_notify(int event, struct inet6_dev *idev)
6211 {
6212 	struct sk_buff *skb;
6213 	struct net *net = dev_net(idev->dev);
6214 	int err = -ENOBUFS;
6215 
6216 	skb = nlmsg_new(inet6_if_nlmsg_size(), GFP_ATOMIC);
6217 	if (!skb)
6218 		goto errout;
6219 
6220 	err = inet6_fill_ifinfo(skb, idev, 0, 0, event, 0);
6221 	if (err < 0) {
6222 		/* -EMSGSIZE implies BUG in inet6_if_nlmsg_size() */
6223 		WARN_ON(err == -EMSGSIZE);
6224 		kfree_skb(skb);
6225 		goto errout;
6226 	}
6227 	rtnl_notify(skb, net, 0, RTNLGRP_IPV6_IFINFO, NULL, GFP_ATOMIC);
6228 	return;
6229 errout:
6230 	rtnl_set_sk_err(net, RTNLGRP_IPV6_IFINFO, err);
6231 }
6232 
inet6_prefix_nlmsg_size(void)6233 static inline size_t inet6_prefix_nlmsg_size(void)
6234 {
6235 	return NLMSG_ALIGN(sizeof(struct prefixmsg))
6236 	       + nla_total_size(sizeof(struct in6_addr))
6237 	       + nla_total_size(sizeof(struct prefix_cacheinfo));
6238 }
6239 
inet6_fill_prefix(struct sk_buff * skb,struct inet6_dev * idev,struct prefix_info * pinfo,u32 portid,u32 seq,int event,unsigned int flags)6240 static int inet6_fill_prefix(struct sk_buff *skb, struct inet6_dev *idev,
6241 			     struct prefix_info *pinfo, u32 portid, u32 seq,
6242 			     int event, unsigned int flags)
6243 {
6244 	struct prefixmsg *pmsg;
6245 	struct nlmsghdr *nlh;
6246 	struct prefix_cacheinfo	ci;
6247 
6248 	nlh = nlmsg_put(skb, portid, seq, event, sizeof(*pmsg), flags);
6249 	if (!nlh)
6250 		return -EMSGSIZE;
6251 
6252 	pmsg = nlmsg_data(nlh);
6253 	pmsg->prefix_family = AF_INET6;
6254 	pmsg->prefix_pad1 = 0;
6255 	pmsg->prefix_pad2 = 0;
6256 	pmsg->prefix_ifindex = idev->dev->ifindex;
6257 	pmsg->prefix_len = pinfo->prefix_len;
6258 	pmsg->prefix_type = pinfo->type;
6259 	pmsg->prefix_pad3 = 0;
6260 	pmsg->prefix_flags = pinfo->flags;
6261 
6262 	if (nla_put(skb, PREFIX_ADDRESS, sizeof(pinfo->prefix), &pinfo->prefix))
6263 		goto nla_put_failure;
6264 	ci.preferred_time = ntohl(pinfo->prefered);
6265 	ci.valid_time = ntohl(pinfo->valid);
6266 	if (nla_put(skb, PREFIX_CACHEINFO, sizeof(ci), &ci))
6267 		goto nla_put_failure;
6268 	nlmsg_end(skb, nlh);
6269 	return 0;
6270 
6271 nla_put_failure:
6272 	nlmsg_cancel(skb, nlh);
6273 	return -EMSGSIZE;
6274 }
6275 
inet6_prefix_notify(int event,struct inet6_dev * idev,struct prefix_info * pinfo)6276 static void inet6_prefix_notify(int event, struct inet6_dev *idev,
6277 			 struct prefix_info *pinfo)
6278 {
6279 	struct sk_buff *skb;
6280 	struct net *net = dev_net(idev->dev);
6281 	int err = -ENOBUFS;
6282 
6283 	skb = nlmsg_new(inet6_prefix_nlmsg_size(), GFP_ATOMIC);
6284 	if (!skb)
6285 		goto errout;
6286 
6287 	err = inet6_fill_prefix(skb, idev, pinfo, 0, 0, event, 0);
6288 	if (err < 0) {
6289 		/* -EMSGSIZE implies BUG in inet6_prefix_nlmsg_size() */
6290 		WARN_ON(err == -EMSGSIZE);
6291 		kfree_skb(skb);
6292 		goto errout;
6293 	}
6294 	rtnl_notify(skb, net, 0, RTNLGRP_IPV6_PREFIX, NULL, GFP_ATOMIC);
6295 	return;
6296 errout:
6297 	rtnl_set_sk_err(net, RTNLGRP_IPV6_PREFIX, err);
6298 }
6299 
__ipv6_ifa_notify(int event,struct inet6_ifaddr * ifp)6300 static void __ipv6_ifa_notify(int event, struct inet6_ifaddr *ifp)
6301 {
6302 	struct net *net = dev_net(ifp->idev->dev);
6303 
6304 	if (event)
6305 		ASSERT_RTNL();
6306 
6307 	inet6_ifa_notify(event ? : RTM_NEWADDR, ifp);
6308 
6309 	switch (event) {
6310 	case RTM_NEWADDR:
6311 		/*
6312 		 * If the address was optimistic we inserted the route at the
6313 		 * start of our DAD process, so we don't need to do it again.
6314 		 * If the device was taken down in the middle of the DAD
6315 		 * cycle there is a race where we could get here without a
6316 		 * host route, so nothing to insert. That will be fixed when
6317 		 * the device is brought up.
6318 		 */
6319 		if (ifp->rt && !rcu_access_pointer(ifp->rt->fib6_node)) {
6320 			ip6_ins_rt(net, ifp->rt);
6321 		} else if (!ifp->rt && (ifp->idev->dev->flags & IFF_UP)) {
6322 			pr_warn("BUG: Address %pI6c on device %s is missing its host route.\n",
6323 				&ifp->addr, ifp->idev->dev->name);
6324 		}
6325 
6326 		if (ifp->idev->cnf.forwarding)
6327 			addrconf_join_anycast(ifp);
6328 		if (!ipv6_addr_any(&ifp->peer_addr))
6329 			addrconf_prefix_route(&ifp->peer_addr, 128,
6330 					      ifp->rt_priority, ifp->idev->dev,
6331 					      0, 0, GFP_ATOMIC);
6332 		break;
6333 	case RTM_DELADDR:
6334 		if (ifp->idev->cnf.forwarding)
6335 			addrconf_leave_anycast(ifp);
6336 		addrconf_leave_solict(ifp->idev, &ifp->addr);
6337 		if (!ipv6_addr_any(&ifp->peer_addr)) {
6338 			struct fib6_info *rt;
6339 
6340 			rt = addrconf_get_prefix_route(&ifp->peer_addr, 128,
6341 						       ifp->idev->dev, 0, 0,
6342 						       false);
6343 			if (rt)
6344 				ip6_del_rt(net, rt, false);
6345 		}
6346 		if (ifp->rt) {
6347 			ip6_del_rt(net, ifp->rt, false);
6348 			ifp->rt = NULL;
6349 		}
6350 		rt_genid_bump_ipv6(net);
6351 		break;
6352 	}
6353 	atomic_inc(&net->ipv6.dev_addr_genid);
6354 }
6355 
ipv6_ifa_notify(int event,struct inet6_ifaddr * ifp)6356 static void ipv6_ifa_notify(int event, struct inet6_ifaddr *ifp)
6357 {
6358 	if (likely(ifp->idev->dead == 0))
6359 		__ipv6_ifa_notify(event, ifp);
6360 }
6361 
6362 #ifdef CONFIG_SYSCTL
6363 
addrconf_sysctl_forward(const struct ctl_table * ctl,int write,void * buffer,size_t * lenp,loff_t * ppos)6364 static int addrconf_sysctl_forward(const struct ctl_table *ctl, int write,
6365 		void *buffer, size_t *lenp, loff_t *ppos)
6366 {
6367 	struct ctl_table lctl;
6368 	int *valp = ctl->data;
6369 	int val = *valp;
6370 	int ret;
6371 
6372 	/*
6373 	 * ctl->data points to idev->cnf.forwarding, we should
6374 	 * not modify it until we get the rtnl lock.
6375 	 */
6376 	lctl = *ctl;
6377 	lctl.data = &val;
6378 
6379 	ret = proc_dointvec(&lctl, write, buffer, lenp, ppos);
6380 	if (ret)
6381 		return ret;
6382 
6383 	if (write)
6384 		ret = addrconf_fixup_forwarding(ctl, valp, val);
6385 	return ret;
6386 }
6387 
addrconf_sysctl_mtu(const struct ctl_table * ctl,int write,void * buffer,size_t * lenp,loff_t * ppos)6388 static int addrconf_sysctl_mtu(const struct ctl_table *ctl, int write,
6389 		void *buffer, size_t *lenp, loff_t *ppos)
6390 {
6391 	struct inet6_dev *idev = ctl->extra1;
6392 	int min_mtu = IPV6_MIN_MTU;
6393 	struct ctl_table lctl;
6394 
6395 	lctl = *ctl;
6396 	lctl.extra1 = &min_mtu;
6397 	lctl.extra2 = idev ? &idev->dev->mtu : NULL;
6398 
6399 	return proc_dointvec_minmax(&lctl, write, buffer, lenp, ppos);
6400 }
6401 
dev_disable_change(struct inet6_dev * idev)6402 static void dev_disable_change(struct inet6_dev *idev)
6403 {
6404 	struct netdev_notifier_info info;
6405 
6406 	if (!idev || !idev->dev)
6407 		return;
6408 
6409 	netdev_notifier_info_init(&info, idev->dev);
6410 	if (idev->cnf.disable_ipv6)
6411 		addrconf_notify(NULL, NETDEV_DOWN, &info);
6412 	else
6413 		addrconf_notify(NULL, NETDEV_UP, &info);
6414 }
6415 
addrconf_disable_change(struct net * net,__s32 newf)6416 static void addrconf_disable_change(struct net *net, __s32 newf)
6417 {
6418 	struct net_device *dev;
6419 	struct inet6_dev *idev;
6420 
6421 	for_each_netdev(net, dev) {
6422 		idev = __in6_dev_get_rtnl_net(dev);
6423 		if (idev) {
6424 			int changed = (!idev->cnf.disable_ipv6) ^ (!newf);
6425 
6426 			WRITE_ONCE(idev->cnf.disable_ipv6, newf);
6427 			if (changed)
6428 				dev_disable_change(idev);
6429 		}
6430 	}
6431 }
6432 
addrconf_disable_ipv6(const struct ctl_table * table,int * p,int newf)6433 static int addrconf_disable_ipv6(const struct ctl_table *table, int *p, int newf)
6434 {
6435 	struct net *net = (struct net *)table->extra2;
6436 	int old;
6437 
6438 	if (p == &net->ipv6.devconf_dflt->disable_ipv6) {
6439 		WRITE_ONCE(*p, newf);
6440 		return 0;
6441 	}
6442 
6443 	if (!rtnl_net_trylock(net))
6444 		return restart_syscall();
6445 
6446 	old = *p;
6447 	WRITE_ONCE(*p, newf);
6448 
6449 	if (p == &net->ipv6.devconf_all->disable_ipv6) {
6450 		WRITE_ONCE(net->ipv6.devconf_dflt->disable_ipv6, newf);
6451 		addrconf_disable_change(net, newf);
6452 	} else if ((!newf) ^ (!old)) {
6453 		dev_disable_change((struct inet6_dev *)table->extra1);
6454 	}
6455 
6456 	rtnl_net_unlock(net);
6457 	return 0;
6458 }
6459 
addrconf_sysctl_disable(const struct ctl_table * ctl,int write,void * buffer,size_t * lenp,loff_t * ppos)6460 static int addrconf_sysctl_disable(const struct ctl_table *ctl, int write,
6461 		void *buffer, size_t *lenp, loff_t *ppos)
6462 {
6463 	struct ctl_table lctl;
6464 	int *valp = ctl->data;
6465 	int val = *valp;
6466 	int ret;
6467 
6468 	/*
6469 	 * ctl->data points to idev->cnf.disable_ipv6, we should
6470 	 * not modify it until we get the rtnl lock.
6471 	 */
6472 	lctl = *ctl;
6473 	lctl.data = &val;
6474 
6475 	ret = proc_dointvec(&lctl, write, buffer, lenp, ppos);
6476 	if (ret)
6477 		return ret;
6478 
6479 	if (write)
6480 		ret = addrconf_disable_ipv6(ctl, valp, val);
6481 	return ret;
6482 }
6483 
addrconf_sysctl_proxy_ndp(const struct ctl_table * ctl,int write,void * buffer,size_t * lenp,loff_t * ppos)6484 static int addrconf_sysctl_proxy_ndp(const struct ctl_table *ctl, int write,
6485 		void *buffer, size_t *lenp, loff_t *ppos)
6486 {
6487 	struct net *net = ctl->extra2;
6488 	int *valp = ctl->data;
6489 	int old, new;
6490 	int ret;
6491 
6492 	if (write && !rtnl_net_trylock(net))
6493 		return restart_syscall();
6494 
6495 	old = *valp;
6496 	ret = proc_dointvec(ctl, write, buffer, lenp, ppos);
6497 	new = *valp;
6498 
6499 	if (write && old != new) {
6500 		if (valp == &net->ipv6.devconf_dflt->proxy_ndp) {
6501 			inet6_netconf_notify_devconf(net, RTM_NEWNETCONF,
6502 						     NETCONFA_PROXY_NEIGH,
6503 						     NETCONFA_IFINDEX_DEFAULT,
6504 						     net->ipv6.devconf_dflt);
6505 		} else if (valp == &net->ipv6.devconf_all->proxy_ndp) {
6506 			inet6_netconf_notify_devconf(net, RTM_NEWNETCONF,
6507 						     NETCONFA_PROXY_NEIGH,
6508 						     NETCONFA_IFINDEX_ALL,
6509 						     net->ipv6.devconf_all);
6510 		} else {
6511 			struct inet6_dev *idev = ctl->extra1;
6512 
6513 			inet6_netconf_notify_devconf(net, RTM_NEWNETCONF,
6514 						     NETCONFA_PROXY_NEIGH,
6515 						     idev->dev->ifindex,
6516 						     &idev->cnf);
6517 		}
6518 	}
6519 	if (write)
6520 		rtnl_net_unlock(net);
6521 
6522 	return ret;
6523 }
6524 
addrconf_sysctl_addr_gen_mode(const struct ctl_table * ctl,int write,void * buffer,size_t * lenp,loff_t * ppos)6525 static int addrconf_sysctl_addr_gen_mode(const struct ctl_table *ctl, int write,
6526 					 void *buffer, size_t *lenp,
6527 					 loff_t *ppos)
6528 {
6529 	int ret = 0;
6530 	u32 new_val;
6531 	struct inet6_dev *idev = (struct inet6_dev *)ctl->extra1;
6532 	struct net *net = (struct net *)ctl->extra2;
6533 	struct ctl_table tmp = {
6534 		.data = &new_val,
6535 		.maxlen = sizeof(new_val),
6536 		.mode = ctl->mode,
6537 	};
6538 
6539 	if (!rtnl_net_trylock(net))
6540 		return restart_syscall();
6541 
6542 	new_val = *((u32 *)ctl->data);
6543 
6544 	ret = proc_douintvec(&tmp, write, buffer, lenp, ppos);
6545 	if (ret != 0)
6546 		goto out;
6547 
6548 	if (write) {
6549 		if (check_addr_gen_mode(new_val) < 0) {
6550 			ret = -EINVAL;
6551 			goto out;
6552 		}
6553 
6554 		if (idev) {
6555 			if (check_stable_privacy(idev, net, new_val) < 0) {
6556 				ret = -EINVAL;
6557 				goto out;
6558 			}
6559 
6560 			if (idev->cnf.addr_gen_mode != new_val) {
6561 				WRITE_ONCE(idev->cnf.addr_gen_mode, new_val);
6562 				netdev_lock_ops(idev->dev);
6563 				addrconf_init_auto_addrs(idev->dev);
6564 				netdev_unlock_ops(idev->dev);
6565 			}
6566 		} else if (&net->ipv6.devconf_all->addr_gen_mode == ctl->data) {
6567 			struct net_device *dev;
6568 
6569 			WRITE_ONCE(net->ipv6.devconf_dflt->addr_gen_mode, new_val);
6570 			for_each_netdev(net, dev) {
6571 				idev = __in6_dev_get_rtnl_net(dev);
6572 				if (idev &&
6573 				    idev->cnf.addr_gen_mode != new_val) {
6574 					WRITE_ONCE(idev->cnf.addr_gen_mode,
6575 						  new_val);
6576 					netdev_lock_ops(idev->dev);
6577 					addrconf_init_auto_addrs(idev->dev);
6578 					netdev_unlock_ops(idev->dev);
6579 				}
6580 			}
6581 		}
6582 
6583 		WRITE_ONCE(*((u32 *)ctl->data), new_val);
6584 	}
6585 
6586 out:
6587 	rtnl_net_unlock(net);
6588 
6589 	return ret;
6590 }
6591 
addrconf_sysctl_stable_secret(const struct ctl_table * ctl,int write,void * buffer,size_t * lenp,loff_t * ppos)6592 static int addrconf_sysctl_stable_secret(const struct ctl_table *ctl, int write,
6593 					 void *buffer, size_t *lenp,
6594 					 loff_t *ppos)
6595 {
6596 	int err;
6597 	struct in6_addr addr;
6598 	char str[IPV6_MAX_STRLEN];
6599 	struct ctl_table lctl = *ctl;
6600 	struct net *net = ctl->extra2;
6601 	struct ipv6_stable_secret *secret = ctl->data;
6602 
6603 	if (&net->ipv6.devconf_all->stable_secret == ctl->data)
6604 		return -EIO;
6605 
6606 	lctl.maxlen = IPV6_MAX_STRLEN;
6607 	lctl.data = str;
6608 
6609 	if (!rtnl_net_trylock(net))
6610 		return restart_syscall();
6611 
6612 	if (!write && !secret->initialized) {
6613 		err = -EIO;
6614 		goto out;
6615 	}
6616 
6617 	err = snprintf(str, sizeof(str), "%pI6", &secret->secret);
6618 	if (err >= sizeof(str)) {
6619 		err = -EIO;
6620 		goto out;
6621 	}
6622 
6623 	err = proc_dostring(&lctl, write, buffer, lenp, ppos);
6624 	if (err || !write)
6625 		goto out;
6626 
6627 	if (in6_pton(str, -1, addr.in6_u.u6_addr8, -1, NULL) != 1) {
6628 		err = -EIO;
6629 		goto out;
6630 	}
6631 
6632 	secret->initialized = true;
6633 	secret->secret = addr;
6634 
6635 	if (&net->ipv6.devconf_dflt->stable_secret == ctl->data) {
6636 		struct net_device *dev;
6637 
6638 		for_each_netdev(net, dev) {
6639 			struct inet6_dev *idev = __in6_dev_get_rtnl_net(dev);
6640 
6641 			if (idev) {
6642 				WRITE_ONCE(idev->cnf.addr_gen_mode,
6643 					   IN6_ADDR_GEN_MODE_STABLE_PRIVACY);
6644 			}
6645 		}
6646 	} else {
6647 		struct inet6_dev *idev = ctl->extra1;
6648 
6649 		WRITE_ONCE(idev->cnf.addr_gen_mode,
6650 			   IN6_ADDR_GEN_MODE_STABLE_PRIVACY);
6651 	}
6652 
6653 out:
6654 	rtnl_net_unlock(net);
6655 
6656 	return err;
6657 }
6658 
6659 static
addrconf_sysctl_ignore_routes_with_linkdown(const struct ctl_table * ctl,int write,void * buffer,size_t * lenp,loff_t * ppos)6660 int addrconf_sysctl_ignore_routes_with_linkdown(const struct ctl_table *ctl,
6661 						int write, void *buffer,
6662 						size_t *lenp,
6663 						loff_t *ppos)
6664 {
6665 	struct ctl_table lctl;
6666 	int *valp = ctl->data;
6667 	int val = *valp;
6668 	int ret;
6669 
6670 	/* ctl->data points to idev->cnf.ignore_routes_when_linkdown
6671 	 * we should not modify it until we get the rtnl lock.
6672 	 */
6673 	lctl = *ctl;
6674 	lctl.data = &val;
6675 
6676 	ret = proc_dointvec(&lctl, write, buffer, lenp, ppos);
6677 	if (ret)
6678 		return ret;
6679 
6680 	if (write)
6681 		ret = addrconf_fixup_linkdown(ctl, valp, val);
6682 	return ret;
6683 }
6684 
6685 static
addrconf_set_nopolicy(struct rt6_info * rt,int action)6686 void addrconf_set_nopolicy(struct rt6_info *rt, int action)
6687 {
6688 	if (rt) {
6689 		if (action)
6690 			rt->dst.flags |= DST_NOPOLICY;
6691 		else
6692 			rt->dst.flags &= ~DST_NOPOLICY;
6693 	}
6694 }
6695 
6696 static
addrconf_disable_policy_idev(struct inet6_dev * idev,int val)6697 void addrconf_disable_policy_idev(struct inet6_dev *idev, int val)
6698 {
6699 	struct inet6_ifaddr *ifa;
6700 
6701 	read_lock_bh(&idev->lock);
6702 	list_for_each_entry(ifa, &idev->addr_list, if_list) {
6703 		spin_lock(&ifa->lock);
6704 		if (ifa->rt) {
6705 			/* host routes only use builtin fib6_nh */
6706 			struct fib6_nh *nh = ifa->rt->fib6_nh;
6707 			int cpu;
6708 
6709 			rcu_read_lock();
6710 			ifa->rt->dst_nopolicy = val ? true : false;
6711 			if (nh->rt6i_pcpu) {
6712 				for_each_possible_cpu(cpu) {
6713 					struct rt6_info **rtp;
6714 
6715 					rtp = per_cpu_ptr(nh->rt6i_pcpu, cpu);
6716 					addrconf_set_nopolicy(*rtp, val);
6717 				}
6718 			}
6719 			rcu_read_unlock();
6720 		}
6721 		spin_unlock(&ifa->lock);
6722 	}
6723 	read_unlock_bh(&idev->lock);
6724 }
6725 
6726 static
addrconf_disable_policy(const struct ctl_table * ctl,int * valp,int val)6727 int addrconf_disable_policy(const struct ctl_table *ctl, int *valp, int val)
6728 {
6729 	struct net *net = (struct net *)ctl->extra2;
6730 	struct inet6_dev *idev;
6731 
6732 	if (valp == &net->ipv6.devconf_dflt->disable_policy) {
6733 		WRITE_ONCE(*valp, val);
6734 		return 0;
6735 	}
6736 
6737 	if (!rtnl_net_trylock(net))
6738 		return restart_syscall();
6739 
6740 	WRITE_ONCE(*valp, val);
6741 
6742 	if (valp == &net->ipv6.devconf_all->disable_policy)  {
6743 		struct net_device *dev;
6744 
6745 		for_each_netdev(net, dev) {
6746 			idev = __in6_dev_get_rtnl_net(dev);
6747 			if (idev)
6748 				addrconf_disable_policy_idev(idev, val);
6749 		}
6750 	} else {
6751 		idev = (struct inet6_dev *)ctl->extra1;
6752 		addrconf_disable_policy_idev(idev, val);
6753 	}
6754 
6755 	rtnl_net_unlock(net);
6756 	return 0;
6757 }
6758 
addrconf_sysctl_disable_policy(const struct ctl_table * ctl,int write,void * buffer,size_t * lenp,loff_t * ppos)6759 static int addrconf_sysctl_disable_policy(const struct ctl_table *ctl, int write,
6760 				   void *buffer, size_t *lenp, loff_t *ppos)
6761 {
6762 	struct ctl_table lctl;
6763 	int *valp = ctl->data;
6764 	int val = *valp;
6765 	int ret;
6766 
6767 	lctl = *ctl;
6768 	lctl.data = &val;
6769 	ret = proc_dointvec(&lctl, write, buffer, lenp, ppos);
6770 	if (ret)
6771 		return ret;
6772 
6773 	if (write && (*valp != val))
6774 		ret = addrconf_disable_policy(ctl, valp, val);
6775 
6776 	return ret;
6777 }
6778 
addrconf_force_forward_change(struct net * net,__s32 newf)6779 static void addrconf_force_forward_change(struct net *net, __s32 newf)
6780 {
6781 	struct net_device *dev;
6782 	struct inet6_dev *idev;
6783 
6784 	for_each_netdev(net, dev) {
6785 		idev = __in6_dev_get_rtnl_net(dev);
6786 		if (idev) {
6787 			int changed = (!idev->cnf.force_forwarding) ^ (!newf);
6788 
6789 			WRITE_ONCE(idev->cnf.force_forwarding, newf);
6790 			if (changed)
6791 				inet6_netconf_notify_devconf(dev_net(dev), RTM_NEWNETCONF,
6792 							     NETCONFA_FORCE_FORWARDING,
6793 							     dev->ifindex, &idev->cnf);
6794 		}
6795 	}
6796 }
6797 
addrconf_sysctl_force_forwarding(const struct ctl_table * ctl,int write,void * buffer,size_t * lenp,loff_t * ppos)6798 static int addrconf_sysctl_force_forwarding(const struct ctl_table *ctl, int write,
6799 					    void *buffer, size_t *lenp, loff_t *ppos)
6800 {
6801 	struct inet6_dev *idev = ctl->extra1;
6802 	struct ctl_table tmp_ctl = *ctl;
6803 	struct net *net = ctl->extra2;
6804 	int *valp = ctl->data;
6805 	int new_val = *valp;
6806 	int old_val = *valp;
6807 	int ret;
6808 
6809 	tmp_ctl.extra1 = SYSCTL_ZERO;
6810 	tmp_ctl.extra2 = SYSCTL_ONE;
6811 	tmp_ctl.data = &new_val;
6812 
6813 	ret = proc_douintvec_minmax(&tmp_ctl, write, buffer, lenp, ppos);
6814 
6815 	if (write && old_val != new_val) {
6816 		if (!rtnl_net_trylock(net))
6817 			return restart_syscall();
6818 
6819 		WRITE_ONCE(*valp, new_val);
6820 
6821 		if (valp == &net->ipv6.devconf_dflt->force_forwarding) {
6822 			inet6_netconf_notify_devconf(net, RTM_NEWNETCONF,
6823 						     NETCONFA_FORCE_FORWARDING,
6824 						     NETCONFA_IFINDEX_DEFAULT,
6825 						     net->ipv6.devconf_dflt);
6826 		} else if (valp == &net->ipv6.devconf_all->force_forwarding) {
6827 			inet6_netconf_notify_devconf(net, RTM_NEWNETCONF,
6828 						     NETCONFA_FORCE_FORWARDING,
6829 						     NETCONFA_IFINDEX_ALL,
6830 						     net->ipv6.devconf_all);
6831 
6832 			addrconf_force_forward_change(net, new_val);
6833 		} else {
6834 			inet6_netconf_notify_devconf(net, RTM_NEWNETCONF,
6835 						     NETCONFA_FORCE_FORWARDING,
6836 						     idev->dev->ifindex,
6837 						     &idev->cnf);
6838 		}
6839 		rtnl_net_unlock(net);
6840 	}
6841 
6842 	return ret;
6843 }
6844 
6845 static int minus_one = -1;
6846 static const int two_five_five = 255;
6847 static u32 ioam6_if_id_max = U16_MAX;
6848 
6849 static const struct ctl_table addrconf_sysctl[] = {
6850 	{
6851 		.procname	= "forwarding",
6852 		.data		= &ipv6_devconf.forwarding,
6853 		.maxlen		= sizeof(int),
6854 		.mode		= 0644,
6855 		.proc_handler	= addrconf_sysctl_forward,
6856 	},
6857 	{
6858 		.procname	= "hop_limit",
6859 		.data		= &ipv6_devconf.hop_limit,
6860 		.maxlen		= sizeof(int),
6861 		.mode		= 0644,
6862 		.proc_handler	= proc_dointvec_minmax,
6863 		.extra1		= (void *)SYSCTL_ONE,
6864 		.extra2		= (void *)&two_five_five,
6865 	},
6866 	{
6867 		.procname	= "mtu",
6868 		.data		= &ipv6_devconf.mtu6,
6869 		.maxlen		= sizeof(int),
6870 		.mode		= 0644,
6871 		.proc_handler	= addrconf_sysctl_mtu,
6872 	},
6873 	{
6874 		.procname	= "accept_ra",
6875 		.data		= &ipv6_devconf.accept_ra,
6876 		.maxlen		= sizeof(int),
6877 		.mode		= 0644,
6878 		.proc_handler	= proc_dointvec,
6879 	},
6880 	{
6881 		.procname	= "accept_redirects",
6882 		.data		= &ipv6_devconf.accept_redirects,
6883 		.maxlen		= sizeof(int),
6884 		.mode		= 0644,
6885 		.proc_handler	= proc_dointvec,
6886 	},
6887 	{
6888 		.procname	= "autoconf",
6889 		.data		= &ipv6_devconf.autoconf,
6890 		.maxlen		= sizeof(int),
6891 		.mode		= 0644,
6892 		.proc_handler	= proc_dointvec,
6893 	},
6894 	{
6895 		.procname	= "dad_transmits",
6896 		.data		= &ipv6_devconf.dad_transmits,
6897 		.maxlen		= sizeof(int),
6898 		.mode		= 0644,
6899 		.proc_handler	= proc_dointvec,
6900 	},
6901 	{
6902 		.procname	= "router_solicitations",
6903 		.data		= &ipv6_devconf.rtr_solicits,
6904 		.maxlen		= sizeof(int),
6905 		.mode		= 0644,
6906 		.proc_handler	= proc_dointvec_minmax,
6907 		.extra1		= &minus_one,
6908 	},
6909 	{
6910 		.procname	= "router_solicitation_interval",
6911 		.data		= &ipv6_devconf.rtr_solicit_interval,
6912 		.maxlen		= sizeof(int),
6913 		.mode		= 0644,
6914 		.proc_handler	= proc_dointvec_jiffies,
6915 	},
6916 	{
6917 		.procname	= "router_solicitation_max_interval",
6918 		.data		= &ipv6_devconf.rtr_solicit_max_interval,
6919 		.maxlen		= sizeof(int),
6920 		.mode		= 0644,
6921 		.proc_handler	= proc_dointvec_jiffies,
6922 	},
6923 	{
6924 		.procname	= "router_solicitation_delay",
6925 		.data		= &ipv6_devconf.rtr_solicit_delay,
6926 		.maxlen		= sizeof(int),
6927 		.mode		= 0644,
6928 		.proc_handler	= proc_dointvec_jiffies,
6929 	},
6930 	{
6931 		.procname	= "force_mld_version",
6932 		.data		= &ipv6_devconf.force_mld_version,
6933 		.maxlen		= sizeof(int),
6934 		.mode		= 0644,
6935 		.proc_handler	= proc_dointvec,
6936 	},
6937 	{
6938 		.procname	= "mldv1_unsolicited_report_interval",
6939 		.data		=
6940 			&ipv6_devconf.mldv1_unsolicited_report_interval,
6941 		.maxlen		= sizeof(int),
6942 		.mode		= 0644,
6943 		.proc_handler	= proc_dointvec_ms_jiffies,
6944 	},
6945 	{
6946 		.procname	= "mldv2_unsolicited_report_interval",
6947 		.data		=
6948 			&ipv6_devconf.mldv2_unsolicited_report_interval,
6949 		.maxlen		= sizeof(int),
6950 		.mode		= 0644,
6951 		.proc_handler	= proc_dointvec_ms_jiffies,
6952 	},
6953 	{
6954 		.procname	= "use_tempaddr",
6955 		.data		= &ipv6_devconf.use_tempaddr,
6956 		.maxlen		= sizeof(int),
6957 		.mode		= 0644,
6958 		.proc_handler	= proc_dointvec,
6959 	},
6960 	{
6961 		.procname	= "temp_valid_lft",
6962 		.data		= &ipv6_devconf.temp_valid_lft,
6963 		.maxlen		= sizeof(int),
6964 		.mode		= 0644,
6965 		.proc_handler	= proc_dointvec,
6966 	},
6967 	{
6968 		.procname	= "temp_prefered_lft",
6969 		.data		= &ipv6_devconf.temp_prefered_lft,
6970 		.maxlen		= sizeof(int),
6971 		.mode		= 0644,
6972 		.proc_handler	= proc_dointvec,
6973 	},
6974 	{
6975 		.procname       = "regen_min_advance",
6976 		.data           = &ipv6_devconf.regen_min_advance,
6977 		.maxlen         = sizeof(int),
6978 		.mode           = 0644,
6979 		.proc_handler   = proc_dointvec,
6980 	},
6981 	{
6982 		.procname	= "regen_max_retry",
6983 		.data		= &ipv6_devconf.regen_max_retry,
6984 		.maxlen		= sizeof(int),
6985 		.mode		= 0644,
6986 		.proc_handler	= proc_dointvec,
6987 	},
6988 	{
6989 		.procname	= "max_desync_factor",
6990 		.data		= &ipv6_devconf.max_desync_factor,
6991 		.maxlen		= sizeof(int),
6992 		.mode		= 0644,
6993 		.proc_handler	= proc_dointvec,
6994 	},
6995 	{
6996 		.procname	= "max_addresses",
6997 		.data		= &ipv6_devconf.max_addresses,
6998 		.maxlen		= sizeof(int),
6999 		.mode		= 0644,
7000 		.proc_handler	= proc_dointvec,
7001 	},
7002 	{
7003 		.procname	= "accept_ra_defrtr",
7004 		.data		= &ipv6_devconf.accept_ra_defrtr,
7005 		.maxlen		= sizeof(int),
7006 		.mode		= 0644,
7007 		.proc_handler	= proc_dointvec,
7008 	},
7009 	{
7010 		.procname	= "ra_defrtr_metric",
7011 		.data		= &ipv6_devconf.ra_defrtr_metric,
7012 		.maxlen		= sizeof(u32),
7013 		.mode		= 0644,
7014 		.proc_handler	= proc_douintvec_minmax,
7015 		.extra1		= (void *)SYSCTL_ONE,
7016 	},
7017 	{
7018 		.procname	= "accept_ra_min_hop_limit",
7019 		.data		= &ipv6_devconf.accept_ra_min_hop_limit,
7020 		.maxlen		= sizeof(int),
7021 		.mode		= 0644,
7022 		.proc_handler	= proc_dointvec,
7023 	},
7024 	{
7025 		.procname	= "accept_ra_min_lft",
7026 		.data		= &ipv6_devconf.accept_ra_min_lft,
7027 		.maxlen		= sizeof(int),
7028 		.mode		= 0644,
7029 		.proc_handler	= proc_dointvec,
7030 	},
7031 	{
7032 		.procname	= "accept_ra_pinfo",
7033 		.data		= &ipv6_devconf.accept_ra_pinfo,
7034 		.maxlen		= sizeof(int),
7035 		.mode		= 0644,
7036 		.proc_handler	= proc_dointvec,
7037 	},
7038 	{
7039 		.procname	= "ra_honor_pio_life",
7040 		.data		= &ipv6_devconf.ra_honor_pio_life,
7041 		.maxlen		= sizeof(u8),
7042 		.mode		= 0644,
7043 		.proc_handler	= proc_dou8vec_minmax,
7044 		.extra1		= SYSCTL_ZERO,
7045 		.extra2		= SYSCTL_ONE,
7046 	},
7047 	{
7048 		.procname	= "ra_honor_pio_pflag",
7049 		.data		= &ipv6_devconf.ra_honor_pio_pflag,
7050 		.maxlen		= sizeof(u8),
7051 		.mode		= 0644,
7052 		.proc_handler	= proc_dou8vec_minmax,
7053 		.extra1		= SYSCTL_ZERO,
7054 		.extra2		= SYSCTL_ONE,
7055 	},
7056 #ifdef CONFIG_IPV6_ROUTER_PREF
7057 	{
7058 		.procname	= "accept_ra_rtr_pref",
7059 		.data		= &ipv6_devconf.accept_ra_rtr_pref,
7060 		.maxlen		= sizeof(int),
7061 		.mode		= 0644,
7062 		.proc_handler	= proc_dointvec,
7063 	},
7064 	{
7065 		.procname	= "router_probe_interval",
7066 		.data		= &ipv6_devconf.rtr_probe_interval,
7067 		.maxlen		= sizeof(int),
7068 		.mode		= 0644,
7069 		.proc_handler	= proc_dointvec_jiffies,
7070 	},
7071 #ifdef CONFIG_IPV6_ROUTE_INFO
7072 	{
7073 		.procname	= "accept_ra_rt_info_min_plen",
7074 		.data		= &ipv6_devconf.accept_ra_rt_info_min_plen,
7075 		.maxlen		= sizeof(int),
7076 		.mode		= 0644,
7077 		.proc_handler	= proc_dointvec,
7078 	},
7079 	{
7080 		.procname	= "accept_ra_rt_info_max_plen",
7081 		.data		= &ipv6_devconf.accept_ra_rt_info_max_plen,
7082 		.maxlen		= sizeof(int),
7083 		.mode		= 0644,
7084 		.proc_handler	= proc_dointvec,
7085 	},
7086 #endif
7087 #endif
7088 	{
7089 		.procname	= "proxy_ndp",
7090 		.data		= &ipv6_devconf.proxy_ndp,
7091 		.maxlen		= sizeof(int),
7092 		.mode		= 0644,
7093 		.proc_handler	= addrconf_sysctl_proxy_ndp,
7094 	},
7095 	{
7096 		.procname	= "accept_source_route",
7097 		.data		= &ipv6_devconf.accept_source_route,
7098 		.maxlen		= sizeof(int),
7099 		.mode		= 0644,
7100 		.proc_handler	= proc_dointvec,
7101 	},
7102 #ifdef CONFIG_IPV6_OPTIMISTIC_DAD
7103 	{
7104 		.procname	= "optimistic_dad",
7105 		.data		= &ipv6_devconf.optimistic_dad,
7106 		.maxlen		= sizeof(int),
7107 		.mode		= 0644,
7108 		.proc_handler   = proc_dointvec,
7109 	},
7110 	{
7111 		.procname	= "use_optimistic",
7112 		.data		= &ipv6_devconf.use_optimistic,
7113 		.maxlen		= sizeof(int),
7114 		.mode		= 0644,
7115 		.proc_handler	= proc_dointvec,
7116 	},
7117 #endif
7118 #ifdef CONFIG_IPV6_MROUTE
7119 	{
7120 		.procname	= "mc_forwarding",
7121 		.data		= &ipv6_devconf.mc_forwarding,
7122 		.maxlen		= sizeof(int),
7123 		.mode		= 0444,
7124 		.proc_handler	= proc_dointvec,
7125 	},
7126 #endif
7127 	{
7128 		.procname	= "disable_ipv6",
7129 		.data		= &ipv6_devconf.disable_ipv6,
7130 		.maxlen		= sizeof(int),
7131 		.mode		= 0644,
7132 		.proc_handler	= addrconf_sysctl_disable,
7133 	},
7134 	{
7135 		.procname	= "accept_dad",
7136 		.data		= &ipv6_devconf.accept_dad,
7137 		.maxlen		= sizeof(int),
7138 		.mode		= 0644,
7139 		.proc_handler	= proc_dointvec,
7140 	},
7141 	{
7142 		.procname	= "force_tllao",
7143 		.data		= &ipv6_devconf.force_tllao,
7144 		.maxlen		= sizeof(int),
7145 		.mode		= 0644,
7146 		.proc_handler	= proc_dointvec
7147 	},
7148 	{
7149 		.procname	= "ndisc_notify",
7150 		.data		= &ipv6_devconf.ndisc_notify,
7151 		.maxlen		= sizeof(int),
7152 		.mode		= 0644,
7153 		.proc_handler	= proc_dointvec
7154 	},
7155 	{
7156 		.procname	= "suppress_frag_ndisc",
7157 		.data		= &ipv6_devconf.suppress_frag_ndisc,
7158 		.maxlen		= sizeof(int),
7159 		.mode		= 0644,
7160 		.proc_handler	= proc_dointvec
7161 	},
7162 	{
7163 		.procname	= "accept_ra_from_local",
7164 		.data		= &ipv6_devconf.accept_ra_from_local,
7165 		.maxlen		= sizeof(int),
7166 		.mode		= 0644,
7167 		.proc_handler	= proc_dointvec,
7168 	},
7169 	{
7170 		.procname	= "accept_ra_mtu",
7171 		.data		= &ipv6_devconf.accept_ra_mtu,
7172 		.maxlen		= sizeof(int),
7173 		.mode		= 0644,
7174 		.proc_handler	= proc_dointvec,
7175 	},
7176 	{
7177 		.procname	= "stable_secret",
7178 		.data		= &ipv6_devconf.stable_secret,
7179 		.maxlen		= IPV6_MAX_STRLEN,
7180 		.mode		= 0600,
7181 		.proc_handler	= addrconf_sysctl_stable_secret,
7182 	},
7183 	{
7184 		.procname	= "use_oif_addrs_only",
7185 		.data		= &ipv6_devconf.use_oif_addrs_only,
7186 		.maxlen		= sizeof(int),
7187 		.mode		= 0644,
7188 		.proc_handler	= proc_dointvec,
7189 	},
7190 	{
7191 		.procname	= "ignore_routes_with_linkdown",
7192 		.data		= &ipv6_devconf.ignore_routes_with_linkdown,
7193 		.maxlen		= sizeof(int),
7194 		.mode		= 0644,
7195 		.proc_handler	= addrconf_sysctl_ignore_routes_with_linkdown,
7196 	},
7197 	{
7198 		.procname	= "drop_unicast_in_l2_multicast",
7199 		.data		= &ipv6_devconf.drop_unicast_in_l2_multicast,
7200 		.maxlen		= sizeof(int),
7201 		.mode		= 0644,
7202 		.proc_handler	= proc_dointvec,
7203 	},
7204 	{
7205 		.procname	= "drop_unsolicited_na",
7206 		.data		= &ipv6_devconf.drop_unsolicited_na,
7207 		.maxlen		= sizeof(int),
7208 		.mode		= 0644,
7209 		.proc_handler	= proc_dointvec,
7210 	},
7211 	{
7212 		.procname	= "keep_addr_on_down",
7213 		.data		= &ipv6_devconf.keep_addr_on_down,
7214 		.maxlen		= sizeof(int),
7215 		.mode		= 0644,
7216 		.proc_handler	= proc_dointvec,
7217 
7218 	},
7219 	{
7220 		.procname	= "seg6_enabled",
7221 		.data		= &ipv6_devconf.seg6_enabled,
7222 		.maxlen		= sizeof(int),
7223 		.mode		= 0644,
7224 		.proc_handler	= proc_dointvec,
7225 	},
7226 #ifdef CONFIG_IPV6_SEG6_HMAC
7227 	{
7228 		.procname	= "seg6_require_hmac",
7229 		.data		= &ipv6_devconf.seg6_require_hmac,
7230 		.maxlen		= sizeof(int),
7231 		.mode		= 0644,
7232 		.proc_handler	= proc_dointvec,
7233 	},
7234 #endif
7235 	{
7236 		.procname       = "enhanced_dad",
7237 		.data           = &ipv6_devconf.enhanced_dad,
7238 		.maxlen         = sizeof(int),
7239 		.mode           = 0644,
7240 		.proc_handler   = proc_dointvec,
7241 	},
7242 	{
7243 		.procname	= "addr_gen_mode",
7244 		.data		= &ipv6_devconf.addr_gen_mode,
7245 		.maxlen		= sizeof(int),
7246 		.mode		= 0644,
7247 		.proc_handler	= addrconf_sysctl_addr_gen_mode,
7248 	},
7249 	{
7250 		.procname       = "disable_policy",
7251 		.data           = &ipv6_devconf.disable_policy,
7252 		.maxlen         = sizeof(int),
7253 		.mode           = 0644,
7254 		.proc_handler   = addrconf_sysctl_disable_policy,
7255 	},
7256 	{
7257 		.procname	= "ndisc_tclass",
7258 		.data		= &ipv6_devconf.ndisc_tclass,
7259 		.maxlen		= sizeof(int),
7260 		.mode		= 0644,
7261 		.proc_handler	= proc_dointvec_minmax,
7262 		.extra1		= (void *)SYSCTL_ZERO,
7263 		.extra2		= (void *)&two_five_five,
7264 	},
7265 	{
7266 		.procname	= "rpl_seg_enabled",
7267 		.data		= &ipv6_devconf.rpl_seg_enabled,
7268 		.maxlen		= sizeof(int),
7269 		.mode		= 0644,
7270 		.proc_handler   = proc_dointvec_minmax,
7271 		.extra1         = SYSCTL_ZERO,
7272 		.extra2         = SYSCTL_ONE,
7273 	},
7274 	{
7275 		.procname	= "ioam6_enabled",
7276 		.data		= &ipv6_devconf.ioam6_enabled,
7277 		.maxlen		= sizeof(u8),
7278 		.mode		= 0644,
7279 		.proc_handler	= proc_dou8vec_minmax,
7280 		.extra1		= (void *)SYSCTL_ZERO,
7281 		.extra2		= (void *)SYSCTL_ONE,
7282 	},
7283 	{
7284 		.procname	= "ioam6_id",
7285 		.data		= &ipv6_devconf.ioam6_id,
7286 		.maxlen		= sizeof(u32),
7287 		.mode		= 0644,
7288 		.proc_handler	= proc_douintvec_minmax,
7289 		.extra1		= (void *)SYSCTL_ZERO,
7290 		.extra2		= (void *)&ioam6_if_id_max,
7291 	},
7292 	{
7293 		.procname	= "ioam6_id_wide",
7294 		.data		= &ipv6_devconf.ioam6_id_wide,
7295 		.maxlen		= sizeof(u32),
7296 		.mode		= 0644,
7297 		.proc_handler	= proc_douintvec,
7298 	},
7299 	{
7300 		.procname	= "ndisc_evict_nocarrier",
7301 		.data		= &ipv6_devconf.ndisc_evict_nocarrier,
7302 		.maxlen		= sizeof(u8),
7303 		.mode		= 0644,
7304 		.proc_handler	= proc_dou8vec_minmax,
7305 		.extra1		= (void *)SYSCTL_ZERO,
7306 		.extra2		= (void *)SYSCTL_ONE,
7307 	},
7308 	{
7309 		.procname	= "accept_untracked_na",
7310 		.data		= &ipv6_devconf.accept_untracked_na,
7311 		.maxlen		= sizeof(int),
7312 		.mode		= 0644,
7313 		.proc_handler	= proc_dointvec_minmax,
7314 		.extra1		= SYSCTL_ZERO,
7315 		.extra2		= SYSCTL_TWO,
7316 	},
7317 	{
7318 		.procname	= "force_forwarding",
7319 		.data		= &ipv6_devconf.force_forwarding,
7320 		.maxlen		= sizeof(int),
7321 		.mode		= 0644,
7322 		.proc_handler	= addrconf_sysctl_force_forwarding,
7323 	},
7324 };
7325 
__addrconf_sysctl_register(struct net * net,char * dev_name,struct inet6_dev * idev,struct ipv6_devconf * p)7326 static int __addrconf_sysctl_register(struct net *net, char *dev_name,
7327 		struct inet6_dev *idev, struct ipv6_devconf *p)
7328 {
7329 	size_t table_size = ARRAY_SIZE(addrconf_sysctl);
7330 	int i, ifindex;
7331 	struct ctl_table *table;
7332 	char path[sizeof("net/ipv6/conf/") + IFNAMSIZ];
7333 
7334 	table = kmemdup(addrconf_sysctl, sizeof(addrconf_sysctl), GFP_KERNEL_ACCOUNT);
7335 	if (!table)
7336 		goto out;
7337 
7338 	for (i = 0; i < table_size; i++) {
7339 		table[i].data += (char *)p - (char *)&ipv6_devconf;
7340 		/* If one of these is already set, then it is not safe to
7341 		 * overwrite either of them: this makes proc_dointvec_minmax
7342 		 * usable.
7343 		 */
7344 		if (!table[i].extra1 && !table[i].extra2) {
7345 			table[i].extra1 = idev; /* embedded; no ref */
7346 			table[i].extra2 = net;
7347 		}
7348 	}
7349 
7350 	snprintf(path, sizeof(path), "net/ipv6/conf/%s", dev_name);
7351 
7352 	p->sysctl_header = register_net_sysctl_sz(net, path, table,
7353 						  table_size);
7354 	if (!p->sysctl_header)
7355 		goto free;
7356 
7357 	if (!strcmp(dev_name, "all"))
7358 		ifindex = NETCONFA_IFINDEX_ALL;
7359 	else if (!strcmp(dev_name, "default"))
7360 		ifindex = NETCONFA_IFINDEX_DEFAULT;
7361 	else
7362 		ifindex = idev->dev->ifindex;
7363 	inet6_netconf_notify_devconf(net, RTM_NEWNETCONF, NETCONFA_ALL,
7364 				     ifindex, p);
7365 	return 0;
7366 
7367 free:
7368 	kfree(table);
7369 out:
7370 	return -ENOBUFS;
7371 }
7372 
__addrconf_sysctl_unregister(struct net * net,struct ipv6_devconf * p,int ifindex)7373 static void __addrconf_sysctl_unregister(struct net *net,
7374 					 struct ipv6_devconf *p, int ifindex)
7375 {
7376 	const struct ctl_table *table;
7377 
7378 	if (!p->sysctl_header)
7379 		return;
7380 
7381 	table = p->sysctl_header->ctl_table_arg;
7382 	unregister_net_sysctl_table(p->sysctl_header);
7383 	p->sysctl_header = NULL;
7384 	kfree(table);
7385 
7386 	inet6_netconf_notify_devconf(net, RTM_DELNETCONF, 0, ifindex, NULL);
7387 }
7388 
addrconf_sysctl_register(struct inet6_dev * idev)7389 static int addrconf_sysctl_register(struct inet6_dev *idev)
7390 {
7391 	int err;
7392 
7393 	if (!sysctl_dev_name_is_allowed(idev->dev->name))
7394 		return -EINVAL;
7395 
7396 	err = neigh_sysctl_register(idev->dev, idev->nd_parms,
7397 				    &ndisc_ifinfo_sysctl_change);
7398 	if (err)
7399 		return err;
7400 	err = __addrconf_sysctl_register(dev_net(idev->dev), idev->dev->name,
7401 					 idev, &idev->cnf);
7402 	if (err)
7403 		neigh_sysctl_unregister(idev->nd_parms);
7404 
7405 	return err;
7406 }
7407 
addrconf_sysctl_unregister(struct inet6_dev * idev)7408 static void addrconf_sysctl_unregister(struct inet6_dev *idev)
7409 {
7410 	__addrconf_sysctl_unregister(dev_net(idev->dev), &idev->cnf,
7411 				     idev->dev->ifindex);
7412 	neigh_sysctl_unregister(idev->nd_parms);
7413 }
7414 
7415 
7416 #endif
7417 
addrconf_init_net(struct net * net)7418 static int __net_init addrconf_init_net(struct net *net)
7419 {
7420 	int err = -ENOMEM;
7421 	struct ipv6_devconf *all, *dflt;
7422 
7423 	spin_lock_init(&net->ipv6.addrconf_hash_lock);
7424 	INIT_DEFERRABLE_WORK(&net->ipv6.addr_chk_work, addrconf_verify_work);
7425 	net->ipv6.inet6_addr_lst = kzalloc_objs(struct hlist_head,
7426 						IN6_ADDR_HSIZE);
7427 	if (!net->ipv6.inet6_addr_lst)
7428 		goto err_alloc_addr;
7429 
7430 	all = kmemdup(&ipv6_devconf, sizeof(ipv6_devconf), GFP_KERNEL);
7431 	if (!all)
7432 		goto err_alloc_all;
7433 
7434 	dflt = kmemdup(&ipv6_devconf_dflt, sizeof(ipv6_devconf_dflt), GFP_KERNEL);
7435 	if (!dflt)
7436 		goto err_alloc_dflt;
7437 
7438 	if (!net_eq(net, &init_net)) {
7439 		switch (net_inherit_devconf()) {
7440 		case 1:  /* copy from init_net */
7441 			memcpy(all, init_net.ipv6.devconf_all,
7442 			       sizeof(ipv6_devconf));
7443 			memcpy(dflt, init_net.ipv6.devconf_dflt,
7444 			       sizeof(ipv6_devconf_dflt));
7445 			break;
7446 		case 3: /* copy from the current netns */
7447 			memcpy(all, current->nsproxy->net_ns->ipv6.devconf_all,
7448 			       sizeof(ipv6_devconf));
7449 			memcpy(dflt,
7450 			       current->nsproxy->net_ns->ipv6.devconf_dflt,
7451 			       sizeof(ipv6_devconf_dflt));
7452 			break;
7453 		case 0:
7454 		case 2:
7455 			/* use compiled values */
7456 			break;
7457 		}
7458 	}
7459 
7460 	/* these will be inherited by all namespaces */
7461 	dflt->autoconf = ipv6_defaults.autoconf;
7462 	dflt->disable_ipv6 = ipv6_defaults.disable_ipv6;
7463 
7464 	dflt->stable_secret.initialized = false;
7465 	all->stable_secret.initialized = false;
7466 
7467 	net->ipv6.devconf_all = all;
7468 	net->ipv6.devconf_dflt = dflt;
7469 
7470 #ifdef CONFIG_SYSCTL
7471 	err = __addrconf_sysctl_register(net, "all", NULL, all);
7472 	if (err < 0)
7473 		goto err_reg_all;
7474 
7475 	err = __addrconf_sysctl_register(net, "default", NULL, dflt);
7476 	if (err < 0)
7477 		goto err_reg_dflt;
7478 #endif
7479 	return 0;
7480 
7481 #ifdef CONFIG_SYSCTL
7482 err_reg_dflt:
7483 	__addrconf_sysctl_unregister(net, all, NETCONFA_IFINDEX_ALL);
7484 err_reg_all:
7485 	kfree(dflt);
7486 	net->ipv6.devconf_dflt = NULL;
7487 #endif
7488 err_alloc_dflt:
7489 	kfree(all);
7490 	net->ipv6.devconf_all = NULL;
7491 err_alloc_all:
7492 	kfree(net->ipv6.inet6_addr_lst);
7493 err_alloc_addr:
7494 	return err;
7495 }
7496 
addrconf_exit_net(struct net * net)7497 static void __net_exit addrconf_exit_net(struct net *net)
7498 {
7499 	int i;
7500 
7501 #ifdef CONFIG_SYSCTL
7502 	__addrconf_sysctl_unregister(net, net->ipv6.devconf_dflt,
7503 				     NETCONFA_IFINDEX_DEFAULT);
7504 	__addrconf_sysctl_unregister(net, net->ipv6.devconf_all,
7505 				     NETCONFA_IFINDEX_ALL);
7506 #endif
7507 	kfree(net->ipv6.devconf_dflt);
7508 	net->ipv6.devconf_dflt = NULL;
7509 	kfree(net->ipv6.devconf_all);
7510 	net->ipv6.devconf_all = NULL;
7511 
7512 	cancel_delayed_work_sync(&net->ipv6.addr_chk_work);
7513 	/*
7514 	 *	Check hash table, then free it.
7515 	 */
7516 	for (i = 0; i < IN6_ADDR_HSIZE; i++)
7517 		WARN_ON_ONCE(!hlist_empty(&net->ipv6.inet6_addr_lst[i]));
7518 
7519 	kfree(net->ipv6.inet6_addr_lst);
7520 	net->ipv6.inet6_addr_lst = NULL;
7521 }
7522 
7523 static struct pernet_operations addrconf_ops = {
7524 	.init = addrconf_init_net,
7525 	.exit = addrconf_exit_net,
7526 };
7527 
7528 static struct rtnl_af_ops inet6_ops __read_mostly = {
7529 	.family		  = AF_INET6,
7530 	.fill_link_af	  = inet6_fill_link_af,
7531 	.get_link_af_size = inet6_get_link_af_size,
7532 	.validate_link_af = inet6_validate_link_af,
7533 	.set_link_af	  = inet6_set_link_af,
7534 };
7535 
7536 static const struct rtnl_msg_handler addrconf_rtnl_msg_handlers[] __initconst_or_module = {
7537 	{.owner = THIS_MODULE, .protocol = PF_INET6, .msgtype = RTM_GETLINK,
7538 	 .dumpit = inet6_dump_ifinfo, .flags = RTNL_FLAG_DUMP_UNLOCKED},
7539 	{.owner = THIS_MODULE, .protocol = PF_INET6, .msgtype = RTM_NEWADDR,
7540 	 .doit = inet6_rtm_newaddr, .flags = RTNL_FLAG_DOIT_PERNET},
7541 	{.owner = THIS_MODULE, .protocol = PF_INET6, .msgtype = RTM_DELADDR,
7542 	 .doit = inet6_rtm_deladdr, .flags = RTNL_FLAG_DOIT_PERNET},
7543 	{.owner = THIS_MODULE, .protocol = PF_INET6, .msgtype = RTM_GETADDR,
7544 	 .doit = inet6_rtm_getaddr, .dumpit = inet6_dump_ifaddr,
7545 	 .flags = RTNL_FLAG_DOIT_UNLOCKED | RTNL_FLAG_DUMP_UNLOCKED},
7546 	{.owner = THIS_MODULE, .protocol = PF_INET6, .msgtype = RTM_GETMULTICAST,
7547 	 .dumpit = inet6_dump_ifmcaddr,
7548 	 .flags = RTNL_FLAG_DUMP_UNLOCKED},
7549 	{.owner = THIS_MODULE, .protocol = PF_INET6, .msgtype = RTM_GETANYCAST,
7550 	 .dumpit = inet6_dump_ifacaddr,
7551 	 .flags = RTNL_FLAG_DUMP_UNLOCKED},
7552 	{.owner = THIS_MODULE, .protocol = PF_INET6, .msgtype = RTM_GETNETCONF,
7553 	 .doit = inet6_netconf_get_devconf, .dumpit = inet6_netconf_dump_devconf,
7554 	 .flags = RTNL_FLAG_DOIT_UNLOCKED | RTNL_FLAG_DUMP_UNLOCKED},
7555 };
7556 
7557 /*
7558  *	Init / cleanup code
7559  */
7560 
addrconf_init(void)7561 int __init addrconf_init(void)
7562 {
7563 	struct inet6_dev *idev;
7564 	int err;
7565 
7566 	err = ipv6_addr_label_init();
7567 	if (err < 0) {
7568 		pr_crit("%s: cannot initialize default policy table: %d\n",
7569 			__func__, err);
7570 		goto out;
7571 	}
7572 
7573 	err = register_pernet_subsys(&addrconf_ops);
7574 	if (err < 0)
7575 		goto out_addrlabel;
7576 
7577 	/* All works using addrconf_wq need to lock rtnl. */
7578 	addrconf_wq = create_singlethread_workqueue("ipv6_addrconf");
7579 	if (!addrconf_wq) {
7580 		err = -ENOMEM;
7581 		goto out_nowq;
7582 	}
7583 
7584 	rtnl_net_lock(&init_net);
7585 	idev = ipv6_add_dev(blackhole_netdev);
7586 	rtnl_net_unlock(&init_net);
7587 	if (IS_ERR(idev)) {
7588 		err = PTR_ERR(idev);
7589 		goto errlo;
7590 	}
7591 
7592 	ip6_route_init_special_entries();
7593 
7594 	register_netdevice_notifier(&ipv6_dev_notf);
7595 
7596 	addrconf_verify(&init_net);
7597 
7598 	err = rtnl_af_register(&inet6_ops);
7599 	if (err)
7600 		goto erraf;
7601 
7602 	err = rtnl_register_many(addrconf_rtnl_msg_handlers);
7603 	if (err)
7604 		goto errout;
7605 
7606 	err = ipv6_addr_label_rtnl_register();
7607 	if (err < 0)
7608 		goto errout;
7609 
7610 	return 0;
7611 errout:
7612 	rtnl_unregister_all(PF_INET6);
7613 	rtnl_af_unregister(&inet6_ops);
7614 erraf:
7615 	unregister_netdevice_notifier(&ipv6_dev_notf);
7616 errlo:
7617 	destroy_workqueue(addrconf_wq);
7618 out_nowq:
7619 	unregister_pernet_subsys(&addrconf_ops);
7620 out_addrlabel:
7621 	ipv6_addr_label_cleanup();
7622 out:
7623 	return err;
7624 }
7625 
addrconf_cleanup(void)7626 void addrconf_cleanup(void)
7627 {
7628 	struct net_device *dev;
7629 
7630 	unregister_netdevice_notifier(&ipv6_dev_notf);
7631 	unregister_pernet_subsys(&addrconf_ops);
7632 	ipv6_addr_label_cleanup();
7633 
7634 	rtnl_af_unregister(&inet6_ops);
7635 
7636 	rtnl_net_lock(&init_net);
7637 
7638 	/* clean dev list */
7639 	for_each_netdev(&init_net, dev) {
7640 		if (!__in6_dev_get_rtnl_net(dev))
7641 			continue;
7642 		addrconf_ifdown(dev, true);
7643 	}
7644 	addrconf_ifdown(init_net.loopback_dev, true);
7645 
7646 	rtnl_net_unlock(&init_net);
7647 
7648 	destroy_workqueue(addrconf_wq);
7649 }
7650