xref: /xnu-10002.61.3/bsd/net/rtsock.c (revision 0f4c859e951fba394238ab619495c4e1d54d0f34)
1 /*
2  * Copyright (c) 2000-2021 Apple Inc. All rights reserved.
3  *
4  * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5  *
6  * This file contains Original Code and/or Modifications of Original Code
7  * as defined in and that are subject to the Apple Public Source License
8  * Version 2.0 (the 'License'). You may not use this file except in
9  * compliance with the License. The rights granted to you under the License
10  * may not be used to create, or enable the creation or redistribution of,
11  * unlawful or unlicensed copies of an Apple operating system, or to
12  * circumvent, violate, or enable the circumvention or violation of, any
13  * terms of an Apple operating system software license agreement.
14  *
15  * Please obtain a copy of the License at
16  * http://www.opensource.apple.com/apsl/ and read it before using this file.
17  *
18  * The Original Code and all software distributed under the License are
19  * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20  * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21  * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22  * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23  * Please see the License for the specific language governing rights and
24  * limitations under the License.
25  *
26  * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27  */
28 /*
29  * Copyright (c) 1988, 1991, 1993
30  *	The Regents of the University of California.  All rights reserved.
31  *
32  * Redistribution and use in source and binary forms, with or without
33  * modification, are permitted provided that the following conditions
34  * are met:
35  * 1. Redistributions of source code must retain the above copyright
36  *    notice, this list of conditions and the following disclaimer.
37  * 2. Redistributions in binary form must reproduce the above copyright
38  *    notice, this list of conditions and the following disclaimer in the
39  *    documentation and/or other materials provided with the distribution.
40  * 3. All advertising materials mentioning features or use of this software
41  *    must display the following acknowledgement:
42  *	This product includes software developed by the University of
43  *	California, Berkeley and its contributors.
44  * 4. Neither the name of the University nor the names of its contributors
45  *    may be used to endorse or promote products derived from this software
46  *    without specific prior written permission.
47  *
48  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
49  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
50  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
51  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
52  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
53  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
54  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
55  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
56  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
57  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
58  * SUCH DAMAGE.
59  *
60  *	@(#)rtsock.c	8.5 (Berkeley) 11/2/94
61  */
62 
63 #include <sys/param.h>
64 #include <sys/systm.h>
65 #include <sys/kauth.h>
66 #include <sys/kernel.h>
67 #include <sys/sysctl.h>
68 #include <sys/proc.h>
69 #include <sys/malloc.h>
70 #include <sys/mbuf.h>
71 #include <sys/socket.h>
72 #include <sys/socketvar.h>
73 #include <sys/domain.h>
74 #include <sys/protosw.h>
75 #include <sys/syslog.h>
76 #include <sys/mcache.h>
77 #include <kern/locks.h>
78 #include <sys/codesign.h>
79 
80 #include <net/if.h>
81 #include <net/route.h>
82 #include <net/dlil.h>
83 #include <net/raw_cb.h>
84 #include <netinet/in.h>
85 #include <netinet/in_var.h>
86 #include <netinet/in_arp.h>
87 #include <netinet/ip.h>
88 #include <netinet/ip6.h>
89 #include <netinet6/nd6.h>
90 
91 #include <IOKit/IOBSD.h>
92 
93 extern struct rtstat rtstat;
94 extern struct domain routedomain_s;
95 static struct domain *routedomain = NULL;
96 
97 static struct sockaddr route_dst = { .sa_len = 2, .sa_family = PF_ROUTE, .sa_data = { 0, } };
98 static struct sockaddr route_src = { .sa_len = 2, .sa_family = PF_ROUTE, .sa_data = { 0, } };
99 static struct sockaddr sa_zero   = { .sa_len = sizeof(sa_zero), .sa_family = AF_INET, .sa_data = { 0, } };
100 
101 struct route_cb {
102 	u_int32_t       ip_count;       /* attached w/ AF_INET */
103 	u_int32_t       ip6_count;      /* attached w/ AF_INET6 */
104 	u_int32_t       any_count;      /* total attached */
105 };
106 
107 static struct route_cb route_cb;
108 
109 struct walkarg {
110 	int     w_tmemsize;
111 	int     w_op, w_arg;
112 	caddr_t w_tmem;
113 	struct sysctl_req *w_req;
114 };
115 
116 static void route_dinit(struct domain *);
117 static int rts_abort(struct socket *);
118 static int rts_attach(struct socket *, int, struct proc *);
119 static int rts_bind(struct socket *, struct sockaddr *, struct proc *);
120 static int rts_connect(struct socket *, struct sockaddr *, struct proc *);
121 static int rts_detach(struct socket *);
122 static int rts_disconnect(struct socket *);
123 static int rts_peeraddr(struct socket *, struct sockaddr **);
124 static int rts_send(struct socket *, int, struct mbuf *, struct sockaddr *,
125     struct mbuf *, struct proc *);
126 static int rts_shutdown(struct socket *);
127 static int rts_sockaddr(struct socket *, struct sockaddr **);
128 
129 static int route_output(struct mbuf *, struct socket *);
130 static int rt_setmetrics(u_int32_t, struct rt_metrics *, struct rtentry *);
131 static void rt_getmetrics(struct rtentry *, struct rt_metrics *);
132 static void rt_setif(struct rtentry *, struct sockaddr *, struct sockaddr *,
133     struct sockaddr *, unsigned int);
134 static int rt_xaddrs(caddr_t, caddr_t, struct rt_addrinfo *);
135 static struct mbuf *rt_msg1(u_char, struct rt_addrinfo *);
136 static int rt_msg2(u_char, struct rt_addrinfo *, caddr_t, struct walkarg *,
137     kauth_cred_t *);
138 static int sysctl_dumpentry(struct radix_node *rn, void *vw);
139 static int sysctl_dumpentry_ext(struct radix_node *rn, void *vw);
140 static int sysctl_iflist(int af, struct walkarg *w);
141 static int sysctl_iflist2(int af, struct walkarg *w);
142 static int sysctl_rtstat(struct sysctl_req *);
143 static int sysctl_rttrash(struct sysctl_req *);
144 static int sysctl_rtsock SYSCTL_HANDLER_ARGS;
145 
146 SYSCTL_NODE(_net, PF_ROUTE, routetable, CTLFLAG_RD | CTLFLAG_LOCKED,
147     sysctl_rtsock, "");
148 
149 SYSCTL_NODE(_net, OID_AUTO, route, CTLFLAG_RW | CTLFLAG_LOCKED, 0, "routing");
150 
151 /* Align x to 1024 (only power of 2) assuming x is positive */
152 #define ALIGN_BYTES(x) do {                                             \
153 	x = (uint32_t)P2ALIGN(x, 1024);                         \
154 } while(0)
155 
156 #define ROUNDUP32(a)                                                    \
157 	((a) > 0 ? (1 + (((a) - 1) | (sizeof (uint32_t) - 1))) :        \
158 	sizeof (uint32_t))
159 
160 #define ADVANCE32(x, n)                                                 \
161 	(x += ROUNDUP32((n)->sa_len))
162 
163 #define RT_HAS_IFADDR(rt)                                               \
164 	((rt)->rt_ifa != NULL && (rt)->rt_ifa->ifa_addr != NULL)
165 
166 /*
167  * It really doesn't make any sense at all for this code to share much
168  * with raw_usrreq.c, since its functionality is so restricted.  XXX
169  */
170 static int
rts_abort(struct socket * so)171 rts_abort(struct socket *so)
172 {
173 	return raw_usrreqs.pru_abort(so);
174 }
175 
176 /* pru_accept is EOPNOTSUPP */
177 
178 static int
rts_attach(struct socket * so,int proto,struct proc * p)179 rts_attach(struct socket *so, int proto, struct proc *p)
180 {
181 #pragma unused(p)
182 	struct rawcb *rp;
183 	int error;
184 
185 	VERIFY(so->so_pcb == NULL);
186 
187 	rp = kalloc_type(struct rawcb, Z_WAITOK_ZERO_NOFAIL);
188 	so->so_pcb = (caddr_t)rp;
189 	/* don't use raw_usrreqs.pru_attach, it checks for SS_PRIV */
190 	error = raw_attach(so, proto);
191 	rp = sotorawcb(so);
192 	if (error) {
193 		kfree_type(struct rawcb, rp);
194 		so->so_pcb = NULL;
195 		so->so_flags |= SOF_PCBCLEARING;
196 		return error;
197 	}
198 
199 	switch (rp->rcb_proto.sp_protocol) {
200 	case AF_INET:
201 		os_atomic_inc(&route_cb.ip_count, relaxed);
202 		break;
203 	case AF_INET6:
204 		os_atomic_inc(&route_cb.ip6_count, relaxed);
205 		break;
206 	}
207 	rp->rcb_faddr = &route_src;
208 	os_atomic_inc(&route_cb.any_count, relaxed);
209 	/* the socket is already locked when we enter rts_attach */
210 	soisconnected(so);
211 	so->so_options |= SO_USELOOPBACK;
212 	return 0;
213 }
214 
215 static int
rts_bind(struct socket * so,struct sockaddr * nam,struct proc * p)216 rts_bind(struct socket *so, struct sockaddr *nam, struct proc *p)
217 {
218 	return raw_usrreqs.pru_bind(so, nam, p); /* xxx just EINVAL */
219 }
220 
221 static int
rts_connect(struct socket * so,struct sockaddr * nam,struct proc * p)222 rts_connect(struct socket *so, struct sockaddr *nam, struct proc *p)
223 {
224 	return raw_usrreqs.pru_connect(so, nam, p); /* XXX just EINVAL */
225 }
226 
227 /* pru_connect2 is EOPNOTSUPP */
228 /* pru_control is EOPNOTSUPP */
229 
230 static int
rts_detach(struct socket * so)231 rts_detach(struct socket *so)
232 {
233 	struct rawcb *rp = sotorawcb(so);
234 
235 	VERIFY(rp != NULL);
236 
237 	switch (rp->rcb_proto.sp_protocol) {
238 	case AF_INET:
239 		os_atomic_dec(&route_cb.ip_count, relaxed);
240 		break;
241 	case AF_INET6:
242 		os_atomic_dec(&route_cb.ip6_count, relaxed);
243 		break;
244 	}
245 	os_atomic_dec(&route_cb.any_count, relaxed);
246 	return raw_usrreqs.pru_detach(so);
247 }
248 
249 static int
rts_disconnect(struct socket * so)250 rts_disconnect(struct socket *so)
251 {
252 	return raw_usrreqs.pru_disconnect(so);
253 }
254 
255 /* pru_listen is EOPNOTSUPP */
256 
257 static int
rts_peeraddr(struct socket * so,struct sockaddr ** nam)258 rts_peeraddr(struct socket *so, struct sockaddr **nam)
259 {
260 	return raw_usrreqs.pru_peeraddr(so, nam);
261 }
262 
263 /* pru_rcvd is EOPNOTSUPP */
264 /* pru_rcvoob is EOPNOTSUPP */
265 
266 static int
rts_send(struct socket * so,int flags,struct mbuf * m,struct sockaddr * nam,struct mbuf * control,struct proc * p)267 rts_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *nam,
268     struct mbuf *control, struct proc *p)
269 {
270 	return raw_usrreqs.pru_send(so, flags, m, nam, control, p);
271 }
272 
273 /* pru_sense is null */
274 
275 static int
rts_shutdown(struct socket * so)276 rts_shutdown(struct socket *so)
277 {
278 	return raw_usrreqs.pru_shutdown(so);
279 }
280 
281 static int
rts_sockaddr(struct socket * so,struct sockaddr ** nam)282 rts_sockaddr(struct socket *so, struct sockaddr **nam)
283 {
284 	return raw_usrreqs.pru_sockaddr(so, nam);
285 }
286 
287 static struct pr_usrreqs route_usrreqs = {
288 	.pru_abort =            rts_abort,
289 	.pru_attach =           rts_attach,
290 	.pru_bind =             rts_bind,
291 	.pru_connect =          rts_connect,
292 	.pru_detach =           rts_detach,
293 	.pru_disconnect =       rts_disconnect,
294 	.pru_peeraddr =         rts_peeraddr,
295 	.pru_send =             rts_send,
296 	.pru_shutdown =         rts_shutdown,
297 	.pru_sockaddr =         rts_sockaddr,
298 	.pru_sosend =           sosend,
299 	.pru_soreceive =        soreceive,
300 };
301 
302 /*ARGSUSED*/
303 static int
route_output(struct mbuf * m,struct socket * so)304 route_output(struct mbuf *m, struct socket *so)
305 {
306 	struct rt_msghdr *rtm = NULL;
307 	size_t rtm_len = 0;
308 	struct rtentry *rt = NULL;
309 	struct rtentry *saved_nrt = NULL;
310 	struct radix_node_head *rnh;
311 	struct rt_addrinfo info;
312 	int len, error = 0;
313 	sa_family_t dst_sa_family = 0;
314 	struct ifnet *ifp = NULL;
315 	struct sockaddr_in dst_in, gate_in;
316 	int sendonlytoself = 0;
317 	unsigned int ifscope = IFSCOPE_NONE;
318 	struct rawcb *rp = NULL;
319 	boolean_t is_router = FALSE;
320 #define senderr(e) { error = (e); goto flush; }
321 	if (m == NULL || ((m->m_len < sizeof(intptr_t)) &&
322 	    (m = m_pullup(m, sizeof(intptr_t))) == NULL)) {
323 		return ENOBUFS;
324 	}
325 	VERIFY(m->m_flags & M_PKTHDR);
326 
327 	/*
328 	 * Unlock the socket (but keep a reference) it won't be
329 	 * accessed until raw_input appends to it.
330 	 */
331 	socket_unlock(so, 0);
332 	lck_mtx_lock(rnh_lock);
333 
334 	len = m->m_pkthdr.len;
335 	if (len < sizeof(*rtm) ||
336 	    len != mtod(m, struct rt_msghdr *)->rtm_msglen) {
337 		info.rti_info[RTAX_DST] = NULL;
338 		senderr(EINVAL);
339 	}
340 	rtm = kalloc_data(len, Z_WAITOK);
341 	if (rtm == NULL) {
342 		info.rti_info[RTAX_DST] = NULL;
343 		senderr(ENOBUFS);
344 	}
345 	rtm_len = (size_t)len;
346 	m_copydata(m, 0, len, (caddr_t)rtm);
347 	if (rtm->rtm_version != RTM_VERSION) {
348 		info.rti_info[RTAX_DST] = NULL;
349 		senderr(EPROTONOSUPPORT);
350 	}
351 
352 	/*
353 	 * Silent version of RTM_GET for Reachabiltiy APIs. We may change
354 	 * all RTM_GETs to be silent in the future, so this is private for now.
355 	 */
356 	if (rtm->rtm_type == RTM_GET_SILENT) {
357 		if (!(so->so_options & SO_USELOOPBACK)) {
358 			senderr(EINVAL);
359 		}
360 		sendonlytoself = 1;
361 		rtm->rtm_type = RTM_GET;
362 	}
363 
364 	/*
365 	 * Perform permission checking, only privileged sockets
366 	 * may perform operations other than RTM_GET
367 	 */
368 	if (rtm->rtm_type != RTM_GET && !(so->so_state & SS_PRIV)) {
369 		info.rti_info[RTAX_DST] = NULL;
370 		senderr(EPERM);
371 	}
372 
373 	rtm->rtm_pid = proc_selfpid();
374 	info.rti_addrs = rtm->rtm_addrs;
375 	if (rt_xaddrs((caddr_t)(rtm + 1), len + (caddr_t)rtm, &info)) {
376 		info.rti_info[RTAX_DST] = NULL;
377 		senderr(EINVAL);
378 	}
379 	if (info.rti_info[RTAX_DST] == NULL ||
380 	    info.rti_info[RTAX_DST]->sa_family >= AF_MAX ||
381 	    (info.rti_info[RTAX_GATEWAY] != NULL &&
382 	    info.rti_info[RTAX_GATEWAY]->sa_family >= AF_MAX)) {
383 		senderr(EINVAL);
384 	}
385 
386 	if (info.rti_info[RTAX_DST]->sa_family == AF_INET &&
387 	    info.rti_info[RTAX_DST]->sa_len != sizeof(struct sockaddr_in)) {
388 		/* At minimum, we need up to sin_addr */
389 		if (info.rti_info[RTAX_DST]->sa_len <
390 		    offsetof(struct sockaddr_in, sin_zero)) {
391 			senderr(EINVAL);
392 		}
393 		bzero(&dst_in, sizeof(dst_in));
394 		dst_in.sin_len = sizeof(dst_in);
395 		dst_in.sin_family = AF_INET;
396 		dst_in.sin_port = SIN(info.rti_info[RTAX_DST])->sin_port;
397 		dst_in.sin_addr = SIN(info.rti_info[RTAX_DST])->sin_addr;
398 		info.rti_info[RTAX_DST] = (struct sockaddr *)&dst_in;
399 		dst_sa_family = info.rti_info[RTAX_DST]->sa_family;
400 	} else if (info.rti_info[RTAX_DST]->sa_family == AF_INET6 &&
401 	    info.rti_info[RTAX_DST]->sa_len < sizeof(struct sockaddr_in6)) {
402 		senderr(EINVAL);
403 	}
404 
405 	if (info.rti_info[RTAX_GATEWAY] != NULL) {
406 		if (info.rti_info[RTAX_GATEWAY]->sa_family == AF_INET &&
407 		    info.rti_info[RTAX_GATEWAY]->sa_len != sizeof(struct sockaddr_in)) {
408 			/* At minimum, we need up to sin_addr */
409 			if (info.rti_info[RTAX_GATEWAY]->sa_len <
410 			    offsetof(struct sockaddr_in, sin_zero)) {
411 				senderr(EINVAL);
412 			}
413 			bzero(&gate_in, sizeof(gate_in));
414 			gate_in.sin_len = sizeof(gate_in);
415 			gate_in.sin_family = AF_INET;
416 			gate_in.sin_port = SIN(info.rti_info[RTAX_GATEWAY])->sin_port;
417 			gate_in.sin_addr = SIN(info.rti_info[RTAX_GATEWAY])->sin_addr;
418 			info.rti_info[RTAX_GATEWAY] = (struct sockaddr *)&gate_in;
419 		} else if (info.rti_info[RTAX_GATEWAY]->sa_family == AF_INET6 &&
420 		    info.rti_info[RTAX_GATEWAY]->sa_len < sizeof(struct sockaddr_in6)) {
421 			senderr(EINVAL);
422 		}
423 	}
424 
425 	if (info.rti_info[RTAX_GENMASK]) {
426 		struct radix_node *t;
427 		t = rn_addmask((caddr_t)info.rti_info[RTAX_GENMASK], 0, 1);
428 		if (t != NULL && Bcmp(info.rti_info[RTAX_GENMASK],
429 		    t->rn_key, *(u_char *)info.rti_info[RTAX_GENMASK]) == 0) {
430 			info.rti_info[RTAX_GENMASK] =
431 			    (struct sockaddr *)(t->rn_key);
432 		} else {
433 			senderr(ENOBUFS);
434 		}
435 	}
436 
437 	/*
438 	 * If RTF_IFSCOPE flag is set, then rtm_index specifies the scope.
439 	 */
440 	if (rtm->rtm_flags & RTF_IFSCOPE) {
441 		if (info.rti_info[RTAX_DST]->sa_family != AF_INET &&
442 		    info.rti_info[RTAX_DST]->sa_family != AF_INET6) {
443 			senderr(EINVAL);
444 		}
445 		ifscope = rtm->rtm_index;
446 	}
447 	/*
448 	 * Block changes on INTCOPROC interfaces.
449 	 */
450 	if (ifscope != IFSCOPE_NONE) {
451 		unsigned int intcoproc_scope = 0;
452 		ifnet_head_lock_shared();
453 		TAILQ_FOREACH(ifp, &ifnet_head, if_link) {
454 			if (IFNET_IS_INTCOPROC(ifp)) {
455 				intcoproc_scope = ifp->if_index;
456 				break;
457 			}
458 		}
459 		ifnet_head_done();
460 		if (intcoproc_scope == ifscope && proc_getpid(current_proc()) != 0) {
461 			senderr(EINVAL);
462 		}
463 	}
464 	/*
465 	 * Require entitlement to change management interfaces
466 	 */
467 	if (management_control_unrestricted == false && if_management_interface_check_needed == true &&
468 	    ifscope != IFSCOPE_NONE && proc_getpid(current_proc()) != 0) {
469 		bool is_management = false;
470 
471 		ifnet_head_lock_shared();
472 		if (IF_INDEX_IN_RANGE(ifscope)) {
473 			ifp = ifindex2ifnet[ifscope];
474 			if (ifp != NULL && IFNET_IS_MANAGEMENT(ifp)) {
475 				is_management = true;
476 			}
477 		}
478 		ifnet_head_done();
479 
480 		if (is_management && !IOCurrentTaskHasEntitlement(MANAGEMENT_CONTROL_ENTITLEMENT)) {
481 			senderr(EINVAL);
482 		}
483 	}
484 
485 	/*
486 	 * RTF_PROXY can only be set internally from within the kernel.
487 	 */
488 	if (rtm->rtm_flags & RTF_PROXY) {
489 		senderr(EINVAL);
490 	}
491 
492 	/*
493 	 * For AF_INET, always zero out the embedded scope ID.  If this is
494 	 * a scoped request, it must be done explicitly by setting RTF_IFSCOPE
495 	 * flag and the corresponding rtm_index value.  This is to prevent
496 	 * false interpretation of the scope ID because it's using the sin_zero
497 	 * field, which might not be properly cleared by the requestor.
498 	 */
499 	if (info.rti_info[RTAX_DST]->sa_family == AF_INET) {
500 		sin_set_ifscope(info.rti_info[RTAX_DST], IFSCOPE_NONE);
501 	}
502 	if (info.rti_info[RTAX_GATEWAY] != NULL &&
503 	    info.rti_info[RTAX_GATEWAY]->sa_family == AF_INET) {
504 		sin_set_ifscope(info.rti_info[RTAX_GATEWAY], IFSCOPE_NONE);
505 	}
506 	if (info.rti_info[RTAX_DST]->sa_family == AF_INET6 &&
507 	    IN6_IS_SCOPE_EMBED(&SIN6(info.rti_info[RTAX_DST])->sin6_addr) &&
508 	    !IN6_IS_ADDR_UNICAST_BASED_MULTICAST(&SIN6(info.rti_info[RTAX_DST])->sin6_addr) &&
509 	    SIN6(info.rti_info[RTAX_DST])->sin6_scope_id == 0) {
510 		SIN6(info.rti_info[RTAX_DST])->sin6_scope_id = ntohs(SIN6(info.rti_info[RTAX_DST])->sin6_addr.s6_addr16[1]);
511 		SIN6(info.rti_info[RTAX_DST])->sin6_addr.s6_addr16[1] = 0;
512 	}
513 
514 	switch (rtm->rtm_type) {
515 	case RTM_ADD:
516 		if (info.rti_info[RTAX_GATEWAY] == NULL) {
517 			senderr(EINVAL);
518 		}
519 
520 		error = rtrequest_scoped_locked(RTM_ADD,
521 		    info.rti_info[RTAX_DST], info.rti_info[RTAX_GATEWAY],
522 		    info.rti_info[RTAX_NETMASK], rtm->rtm_flags, &saved_nrt,
523 		    ifscope);
524 		if (error == 0 && saved_nrt != NULL) {
525 			RT_LOCK(saved_nrt);
526 			/*
527 			 * If the route request specified an interface with
528 			 * IFA and/or IFP, we set the requested interface on
529 			 * the route with rt_setif.  It would be much better
530 			 * to do this inside rtrequest, but that would
531 			 * require passing the desired interface, in some
532 			 * form, to rtrequest.  Since rtrequest is called in
533 			 * so many places (roughly 40 in our source), adding
534 			 * a parameter is to much for us to swallow; this is
535 			 * something for the FreeBSD developers to tackle.
536 			 * Instead, we let rtrequest compute whatever
537 			 * interface it wants, then come in behind it and
538 			 * stick in the interface that we really want.  This
539 			 * works reasonably well except when rtrequest can't
540 			 * figure out what interface to use (with
541 			 * ifa_withroute) and returns ENETUNREACH.  Ideally
542 			 * it shouldn't matter if rtrequest can't figure out
543 			 * the interface if we're going to explicitly set it
544 			 * ourselves anyway.  But practically we can't
545 			 * recover here because rtrequest will not do any of
546 			 * the work necessary to add the route if it can't
547 			 * find an interface.  As long as there is a default
548 			 * route that leads to some interface, rtrequest will
549 			 * find an interface, so this problem should be
550 			 * rarely encountered.
551 			 * [email protected]
552 			 */
553 			rt_setif(saved_nrt,
554 			    info.rti_info[RTAX_IFP], info.rti_info[RTAX_IFA],
555 			    info.rti_info[RTAX_GATEWAY], ifscope);
556 			(void)rt_setmetrics(rtm->rtm_inits, &rtm->rtm_rmx, saved_nrt);
557 			saved_nrt->rt_rmx.rmx_locks &= ~(rtm->rtm_inits);
558 			saved_nrt->rt_rmx.rmx_locks |=
559 			    (rtm->rtm_inits & rtm->rtm_rmx.rmx_locks);
560 			saved_nrt->rt_genmask = info.rti_info[RTAX_GENMASK];
561 			RT_REMREF_LOCKED(saved_nrt);
562 			RT_UNLOCK(saved_nrt);
563 		}
564 		break;
565 
566 	case RTM_DELETE:
567 		error = rtrequest_scoped_locked(RTM_DELETE,
568 		    info.rti_info[RTAX_DST], info.rti_info[RTAX_GATEWAY],
569 		    info.rti_info[RTAX_NETMASK], rtm->rtm_flags, &saved_nrt,
570 		    ifscope);
571 		if (error == 0) {
572 			rt = saved_nrt;
573 			RT_LOCK(rt);
574 			goto report;
575 		}
576 		break;
577 
578 	case RTM_GET:
579 	case RTM_CHANGE:
580 	case RTM_LOCK:
581 		rnh = rt_tables[info.rti_info[RTAX_DST]->sa_family];
582 		if (rnh == NULL) {
583 			senderr(EAFNOSUPPORT);
584 		}
585 		/*
586 		 * Lookup the best match based on the key-mask pair;
587 		 * callee adds a reference and checks for root node.
588 		 */
589 		rt = rt_lookup(TRUE, info.rti_info[RTAX_DST],
590 		    info.rti_info[RTAX_NETMASK], rnh, ifscope);
591 		if (rt == NULL) {
592 			senderr(ESRCH);
593 		}
594 		RT_LOCK(rt);
595 
596 		/*
597 		 * Holding rnh_lock here prevents the possibility of
598 		 * ifa from changing (e.g. in_ifinit), so it is safe
599 		 * to access its ifa_addr (down below) without locking.
600 		 */
601 		switch (rtm->rtm_type) {
602 		case RTM_GET: {
603 			kauth_cred_t cred;
604 			kauth_cred_t* credp;
605 			struct ifaddr *ifa2;
606 report:
607 			cred = kauth_cred_proc_ref(current_proc());
608 			credp = &cred;
609 
610 			ifa2 = NULL;
611 			RT_LOCK_ASSERT_HELD(rt);
612 			info.rti_info[RTAX_DST] = rt_key(rt);
613 			dst_sa_family = info.rti_info[RTAX_DST]->sa_family;
614 			info.rti_info[RTAX_GATEWAY] = rt->rt_gateway;
615 			info.rti_info[RTAX_NETMASK] = rt_mask(rt);
616 			info.rti_info[RTAX_GENMASK] = rt->rt_genmask;
617 			if (rtm->rtm_addrs & (RTA_IFP | RTA_IFA)) {
618 				ifp = rt->rt_ifp;
619 				if (ifp != NULL) {
620 					ifnet_lock_shared(ifp);
621 					ifa2 = ifp->if_lladdr;
622 					info.rti_info[RTAX_IFP] =
623 					    ifa2->ifa_addr;
624 					IFA_ADDREF(ifa2);
625 					ifnet_lock_done(ifp);
626 					info.rti_info[RTAX_IFA] =
627 					    rt->rt_ifa->ifa_addr;
628 					rtm->rtm_index = ifp->if_index;
629 				} else {
630 					info.rti_info[RTAX_IFP] = NULL;
631 					info.rti_info[RTAX_IFA] = NULL;
632 				}
633 			} else if ((ifp = rt->rt_ifp) != NULL) {
634 				rtm->rtm_index = ifp->if_index;
635 			}
636 			if (ifa2 != NULL) {
637 				IFA_LOCK(ifa2);
638 			}
639 			len = rt_msg2(rtm->rtm_type, &info, NULL, NULL, credp);
640 			if (ifa2 != NULL) {
641 				IFA_UNLOCK(ifa2);
642 			}
643 			struct rt_msghdr *out_rtm;
644 			out_rtm = kalloc_data(len, Z_WAITOK);
645 			if (out_rtm == NULL) {
646 				RT_UNLOCK(rt);
647 				if (ifa2 != NULL) {
648 					IFA_REMREF(ifa2);
649 				}
650 				senderr(ENOBUFS);
651 			}
652 			Bcopy(rtm, out_rtm, sizeof(struct rt_msghdr));
653 			if (ifa2 != NULL) {
654 				IFA_LOCK(ifa2);
655 			}
656 			(void) rt_msg2(out_rtm->rtm_type, &info, (caddr_t)out_rtm,
657 			    NULL, &cred);
658 			if (ifa2 != NULL) {
659 				IFA_UNLOCK(ifa2);
660 			}
661 			kfree_data(rtm, rtm_len);
662 			rtm = out_rtm;
663 			rtm_len = len;
664 			rtm->rtm_flags = rt->rt_flags;
665 			rt_getmetrics(rt, &rtm->rtm_rmx);
666 			rtm->rtm_addrs = info.rti_addrs;
667 			if (ifa2 != NULL) {
668 				IFA_REMREF(ifa2);
669 			}
670 
671 			kauth_cred_unref(&cred);
672 			break;
673 		}
674 
675 		case RTM_CHANGE:
676 			is_router = (rt->rt_flags & RTF_ROUTER) ? TRUE : FALSE;
677 
678 			if (info.rti_info[RTAX_GATEWAY] != NULL &&
679 			    (error = rt_setgate(rt, rt_key(rt),
680 			    info.rti_info[RTAX_GATEWAY]))) {
681 				int tmp = error;
682 				RT_UNLOCK(rt);
683 				senderr(tmp);
684 			}
685 			/*
686 			 * If they tried to change things but didn't specify
687 			 * the required gateway, then just use the old one.
688 			 * This can happen if the user tries to change the
689 			 * flags on the default route without changing the
690 			 * default gateway. Changing flags still doesn't work.
691 			 */
692 			if ((rt->rt_flags & RTF_GATEWAY) &&
693 			    info.rti_info[RTAX_GATEWAY] == NULL) {
694 				info.rti_info[RTAX_GATEWAY] = rt->rt_gateway;
695 			}
696 
697 			/*
698 			 * On Darwin, we call rt_setif which contains the
699 			 * equivalent to the code found at this very spot
700 			 * in BSD.
701 			 */
702 			rt_setif(rt,
703 			    info.rti_info[RTAX_IFP], info.rti_info[RTAX_IFA],
704 			    info.rti_info[RTAX_GATEWAY], ifscope);
705 
706 			if ((error = rt_setmetrics(rtm->rtm_inits,
707 			    &rtm->rtm_rmx, rt))) {
708 				int tmp = error;
709 				RT_UNLOCK(rt);
710 				senderr(tmp);
711 			}
712 			if (info.rti_info[RTAX_GENMASK]) {
713 				rt->rt_genmask = info.rti_info[RTAX_GENMASK];
714 			}
715 
716 			/*
717 			 * Enqueue work item to invoke callback for this route entry
718 			 * This may not be needed always, but for now issue it anytime
719 			 * RTM_CHANGE gets called.
720 			 */
721 			route_event_enqueue_nwk_wq_entry(rt, NULL, ROUTE_ENTRY_REFRESH, NULL, TRUE);
722 			/*
723 			 * If the route is for a router, walk the tree to send refresh
724 			 * event to protocol cloned entries
725 			 */
726 			if (is_router) {
727 				struct route_event rt_ev;
728 				route_event_init(&rt_ev, rt, NULL, ROUTE_ENTRY_REFRESH);
729 				RT_UNLOCK(rt);
730 				(void) rnh->rnh_walktree(rnh, route_event_walktree, (void *)&rt_ev);
731 				RT_LOCK(rt);
732 			}
733 			OS_FALLTHROUGH;
734 		case RTM_LOCK:
735 			rt->rt_rmx.rmx_locks &= ~(rtm->rtm_inits);
736 			rt->rt_rmx.rmx_locks |=
737 			    (rtm->rtm_inits & rtm->rtm_rmx.rmx_locks);
738 			break;
739 		}
740 		RT_UNLOCK(rt);
741 		break;
742 	default:
743 		senderr(EOPNOTSUPP);
744 	}
745 flush:
746 	if (rtm != NULL) {
747 		if (error) {
748 			rtm->rtm_errno = error;
749 		} else {
750 			rtm->rtm_flags |= RTF_DONE;
751 		}
752 	}
753 	if (rt != NULL) {
754 		RT_LOCK_ASSERT_NOTHELD(rt);
755 		rtfree_locked(rt);
756 	}
757 	lck_mtx_unlock(rnh_lock);
758 
759 	/* relock the socket now */
760 	socket_lock(so, 0);
761 	/*
762 	 * Check to see if we don't want our own messages.
763 	 */
764 	if (!(so->so_options & SO_USELOOPBACK)) {
765 		if (route_cb.any_count <= 1) {
766 			kfree_data(rtm, rtm_len);
767 			m_freem(m);
768 			return error;
769 		}
770 		/* There is another listener, so construct message */
771 		rp = sotorawcb(so);
772 	}
773 	if (rtm != NULL) {
774 		m_copyback(m, 0, rtm->rtm_msglen, (caddr_t)rtm);
775 		if (m->m_pkthdr.len < rtm->rtm_msglen) {
776 			m_freem(m);
777 			m = NULL;
778 		} else if (m->m_pkthdr.len > rtm->rtm_msglen) {
779 			m_adj(m, rtm->rtm_msglen - m->m_pkthdr.len);
780 		}
781 		kfree_data(rtm, rtm_len);
782 	}
783 	if (sendonlytoself && m != NULL) {
784 		error = 0;
785 		if (sbappendaddr(&so->so_rcv, &route_src, m,
786 		    NULL, &error) != 0) {
787 			sorwakeup(so);
788 		}
789 		if (error) {
790 			return error;
791 		}
792 	} else {
793 		struct sockproto route_proto = { .sp_family = PF_ROUTE, .sp_protocol = 0 };
794 		if (rp != NULL) {
795 			rp->rcb_proto.sp_family = 0; /* Avoid us */
796 		}
797 		if (dst_sa_family != 0) {
798 			route_proto.sp_protocol = dst_sa_family;
799 		}
800 		if (m != NULL) {
801 			socket_unlock(so, 0);
802 			raw_input(m, &route_proto, &route_src, &route_dst);
803 			socket_lock(so, 0);
804 		}
805 		if (rp != NULL) {
806 			rp->rcb_proto.sp_family = PF_ROUTE;
807 		}
808 	}
809 	return error;
810 }
811 
812 void
rt_setexpire(struct rtentry * rt,uint64_t expiry)813 rt_setexpire(struct rtentry *rt, uint64_t expiry)
814 {
815 	/* set both rt_expire and rmx_expire */
816 	rt->rt_expire = expiry;
817 	if (expiry) {
818 		rt->rt_rmx.rmx_expire =
819 		    (int32_t)(expiry + rt->base_calendartime -
820 		    rt->base_uptime);
821 	} else {
822 		rt->rt_rmx.rmx_expire = 0;
823 	}
824 }
825 
826 static int
rt_setmetrics(u_int32_t which,struct rt_metrics * in,struct rtentry * out)827 rt_setmetrics(u_int32_t which, struct rt_metrics *in, struct rtentry *out)
828 {
829 	if (!(which & RTV_REFRESH_HOST)) {
830 		struct timeval caltime;
831 		getmicrotime(&caltime);
832 #define metric(f, e) if (which & (f)) out->rt_rmx.e = in->e;
833 		metric(RTV_RPIPE, rmx_recvpipe);
834 		metric(RTV_SPIPE, rmx_sendpipe);
835 		metric(RTV_SSTHRESH, rmx_ssthresh);
836 		metric(RTV_RTT, rmx_rtt);
837 		metric(RTV_RTTVAR, rmx_rttvar);
838 		metric(RTV_HOPCOUNT, rmx_hopcount);
839 		metric(RTV_MTU, rmx_mtu);
840 		metric(RTV_EXPIRE, rmx_expire);
841 #undef metric
842 		if (out->rt_rmx.rmx_expire > 0) {
843 			/* account for system time change */
844 			getmicrotime(&caltime);
845 			out->base_calendartime +=
846 			    NET_CALCULATE_CLOCKSKEW(caltime,
847 			    out->base_calendartime,
848 			    net_uptime(), out->base_uptime);
849 			rt_setexpire(out,
850 			    out->rt_rmx.rmx_expire -
851 			    out->base_calendartime +
852 			    out->base_uptime);
853 		} else {
854 			rt_setexpire(out, 0);
855 		}
856 
857 		VERIFY(out->rt_expire == 0 || out->rt_rmx.rmx_expire != 0);
858 		VERIFY(out->rt_expire != 0 || out->rt_rmx.rmx_expire == 0);
859 	} else {
860 		/* Only RTV_REFRESH_HOST must be set */
861 		if ((which & ~RTV_REFRESH_HOST) ||
862 		    (out->rt_flags & RTF_STATIC) ||
863 		    !(out->rt_flags & RTF_LLINFO)) {
864 			return EINVAL;
865 		}
866 
867 		if (out->rt_llinfo_refresh == NULL) {
868 			return ENOTSUP;
869 		}
870 
871 		out->rt_llinfo_refresh(out);
872 	}
873 	return 0;
874 }
875 
876 static void
rt_getmetrics(struct rtentry * in,struct rt_metrics * out)877 rt_getmetrics(struct rtentry *in, struct rt_metrics *out)
878 {
879 	struct timeval caltime;
880 
881 	VERIFY(in->rt_expire == 0 || in->rt_rmx.rmx_expire != 0);
882 	VERIFY(in->rt_expire != 0 || in->rt_rmx.rmx_expire == 0);
883 
884 	*out = in->rt_rmx;
885 
886 	if (in->rt_expire != 0) {
887 		/* account for system time change */
888 		getmicrotime(&caltime);
889 
890 		in->base_calendartime +=
891 		    NET_CALCULATE_CLOCKSKEW(caltime,
892 		    in->base_calendartime, net_uptime(), in->base_uptime);
893 
894 		out->rmx_expire = (int32_t)(in->base_calendartime +
895 		    in->rt_expire - in->base_uptime);
896 	} else {
897 		out->rmx_expire = 0;
898 	}
899 }
900 
901 /*
902  * Set route's interface given info.rti_info[RTAX_IFP],
903  * info.rti_info[RTAX_IFA], and gateway.
904  */
905 static void
rt_setif(struct rtentry * rt,struct sockaddr * Ifpaddr,struct sockaddr * Ifaaddr,struct sockaddr * Gate,unsigned int ifscope)906 rt_setif(struct rtentry *rt, struct sockaddr *Ifpaddr, struct sockaddr *Ifaaddr,
907     struct sockaddr *Gate, unsigned int ifscope)
908 {
909 	struct ifaddr *ifa = NULL;
910 	struct ifnet *ifp = NULL;
911 	void (*ifa_rtrequest)(int, struct rtentry *, struct sockaddr *);
912 
913 	LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_OWNED);
914 
915 	RT_LOCK_ASSERT_HELD(rt);
916 
917 	/* Don't update a defunct route */
918 	if (rt->rt_flags & RTF_CONDEMNED) {
919 		return;
920 	}
921 
922 	/* Add an extra ref for ourselves */
923 	RT_ADDREF_LOCKED(rt);
924 
925 	/* Become a regular mutex, just in case */
926 	RT_CONVERT_LOCK(rt);
927 
928 	/*
929 	 * New gateway could require new ifaddr, ifp; flags may also
930 	 * be different; ifp may be specified by ll sockaddr when
931 	 * protocol address is ambiguous.
932 	 */
933 	if (Ifpaddr && (ifa = ifa_ifwithnet_scoped(Ifpaddr, ifscope)) &&
934 	    (ifp = ifa->ifa_ifp) && (Ifaaddr || Gate)) {
935 		IFA_REMREF(ifa);
936 		ifa = ifaof_ifpforaddr(Ifaaddr ? Ifaaddr : Gate, ifp);
937 	} else {
938 		if (ifa != NULL) {
939 			IFA_REMREF(ifa);
940 			ifa = NULL;
941 		}
942 		if (Ifpaddr && (ifp = if_withname(Ifpaddr))) {
943 			if (Gate) {
944 				ifa = ifaof_ifpforaddr(Gate, ifp);
945 			} else {
946 				ifnet_lock_shared(ifp);
947 				ifa = TAILQ_FIRST(&ifp->if_addrhead);
948 				if (ifa != NULL) {
949 					IFA_ADDREF(ifa);
950 				}
951 				ifnet_lock_done(ifp);
952 			}
953 		} else if (Ifaaddr &&
954 		    (ifa = ifa_ifwithaddr_scoped(Ifaaddr, ifscope))) {
955 			ifp = ifa->ifa_ifp;
956 		} else if (Gate != NULL) {
957 			/*
958 			 * Safe to drop rt_lock and use rt_key, since holding
959 			 * rnh_lock here prevents another thread from calling
960 			 * rt_setgate() on this route.  We cannot hold the
961 			 * lock across ifa_ifwithroute since the lookup done
962 			 * by that routine may point to the same route.
963 			 */
964 			RT_UNLOCK(rt);
965 			if ((ifa = ifa_ifwithroute_scoped_locked(rt->rt_flags,
966 			    rt_key(rt), Gate, ifscope)) != NULL) {
967 				ifp = ifa->ifa_ifp;
968 			}
969 			RT_LOCK(rt);
970 			/* Don't update a defunct route */
971 			if (rt->rt_flags & RTF_CONDEMNED) {
972 				if (ifa != NULL) {
973 					IFA_REMREF(ifa);
974 				}
975 				/* Release extra ref */
976 				RT_REMREF_LOCKED(rt);
977 				return;
978 			}
979 		}
980 	}
981 
982 	/* trigger route cache reevaluation */
983 	if (rt_key(rt)->sa_family == AF_INET) {
984 		routegenid_inet_update();
985 	} else if (rt_key(rt)->sa_family == AF_INET6) {
986 		routegenid_inet6_update();
987 	}
988 
989 	if (ifa != NULL) {
990 		struct ifaddr *oifa = rt->rt_ifa;
991 		if (oifa != ifa) {
992 			if (oifa != NULL) {
993 				IFA_LOCK_SPIN(oifa);
994 				ifa_rtrequest = oifa->ifa_rtrequest;
995 				IFA_UNLOCK(oifa);
996 				if (ifa_rtrequest != NULL) {
997 					ifa_rtrequest(RTM_DELETE, rt, Gate);
998 				}
999 			}
1000 			rtsetifa(rt, ifa);
1001 
1002 			if (rt->rt_ifp != ifp) {
1003 				/*
1004 				 * Purge any link-layer info caching.
1005 				 */
1006 				if (rt->rt_llinfo_purge != NULL) {
1007 					rt->rt_llinfo_purge(rt);
1008 				}
1009 
1010 				/*
1011 				 * Adjust route ref count for the interfaces.
1012 				 */
1013 				if (rt->rt_if_ref_fn != NULL) {
1014 					rt->rt_if_ref_fn(ifp, 1);
1015 					rt->rt_if_ref_fn(rt->rt_ifp, -1);
1016 				}
1017 			}
1018 			rt->rt_ifp = ifp;
1019 			/*
1020 			 * If this is the (non-scoped) default route, record
1021 			 * the interface index used for the primary ifscope.
1022 			 */
1023 			if (rt_primary_default(rt, rt_key(rt))) {
1024 				set_primary_ifscope(rt_key(rt)->sa_family,
1025 				    rt->rt_ifp->if_index);
1026 			}
1027 			/*
1028 			 * If rmx_mtu is not locked, update it
1029 			 * to the MTU used by the new interface.
1030 			 */
1031 			if (!(rt->rt_rmx.rmx_locks & RTV_MTU)) {
1032 				rt->rt_rmx.rmx_mtu = rt->rt_ifp->if_mtu;
1033 				if (rt_key(rt)->sa_family == AF_INET &&
1034 				    INTF_ADJUST_MTU_FOR_CLAT46(ifp)) {
1035 					rt->rt_rmx.rmx_mtu = IN6_LINKMTU(rt->rt_ifp);
1036 					/* Further adjust the size for CLAT46 expansion */
1037 					rt->rt_rmx.rmx_mtu -= CLAT46_HDR_EXPANSION_OVERHD;
1038 				}
1039 			}
1040 
1041 			if (rt->rt_ifa != NULL) {
1042 				IFA_LOCK_SPIN(rt->rt_ifa);
1043 				ifa_rtrequest = rt->rt_ifa->ifa_rtrequest;
1044 				IFA_UNLOCK(rt->rt_ifa);
1045 				if (ifa_rtrequest != NULL) {
1046 					ifa_rtrequest(RTM_ADD, rt, Gate);
1047 				}
1048 			}
1049 			IFA_REMREF(ifa);
1050 			/* Release extra ref */
1051 			RT_REMREF_LOCKED(rt);
1052 			return;
1053 		}
1054 		IFA_REMREF(ifa);
1055 		ifa = NULL;
1056 	}
1057 
1058 	/* XXX: to reset gateway to correct value, at RTM_CHANGE */
1059 	if (rt->rt_ifa != NULL) {
1060 		IFA_LOCK_SPIN(rt->rt_ifa);
1061 		ifa_rtrequest = rt->rt_ifa->ifa_rtrequest;
1062 		IFA_UNLOCK(rt->rt_ifa);
1063 		if (ifa_rtrequest != NULL) {
1064 			ifa_rtrequest(RTM_ADD, rt, Gate);
1065 		}
1066 	}
1067 
1068 	/*
1069 	 * Workaround for local address routes pointing to the loopback
1070 	 * interface added by configd, until <rdar://problem/12970142>.
1071 	 */
1072 	if ((rt->rt_ifp->if_flags & IFF_LOOPBACK) &&
1073 	    (rt->rt_flags & RTF_HOST) && rt->rt_ifa->ifa_ifp == rt->rt_ifp) {
1074 		ifa = ifa_ifwithaddr(rt_key(rt));
1075 		if (ifa != NULL) {
1076 			if (ifa != rt->rt_ifa) {
1077 				rtsetifa(rt, ifa);
1078 			}
1079 			IFA_REMREF(ifa);
1080 		}
1081 	}
1082 
1083 	/* Release extra ref */
1084 	RT_REMREF_LOCKED(rt);
1085 }
1086 
1087 /*
1088  * Extract the addresses of the passed sockaddrs.
1089  * Do a little sanity checking so as to avoid bad memory references.
1090  * This data is derived straight from userland.
1091  */
1092 static int
rt_xaddrs(caddr_t cp,caddr_t cplim,struct rt_addrinfo * rtinfo)1093 rt_xaddrs(caddr_t cp, caddr_t cplim, struct rt_addrinfo *rtinfo)
1094 {
1095 	struct sockaddr *sa;
1096 	int i;
1097 
1098 	bzero(rtinfo->rti_info, sizeof(rtinfo->rti_info));
1099 	for (i = 0; (i < RTAX_MAX) && (cp < cplim); i++) {
1100 		if ((rtinfo->rti_addrs & (1 << i)) == 0) {
1101 			continue;
1102 		}
1103 		sa = (struct sockaddr *)cp;
1104 		/*
1105 		 * It won't fit.
1106 		 */
1107 		if ((cp + sa->sa_len) > cplim) {
1108 			return EINVAL;
1109 		}
1110 		if (sa->sa_len > sizeof(struct sockaddr_storage)) {
1111 			return EINVAL;
1112 		}
1113 		/*
1114 		 * there are no more.. quit now
1115 		 * If there are more bits, they are in error.
1116 		 * I've seen this. route(1) can evidently generate these.
1117 		 * This causes kernel to core dump.
1118 		 * for compatibility, If we see this, point to a safe address.
1119 		 */
1120 		if (sa->sa_len == 0) {
1121 			rtinfo->rti_info[i] = &sa_zero;
1122 			return 0; /* should be EINVAL but for compat */
1123 		}
1124 		if (sa->sa_len < offsetof(struct sockaddr, sa_data)) {
1125 			return EINVAL;
1126 		}
1127 		/* accept it */
1128 		rtinfo->rti_info[i] = sa;
1129 		ADVANCE32(cp, sa);
1130 	}
1131 	return 0;
1132 }
1133 
1134 static struct mbuf *
rt_msg1(u_char type,struct rt_addrinfo * rtinfo)1135 rt_msg1(u_char type, struct rt_addrinfo *rtinfo)
1136 {
1137 	struct rt_msghdr *rtm;
1138 	struct mbuf *m;
1139 	int i;
1140 	int len, dlen, off;
1141 
1142 	switch (type) {
1143 	case RTM_DELADDR:
1144 	case RTM_NEWADDR:
1145 		len = sizeof(struct ifa_msghdr);
1146 		break;
1147 
1148 	case RTM_DELMADDR:
1149 	case RTM_NEWMADDR:
1150 		len = sizeof(struct ifma_msghdr);
1151 		break;
1152 
1153 	case RTM_IFINFO:
1154 		len = sizeof(struct if_msghdr);
1155 		break;
1156 
1157 	default:
1158 		len = sizeof(struct rt_msghdr);
1159 	}
1160 	m = m_gethdr(M_DONTWAIT, MT_DATA);
1161 	if (m && len > MHLEN) {
1162 		MCLGET(m, M_DONTWAIT);
1163 		if (!(m->m_flags & M_EXT)) {
1164 			m_free(m);
1165 			m = NULL;
1166 		}
1167 	}
1168 	if (m == NULL) {
1169 		return NULL;
1170 	}
1171 	m->m_pkthdr.len = m->m_len = len;
1172 	m->m_pkthdr.rcvif = NULL;
1173 	rtm = mtod(m, struct rt_msghdr *);
1174 	bzero((caddr_t)rtm, len);
1175 	off = len;
1176 	for (i = 0; i < RTAX_MAX; i++) {
1177 		struct sockaddr *sa, *hint;
1178 		uint8_t ssbuf[SOCK_MAXADDRLEN + 1];
1179 
1180 		/*
1181 		 * Make sure to accomodate the largest possible size of sa_len.
1182 		 */
1183 		_CASSERT(sizeof(ssbuf) == (SOCK_MAXADDRLEN + 1));
1184 
1185 		if ((sa = rtinfo->rti_info[i]) == NULL) {
1186 			continue;
1187 		}
1188 
1189 		switch (i) {
1190 		case RTAX_DST:
1191 		case RTAX_NETMASK:
1192 			if ((hint = rtinfo->rti_info[RTAX_DST]) == NULL) {
1193 				hint = rtinfo->rti_info[RTAX_IFA];
1194 			}
1195 
1196 			/* Scrub away any trace of embedded interface scope */
1197 			sa = rtm_scrub(type, i, hint, sa, &ssbuf,
1198 			    sizeof(ssbuf), NULL);
1199 			break;
1200 
1201 		default:
1202 			break;
1203 		}
1204 
1205 		rtinfo->rti_addrs |= (1 << i);
1206 		dlen = sa->sa_len;
1207 		m_copyback(m, off, dlen, (caddr_t)sa);
1208 		len = off + dlen;
1209 		off += ROUNDUP32(dlen);
1210 	}
1211 	if (m->m_pkthdr.len != len) {
1212 		m_freem(m);
1213 		return NULL;
1214 	}
1215 	rtm->rtm_msglen = (u_short)len;
1216 	rtm->rtm_version = RTM_VERSION;
1217 	rtm->rtm_type = type;
1218 	return m;
1219 }
1220 
1221 static int
rt_msg2(u_char type,struct rt_addrinfo * rtinfo,caddr_t cp,struct walkarg * w,kauth_cred_t * credp)1222 rt_msg2(u_char type, struct rt_addrinfo *rtinfo, caddr_t cp, struct walkarg *w,
1223     kauth_cred_t* credp)
1224 {
1225 	int i;
1226 	int len, dlen, rlen, second_time = 0;
1227 	caddr_t cp0;
1228 
1229 	rtinfo->rti_addrs = 0;
1230 again:
1231 	switch (type) {
1232 	case RTM_DELADDR:
1233 	case RTM_NEWADDR:
1234 		len = sizeof(struct ifa_msghdr);
1235 		break;
1236 
1237 	case RTM_DELMADDR:
1238 	case RTM_NEWMADDR:
1239 		len = sizeof(struct ifma_msghdr);
1240 		break;
1241 
1242 	case RTM_IFINFO:
1243 		len = sizeof(struct if_msghdr);
1244 		break;
1245 
1246 	case RTM_IFINFO2:
1247 		len = sizeof(struct if_msghdr2);
1248 		break;
1249 
1250 	case RTM_NEWMADDR2:
1251 		len = sizeof(struct ifma_msghdr2);
1252 		break;
1253 
1254 	case RTM_GET_EXT:
1255 		len = sizeof(struct rt_msghdr_ext);
1256 		break;
1257 
1258 	case RTM_GET2:
1259 		len = sizeof(struct rt_msghdr2);
1260 		break;
1261 
1262 	default:
1263 		len = sizeof(struct rt_msghdr);
1264 	}
1265 	cp0 = cp;
1266 	if (cp0) {
1267 		cp += len;
1268 	}
1269 	for (i = 0; i < RTAX_MAX; i++) {
1270 		struct sockaddr *sa, *hint;
1271 		uint8_t ssbuf[SOCK_MAXADDRLEN + 1];
1272 
1273 		/*
1274 		 * Make sure to accomodate the largest possible size of sa_len.
1275 		 */
1276 		_CASSERT(sizeof(ssbuf) == (SOCK_MAXADDRLEN + 1));
1277 
1278 		if ((sa = rtinfo->rti_info[i]) == NULL) {
1279 			continue;
1280 		}
1281 
1282 		switch (i) {
1283 		case RTAX_DST:
1284 		case RTAX_NETMASK:
1285 			if ((hint = rtinfo->rti_info[RTAX_DST]) == NULL) {
1286 				hint = rtinfo->rti_info[RTAX_IFA];
1287 			}
1288 
1289 			/* Scrub away any trace of embedded interface scope */
1290 			sa = rtm_scrub(type, i, hint, sa, &ssbuf,
1291 			    sizeof(ssbuf), NULL);
1292 			break;
1293 		case RTAX_GATEWAY:
1294 		case RTAX_IFP:
1295 			sa = rtm_scrub(type, i, NULL, sa, &ssbuf,
1296 			    sizeof(ssbuf), credp);
1297 			break;
1298 
1299 		default:
1300 			break;
1301 		}
1302 
1303 		rtinfo->rti_addrs |= (1 << i);
1304 		dlen = sa->sa_len;
1305 		rlen = ROUNDUP32(dlen);
1306 		if (cp) {
1307 			bcopy((caddr_t)sa, cp, (size_t)dlen);
1308 			if (dlen != rlen) {
1309 				bzero(cp + dlen, rlen - dlen);
1310 			}
1311 			cp += rlen;
1312 		}
1313 		len += rlen;
1314 	}
1315 	if (cp == NULL && w != NULL && !second_time) {
1316 		struct walkarg *rw = w;
1317 
1318 		if (rw->w_req != NULL) {
1319 			if (rw->w_tmemsize < len) {
1320 				if (rw->w_tmem != NULL) {
1321 					kfree_data(rw->w_tmem, rw->w_tmemsize);
1322 				}
1323 				rw->w_tmem = (caddr_t) kalloc_data(len, Z_ZERO | Z_WAITOK);
1324 				if (rw->w_tmem != NULL) {
1325 					rw->w_tmemsize = len;
1326 				}
1327 			}
1328 			if (rw->w_tmem != NULL) {
1329 				cp = rw->w_tmem;
1330 				second_time = 1;
1331 				goto again;
1332 			}
1333 		}
1334 	}
1335 	if (cp) {
1336 		struct rt_msghdr *rtm = (struct rt_msghdr *)(void *)cp0;
1337 
1338 		rtm->rtm_version = RTM_VERSION;
1339 		rtm->rtm_type = type;
1340 		rtm->rtm_msglen = (u_short)len;
1341 	}
1342 	return len;
1343 }
1344 
1345 /*
1346  * This routine is called to generate a message from the routing
1347  * socket indicating that a redirect has occurred, a routing lookup
1348  * has failed, or that a protocol has detected timeouts to a particular
1349  * destination.
1350  */
1351 void
rt_missmsg(u_char type,struct rt_addrinfo * rtinfo,int flags,int error)1352 rt_missmsg(u_char type, struct rt_addrinfo *rtinfo, int flags, int error)
1353 {
1354 	struct rt_msghdr *rtm;
1355 	struct mbuf *m;
1356 	struct sockaddr *sa = rtinfo->rti_info[RTAX_DST];
1357 	struct sockproto route_proto = { .sp_family = PF_ROUTE, .sp_protocol = 0 };
1358 
1359 	if (route_cb.any_count == 0) {
1360 		return;
1361 	}
1362 	m = rt_msg1(type, rtinfo);
1363 	if (m == NULL) {
1364 		return;
1365 	}
1366 	rtm = mtod(m, struct rt_msghdr *);
1367 	rtm->rtm_flags = RTF_DONE | flags;
1368 	rtm->rtm_errno = error;
1369 	rtm->rtm_addrs = rtinfo->rti_addrs;
1370 	route_proto.sp_family = sa ? sa->sa_family : 0;
1371 	raw_input(m, &route_proto, &route_src, &route_dst);
1372 }
1373 
1374 /*
1375  * This routine is called to generate a message from the routing
1376  * socket indicating that the status of a network interface has changed.
1377  */
1378 void
rt_ifmsg(struct ifnet * ifp)1379 rt_ifmsg(struct ifnet *ifp)
1380 {
1381 	struct if_msghdr *ifm;
1382 	struct mbuf *m;
1383 	struct rt_addrinfo info;
1384 	struct  sockproto route_proto = { .sp_family = PF_ROUTE, .sp_protocol = 0 };
1385 
1386 	if (route_cb.any_count == 0) {
1387 		return;
1388 	}
1389 	bzero((caddr_t)&info, sizeof(info));
1390 	m = rt_msg1(RTM_IFINFO, &info);
1391 	if (m == NULL) {
1392 		return;
1393 	}
1394 	ifm = mtod(m, struct if_msghdr *);
1395 	ifm->ifm_index = ifp->if_index;
1396 	ifm->ifm_flags = (u_short)ifp->if_flags;
1397 	if_data_internal_to_if_data(ifp, &ifp->if_data, &ifm->ifm_data);
1398 	ifm->ifm_addrs = 0;
1399 	raw_input(m, &route_proto, &route_src, &route_dst);
1400 }
1401 
1402 /*
1403  * This is called to generate messages from the routing socket
1404  * indicating a network interface has had addresses associated with it.
1405  * if we ever reverse the logic and replace messages TO the routing
1406  * socket indicate a request to configure interfaces, then it will
1407  * be unnecessary as the routing socket will automatically generate
1408  * copies of it.
1409  *
1410  * Since this is coming from the interface, it is expected that the
1411  * interface will be locked.  Caller must hold rnh_lock and rt_lock.
1412  */
1413 void
rt_newaddrmsg(u_char cmd,struct ifaddr * ifa,int error,struct rtentry * rt)1414 rt_newaddrmsg(u_char cmd, struct ifaddr *ifa, int error, struct rtentry *rt)
1415 {
1416 	struct rt_addrinfo info;
1417 	struct sockaddr *sa = 0;
1418 	int pass;
1419 	struct mbuf *m = 0;
1420 	struct ifnet *ifp = ifa->ifa_ifp;
1421 	struct sockproto route_proto = { .sp_family = PF_ROUTE, .sp_protocol = 0 };
1422 
1423 	LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_OWNED);
1424 	RT_LOCK_ASSERT_HELD(rt);
1425 
1426 	if (route_cb.any_count == 0) {
1427 		return;
1428 	}
1429 
1430 	/* Become a regular mutex, just in case */
1431 	RT_CONVERT_LOCK(rt);
1432 	for (pass = 1; pass < 3; pass++) {
1433 		bzero((caddr_t)&info, sizeof(info));
1434 		if ((cmd == RTM_ADD && pass == 1) ||
1435 		    (cmd == RTM_DELETE && pass == 2)) {
1436 			struct ifa_msghdr *ifam;
1437 			u_char ncmd = cmd == RTM_ADD ? RTM_NEWADDR : RTM_DELADDR;
1438 
1439 			/* Lock ifp for if_lladdr */
1440 			ifnet_lock_shared(ifp);
1441 			IFA_LOCK(ifa);
1442 			info.rti_info[RTAX_IFA] = sa = ifa->ifa_addr;
1443 			/*
1444 			 * Holding ifnet lock here prevents the link address
1445 			 * from changing contents, so no need to hold its
1446 			 * lock.  The link address is always present; it's
1447 			 * never freed.
1448 			 */
1449 			info.rti_info[RTAX_IFP] = ifp->if_lladdr->ifa_addr;
1450 			info.rti_info[RTAX_NETMASK] = ifa->ifa_netmask;
1451 			info.rti_info[RTAX_BRD] = ifa->ifa_dstaddr;
1452 			if ((m = rt_msg1(ncmd, &info)) == NULL) {
1453 				IFA_UNLOCK(ifa);
1454 				ifnet_lock_done(ifp);
1455 				continue;
1456 			}
1457 			IFA_UNLOCK(ifa);
1458 			ifnet_lock_done(ifp);
1459 			ifam = mtod(m, struct ifa_msghdr *);
1460 			ifam->ifam_index = ifp->if_index;
1461 			IFA_LOCK_SPIN(ifa);
1462 			ifam->ifam_metric = ifa->ifa_metric;
1463 			ifam->ifam_flags = ifa->ifa_flags;
1464 			IFA_UNLOCK(ifa);
1465 			ifam->ifam_addrs = info.rti_addrs;
1466 		}
1467 		if ((cmd == RTM_ADD && pass == 2) ||
1468 		    (cmd == RTM_DELETE && pass == 1)) {
1469 			struct rt_msghdr *rtm;
1470 
1471 			if (rt == NULL) {
1472 				continue;
1473 			}
1474 			info.rti_info[RTAX_NETMASK] = rt_mask(rt);
1475 			info.rti_info[RTAX_DST] = sa = rt_key(rt);
1476 			info.rti_info[RTAX_GATEWAY] = rt->rt_gateway;
1477 			if ((m = rt_msg1(cmd, &info)) == NULL) {
1478 				continue;
1479 			}
1480 			rtm = mtod(m, struct rt_msghdr *);
1481 			rtm->rtm_index = ifp->if_index;
1482 			rtm->rtm_flags |= rt->rt_flags;
1483 			rtm->rtm_errno = error;
1484 			rtm->rtm_addrs = info.rti_addrs;
1485 		}
1486 		route_proto.sp_protocol = sa ? sa->sa_family : 0;
1487 		raw_input(m, &route_proto, &route_src, &route_dst);
1488 	}
1489 }
1490 
1491 /*
1492  * This is the analogue to the rt_newaddrmsg which performs the same
1493  * function but for multicast group memberhips.  This is easier since
1494  * there is no route state to worry about.
1495  */
1496 void
rt_newmaddrmsg(u_char cmd,struct ifmultiaddr * ifma)1497 rt_newmaddrmsg(u_char cmd, struct ifmultiaddr *ifma)
1498 {
1499 	struct rt_addrinfo info;
1500 	struct mbuf *m = 0;
1501 	struct ifnet *ifp = ifma->ifma_ifp;
1502 	struct ifma_msghdr *ifmam;
1503 	struct sockproto route_proto = { .sp_family = PF_ROUTE, .sp_protocol = 0 };
1504 
1505 	if (route_cb.any_count == 0) {
1506 		return;
1507 	}
1508 
1509 	/* Lock ifp for if_lladdr */
1510 	ifnet_lock_shared(ifp);
1511 	bzero((caddr_t)&info, sizeof(info));
1512 	IFMA_LOCK(ifma);
1513 	info.rti_info[RTAX_IFA] = ifma->ifma_addr;
1514 	/* lladdr doesn't need lock */
1515 	info.rti_info[RTAX_IFP] = ifp->if_lladdr->ifa_addr;
1516 
1517 	/*
1518 	 * If a link-layer address is present, present it as a ``gateway''
1519 	 * (similarly to how ARP entries, e.g., are presented).
1520 	 */
1521 	info.rti_info[RTAX_GATEWAY] = (ifma->ifma_ll != NULL) ?
1522 	    ifma->ifma_ll->ifma_addr : NULL;
1523 	if ((m = rt_msg1(cmd, &info)) == NULL) {
1524 		IFMA_UNLOCK(ifma);
1525 		ifnet_lock_done(ifp);
1526 		return;
1527 	}
1528 	ifmam = mtod(m, struct ifma_msghdr *);
1529 	ifmam->ifmam_index = ifp->if_index;
1530 	ifmam->ifmam_addrs = info.rti_addrs;
1531 	route_proto.sp_protocol = ifma->ifma_addr->sa_family;
1532 	IFMA_UNLOCK(ifma);
1533 	ifnet_lock_done(ifp);
1534 	raw_input(m, &route_proto, &route_src, &route_dst);
1535 }
1536 
1537 const char *
rtm2str(int cmd)1538 rtm2str(int cmd)
1539 {
1540 	const char *c = "RTM_?";
1541 
1542 	switch (cmd) {
1543 	case RTM_ADD:
1544 		c = "RTM_ADD";
1545 		break;
1546 	case RTM_DELETE:
1547 		c = "RTM_DELETE";
1548 		break;
1549 	case RTM_CHANGE:
1550 		c = "RTM_CHANGE";
1551 		break;
1552 	case RTM_GET:
1553 		c = "RTM_GET";
1554 		break;
1555 	case RTM_LOSING:
1556 		c = "RTM_LOSING";
1557 		break;
1558 	case RTM_REDIRECT:
1559 		c = "RTM_REDIRECT";
1560 		break;
1561 	case RTM_MISS:
1562 		c = "RTM_MISS";
1563 		break;
1564 	case RTM_LOCK:
1565 		c = "RTM_LOCK";
1566 		break;
1567 	case RTM_OLDADD:
1568 		c = "RTM_OLDADD";
1569 		break;
1570 	case RTM_OLDDEL:
1571 		c = "RTM_OLDDEL";
1572 		break;
1573 	case RTM_RESOLVE:
1574 		c = "RTM_RESOLVE";
1575 		break;
1576 	case RTM_NEWADDR:
1577 		c = "RTM_NEWADDR";
1578 		break;
1579 	case RTM_DELADDR:
1580 		c = "RTM_DELADDR";
1581 		break;
1582 	case RTM_IFINFO:
1583 		c = "RTM_IFINFO";
1584 		break;
1585 	case RTM_NEWMADDR:
1586 		c = "RTM_NEWMADDR";
1587 		break;
1588 	case RTM_DELMADDR:
1589 		c = "RTM_DELMADDR";
1590 		break;
1591 	case RTM_GET_SILENT:
1592 		c = "RTM_GET_SILENT";
1593 		break;
1594 	case RTM_IFINFO2:
1595 		c = "RTM_IFINFO2";
1596 		break;
1597 	case RTM_NEWMADDR2:
1598 		c = "RTM_NEWMADDR2";
1599 		break;
1600 	case RTM_GET2:
1601 		c = "RTM_GET2";
1602 		break;
1603 	case RTM_GET_EXT:
1604 		c = "RTM_GET_EXT";
1605 		break;
1606 	}
1607 
1608 	return c;
1609 }
1610 
1611 /*
1612  * This is used in dumping the kernel table via sysctl().
1613  */
1614 static int
sysctl_dumpentry(struct radix_node * rn,void * vw)1615 sysctl_dumpentry(struct radix_node *rn, void *vw)
1616 {
1617 	struct walkarg *w = vw;
1618 	struct rtentry *rt = (struct rtentry *)rn;
1619 	int error = 0, size;
1620 	struct rt_addrinfo info;
1621 	kauth_cred_t cred;
1622 	kauth_cred_t *credp;
1623 
1624 	cred = kauth_cred_proc_ref(current_proc());
1625 	credp = &cred;
1626 
1627 	RT_LOCK(rt);
1628 	if ((w->w_op == NET_RT_FLAGS || w->w_op == NET_RT_FLAGS_PRIV) &&
1629 	    !(rt->rt_flags & w->w_arg)) {
1630 		goto done;
1631 	}
1632 
1633 	/*
1634 	 * If the matching route has RTF_LLINFO set, then we can skip scrubbing the MAC
1635 	 * only if the outgoing interface is not loopback and the process has entitlement
1636 	 * for neighbor cache read.
1637 	 */
1638 	if (w->w_op == NET_RT_FLAGS_PRIV && (rt->rt_flags & RTF_LLINFO)) {
1639 		if (rt->rt_ifp != lo_ifp &&
1640 		    (route_op_entitlement_check(NULL, cred, ROUTE_OP_READ, TRUE) == 0)) {
1641 			credp = NULL;
1642 		}
1643 	}
1644 
1645 	bzero((caddr_t)&info, sizeof(info));
1646 	info.rti_info[RTAX_DST] = rt_key(rt);
1647 	info.rti_info[RTAX_GATEWAY] = rt->rt_gateway;
1648 	info.rti_info[RTAX_NETMASK] = rt_mask(rt);
1649 	info.rti_info[RTAX_GENMASK] = rt->rt_genmask;
1650 	if (RT_HAS_IFADDR(rt)) {
1651 		info.rti_info[RTAX_IFA] = rt->rt_ifa->ifa_addr;
1652 	}
1653 
1654 	if (w->w_op != NET_RT_DUMP2) {
1655 		size = rt_msg2(RTM_GET, &info, NULL, w, credp);
1656 		if (w->w_req != NULL && w->w_tmem != NULL) {
1657 			struct rt_msghdr *rtm =
1658 			    (struct rt_msghdr *)(void *)w->w_tmem;
1659 
1660 			rtm->rtm_flags = rt->rt_flags;
1661 			rtm->rtm_use = rt->rt_use;
1662 			rt_getmetrics(rt, &rtm->rtm_rmx);
1663 			rtm->rtm_index = rt->rt_ifp->if_index;
1664 			rtm->rtm_pid = 0;
1665 			rtm->rtm_seq = 0;
1666 			rtm->rtm_errno = 0;
1667 			rtm->rtm_addrs = info.rti_addrs;
1668 			error = SYSCTL_OUT(w->w_req, (caddr_t)rtm, size);
1669 		}
1670 	} else {
1671 		size = rt_msg2(RTM_GET2, &info, NULL, w, credp);
1672 		if (w->w_req != NULL && w->w_tmem != NULL) {
1673 			struct rt_msghdr2 *rtm =
1674 			    (struct rt_msghdr2 *)(void *)w->w_tmem;
1675 
1676 			rtm->rtm_flags = rt->rt_flags;
1677 			rtm->rtm_use = rt->rt_use;
1678 			rt_getmetrics(rt, &rtm->rtm_rmx);
1679 			rtm->rtm_index = rt->rt_ifp->if_index;
1680 			rtm->rtm_refcnt = rt->rt_refcnt;
1681 			if (rt->rt_parent) {
1682 				rtm->rtm_parentflags = rt->rt_parent->rt_flags;
1683 			} else {
1684 				rtm->rtm_parentflags = 0;
1685 			}
1686 			rtm->rtm_reserved = 0;
1687 			rtm->rtm_addrs = info.rti_addrs;
1688 			error = SYSCTL_OUT(w->w_req, (caddr_t)rtm, size);
1689 		}
1690 	}
1691 
1692 done:
1693 	RT_UNLOCK(rt);
1694 	kauth_cred_unref(&cred);
1695 	return error;
1696 }
1697 
1698 /*
1699  * This is used for dumping extended information from route entries.
1700  */
1701 static int
sysctl_dumpentry_ext(struct radix_node * rn,void * vw)1702 sysctl_dumpentry_ext(struct radix_node *rn, void *vw)
1703 {
1704 	struct walkarg *w = vw;
1705 	struct rtentry *rt = (struct rtentry *)rn;
1706 	int error = 0, size;
1707 	struct rt_addrinfo info;
1708 	kauth_cred_t cred;
1709 
1710 	cred = kauth_cred_proc_ref(current_proc());
1711 
1712 	RT_LOCK(rt);
1713 	if (w->w_op == NET_RT_DUMPX_FLAGS && !(rt->rt_flags & w->w_arg)) {
1714 		goto done;
1715 	}
1716 	bzero(&info, sizeof(info));
1717 	info.rti_info[RTAX_DST] = rt_key(rt);
1718 	info.rti_info[RTAX_GATEWAY] = rt->rt_gateway;
1719 	info.rti_info[RTAX_NETMASK] = rt_mask(rt);
1720 	info.rti_info[RTAX_GENMASK] = rt->rt_genmask;
1721 
1722 	size = rt_msg2(RTM_GET_EXT, &info, NULL, w, &cred);
1723 	if (w->w_req != NULL && w->w_tmem != NULL) {
1724 		struct rt_msghdr_ext *ertm =
1725 		    (struct rt_msghdr_ext *)(void *)w->w_tmem;
1726 
1727 		ertm->rtm_flags = rt->rt_flags;
1728 		ertm->rtm_use = rt->rt_use;
1729 		rt_getmetrics(rt, &ertm->rtm_rmx);
1730 		ertm->rtm_index = rt->rt_ifp->if_index;
1731 		ertm->rtm_pid = 0;
1732 		ertm->rtm_seq = 0;
1733 		ertm->rtm_errno = 0;
1734 		ertm->rtm_addrs = info.rti_addrs;
1735 		if (rt->rt_llinfo_get_ri == NULL) {
1736 			bzero(&ertm->rtm_ri, sizeof(ertm->rtm_ri));
1737 			ertm->rtm_ri.ri_rssi = IFNET_RSSI_UNKNOWN;
1738 			ertm->rtm_ri.ri_lqm = IFNET_LQM_THRESH_OFF;
1739 			ertm->rtm_ri.ri_npm = IFNET_NPM_THRESH_UNKNOWN;
1740 		} else {
1741 			rt->rt_llinfo_get_ri(rt, &ertm->rtm_ri);
1742 		}
1743 		error = SYSCTL_OUT(w->w_req, (caddr_t)ertm, size);
1744 	}
1745 
1746 done:
1747 	RT_UNLOCK(rt);
1748 	kauth_cred_unref(&cred);
1749 	return error;
1750 }
1751 
1752 /*
1753  * rdar://9307819
1754  * To avoid to call copyout() while holding locks and to cause problems
1755  * in the paging path, sysctl_iflist() and sysctl_iflist2() contstruct
1756  * the list in two passes. In the first pass we compute the total
1757  * length of the data we are going to copyout, then we release
1758  * all locks to allocate a temporary buffer that gets filled
1759  * in the second pass.
1760  *
1761  * Note that we are verifying the assumption that kalloc() returns a buffer
1762  * that is at least 32 bits aligned and that the messages and addresses are
1763  * 32 bits aligned.
1764  */
1765 static int
sysctl_iflist(int af,struct walkarg * w)1766 sysctl_iflist(int af, struct walkarg *w)
1767 {
1768 	struct ifnet *ifp;
1769 	struct ifaddr *ifa;
1770 	struct  rt_addrinfo info;
1771 	int     error = 0;
1772 	int     pass = 0;
1773 	size_t  len = 0, total_len = 0, total_buffer_len = 0, current_len = 0;
1774 	char    *total_buffer = NULL, *cp = NULL;
1775 	kauth_cred_t cred;
1776 
1777 	cred = kauth_cred_proc_ref(current_proc());
1778 
1779 	bzero((caddr_t)&info, sizeof(info));
1780 
1781 	for (pass = 0; pass < 2; pass++) {
1782 		ifnet_head_lock_shared();
1783 
1784 		TAILQ_FOREACH(ifp, &ifnet_head, if_link) {
1785 			if (error) {
1786 				break;
1787 			}
1788 			if (w->w_arg && w->w_arg != ifp->if_index) {
1789 				continue;
1790 			}
1791 			ifnet_lock_shared(ifp);
1792 			/*
1793 			 * Holding ifnet lock here prevents the link address
1794 			 * from changing contents, so no need to hold the ifa
1795 			 * lock.  The link address is always present; it's
1796 			 * never freed.
1797 			 */
1798 			ifa = ifp->if_lladdr;
1799 			info.rti_info[RTAX_IFP] = ifa->ifa_addr;
1800 			len = rt_msg2(RTM_IFINFO, &info, NULL, NULL, &cred);
1801 			if (pass == 0) {
1802 				if (os_add_overflow(total_len, len, &total_len)) {
1803 					ifnet_lock_done(ifp);
1804 					error = ENOBUFS;
1805 					break;
1806 				}
1807 			} else {
1808 				struct if_msghdr *ifm;
1809 
1810 				if (current_len + len > total_len) {
1811 					ifnet_lock_done(ifp);
1812 					error = ENOBUFS;
1813 					break;
1814 				}
1815 				info.rti_info[RTAX_IFP] = ifa->ifa_addr;
1816 				len = rt_msg2(RTM_IFINFO, &info,
1817 				    (caddr_t)cp, NULL, &cred);
1818 				info.rti_info[RTAX_IFP] = NULL;
1819 
1820 				ifm = (struct if_msghdr *)(void *)cp;
1821 				ifm->ifm_index = ifp->if_index;
1822 				ifm->ifm_flags = (u_short)ifp->if_flags;
1823 				if_data_internal_to_if_data(ifp, &ifp->if_data,
1824 				    &ifm->ifm_data);
1825 				ifm->ifm_addrs = info.rti_addrs;
1826 				/*
1827 				 * <rdar://problem/32940901>
1828 				 * Round bytes only for non-platform
1829 				 */
1830 				if (!csproc_get_platform_binary(w->w_req->p)) {
1831 					ALIGN_BYTES(ifm->ifm_data.ifi_ibytes);
1832 					ALIGN_BYTES(ifm->ifm_data.ifi_obytes);
1833 				}
1834 
1835 				cp += len;
1836 				VERIFY(IS_P2ALIGNED(cp, sizeof(u_int32_t)));
1837 				current_len += len;
1838 				VERIFY(current_len <= total_len);
1839 			}
1840 			while ((ifa = ifa->ifa_link.tqe_next) != NULL) {
1841 				IFA_LOCK(ifa);
1842 				if (af && af != ifa->ifa_addr->sa_family) {
1843 					IFA_UNLOCK(ifa);
1844 					continue;
1845 				}
1846 				if (ifa->ifa_addr->sa_family == AF_INET6 &&
1847 				    (((struct in6_ifaddr *)ifa)->ia6_flags &
1848 				    IN6_IFF_CLAT46) != 0) {
1849 					IFA_UNLOCK(ifa);
1850 					continue;
1851 				}
1852 				info.rti_info[RTAX_IFA] = ifa->ifa_addr;
1853 				info.rti_info[RTAX_NETMASK] = ifa->ifa_netmask;
1854 				info.rti_info[RTAX_BRD] = ifa->ifa_dstaddr;
1855 				len = rt_msg2(RTM_NEWADDR, &info, NULL, NULL,
1856 				    &cred);
1857 				if (pass == 0) {
1858 					if (os_add_overflow(total_len, len, &total_len)) {
1859 						IFA_UNLOCK(ifa);
1860 						error = ENOBUFS;
1861 						break;
1862 					}
1863 				} else {
1864 					struct ifa_msghdr *ifam;
1865 
1866 					if (current_len + len > total_len) {
1867 						IFA_UNLOCK(ifa);
1868 						error = ENOBUFS;
1869 						break;
1870 					}
1871 					len = rt_msg2(RTM_NEWADDR, &info,
1872 					    (caddr_t)cp, NULL, &cred);
1873 
1874 					ifam = (struct ifa_msghdr *)(void *)cp;
1875 					ifam->ifam_index =
1876 					    ifa->ifa_ifp->if_index;
1877 					ifam->ifam_flags = ifa->ifa_flags;
1878 					ifam->ifam_metric = ifa->ifa_metric;
1879 					ifam->ifam_addrs = info.rti_addrs;
1880 
1881 					cp += len;
1882 					VERIFY(IS_P2ALIGNED(cp,
1883 					    sizeof(u_int32_t)));
1884 					current_len += len;
1885 					VERIFY(current_len <= total_len);
1886 				}
1887 				IFA_UNLOCK(ifa);
1888 			}
1889 			ifnet_lock_done(ifp);
1890 			info.rti_info[RTAX_IFA] = info.rti_info[RTAX_NETMASK] =
1891 			    info.rti_info[RTAX_BRD] = NULL;
1892 		}
1893 
1894 		ifnet_head_done();
1895 
1896 		if (error != 0) {
1897 			if (error == ENOBUFS) {
1898 				printf("%s: current_len (%lu) + len (%lu) > "
1899 				    "total_len (%lu)\n", __func__, current_len,
1900 				    len, total_len);
1901 			}
1902 			break;
1903 		}
1904 
1905 		if (pass == 0) {
1906 			/* Better to return zero length buffer than ENOBUFS */
1907 			if (total_len == 0) {
1908 				total_len = 1;
1909 			}
1910 			total_len += total_len >> 3;
1911 			total_buffer_len = total_len;
1912 			total_buffer = (char *) kalloc_data(total_len, Z_ZERO | Z_WAITOK);
1913 			if (total_buffer == NULL) {
1914 				printf("%s: kalloc_data(%lu) failed\n", __func__,
1915 				    total_len);
1916 				error = ENOBUFS;
1917 				break;
1918 			}
1919 			cp = total_buffer;
1920 			VERIFY(IS_P2ALIGNED(cp, sizeof(u_int32_t)));
1921 		} else {
1922 			error = SYSCTL_OUT(w->w_req, total_buffer, current_len);
1923 			if (error) {
1924 				break;
1925 			}
1926 		}
1927 	}
1928 
1929 	if (total_buffer != NULL) {
1930 		kfree_data(total_buffer, total_buffer_len);
1931 	}
1932 
1933 	kauth_cred_unref(&cred);
1934 	return error;
1935 }
1936 
1937 static int
sysctl_iflist2(int af,struct walkarg * w)1938 sysctl_iflist2(int af, struct walkarg *w)
1939 {
1940 	struct ifnet *ifp;
1941 	struct ifaddr *ifa;
1942 	struct  rt_addrinfo info;
1943 	int     error = 0;
1944 	int     pass = 0;
1945 	size_t  len = 0, total_len = 0, total_buffer_len = 0, current_len = 0;
1946 	char    *total_buffer = NULL, *cp = NULL;
1947 	kauth_cred_t cred;
1948 
1949 	cred = kauth_cred_proc_ref(current_proc());
1950 
1951 	bzero((caddr_t)&info, sizeof(info));
1952 
1953 	for (pass = 0; pass < 2; pass++) {
1954 		struct ifmultiaddr *ifma;
1955 
1956 		ifnet_head_lock_shared();
1957 
1958 		TAILQ_FOREACH(ifp, &ifnet_head, if_link) {
1959 			if (error) {
1960 				break;
1961 			}
1962 			if (w->w_arg && w->w_arg != ifp->if_index) {
1963 				continue;
1964 			}
1965 			ifnet_lock_shared(ifp);
1966 			/*
1967 			 * Holding ifnet lock here prevents the link address
1968 			 * from changing contents, so no need to hold the ifa
1969 			 * lock.  The link address is always present; it's
1970 			 * never freed.
1971 			 */
1972 			ifa = ifp->if_lladdr;
1973 			info.rti_info[RTAX_IFP] = ifa->ifa_addr;
1974 			len = rt_msg2(RTM_IFINFO2, &info, NULL, NULL, &cred);
1975 			if (pass == 0) {
1976 				if (os_add_overflow(total_len, len, &total_len)) {
1977 					ifnet_lock_done(ifp);
1978 					error = ENOBUFS;
1979 					break;
1980 				}
1981 			} else {
1982 				struct if_msghdr2 *ifm;
1983 
1984 				if (current_len + len > total_len) {
1985 					ifnet_lock_done(ifp);
1986 					error = ENOBUFS;
1987 					break;
1988 				}
1989 				info.rti_info[RTAX_IFP] = ifa->ifa_addr;
1990 				len = rt_msg2(RTM_IFINFO2, &info,
1991 				    (caddr_t)cp, NULL, &cred);
1992 				info.rti_info[RTAX_IFP] = NULL;
1993 
1994 				ifm = (struct if_msghdr2 *)(void *)cp;
1995 				ifm->ifm_addrs = info.rti_addrs;
1996 				ifm->ifm_flags = (u_short)ifp->if_flags;
1997 				ifm->ifm_index = ifp->if_index;
1998 				ifm->ifm_snd_len = IFCQ_LEN(ifp->if_snd);
1999 				ifm->ifm_snd_maxlen = IFCQ_MAXLEN(ifp->if_snd);
2000 				ifm->ifm_snd_drops =
2001 				    (int)ifp->if_snd->ifcq_dropcnt.packets;
2002 				ifm->ifm_timer = ifp->if_timer;
2003 				if_data_internal_to_if_data64(ifp,
2004 				    &ifp->if_data, &ifm->ifm_data);
2005 				/*
2006 				 * <rdar://problem/32940901>
2007 				 * Round bytes only for non-platform
2008 				 */
2009 				if (!csproc_get_platform_binary(w->w_req->p)) {
2010 					ALIGN_BYTES(ifm->ifm_data.ifi_ibytes);
2011 					ALIGN_BYTES(ifm->ifm_data.ifi_obytes);
2012 				}
2013 
2014 				cp += len;
2015 				VERIFY(IS_P2ALIGNED(cp, sizeof(u_int32_t)));
2016 				current_len += len;
2017 				VERIFY(current_len <= total_len);
2018 			}
2019 			while ((ifa = ifa->ifa_link.tqe_next) != NULL) {
2020 				IFA_LOCK(ifa);
2021 				if (af && af != ifa->ifa_addr->sa_family) {
2022 					IFA_UNLOCK(ifa);
2023 					continue;
2024 				}
2025 				if (ifa->ifa_addr->sa_family == AF_INET6 &&
2026 				    (((struct in6_ifaddr *)ifa)->ia6_flags &
2027 				    IN6_IFF_CLAT46) != 0) {
2028 					IFA_UNLOCK(ifa);
2029 					continue;
2030 				}
2031 
2032 				info.rti_info[RTAX_IFA] = ifa->ifa_addr;
2033 				info.rti_info[RTAX_NETMASK] = ifa->ifa_netmask;
2034 				info.rti_info[RTAX_BRD] = ifa->ifa_dstaddr;
2035 				len = rt_msg2(RTM_NEWADDR, &info, NULL, NULL,
2036 				    &cred);
2037 				if (pass == 0) {
2038 					if (os_add_overflow(total_len, len, &total_len)) {
2039 						IFA_UNLOCK(ifa);
2040 						error = ENOBUFS;
2041 						break;
2042 					}
2043 				} else {
2044 					struct ifa_msghdr *ifam;
2045 
2046 					if (current_len + len > total_len) {
2047 						IFA_UNLOCK(ifa);
2048 						error = ENOBUFS;
2049 						break;
2050 					}
2051 					len = rt_msg2(RTM_NEWADDR, &info,
2052 					    (caddr_t)cp, NULL, &cred);
2053 
2054 					ifam = (struct ifa_msghdr *)(void *)cp;
2055 					ifam->ifam_index =
2056 					    ifa->ifa_ifp->if_index;
2057 					ifam->ifam_flags = ifa->ifa_flags;
2058 					ifam->ifam_metric = ifa->ifa_metric;
2059 					ifam->ifam_addrs = info.rti_addrs;
2060 
2061 					cp += len;
2062 					VERIFY(IS_P2ALIGNED(cp,
2063 					    sizeof(u_int32_t)));
2064 					current_len += len;
2065 					VERIFY(current_len <= total_len);
2066 				}
2067 				IFA_UNLOCK(ifa);
2068 			}
2069 			if (error) {
2070 				ifnet_lock_done(ifp);
2071 				break;
2072 			}
2073 
2074 			for (ifma = LIST_FIRST(&ifp->if_multiaddrs);
2075 			    ifma != NULL; ifma = LIST_NEXT(ifma, ifma_link)) {
2076 				struct ifaddr *ifa0;
2077 
2078 				IFMA_LOCK(ifma);
2079 				if (af && af != ifma->ifma_addr->sa_family) {
2080 					IFMA_UNLOCK(ifma);
2081 					continue;
2082 				}
2083 				bzero((caddr_t)&info, sizeof(info));
2084 				info.rti_info[RTAX_IFA] = ifma->ifma_addr;
2085 				/*
2086 				 * Holding ifnet lock here prevents the link
2087 				 * address from changing contents, so no need
2088 				 * to hold the ifa0 lock.  The link address is
2089 				 * always present; it's never freed.
2090 				 */
2091 				ifa0 = ifp->if_lladdr;
2092 				info.rti_info[RTAX_IFP] = ifa0->ifa_addr;
2093 				if (ifma->ifma_ll != NULL) {
2094 					info.rti_info[RTAX_GATEWAY] =
2095 					    ifma->ifma_ll->ifma_addr;
2096 				}
2097 				len = rt_msg2(RTM_NEWMADDR2, &info, NULL, NULL,
2098 				    &cred);
2099 				if (pass == 0) {
2100 					total_len += len;
2101 				} else {
2102 					struct ifma_msghdr2 *ifmam;
2103 
2104 					if (current_len + len > total_len) {
2105 						IFMA_UNLOCK(ifma);
2106 						error = ENOBUFS;
2107 						break;
2108 					}
2109 					len = rt_msg2(RTM_NEWMADDR2, &info,
2110 					    (caddr_t)cp, NULL, &cred);
2111 
2112 					ifmam =
2113 					    (struct ifma_msghdr2 *)(void *)cp;
2114 					ifmam->ifmam_addrs = info.rti_addrs;
2115 					ifmam->ifmam_flags = 0;
2116 					ifmam->ifmam_index =
2117 					    ifma->ifma_ifp->if_index;
2118 					ifmam->ifmam_refcount =
2119 					    ifma->ifma_reqcnt;
2120 
2121 					cp += len;
2122 					VERIFY(IS_P2ALIGNED(cp,
2123 					    sizeof(u_int32_t)));
2124 					current_len += len;
2125 				}
2126 				IFMA_UNLOCK(ifma);
2127 			}
2128 			ifnet_lock_done(ifp);
2129 			info.rti_info[RTAX_IFA] = info.rti_info[RTAX_NETMASK] =
2130 			    info.rti_info[RTAX_BRD] = NULL;
2131 		}
2132 		ifnet_head_done();
2133 
2134 		if (error) {
2135 			if (error == ENOBUFS) {
2136 				printf("%s: current_len (%lu) + len (%lu) > "
2137 				    "total_len (%lu)\n", __func__, current_len,
2138 				    len, total_len);
2139 			}
2140 			break;
2141 		}
2142 
2143 		if (pass == 0) {
2144 			/* Better to return zero length buffer than ENOBUFS */
2145 			if (total_len == 0) {
2146 				total_len = 1;
2147 			}
2148 			total_len += total_len >> 3;
2149 			total_buffer_len = total_len;
2150 			total_buffer = (char *) kalloc_data(total_len, Z_ZERO | Z_WAITOK);
2151 			if (total_buffer == NULL) {
2152 				printf("%s: kalloc_data(%lu) failed\n", __func__,
2153 				    total_len);
2154 				error = ENOBUFS;
2155 				break;
2156 			}
2157 			cp = total_buffer;
2158 			VERIFY(IS_P2ALIGNED(cp, sizeof(u_int32_t)));
2159 		} else {
2160 			error = SYSCTL_OUT(w->w_req, total_buffer, current_len);
2161 			if (error) {
2162 				break;
2163 			}
2164 		}
2165 	}
2166 
2167 	if (total_buffer != NULL) {
2168 		kfree_data(total_buffer, total_buffer_len);
2169 	}
2170 
2171 	kauth_cred_unref(&cred);
2172 	return error;
2173 }
2174 
2175 
2176 static int
sysctl_rtstat(struct sysctl_req * req)2177 sysctl_rtstat(struct sysctl_req *req)
2178 {
2179 	return SYSCTL_OUT(req, &rtstat, sizeof(struct rtstat));
2180 }
2181 
2182 static int
sysctl_rttrash(struct sysctl_req * req)2183 sysctl_rttrash(struct sysctl_req *req)
2184 {
2185 	return SYSCTL_OUT(req, &rttrash, sizeof(rttrash));
2186 }
2187 
2188 static int
2189 sysctl_rtsock SYSCTL_HANDLER_ARGS
2190 {
2191 #pragma unused(oidp)
2192 	int     *name = (int *)arg1;
2193 	u_int   namelen = arg2;
2194 	struct radix_node_head *rnh;
2195 	int     i, error = EINVAL;
2196 	u_char  af;
2197 	struct  walkarg w;
2198 
2199 	name++;
2200 	namelen--;
2201 	if (req->newptr) {
2202 		return EPERM;
2203 	}
2204 	if (namelen != 3) {
2205 		return EINVAL;
2206 	}
2207 	af = (u_char)name[0];
2208 	Bzero(&w, sizeof(w));
2209 	w.w_op = name[1];
2210 	w.w_arg = name[2];
2211 	w.w_req = req;
2212 
2213 	switch (w.w_op) {
2214 	case NET_RT_DUMP:
2215 	case NET_RT_DUMP2:
2216 	case NET_RT_FLAGS:
2217 	case NET_RT_FLAGS_PRIV:
2218 		lck_mtx_lock(rnh_lock);
2219 		for (i = 1; i <= AF_MAX; i++) {
2220 			if ((rnh = rt_tables[i]) && (af == 0 || af == i) &&
2221 			    (error = rnh->rnh_walktree(rnh,
2222 			    sysctl_dumpentry, &w))) {
2223 				break;
2224 			}
2225 		}
2226 		lck_mtx_unlock(rnh_lock);
2227 		break;
2228 	case NET_RT_DUMPX:
2229 	case NET_RT_DUMPX_FLAGS:
2230 		lck_mtx_lock(rnh_lock);
2231 		for (i = 1; i <= AF_MAX; i++) {
2232 			if ((rnh = rt_tables[i]) && (af == 0 || af == i) &&
2233 			    (error = rnh->rnh_walktree(rnh,
2234 			    sysctl_dumpentry_ext, &w))) {
2235 				break;
2236 			}
2237 		}
2238 		lck_mtx_unlock(rnh_lock);
2239 		break;
2240 	case NET_RT_IFLIST:
2241 		error = sysctl_iflist(af, &w);
2242 		break;
2243 	case NET_RT_IFLIST2:
2244 		error = sysctl_iflist2(af, &w);
2245 		break;
2246 	case NET_RT_STAT:
2247 		error = sysctl_rtstat(req);
2248 		break;
2249 	case NET_RT_TRASH:
2250 		error = sysctl_rttrash(req);
2251 		break;
2252 	}
2253 	if (w.w_tmem != NULL) {
2254 		kfree_data(w.w_tmem, w.w_tmemsize);
2255 	}
2256 	return error;
2257 }
2258 
2259 /*
2260  * Definitions of protocols supported in the ROUTE domain.
2261  */
2262 static struct protosw routesw[] = {
2263 	{
2264 		.pr_type =              SOCK_RAW,
2265 		.pr_protocol =          0,
2266 		.pr_flags =             PR_ATOMIC | PR_ADDR,
2267 		.pr_output =            route_output,
2268 		.pr_ctlinput =          raw_ctlinput,
2269 		.pr_usrreqs =           &route_usrreqs,
2270 	}
2271 };
2272 
2273 static int route_proto_count = (sizeof(routesw) / sizeof(struct protosw));
2274 
2275 struct domain routedomain_s = {
2276 	.dom_family =           PF_ROUTE,
2277 	.dom_name =             "route",
2278 	.dom_init =             route_dinit,
2279 };
2280 
2281 static void
route_dinit(struct domain * dp)2282 route_dinit(struct domain *dp)
2283 {
2284 	struct protosw *pr;
2285 	int i;
2286 
2287 	VERIFY(!(dp->dom_flags & DOM_INITIALIZED));
2288 	VERIFY(routedomain == NULL);
2289 
2290 	routedomain = dp;
2291 
2292 	for (i = 0, pr = &routesw[0]; i < route_proto_count; i++, pr++) {
2293 		net_add_proto(pr, dp, 1);
2294 	}
2295 
2296 	route_init();
2297 }
2298