xref: /freebsd/sys/netinet6/in6_ifattach.c (revision 117306dc606bf331795636b165b25be66e40d6a0)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the project nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  *
31  *	$KAME: in6_ifattach.c,v 1.118 2001/05/24 07:44:00 itojun Exp $
32  */
33 
34 #include <sys/param.h>
35 #include <sys/eventhandler.h>
36 #include <sys/systm.h>
37 #include <sys/counter.h>
38 #include <sys/malloc.h>
39 #include <sys/socket.h>
40 #include <sys/sockio.h>
41 #include <sys/jail.h>
42 #include <sys/kernel.h>
43 #include <sys/lock.h>
44 #include <sys/proc.h>
45 #include <sys/rmlock.h>
46 #include <sys/syslog.h>
47 #include <sys/md5.h>
48 
49 #include <net/if.h>
50 #include <net/if_var.h>
51 #include <net/if_dl.h>
52 #include <net/if_private.h>
53 #include <net/if_types.h>
54 #include <net/if_llatbl.h>
55 #include <net/route.h>
56 #include <net/vnet.h>
57 
58 #include <netinet/in.h>
59 #include <netinet/in_var.h>
60 #include <netinet/if_ether.h>
61 #include <netinet/in_pcb.h>
62 #include <netinet/ip_var.h>
63 #include <netinet/udp.h>
64 #include <netinet/udp_var.h>
65 
66 #include <netinet/ip6.h>
67 #include <netinet6/ip6_var.h>
68 #include <netinet6/in6_var.h>
69 #include <netinet6/in6_pcb.h>
70 #include <netinet6/in6_ifattach.h>
71 #include <netinet6/ip6_var.h>
72 #include <netinet6/nd6.h>
73 #include <netinet6/mld6_var.h>
74 #include <netinet6/scope6_var.h>
75 
76 #include <crypto/sha2/sha256.h>
77 #include <machine/atomic.h>
78 
79 #ifdef IP6_AUTO_LINKLOCAL
80 VNET_DEFINE(int, ip6_auto_linklocal) = IP6_AUTO_LINKLOCAL;
81 #else
82 VNET_DEFINE(int, ip6_auto_linklocal) = 1;	/* enabled by default */
83 #endif
84 
85 VNET_DEFINE(struct callout, in6_tmpaddrtimer_ch);
86 #define	V_in6_tmpaddrtimer_ch		VNET(in6_tmpaddrtimer_ch)
87 
88 VNET_DEFINE(int, ip6_stableaddr_netifsource) = IP6_STABLEADDR_NETIFSRC_NAME; /* Use interface name by default */
89 
90 VNET_DECLARE(struct inpcbinfo, ripcbinfo);
91 #define	V_ripcbinfo			VNET(ripcbinfo)
92 
93 static int get_rand_ifid(struct ifnet *, struct in6_addr *);
94 static int in6_ifattach_linklocal(struct ifnet *, struct ifnet *);
95 static int in6_ifattach_loopback(struct ifnet *);
96 static void in6_purgemaddrs(struct ifnet *);
97 
98 #define EUI64_GBIT	0x01
99 #define EUI64_UBIT	0x02
100 #define EUI64_TO_IFID(in6)	do {(in6)->s6_addr[8] ^= EUI64_UBIT; } while (0)
101 #define EUI64_GROUP(in6)	((in6)->s6_addr[8] & EUI64_GBIT)
102 #define EUI64_INDIVIDUAL(in6)	(!EUI64_GROUP(in6))
103 #define EUI64_LOCAL(in6)	((in6)->s6_addr[8] & EUI64_UBIT)
104 #define EUI64_UNIVERSAL(in6)	(!EUI64_LOCAL(in6))
105 
106 #define IFID_LOCAL(in6)		(!EUI64_LOCAL(in6))
107 #define IFID_UNIVERSAL(in6)	(!EUI64_UNIVERSAL(in6))
108 
109 #define HMAC_IPAD	0x36
110 #define HMAC_OPAD	0x5C
111 
112 /*
113  * Generate a last-resort interface identifier, when the machine has no
114  * IEEE802/EUI64 address sources.
115  * The goal here is to get an interface identifier that is
116  * (1) random enough and (2) does not change across reboot.
117  * We currently use MD5(hostname) for it.
118  *
119  * in6 - upper 64bits are preserved
120  */
121 static int
get_rand_ifid(struct ifnet * ifp,struct in6_addr * in6)122 get_rand_ifid(struct ifnet *ifp, struct in6_addr *in6)
123 {
124 	MD5_CTX ctxt;
125 	struct prison *pr;
126 	u_int8_t digest[16];
127 	int hostnamelen;
128 
129 	pr = curthread->td_ucred->cr_prison;
130 	mtx_lock(&pr->pr_mtx);
131 	hostnamelen = strlen(pr->pr_hostname);
132 #if 0
133 	/* we need at least several letters as seed for ifid */
134 	if (hostnamelen < 3) {
135 		mtx_unlock(&pr->pr_mtx);
136 		return -1;
137 	}
138 #endif
139 
140 	/* generate 8 bytes of pseudo-random value. */
141 	bzero(&ctxt, sizeof(ctxt));
142 	MD5Init(&ctxt);
143 	MD5Update(&ctxt, pr->pr_hostname, hostnamelen);
144 	mtx_unlock(&pr->pr_mtx);
145 	MD5Final(digest, &ctxt);
146 
147 	/* assumes sizeof(digest) > sizeof(ifid) */
148 	bcopy(digest, &in6->s6_addr[8], 8);
149 
150 	/* make sure to set "u" bit to local, and "g" bit to individual. */
151 	in6->s6_addr[8] &= ~EUI64_GBIT;	/* g bit to "individual" */
152 	in6->s6_addr[8] |= EUI64_UBIT;	/* u bit to "local" */
153 
154 	/* convert EUI64 into IPv6 interface identifier */
155 	EUI64_TO_IFID(in6);
156 
157 	return 0;
158 }
159 
160 
161 /**
162  * Get interface link level sockaddr
163  */
164 static struct sockaddr_dl *
get_interface_link_level(struct ifnet * ifp)165 get_interface_link_level(struct ifnet *ifp)
166 {
167 	struct ifaddr *ifa;
168 	struct sockaddr_dl *sdl;
169 
170 	NET_EPOCH_ASSERT();
171 
172 	CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
173 		if (ifa->ifa_addr->sa_family != AF_LINK)
174 			continue;
175 		sdl = (struct sockaddr_dl *)ifa->ifa_addr;
176 		if (sdl == NULL)
177 			continue;
178 		if (sdl->sdl_alen == 0)
179 			continue;
180 
181 		return sdl;
182 	}
183 
184 	return NULL;
185 }
186 
187 /*
188  * Get hwaddr from link interface
189  */
190 static uint8_t *
in6_get_interface_hwaddr(struct ifnet * ifp,size_t * len)191 in6_get_interface_hwaddr(struct ifnet *ifp, size_t *len)
192 {
193 	struct sockaddr_dl *sdl;
194 	u_int8_t *addr;
195 	static u_int8_t allzero[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
196 	static u_int8_t allone[8] =
197 		{ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
198 
199 	sdl = get_interface_link_level(ifp);
200 	if (sdl == NULL)
201 		return (NULL);
202 
203 	addr = LLADDR(sdl);
204 	*len = sdl->sdl_alen;
205 
206 	/* get EUI64 */
207 	switch (ifp->if_type) {
208 	case IFT_BRIDGE:
209 	case IFT_ETHER:
210 	case IFT_L2VLAN:
211 	case IFT_ATM:
212 	case IFT_IEEE1394:
213 		/* IEEE802/EUI64 cases - what others? */
214 		/* IEEE1394 uses 16byte length address starting with EUI64 */
215 		if (*len > 8)
216 			*len = 8;
217 
218 		/* look at IEEE802/EUI64 only */
219 		if (*len != 8 && *len != 6)
220 			return (NULL);
221 
222 		/*
223 		 * check for invalid MAC address - on bsdi, we see it a lot
224 		 * since wildboar configures all-zero MAC on pccard before
225 		 * card insertion.
226 		 */
227 		if (memcmp(addr, allzero, *len) == 0 || memcmp(addr, allone, *len) == 0)
228 			return (NULL);
229 
230 		break;
231 
232 	case IFT_GIF:
233 	case IFT_STF:
234 		/*
235 		 * RFC2893 says: "SHOULD use IPv4 address as ifid source".
236 		 * however, IPv4 address is not very suitable as unique
237 		 * identifier source (can be renumbered).
238 		 * we don't do this.
239 		 */
240 		return (NULL);
241 
242 	case IFT_INFINIBAND:
243 		if (*len != 20)
244 			return (NULL);
245 		*len = 8;
246 		addr += 12;
247 		break;
248 
249 	default:
250 		return (NULL);
251 	}
252 
253 	return addr;
254 }
255 
256  /*
257  * Get interface identifier for the specified interface.
258  * XXX assumes single sockaddr_dl (AF_LINK address) per an interface
259  *
260  * in6 - upper 64bits are preserved
261  */
262 int
in6_get_hw_ifid(struct ifnet * ifp,struct in6_addr * in6)263 in6_get_hw_ifid(struct ifnet *ifp, struct in6_addr *in6)
264 {
265 	size_t hwaddr_len;
266 	uint8_t *hwaddr;
267 	static u_int8_t allzero[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
268 
269 	hwaddr = in6_get_interface_hwaddr(ifp, &hwaddr_len);
270 	if (hwaddr == NULL || (hwaddr_len != 6 && hwaddr_len != 8))
271 		return -1;
272 
273 	/* make EUI64 address */
274 	if (hwaddr_len == 8)
275 		memcpy(&in6->s6_addr[8], hwaddr, 8);
276 	else if (hwaddr_len == 6) {
277 		in6->s6_addr[8] = hwaddr[0];
278 		in6->s6_addr[9] = hwaddr[1];
279 		in6->s6_addr[10] = hwaddr[2];
280 		in6->s6_addr[11] = 0xff;
281 		in6->s6_addr[12] = 0xfe;
282 		in6->s6_addr[13] = hwaddr[3];
283 		in6->s6_addr[14] = hwaddr[4];
284 		in6->s6_addr[15] = hwaddr[5];
285 	}
286 
287 	/* sanity check: g bit must not indicate "group" */
288 	if (EUI64_GROUP(in6))
289 		return -1;
290 
291 	/* convert EUI64 into IPv6 interface identifier */
292 	EUI64_TO_IFID(in6);
293 
294 	/*
295 	 * sanity check: ifid must not be all zero, avoid conflict with
296 	 * subnet router anycast
297 	 */
298 	if ((in6->s6_addr[8] & ~(EUI64_GBIT | EUI64_UBIT)) == 0x00 &&
299 	    bcmp(&in6->s6_addr[9], allzero, 7) == 0)
300 		return -1;
301 
302 	return 0;
303 }
304 
305 /*
306  * Validate generated interface id to make sure it does not fall in any reserved range:
307  *
308  * https://www.iana.org/assignments/ipv6-interface-ids/ipv6-interface-ids.xhtml
309  */
310 static bool
validate_ifid(uint8_t * iid)311 validate_ifid(uint8_t *iid)
312 {
313 	static uint8_t allzero[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
314 	static uint8_t reserved_eth[5] = { 0x02, 0x00, 0x5E, 0xFF, 0xFE };
315 	static uint8_t reserved_anycast[7] = { 0xFD, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };
316 
317 	/* Subnet-Router Anycast (RFC 4291)*/
318 	if (memcmp(iid, allzero, 8) == 0)
319 		return (false);
320 
321 	/*
322 	 * Reserved IPv6 Interface Identifiers corresponding to the IANA Ethernet Block (RFC 4291)
323 	 * and
324 	 * Proxy Mobile IPv6 (RFC 6543)
325 	 */
326 	if (memcmp(iid, reserved_eth, 5) == 0)
327 		return (false);
328 
329 	/* Reserved Subnet Anycast Addresses (RFC 2526) */
330 	if (memcmp(iid, reserved_anycast, 7) == 0 && iid[7] >= 0x80)
331 		return (false);
332 
333 	return (true);
334 }
335 
336 /*
337  * Get interface identifier for the specified interface, according to
338  * RFC 7217 Stable and Opaque IDs with SLAAC, using HMAC-SHA256 digest.
339  *
340  * in6 - upper 64bits are preserved
341  */
342 bool
in6_get_stableifid(struct ifnet * ifp,struct in6_addr * in6,int prefixlen)343 in6_get_stableifid(struct ifnet *ifp, struct in6_addr *in6, int prefixlen)
344 {
345 	struct sockaddr_dl *sdl;
346 	const uint8_t *netiface;
347 	size_t netiface_len, hostuuid_len;
348 	uint8_t hostuuid[HOSTUUIDLEN + 1], hmac_key[SHA256_BLOCK_LENGTH],
349 		hk_ipad[SHA256_BLOCK_LENGTH], hk_opad[SHA256_BLOCK_LENGTH];
350 	uint64_t dad_failures;
351 	SHA256_CTX ctxt;
352 
353 	switch (V_ip6_stableaddr_netifsource) {
354 		case IP6_STABLEADDR_NETIFSRC_ID:
355 			sdl = get_interface_link_level(ifp);
356 			if (sdl == NULL)
357 				return (false);
358 			netiface = (uint8_t *)&LLINDEX(sdl);
359 			netiface_len = sizeof(u_short); /* real return type of LLINDEX */
360 			break;
361 
362 		case IP6_STABLEADDR_NETIFSRC_MAC:
363 			netiface = in6_get_interface_hwaddr(ifp, &netiface_len);
364 			if (netiface == NULL)
365 				return (false);
366 			break;
367 
368 		case IP6_STABLEADDR_NETIFSRC_NAME:
369 		default:
370 			netiface = (const uint8_t *)if_name(ifp);
371 			netiface_len = strlen(netiface);
372 			break;
373 	}
374 
375 	/* Use hostuuid as constant "secret" key */
376 	getcredhostuuid(curthread->td_ucred, hostuuid, sizeof(hostuuid));
377 	if (strncmp(hostuuid, DEFAULT_HOSTUUID, sizeof(hostuuid)) == 0) {
378 		// If hostuuid is not set, use a random value
379 		arc4rand(hostuuid, HOSTUUIDLEN, 0);
380 		hostuuid[HOSTUUIDLEN] = '\0';
381 	}
382 	hostuuid_len = strlen(hostuuid);
383 
384 	dad_failures = atomic_load_int(&DAD_FAILURES(ifp));
385 
386 	/*
387 	 * RFC 7217 section 7
388 	 *
389 	 * default max retries
390 	 */
391 	if (dad_failures > V_ip6_stableaddr_maxretries)
392 		return (false);
393 
394 	/*
395 	 * Use hostuuid as basis for HMAC key
396 	 */
397 	memset(hmac_key, 0, sizeof(hmac_key));
398 	if (hostuuid_len <= SHA256_BLOCK_LENGTH) {
399 		/* copy to hmac key variable, zero padded */
400 		memcpy(hmac_key, hostuuid, hostuuid_len);
401 	} else {
402 		/* if longer than block length, use hash of the value, zero padded */
403 		SHA256_Init(&ctxt);
404 		SHA256_Update(&ctxt, hostuuid, hostuuid_len);
405 		SHA256_Final(hmac_key, &ctxt);
406 	}
407 	/* XOR key with ipad and opad values */
408 	for (uint16_t i = 0; i < sizeof(hmac_key); i++) {
409 		hk_ipad[i] = hmac_key[i] ^ HMAC_IPAD;
410 		hk_opad[i] = hmac_key[i] ^ HMAC_OPAD;
411 	}
412 
413 	/*
414 	 * Generate interface id in a loop, adding an offset to be factored in the hash function.
415 	 * This is necessary, because if the generated interface id happens to be invalid we
416 	 * want to force the hash function to generate a different one, otherwise we would end up
417 	 * in an infinite loop trying the same invalid interface id over and over again.
418 	 *
419 	 * Using an uint8 counter for the offset, so limit iteration at UINT8_MAX. This is a safety
420 	 * measure, this will never iterate more than once or twice in practice.
421 	 */
422 	for(uint8_t offset = 0; offset < UINT8_MAX; offset++) {
423 		uint8_t digest[SHA256_DIGEST_LENGTH];
424 
425 		/* Calculate inner hash */
426 		SHA256_Init(&ctxt);
427 		SHA256_Update(&ctxt, hk_ipad, sizeof(hk_ipad));
428 		SHA256_Update(&ctxt, in6->s6_addr, prefixlen / 8);
429 		SHA256_Update(&ctxt, netiface, netiface_len);
430 		SHA256_Update(&ctxt, (uint8_t *)&dad_failures, 8);
431 		SHA256_Update(&ctxt, hostuuid, hostuuid_len);
432 		SHA256_Update(&ctxt, &offset, 1);
433 		SHA256_Final(digest, &ctxt);
434 
435 		/* Calculate outer hash */
436 		SHA256_Init(&ctxt);
437 		SHA256_Update(&ctxt, hk_opad, sizeof(hk_opad));
438 		SHA256_Update(&ctxt, digest, sizeof(digest));
439 		SHA256_Final(digest, &ctxt);
440 
441 		if (validate_ifid(digest)) {
442 			/* assumes sizeof(digest) > sizeof(ifid) */
443 			memcpy(&in6->s6_addr[8], digest, 8);
444 
445 			return (true);
446 		}
447 	}
448 
449 	return (false);
450 }
451 
452 /*
453  * Get interface identifier for the specified interface.  If it is not
454  * available on ifp0, borrow interface identifier from other information
455  * sources.
456  *
457  * altifp - secondary EUI64 source
458  */
459 int
in6_get_ifid(struct ifnet * ifp0,struct ifnet * altifp,struct in6_addr * in6)460 in6_get_ifid(struct ifnet *ifp0, struct ifnet *altifp,
461     struct in6_addr *in6)
462 {
463 	struct ifnet *ifp;
464 
465 	NET_EPOCH_ASSERT();
466 
467 	/* first, try to get it from the interface itself, with stable algorithm, if configured */
468 	if ((ND_IFINFO(ifp0)->flags & ND6_IFF_STABLEADDR) && in6_get_stableifid(ifp0, in6, 64) == 0) {
469 		nd6log((LOG_DEBUG, "%s: got interface identifier from itself (stable private)\n",
470 		    if_name(ifp0)));
471 		goto success;
472 	}
473 
474 	/* then/otherwise try to get it from the interface itself */
475 	if (in6_get_hw_ifid(ifp0, in6) == 0) {
476 		nd6log((LOG_DEBUG, "%s: got interface identifier from itself\n",
477 		    if_name(ifp0)));
478 		goto success;
479 	}
480 
481 	/* try secondary EUI64 source. this basically is for ATM PVC */
482 	if (altifp && in6_get_hw_ifid(altifp, in6) == 0) {
483 		nd6log((LOG_DEBUG, "%s: got interface identifier from %s\n",
484 		    if_name(ifp0), if_name(altifp)));
485 		goto success;
486 	}
487 
488 	/* next, try to get it from some other hardware interface */
489 	CK_STAILQ_FOREACH(ifp, &V_ifnet, if_link) {
490 		if (ifp == ifp0)
491 			continue;
492 		if (in6_get_hw_ifid(ifp, in6) != 0)
493 			continue;
494 
495 		/*
496 		 * to borrow ifid from other interface, ifid needs to be
497 		 * globally unique
498 		 */
499 		if (IFID_UNIVERSAL(in6)) {
500 			nd6log((LOG_DEBUG,
501 			    "%s: borrow interface identifier from %s\n",
502 			    if_name(ifp0), if_name(ifp)));
503 			goto success;
504 		}
505 	}
506 
507 	/* last resort: get from random number source */
508 	if (get_rand_ifid(ifp, in6) == 0) {
509 		nd6log((LOG_DEBUG,
510 		    "%s: interface identifier generated by random number\n",
511 		    if_name(ifp0)));
512 		goto success;
513 	}
514 
515 	printf("%s: failed to get interface identifier\n", if_name(ifp0));
516 	return -1;
517 
518 success:
519 	nd6log((LOG_INFO, "%s: ifid: %02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x\n",
520 	    if_name(ifp0), in6->s6_addr[8], in6->s6_addr[9], in6->s6_addr[10],
521 	    in6->s6_addr[11], in6->s6_addr[12], in6->s6_addr[13],
522 	    in6->s6_addr[14], in6->s6_addr[15]));
523 	return 0;
524 }
525 
526 /*
527  * altifp - secondary EUI64 source
528  */
529 static int
in6_ifattach_linklocal(struct ifnet * ifp,struct ifnet * altifp)530 in6_ifattach_linklocal(struct ifnet *ifp, struct ifnet *altifp)
531 {
532 	struct in6_ifaddr *ia;
533 	struct in6_aliasreq ifra;
534 	struct nd_prefixctl pr0;
535 	struct epoch_tracker et;
536 	struct nd_prefix *pr;
537 	int error;
538 
539 	/*
540 	 * configure link-local address.
541 	 */
542 	in6_prepare_ifra(&ifra, NULL, &in6mask64);
543 
544 	ifra.ifra_addr.sin6_addr.s6_addr32[0] = htonl(0xfe800000);
545 	ifra.ifra_addr.sin6_addr.s6_addr32[1] = 0;
546 	if ((ifp->if_flags & IFF_LOOPBACK) != 0) {
547 		ifra.ifra_addr.sin6_addr.s6_addr32[2] = 0;
548 		ifra.ifra_addr.sin6_addr.s6_addr32[3] = htonl(1);
549 	} else {
550 		NET_EPOCH_ENTER(et);
551 		error = in6_get_ifid(ifp, altifp, &ifra.ifra_addr.sin6_addr);
552 		NET_EPOCH_EXIT(et);
553 		if (error != 0) {
554 			nd6log((LOG_ERR,
555 			    "%s: no ifid available\n", if_name(ifp)));
556 			return (-1);
557 		}
558 	}
559 	if (in6_setscope(&ifra.ifra_addr.sin6_addr, ifp, NULL))
560 		return (-1);
561 
562 	/* link-local addresses should NEVER expire. */
563 	ifra.ifra_lifetime.ia6t_vltime = ND6_INFINITE_LIFETIME;
564 	ifra.ifra_lifetime.ia6t_pltime = ND6_INFINITE_LIFETIME;
565 
566 	/*
567 	 * Now call in6_update_ifa() to do a bunch of procedures to configure
568 	 * a link-local address. We can set the 3rd argument to NULL, because
569 	 * we know there's no other link-local address on the interface
570 	 * and therefore we are adding one (instead of updating one).
571 	 */
572 	if ((error = in6_update_ifa(ifp, &ifra, NULL,
573 				    IN6_IFAUPDATE_DADDELAY)) != 0) {
574 		/*
575 		 * XXX: When the interface does not support IPv6, this call
576 		 * would fail in the SIOCSIFADDR ioctl.  I believe the
577 		 * notification is rather confusing in this case, so just
578 		 * suppress it.  (jinmei@kame.net 20010130)
579 		 */
580 		if (error != EAFNOSUPPORT)
581 			nd6log((LOG_NOTICE, "in6_ifattach_linklocal: failed to "
582 			    "configure a link-local address on %s "
583 			    "(errno=%d)\n",
584 			    if_name(ifp), error));
585 		return (-1);
586 	}
587 
588 	NET_EPOCH_ENTER(et);
589 	ia = in6ifa_ifpforlinklocal(ifp, 0);
590 	NET_EPOCH_EXIT(et);
591 	if (ia == NULL) {
592 		/*
593 		 * Another thread removed the address that we just added.
594 		 * This should be rare, but it happens.
595 		 */
596 		nd6log((LOG_NOTICE, "%s: %s: new link-local address "
597 			"disappeared\n", __func__, if_name(ifp)));
598 		return (-1);
599 	}
600 	ifa_free(&ia->ia_ifa);
601 
602 	/*
603 	 * Make the link-local prefix (fe80::%link/64) as on-link.
604 	 * Since we'd like to manage prefixes separately from addresses,
605 	 * we make an ND6 prefix structure for the link-local prefix,
606 	 * and add it to the prefix list as a never-expire prefix.
607 	 * XXX: this change might affect some existing code base...
608 	 */
609 	bzero(&pr0, sizeof(pr0));
610 	pr0.ndpr_ifp = ifp;
611 	/* this should be 64 at this moment. */
612 	pr0.ndpr_plen = in6_mask2len(&ifra.ifra_prefixmask.sin6_addr, NULL);
613 	pr0.ndpr_prefix = ifra.ifra_addr;
614 	/* apply the mask for safety. (nd6_prelist_add will apply it again) */
615 	IN6_MASK_ADDR(&pr0.ndpr_prefix.sin6_addr, &in6mask64);
616 	/*
617 	 * Initialize parameters.  The link-local prefix must always be
618 	 * on-link, and its lifetimes never expire.
619 	 */
620 	pr0.ndpr_raf_onlink = 1;
621 	pr0.ndpr_raf_auto = 1;	/* probably meaningless */
622 	pr0.ndpr_vltime = ND6_INFINITE_LIFETIME;
623 	pr0.ndpr_pltime = ND6_INFINITE_LIFETIME;
624 	/*
625 	 * Since there is no other link-local addresses, nd6_prefix_lookup()
626 	 * probably returns NULL.  However, we cannot always expect the result.
627 	 * For example, if we first remove the (only) existing link-local
628 	 * address, and then reconfigure another one, the prefix is still
629 	 * valid with referring to the old link-local address.
630 	 */
631 	if ((pr = nd6_prefix_lookup(&pr0)) == NULL) {
632 		if ((error = nd6_prelist_add(&pr0, NULL, &pr)) != 0)
633 			return (error);
634 		/* Reference prefix */
635 		ia->ia6_ndpr = pr;
636 		pr->ndpr_addrcnt++;
637 	} else
638 		nd6_prefix_rele(pr);
639 
640 	return 0;
641 }
642 
643 /*
644  * ifp - must be IFT_LOOP
645  */
646 static int
in6_ifattach_loopback(struct ifnet * ifp)647 in6_ifattach_loopback(struct ifnet *ifp)
648 {
649 	struct in6_aliasreq ifra;
650 	int error;
651 
652 	in6_prepare_ifra(&ifra, &in6addr_loopback, &in6mask128);
653 
654 	/*
655 	 * Always initialize ia_dstaddr (= broadcast address) to loopback
656 	 * address.  Follows IPv4 practice - see in_ifinit().
657 	 */
658 	ifra.ifra_dstaddr.sin6_len = sizeof(struct sockaddr_in6);
659 	ifra.ifra_dstaddr.sin6_family = AF_INET6;
660 	ifra.ifra_dstaddr.sin6_addr = in6addr_loopback;
661 
662 	/* the loopback  address should NEVER expire. */
663 	ifra.ifra_lifetime.ia6t_vltime = ND6_INFINITE_LIFETIME;
664 	ifra.ifra_lifetime.ia6t_pltime = ND6_INFINITE_LIFETIME;
665 
666 	/*
667 	 * We are sure that this is a newly assigned address, so we can set
668 	 * NULL to the 3rd arg.
669 	 */
670 	if ((error = in6_update_ifa(ifp, &ifra, NULL, 0)) != 0) {
671 		nd6log((LOG_ERR, "in6_ifattach_loopback: failed to configure "
672 		    "the loopback address on %s (errno=%d)\n",
673 		    if_name(ifp), error));
674 		return (-1);
675 	}
676 
677 	return 0;
678 }
679 
680 /*
681  * compute NI group address, based on the current hostname setting.
682  * see RFC 4620.
683  *
684  * when ifp == NULL, the caller is responsible for filling scopeid.
685  *
686  * If oldmcprefix == 1, FF02:0:0:0:0:2::/96 is used for NI group address
687  * while it is FF02:0:0:0:0:2:FF00::/104 in RFC 4620.
688  */
689 static int
in6_nigroup0(struct ifnet * ifp,const char * name,int namelen,struct in6_addr * in6,int oldmcprefix)690 in6_nigroup0(struct ifnet *ifp, const char *name, int namelen,
691     struct in6_addr *in6, int oldmcprefix)
692 {
693 	struct prison *pr;
694 	const char *p;
695 	u_char *q;
696 	MD5_CTX ctxt;
697 	u_int8_t digest[16];
698 	char l;
699 	char n[64];	/* a single label must not exceed 63 chars */
700 
701 	/*
702 	 * If no name is given and namelen is -1,
703 	 * we try to do the hostname lookup ourselves.
704 	 */
705 	if (!name && namelen == -1) {
706 		pr = curthread->td_ucred->cr_prison;
707 		mtx_lock(&pr->pr_mtx);
708 		name = pr->pr_hostname;
709 		namelen = strlen(name);
710 	} else
711 		pr = NULL;
712 	if (!name || !namelen) {
713 		if (pr != NULL)
714 			mtx_unlock(&pr->pr_mtx);
715 		return -1;
716 	}
717 
718 	p = name;
719 	while (p && *p && *p != '.' && p - name < namelen)
720 		p++;
721 	if (p == name || p - name > sizeof(n) - 1) {
722 		if (pr != NULL)
723 			mtx_unlock(&pr->pr_mtx);
724 		return -1;	/* label too long */
725 	}
726 	l = p - name;
727 	strncpy(n, name, l);
728 	if (pr != NULL)
729 		mtx_unlock(&pr->pr_mtx);
730 	n[(int)l] = '\0';
731 	for (q = n; *q; q++) {
732 		if ('A' <= *q && *q <= 'Z')
733 			*q = *q - 'A' + 'a';
734 	}
735 
736 	/* generate 16 bytes of pseudo-random value. */
737 	bzero(&ctxt, sizeof(ctxt));
738 	MD5Init(&ctxt);
739 	MD5Update(&ctxt, &l, sizeof(l));
740 	MD5Update(&ctxt, n, l);
741 	MD5Final(digest, &ctxt);
742 
743 	bzero(in6, sizeof(*in6));
744 	in6->s6_addr16[0] = IPV6_ADDR_INT16_MLL;
745 	in6->s6_addr8[11] = 2;
746 	if (oldmcprefix == 0) {
747 		in6->s6_addr8[12] = 0xff;
748 	 	/* Copy the first 24 bits of 128-bit hash into the address. */
749 		bcopy(digest, &in6->s6_addr8[13], 3);
750 	} else {
751 	 	/* Copy the first 32 bits of 128-bit hash into the address. */
752 		bcopy(digest, &in6->s6_addr32[3], sizeof(in6->s6_addr32[3]));
753 	}
754 	if (in6_setscope(in6, ifp, NULL))
755 		return (-1); /* XXX: should not fail */
756 
757 	return 0;
758 }
759 
760 int
in6_nigroup(struct ifnet * ifp,const char * name,int namelen,struct in6_addr * in6)761 in6_nigroup(struct ifnet *ifp, const char *name, int namelen,
762     struct in6_addr *in6)
763 {
764 
765 	return (in6_nigroup0(ifp, name, namelen, in6, 0));
766 }
767 
768 int
in6_nigroup_oldmcprefix(struct ifnet * ifp,const char * name,int namelen,struct in6_addr * in6)769 in6_nigroup_oldmcprefix(struct ifnet *ifp, const char *name, int namelen,
770     struct in6_addr *in6)
771 {
772 
773 	return (in6_nigroup0(ifp, name, namelen, in6, 1));
774 }
775 
776 /*
777  * XXX multiple loopback interface needs more care.  for instance,
778  * nodelocal address needs to be configured onto only one of them.
779  * XXX multiple link-local address case
780  *
781  * altifp - secondary EUI64 source
782  */
783 void
in6_ifattach(struct ifnet * ifp,struct ifnet * altifp)784 in6_ifattach(struct ifnet *ifp, struct ifnet *altifp)
785 {
786 	struct in6_ifaddr *ia;
787 
788 	/* XXXGL: can this happen after IFT_PFLOG and IFT_PFSYNC are gone? */
789 	if (ifp->if_inet6 == NULL)
790 		return;
791 	/*
792 	 * quirks based on interface type
793 	 */
794 	switch (ifp->if_type) {
795 	case IFT_STF:
796 		/*
797 		 * 6to4 interface is a very special kind of beast.
798 		 * no multicast, no linklocal.  RFC2529 specifies how to make
799 		 * linklocals for 6to4 interface, but there's no use and
800 		 * it is rather harmful to have one.
801 		 */
802 		ND_IFINFO(ifp)->flags &= ~ND6_IFF_AUTO_LINKLOCAL;
803 		ND_IFINFO(ifp)->flags |= ND6_IFF_NO_DAD;
804 		break;
805 	default:
806 		break;
807 	}
808 
809 	/*
810 	 * usually, we require multicast capability to the interface
811 	 */
812 	if ((ifp->if_flags & IFF_MULTICAST) == 0) {
813 		nd6log((LOG_INFO, "in6_ifattach: "
814 		    "%s is not multicast capable, IPv6 not enabled\n",
815 		    if_name(ifp)));
816 		return;
817 	}
818 
819 	/*
820 	 * assign loopback address for loopback interface.
821 	 */
822 	if ((ifp->if_flags & IFF_LOOPBACK) != 0) {
823 		/*
824 		 * check that loopback address doesn't exist yet.
825 		 */
826 		ia = in6ifa_ifwithaddr(&in6addr_loopback, 0, false);
827 		if (ia == NULL)
828 			in6_ifattach_loopback(ifp);
829 	}
830 
831 	/*
832 	 * assign a link-local address, if there's none.
833 	 */
834 	if (!(ND_IFINFO(ifp)->flags & ND6_IFF_IFDISABLED) &&
835 	    ND_IFINFO(ifp)->flags & ND6_IFF_AUTO_LINKLOCAL) {
836 		struct epoch_tracker et;
837 
838 		NET_EPOCH_ENTER(et);
839 		ia = in6ifa_ifpforlinklocal(ifp, 0);
840 		NET_EPOCH_EXIT(et);
841 		if (ia == NULL)
842 			in6_ifattach_linklocal(ifp, altifp);
843 		else
844 			ifa_free(&ia->ia_ifa);
845 	}
846 }
847 
848 /*
849  * NOTE: in6_ifdetach() does not support loopback if at this moment.
850  *
851  * When shutting down a VNET we clean up layers top-down.  In that case
852  * upper layer protocols (ulp) are cleaned up already and locks are destroyed
853  * and we must not call into these cleanup functions anymore, thus purgeulp
854  * is set to 0 in that case by in6_ifdetach_destroy().
855  * The normal case of destroying a (cloned) interface still needs to cleanup
856  * everything related to the interface and will have purgeulp set to 1.
857  */
858 static void
_in6_ifdetach(struct ifnet * ifp,int purgeulp)859 _in6_ifdetach(struct ifnet *ifp, int purgeulp)
860 {
861 	struct ifaddr *ifa, *next;
862 
863 	/* XXXGL: can this happen after IFT_PFLOG and IFT_PFSYNC are gone? */
864 	if (ifp->if_inet6 == NULL)
865 		return;
866 
867 	/*
868 	 * nuke any of IPv6 addresses we have
869 	 */
870 	CK_STAILQ_FOREACH_SAFE(ifa, &ifp->if_addrhead, ifa_link, next) {
871 		if (ifa->ifa_addr->sa_family != AF_INET6)
872 			continue;
873 		in6_purgeaddr(ifa);
874 	}
875 	if (purgeulp) {
876 		IN6_MULTI_LOCK();
877 		in6_pcbpurgeif0(&V_udbinfo, ifp);
878 		in6_pcbpurgeif0(&V_ulitecbinfo, ifp);
879 		in6_pcbpurgeif0(&V_ripcbinfo, ifp);
880 		IN6_MULTI_UNLOCK();
881 	}
882 	/* leave from all multicast groups joined */
883 	in6_purgemaddrs(ifp);
884 
885 	/*
886 	 * Remove neighbor management table.
887 	 * Enabling the nd6_purge will panic on vmove for interfaces on VNET
888 	 * teardown as the IPv6 layer is cleaned up already and the locks
889 	 * are destroyed.
890 	 */
891 	if (purgeulp)
892 		nd6_purge(ifp);
893 }
894 
895 void
in6_ifdetach(struct ifnet * ifp)896 in6_ifdetach(struct ifnet *ifp)
897 {
898 
899 	_in6_ifdetach(ifp, 1);
900 }
901 
902 static void
in6_ifdeparture(void * arg __unused,struct ifnet * ifp)903 in6_ifdeparture(void *arg __unused, struct ifnet *ifp)
904 {
905 	struct in6_ifextra *ext = ifp->if_inet6;
906 
907 	/* XXXGL: can this happen after IFT_PFLOG and IFT_PFSYNC are gone? */
908 	if (ifp->if_inet6 == NULL)
909 		return;
910 
911 #ifdef VIMAGE
912 	/*
913 	 * On VNET shutdown abort here as the stack teardown will do all
914 	 * the work top-down for us.  XXXGL: see comment in in.c:in_ifdetach().
915 	 */
916 	if (!VNET_IS_SHUTTING_DOWN(ifp->if_vnet))
917 #endif
918 		_in6_ifdetach(ifp, 1);
919 	mld_domifdetach(ifp);
920 	scope6_ifdetach(ext->scope6_id);
921 	nd6_ifdetach(ifp, ext->nd_ifinfo);
922 	lltable_free(ext->lltable);
923 	COUNTER_ARRAY_FREE(ext->in6_ifstat,
924 	    sizeof(struct in6_ifstat) / sizeof(uint64_t));
925 	free(ext->in6_ifstat, M_IFADDR);
926 	COUNTER_ARRAY_FREE(ext->icmp6_ifstat,
927 	    sizeof(struct icmp6_ifstat) / sizeof(uint64_t));
928 	free(ext->icmp6_ifstat, M_IFADDR);
929 	free(ext, M_IFADDR);
930 }
931 EVENTHANDLER_DEFINE(ifnet_departure_event, in6_ifdeparture, NULL,
932     EVENTHANDLER_PRI_ANY);
933 
934 void
in6_ifdetach_destroy(struct ifnet * ifp)935 in6_ifdetach_destroy(struct ifnet *ifp)
936 {
937 
938 	_in6_ifdetach(ifp, 0);
939 }
940 
941 void
in6_tmpaddrtimer(void * arg)942 in6_tmpaddrtimer(void *arg)
943 {
944 	CURVNET_SET((struct vnet *) arg);
945 
946 	callout_reset(&V_in6_tmpaddrtimer_ch,
947 	    (V_ip6_temp_preferred_lifetime - V_ip6_desync_factor -
948 	    V_ip6_temp_regen_advance) * hz, in6_tmpaddrtimer, curvnet);
949 
950 	CURVNET_RESTORE();
951 }
952 
953 static void
in6_purgemaddrs(struct ifnet * ifp)954 in6_purgemaddrs(struct ifnet *ifp)
955 {
956 	struct in6_multi_head inmh;
957 
958 	SLIST_INIT(&inmh);
959 	IN6_MULTI_LOCK();
960 	IN6_MULTI_LIST_LOCK();
961 	mld_ifdetach(ifp, &inmh);
962 	IN6_MULTI_LIST_UNLOCK();
963 	IN6_MULTI_UNLOCK();
964 	in6m_release_list_deferred(&inmh);
965 
966 	/*
967 	 * Make sure all multicast deletions invoking if_ioctl() are
968 	 * completed before returning. Else we risk accessing a freed
969 	 * ifnet structure pointer.
970 	 */
971 	in6m_release_wait(NULL);
972 }
973 
974 void
in6_ifattach_destroy(void)975 in6_ifattach_destroy(void)
976 {
977 
978 	callout_drain(&V_in6_tmpaddrtimer_ch);
979 }
980 
981 static void
in6_ifattach_init(void * dummy)982 in6_ifattach_init(void *dummy)
983 {
984 
985 	/* Timer for regeneranation of temporary addresses randomize ID. */
986 	callout_init(&V_in6_tmpaddrtimer_ch, 1);
987 	callout_reset(&V_in6_tmpaddrtimer_ch,
988 	    (V_ip6_temp_preferred_lifetime - V_ip6_desync_factor -
989 	    V_ip6_temp_regen_advance) * hz,
990 	    in6_tmpaddrtimer, curvnet);
991 }
992 
993 /*
994  * Cheat.
995  * This must be after route_init(), which is now SI_ORDER_THIRD.
996  */
997 SYSINIT(in6_ifattach_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_MIDDLE,
998     in6_ifattach_init, NULL);
999