xref: /freebsd/sys/netinet/raw_ip.c (revision 882f88ff77194ef2eea005232780468404438788)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1982, 1986, 1988, 1993
5  *	The Regents of the University of California.
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  *
32  *	@(#)raw_ip.c	8.7 (Berkeley) 5/15/95
33  */
34 
35 #include <sys/cdefs.h>
36 __FBSDID("$FreeBSD$");
37 
38 #include "opt_inet.h"
39 #include "opt_inet6.h"
40 #include "opt_ipsec.h"
41 
42 #include <sys/param.h>
43 #include <sys/jail.h>
44 #include <sys/kernel.h>
45 #include <sys/eventhandler.h>
46 #include <sys/lock.h>
47 #include <sys/malloc.h>
48 #include <sys/mbuf.h>
49 #include <sys/priv.h>
50 #include <sys/proc.h>
51 #include <sys/protosw.h>
52 #include <sys/rmlock.h>
53 #include <sys/rwlock.h>
54 #include <sys/signalvar.h>
55 #include <sys/socket.h>
56 #include <sys/socketvar.h>
57 #include <sys/sx.h>
58 #include <sys/sysctl.h>
59 #include <sys/systm.h>
60 
61 #include <vm/uma.h>
62 
63 #include <net/if.h>
64 #include <net/if_var.h>
65 #include <net/route.h>
66 #include <net/vnet.h>
67 
68 #include <netinet/in.h>
69 #include <netinet/in_systm.h>
70 #include <netinet/in_pcb.h>
71 #include <netinet/in_var.h>
72 #include <netinet/if_ether.h>
73 #include <netinet/ip.h>
74 #include <netinet/ip_var.h>
75 #include <netinet/ip_mroute.h>
76 #include <netinet/ip_icmp.h>
77 
78 #include <netipsec/ipsec_support.h>
79 
80 #include <machine/stdarg.h>
81 #include <security/mac/mac_framework.h>
82 
83 VNET_DEFINE(int, ip_defttl) = IPDEFTTL;
84 SYSCTL_INT(_net_inet_ip, IPCTL_DEFTTL, ttl, CTLFLAG_VNET | CTLFLAG_RW,
85     &VNET_NAME(ip_defttl), 0,
86     "Maximum TTL on IP packets");
87 
88 VNET_DEFINE(struct inpcbhead, ripcb);
89 VNET_DEFINE(struct inpcbinfo, ripcbinfo);
90 
91 #define	V_ripcb			VNET(ripcb)
92 #define	V_ripcbinfo		VNET(ripcbinfo)
93 
94 /*
95  * Control and data hooks for ipfw, dummynet, divert and so on.
96  * The data hooks are not used here but it is convenient
97  * to keep them all in one place.
98  */
99 VNET_DEFINE(ip_fw_chk_ptr_t, ip_fw_chk_ptr) = NULL;
100 VNET_DEFINE(ip_fw_ctl_ptr_t, ip_fw_ctl_ptr) = NULL;
101 
102 int	(*ip_dn_ctl_ptr)(struct sockopt *);
103 int	(*ip_dn_io_ptr)(struct mbuf **, struct ip_fw_args *);
104 void	(*ip_divert_ptr)(struct mbuf *, bool);
105 int	(*ng_ipfw_input_p)(struct mbuf **, struct ip_fw_args *, bool);
106 
107 #ifdef INET
108 /*
109  * Hooks for multicast routing. They all default to NULL, so leave them not
110  * initialized and rely on BSS being set to 0.
111  */
112 
113 /*
114  * The socket used to communicate with the multicast routing daemon.
115  */
116 VNET_DEFINE(struct socket *, ip_mrouter);
117 
118 /*
119  * The various mrouter and rsvp functions.
120  */
121 int (*ip_mrouter_set)(struct socket *, struct sockopt *);
122 int (*ip_mrouter_get)(struct socket *, struct sockopt *);
123 int (*ip_mrouter_done)(void);
124 int (*ip_mforward)(struct ip *, struct ifnet *, struct mbuf *,
125 		   struct ip_moptions *);
126 int (*mrt_ioctl)(u_long, caddr_t, int);
127 int (*legal_vif_num)(int);
128 u_long (*ip_mcast_src)(int);
129 
130 int (*rsvp_input_p)(struct mbuf **, int *, int);
131 int (*ip_rsvp_vif)(struct socket *, struct sockopt *);
132 void (*ip_rsvp_force_done)(struct socket *);
133 #endif /* INET */
134 
135 extern	struct protosw inetsw[];
136 
137 u_long	rip_sendspace = 9216;
138 SYSCTL_ULONG(_net_inet_raw, OID_AUTO, maxdgram, CTLFLAG_RW,
139     &rip_sendspace, 0, "Maximum outgoing raw IP datagram size");
140 
141 u_long	rip_recvspace = 9216;
142 SYSCTL_ULONG(_net_inet_raw, OID_AUTO, recvspace, CTLFLAG_RW,
143     &rip_recvspace, 0, "Maximum space for incoming raw IP datagrams");
144 
145 /*
146  * Hash functions
147  */
148 
149 #define INP_PCBHASH_RAW_SIZE	256
150 #define INP_PCBHASH_RAW(proto, laddr, faddr, mask) \
151         (((proto) + (laddr) + (faddr)) % (mask) + 1)
152 
153 #ifdef INET
154 static void
155 rip_inshash(struct inpcb *inp)
156 {
157 	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
158 	struct inpcbhead *pcbhash;
159 	int hash;
160 
161 	INP_INFO_WLOCK_ASSERT(pcbinfo);
162 	INP_WLOCK_ASSERT(inp);
163 
164 	if (inp->inp_ip_p != 0 &&
165 	    inp->inp_laddr.s_addr != INADDR_ANY &&
166 	    inp->inp_faddr.s_addr != INADDR_ANY) {
167 		hash = INP_PCBHASH_RAW(inp->inp_ip_p, inp->inp_laddr.s_addr,
168 		    inp->inp_faddr.s_addr, pcbinfo->ipi_hashmask);
169 	} else
170 		hash = 0;
171 	pcbhash = &pcbinfo->ipi_hashbase[hash];
172 	CK_LIST_INSERT_HEAD(pcbhash, inp, inp_hash);
173 }
174 
175 static void
176 rip_delhash(struct inpcb *inp)
177 {
178 
179 	INP_INFO_WLOCK_ASSERT(inp->inp_pcbinfo);
180 	INP_WLOCK_ASSERT(inp);
181 
182 	CK_LIST_REMOVE(inp, inp_hash);
183 }
184 #endif /* INET */
185 
186 /*
187  * Raw interface to IP protocol.
188  */
189 
190 /*
191  * Initialize raw connection block q.
192  */
193 static void
194 rip_zone_change(void *tag)
195 {
196 
197 	uma_zone_set_max(V_ripcbinfo.ipi_zone, maxsockets);
198 }
199 
200 static int
201 rip_inpcb_init(void *mem, int size, int flags)
202 {
203 	struct inpcb *inp = mem;
204 
205 	INP_LOCK_INIT(inp, "inp", "rawinp");
206 	return (0);
207 }
208 
209 void
210 rip_init(void)
211 {
212 
213 	in_pcbinfo_init(&V_ripcbinfo, "rip", &V_ripcb, INP_PCBHASH_RAW_SIZE,
214 	    1, "ripcb", rip_inpcb_init, IPI_HASHFIELDS_NONE);
215 	EVENTHANDLER_REGISTER(maxsockets_change, rip_zone_change, NULL,
216 	    EVENTHANDLER_PRI_ANY);
217 }
218 
219 #ifdef VIMAGE
220 static void
221 rip_destroy(void *unused __unused)
222 {
223 
224 	in_pcbinfo_destroy(&V_ripcbinfo);
225 }
226 VNET_SYSUNINIT(raw_ip, SI_SUB_PROTO_DOMAIN, SI_ORDER_FOURTH, rip_destroy, NULL);
227 #endif
228 
229 #ifdef INET
230 static int
231 rip_append(struct inpcb *last, struct ip *ip, struct mbuf *n,
232     struct sockaddr_in *ripsrc)
233 {
234 	int policyfail = 0;
235 
236 	INP_LOCK_ASSERT(last);
237 
238 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
239 	/* check AH/ESP integrity. */
240 	if (IPSEC_ENABLED(ipv4)) {
241 		if (IPSEC_CHECK_POLICY(ipv4, n, last) != 0)
242 			policyfail = 1;
243 	}
244 #endif /* IPSEC */
245 #ifdef MAC
246 	if (!policyfail && mac_inpcb_check_deliver(last, n) != 0)
247 		policyfail = 1;
248 #endif
249 	/* Check the minimum TTL for socket. */
250 	if (last->inp_ip_minttl && last->inp_ip_minttl > ip->ip_ttl)
251 		policyfail = 1;
252 	if (!policyfail) {
253 		struct mbuf *opts = NULL;
254 		struct socket *so;
255 
256 		so = last->inp_socket;
257 		if ((last->inp_flags & INP_CONTROLOPTS) ||
258 		    (so->so_options & (SO_TIMESTAMP | SO_BINTIME)))
259 			ip_savecontrol(last, &opts, ip, n);
260 		SOCKBUF_LOCK(&so->so_rcv);
261 		if (sbappendaddr_locked(&so->so_rcv,
262 		    (struct sockaddr *)ripsrc, n, opts) == 0) {
263 			/* should notify about lost packet */
264 			m_freem(n);
265 			if (opts)
266 				m_freem(opts);
267 			SOCKBUF_UNLOCK(&so->so_rcv);
268 		} else
269 			sorwakeup_locked(so);
270 	} else
271 		m_freem(n);
272 	return (policyfail);
273 }
274 
275 /*
276  * Setup generic address and protocol structures for raw_input routine, then
277  * pass them along with mbuf chain.
278  */
279 int
280 rip_input(struct mbuf **mp, int *offp, int proto)
281 {
282 	struct ifnet *ifp;
283 	struct mbuf *m = *mp;
284 	struct ip *ip = mtod(m, struct ip *);
285 	struct inpcb *inp, *last;
286 	struct sockaddr_in ripsrc;
287 	int hash;
288 
289 	NET_EPOCH_ASSERT();
290 
291 	*mp = NULL;
292 
293 	bzero(&ripsrc, sizeof(ripsrc));
294 	ripsrc.sin_len = sizeof(ripsrc);
295 	ripsrc.sin_family = AF_INET;
296 	ripsrc.sin_addr = ip->ip_src;
297 	last = NULL;
298 
299 	ifp = m->m_pkthdr.rcvif;
300 
301 	hash = INP_PCBHASH_RAW(proto, ip->ip_src.s_addr,
302 	    ip->ip_dst.s_addr, V_ripcbinfo.ipi_hashmask);
303 	CK_LIST_FOREACH(inp, &V_ripcbinfo.ipi_hashbase[hash], inp_hash) {
304 		if (inp->inp_ip_p != proto)
305 			continue;
306 #ifdef INET6
307 		/* XXX inp locking */
308 		if ((inp->inp_vflag & INP_IPV4) == 0)
309 			continue;
310 #endif
311 		if (inp->inp_laddr.s_addr != ip->ip_dst.s_addr)
312 			continue;
313 		if (inp->inp_faddr.s_addr != ip->ip_src.s_addr)
314 			continue;
315 		if (last != NULL) {
316 			struct mbuf *n;
317 
318 			n = m_copym(m, 0, M_COPYALL, M_NOWAIT);
319 			if (n != NULL)
320 			    (void) rip_append(last, ip, n, &ripsrc);
321 			/* XXX count dropped packet */
322 			INP_RUNLOCK(last);
323 			last = NULL;
324 		}
325 		INP_RLOCK(inp);
326 		if (__predict_false(inp->inp_flags2 & INP_FREED))
327 			goto skip_1;
328 		if (jailed_without_vnet(inp->inp_cred)) {
329 			/*
330 			 * XXX: If faddr was bound to multicast group,
331 			 * jailed raw socket will drop datagram.
332 			 */
333 			if (prison_check_ip4(inp->inp_cred, &ip->ip_dst) != 0)
334 				goto skip_1;
335 		}
336 		last = inp;
337 		continue;
338 	skip_1:
339 		INP_RUNLOCK(inp);
340 	}
341 	CK_LIST_FOREACH(inp, &V_ripcbinfo.ipi_hashbase[0], inp_hash) {
342 		if (inp->inp_ip_p && inp->inp_ip_p != proto)
343 			continue;
344 #ifdef INET6
345 		/* XXX inp locking */
346 		if ((inp->inp_vflag & INP_IPV4) == 0)
347 			continue;
348 #endif
349 		if (!in_nullhost(inp->inp_laddr) &&
350 		    !in_hosteq(inp->inp_laddr, ip->ip_dst))
351 			continue;
352 		if (!in_nullhost(inp->inp_faddr) &&
353 		    !in_hosteq(inp->inp_faddr, ip->ip_src))
354 			continue;
355 		if (last != NULL) {
356 			struct mbuf *n;
357 
358 			n = m_copym(m, 0, M_COPYALL, M_NOWAIT);
359 			if (n != NULL)
360 				(void) rip_append(last, ip, n, &ripsrc);
361 			/* XXX count dropped packet */
362 			INP_RUNLOCK(last);
363 			last = NULL;
364 		}
365 		INP_RLOCK(inp);
366 		if (__predict_false(inp->inp_flags2 & INP_FREED))
367 			goto skip_2;
368 		if (jailed_without_vnet(inp->inp_cred)) {
369 			/*
370 			 * Allow raw socket in jail to receive multicast;
371 			 * assume process had PRIV_NETINET_RAW at attach,
372 			 * and fall through into normal filter path if so.
373 			 */
374 			if (!IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) &&
375 			    prison_check_ip4(inp->inp_cred, &ip->ip_dst) != 0)
376 				goto skip_2;
377 		}
378 		/*
379 		 * If this raw socket has multicast state, and we
380 		 * have received a multicast, check if this socket
381 		 * should receive it, as multicast filtering is now
382 		 * the responsibility of the transport layer.
383 		 */
384 		if (inp->inp_moptions != NULL &&
385 		    IN_MULTICAST(ntohl(ip->ip_dst.s_addr))) {
386 			/*
387 			 * If the incoming datagram is for IGMP, allow it
388 			 * through unconditionally to the raw socket.
389 			 *
390 			 * In the case of IGMPv2, we may not have explicitly
391 			 * joined the group, and may have set IFF_ALLMULTI
392 			 * on the interface. imo_multi_filter() may discard
393 			 * control traffic we actually need to see.
394 			 *
395 			 * Userland multicast routing daemons should continue
396 			 * filter the control traffic appropriately.
397 			 */
398 			int blocked;
399 
400 			blocked = MCAST_PASS;
401 			if (proto != IPPROTO_IGMP) {
402 				struct sockaddr_in group;
403 
404 				bzero(&group, sizeof(struct sockaddr_in));
405 				group.sin_len = sizeof(struct sockaddr_in);
406 				group.sin_family = AF_INET;
407 				group.sin_addr = ip->ip_dst;
408 
409 				blocked = imo_multi_filter(inp->inp_moptions,
410 				    ifp,
411 				    (struct sockaddr *)&group,
412 				    (struct sockaddr *)&ripsrc);
413 			}
414 
415 			if (blocked != MCAST_PASS) {
416 				IPSTAT_INC(ips_notmember);
417 				goto skip_2;
418 			}
419 		}
420 		last = inp;
421 		continue;
422 	skip_2:
423 		INP_RUNLOCK(inp);
424 	}
425 	if (last != NULL) {
426 		if (rip_append(last, ip, m, &ripsrc) != 0)
427 			IPSTAT_INC(ips_delivered);
428 		INP_RUNLOCK(last);
429 	} else {
430 		if (inetsw[ip_protox[ip->ip_p]].pr_input == rip_input) {
431 			IPSTAT_INC(ips_noproto);
432 			IPSTAT_DEC(ips_delivered);
433 			icmp_error(m, ICMP_UNREACH, ICMP_UNREACH_PROTOCOL, 0, 0);
434 		} else {
435 			m_freem(m);
436 		}
437 	}
438 	return (IPPROTO_DONE);
439 }
440 
441 /*
442  * Generate IP header and pass packet to ip_output.  Tack on options user may
443  * have setup with control call.
444  */
445 int
446 rip_output(struct mbuf *m, struct socket *so, ...)
447 {
448 	struct epoch_tracker et;
449 	struct ip *ip;
450 	int error;
451 	struct inpcb *inp = sotoinpcb(so);
452 	va_list ap;
453 	u_long dst;
454 	int flags = ((so->so_options & SO_DONTROUTE) ? IP_ROUTETOIF : 0) |
455 	    IP_ALLOWBROADCAST;
456 	int cnt, hlen;
457 	u_char opttype, optlen, *cp;
458 
459 	va_start(ap, so);
460 	dst = va_arg(ap, u_long);
461 	va_end(ap);
462 
463 	/*
464 	 * If the user handed us a complete IP packet, use it.  Otherwise,
465 	 * allocate an mbuf for a header and fill it in.
466 	 */
467 	if ((inp->inp_flags & INP_HDRINCL) == 0) {
468 		if (m->m_pkthdr.len + sizeof(struct ip) > IP_MAXPACKET) {
469 			m_freem(m);
470 			return(EMSGSIZE);
471 		}
472 		M_PREPEND(m, sizeof(struct ip), M_NOWAIT);
473 		if (m == NULL)
474 			return(ENOBUFS);
475 
476 		INP_RLOCK(inp);
477 		ip = mtod(m, struct ip *);
478 		ip->ip_tos = inp->inp_ip_tos;
479 		if (inp->inp_flags & INP_DONTFRAG)
480 			ip->ip_off = htons(IP_DF);
481 		else
482 			ip->ip_off = htons(0);
483 		ip->ip_p = inp->inp_ip_p;
484 		ip->ip_len = htons(m->m_pkthdr.len);
485 		ip->ip_src = inp->inp_laddr;
486 		ip->ip_dst.s_addr = dst;
487 		if (jailed(inp->inp_cred)) {
488 			/*
489 			 * prison_local_ip4() would be good enough but would
490 			 * let a source of INADDR_ANY pass, which we do not
491 			 * want to see from jails.
492 			 */
493 			if (ip->ip_src.s_addr == INADDR_ANY) {
494 				NET_EPOCH_ENTER(et);
495 				error = in_pcbladdr(inp, &ip->ip_dst,
496 				    &ip->ip_src, inp->inp_cred);
497 				NET_EPOCH_EXIT(et);
498 			} else {
499 				error = prison_local_ip4(inp->inp_cred,
500 				    &ip->ip_src);
501 			}
502 			if (error != 0) {
503 				INP_RUNLOCK(inp);
504 				m_freem(m);
505 				return (error);
506 			}
507 		}
508 		ip->ip_ttl = inp->inp_ip_ttl;
509 	} else {
510 		if (m->m_pkthdr.len > IP_MAXPACKET) {
511 			m_freem(m);
512 			return(EMSGSIZE);
513 		}
514 		ip = mtod(m, struct ip *);
515 		hlen = ip->ip_hl << 2;
516 		if (m->m_len < hlen) {
517 			m = m_pullup(m, hlen);
518 			if (m == NULL)
519 				return (EINVAL);
520 			ip = mtod(m, struct ip *);
521 		}
522 
523 		INP_RLOCK(inp);
524 		/*
525 		 * Don't allow both user specified and setsockopt options,
526 		 * and don't allow packet length sizes that will crash.
527 		 */
528 		if ((hlen < sizeof (*ip))
529 		    || ((hlen > sizeof (*ip)) && inp->inp_options)
530 		    || (ntohs(ip->ip_len) != m->m_pkthdr.len)) {
531 			INP_RUNLOCK(inp);
532 			m_freem(m);
533 			return (EINVAL);
534 		}
535 		error = prison_check_ip4(inp->inp_cred, &ip->ip_src);
536 		if (error != 0) {
537 			INP_RUNLOCK(inp);
538 			m_freem(m);
539 			return (error);
540 		}
541 		/*
542 		 * Don't allow IP options which do not have the required
543 		 * structure as specified in section 3.1 of RFC 791 on
544 		 * pages 15-23.
545 		 */
546 		cp = (u_char *)(ip + 1);
547 		cnt = hlen - sizeof (struct ip);
548 		for (; cnt > 0; cnt -= optlen, cp += optlen) {
549 			opttype = cp[IPOPT_OPTVAL];
550 			if (opttype == IPOPT_EOL)
551 				break;
552 			if (opttype == IPOPT_NOP) {
553 				optlen = 1;
554 				continue;
555 			}
556 			if (cnt < IPOPT_OLEN + sizeof(u_char)) {
557 				INP_RUNLOCK(inp);
558 				m_freem(m);
559 				return (EINVAL);
560 			}
561 			optlen = cp[IPOPT_OLEN];
562 			if (optlen < IPOPT_OLEN + sizeof(u_char) ||
563 			    optlen > cnt) {
564 				INP_RUNLOCK(inp);
565 				m_freem(m);
566 				return (EINVAL);
567 			}
568 		}
569 		/*
570 		 * This doesn't allow application to specify ID of zero,
571 		 * but we got this limitation from the beginning of history.
572 		 */
573 		if (ip->ip_id == 0)
574 			ip_fillid(ip);
575 
576 		/*
577 		 * XXX prevent ip_output from overwriting header fields.
578 		 */
579 		flags |= IP_RAWOUTPUT;
580 		IPSTAT_INC(ips_rawout);
581 	}
582 
583 	if (inp->inp_flags & INP_ONESBCAST)
584 		flags |= IP_SENDONES;
585 
586 #ifdef MAC
587 	mac_inpcb_create_mbuf(inp, m);
588 #endif
589 
590 	NET_EPOCH_ENTER(et);
591 	error = ip_output(m, inp->inp_options, NULL, flags,
592 	    inp->inp_moptions, inp);
593 	NET_EPOCH_EXIT(et);
594 	INP_RUNLOCK(inp);
595 	return (error);
596 }
597 
598 /*
599  * Raw IP socket option processing.
600  *
601  * IMPORTANT NOTE regarding access control: Traditionally, raw sockets could
602  * only be created by a privileged process, and as such, socket option
603  * operations to manage system properties on any raw socket were allowed to
604  * take place without explicit additional access control checks.  However,
605  * raw sockets can now also be created in jail(), and therefore explicit
606  * checks are now required.  Likewise, raw sockets can be used by a process
607  * after it gives up privilege, so some caution is required.  For options
608  * passed down to the IP layer via ip_ctloutput(), checks are assumed to be
609  * performed in ip_ctloutput() and therefore no check occurs here.
610  * Unilaterally checking priv_check() here breaks normal IP socket option
611  * operations on raw sockets.
612  *
613  * When adding new socket options here, make sure to add access control
614  * checks here as necessary.
615  *
616  * XXX-BZ inp locking?
617  */
618 int
619 rip_ctloutput(struct socket *so, struct sockopt *sopt)
620 {
621 	struct	inpcb *inp = sotoinpcb(so);
622 	int	error, optval;
623 
624 	if (sopt->sopt_level != IPPROTO_IP) {
625 		if ((sopt->sopt_level == SOL_SOCKET) &&
626 		    (sopt->sopt_name == SO_SETFIB)) {
627 			inp->inp_inc.inc_fibnum = so->so_fibnum;
628 			return (0);
629 		}
630 		return (EINVAL);
631 	}
632 
633 	error = 0;
634 	switch (sopt->sopt_dir) {
635 	case SOPT_GET:
636 		switch (sopt->sopt_name) {
637 		case IP_HDRINCL:
638 			optval = inp->inp_flags & INP_HDRINCL;
639 			error = sooptcopyout(sopt, &optval, sizeof optval);
640 			break;
641 
642 		case IP_FW3:	/* generic ipfw v.3 functions */
643 		case IP_FW_ADD:	/* ADD actually returns the body... */
644 		case IP_FW_GET:
645 		case IP_FW_TABLE_GETSIZE:
646 		case IP_FW_TABLE_LIST:
647 		case IP_FW_NAT_GET_CONFIG:
648 		case IP_FW_NAT_GET_LOG:
649 			if (V_ip_fw_ctl_ptr != NULL)
650 				error = V_ip_fw_ctl_ptr(sopt);
651 			else
652 				error = ENOPROTOOPT;
653 			break;
654 
655 		case IP_DUMMYNET3:	/* generic dummynet v.3 functions */
656 		case IP_DUMMYNET_GET:
657 			if (ip_dn_ctl_ptr != NULL)
658 				error = ip_dn_ctl_ptr(sopt);
659 			else
660 				error = ENOPROTOOPT;
661 			break ;
662 
663 		case MRT_INIT:
664 		case MRT_DONE:
665 		case MRT_ADD_VIF:
666 		case MRT_DEL_VIF:
667 		case MRT_ADD_MFC:
668 		case MRT_DEL_MFC:
669 		case MRT_VERSION:
670 		case MRT_ASSERT:
671 		case MRT_API_SUPPORT:
672 		case MRT_API_CONFIG:
673 		case MRT_ADD_BW_UPCALL:
674 		case MRT_DEL_BW_UPCALL:
675 			error = priv_check(curthread, PRIV_NETINET_MROUTE);
676 			if (error != 0)
677 				return (error);
678 			error = ip_mrouter_get ? ip_mrouter_get(so, sopt) :
679 				EOPNOTSUPP;
680 			break;
681 
682 		default:
683 			error = ip_ctloutput(so, sopt);
684 			break;
685 		}
686 		break;
687 
688 	case SOPT_SET:
689 		switch (sopt->sopt_name) {
690 		case IP_HDRINCL:
691 			error = sooptcopyin(sopt, &optval, sizeof optval,
692 					    sizeof optval);
693 			if (error)
694 				break;
695 			if (optval)
696 				inp->inp_flags |= INP_HDRINCL;
697 			else
698 				inp->inp_flags &= ~INP_HDRINCL;
699 			break;
700 
701 		case IP_FW3:	/* generic ipfw v.3 functions */
702 		case IP_FW_ADD:
703 		case IP_FW_DEL:
704 		case IP_FW_FLUSH:
705 		case IP_FW_ZERO:
706 		case IP_FW_RESETLOG:
707 		case IP_FW_TABLE_ADD:
708 		case IP_FW_TABLE_DEL:
709 		case IP_FW_TABLE_FLUSH:
710 		case IP_FW_NAT_CFG:
711 		case IP_FW_NAT_DEL:
712 			if (V_ip_fw_ctl_ptr != NULL)
713 				error = V_ip_fw_ctl_ptr(sopt);
714 			else
715 				error = ENOPROTOOPT;
716 			break;
717 
718 		case IP_DUMMYNET3:	/* generic dummynet v.3 functions */
719 		case IP_DUMMYNET_CONFIGURE:
720 		case IP_DUMMYNET_DEL:
721 		case IP_DUMMYNET_FLUSH:
722 			if (ip_dn_ctl_ptr != NULL)
723 				error = ip_dn_ctl_ptr(sopt);
724 			else
725 				error = ENOPROTOOPT ;
726 			break ;
727 
728 		case IP_RSVP_ON:
729 			error = priv_check(curthread, PRIV_NETINET_MROUTE);
730 			if (error != 0)
731 				return (error);
732 			error = ip_rsvp_init(so);
733 			break;
734 
735 		case IP_RSVP_OFF:
736 			error = priv_check(curthread, PRIV_NETINET_MROUTE);
737 			if (error != 0)
738 				return (error);
739 			error = ip_rsvp_done();
740 			break;
741 
742 		case IP_RSVP_VIF_ON:
743 		case IP_RSVP_VIF_OFF:
744 			error = priv_check(curthread, PRIV_NETINET_MROUTE);
745 			if (error != 0)
746 				return (error);
747 			error = ip_rsvp_vif ?
748 				ip_rsvp_vif(so, sopt) : EINVAL;
749 			break;
750 
751 		case MRT_INIT:
752 		case MRT_DONE:
753 		case MRT_ADD_VIF:
754 		case MRT_DEL_VIF:
755 		case MRT_ADD_MFC:
756 		case MRT_DEL_MFC:
757 		case MRT_VERSION:
758 		case MRT_ASSERT:
759 		case MRT_API_SUPPORT:
760 		case MRT_API_CONFIG:
761 		case MRT_ADD_BW_UPCALL:
762 		case MRT_DEL_BW_UPCALL:
763 			error = priv_check(curthread, PRIV_NETINET_MROUTE);
764 			if (error != 0)
765 				return (error);
766 			error = ip_mrouter_set ? ip_mrouter_set(so, sopt) :
767 					EOPNOTSUPP;
768 			break;
769 
770 		default:
771 			error = ip_ctloutput(so, sopt);
772 			break;
773 		}
774 		break;
775 	}
776 
777 	return (error);
778 }
779 
780 /*
781  * This function exists solely to receive the PRC_IFDOWN messages which are
782  * sent by if_down().  It looks for an ifaddr whose ifa_addr is sa, and calls
783  * in_ifadown() to remove all routes corresponding to that address.  It also
784  * receives the PRC_IFUP messages from if_up() and reinstalls the interface
785  * routes.
786  */
787 void
788 rip_ctlinput(int cmd, struct sockaddr *sa, void *vip)
789 {
790 	struct rm_priotracker in_ifa_tracker;
791 	struct in_ifaddr *ia;
792 	struct ifnet *ifp;
793 	int err;
794 	int flags;
795 
796 	switch (cmd) {
797 	case PRC_IFDOWN:
798 		IN_IFADDR_RLOCK(&in_ifa_tracker);
799 		CK_STAILQ_FOREACH(ia, &V_in_ifaddrhead, ia_link) {
800 			if (ia->ia_ifa.ifa_addr == sa
801 			    && (ia->ia_flags & IFA_ROUTE)) {
802 				ifa_ref(&ia->ia_ifa);
803 				IN_IFADDR_RUNLOCK(&in_ifa_tracker);
804 				/*
805 				 * in_scrubprefix() kills the interface route.
806 				 */
807 				in_scrubprefix(ia, 0);
808 				/*
809 				 * in_ifadown gets rid of all the rest of the
810 				 * routes.  This is not quite the right thing
811 				 * to do, but at least if we are running a
812 				 * routing process they will come back.
813 				 */
814 				in_ifadown(&ia->ia_ifa, 0);
815 				ifa_free(&ia->ia_ifa);
816 				break;
817 			}
818 		}
819 		if (ia == NULL)		/* If ia matched, already unlocked. */
820 			IN_IFADDR_RUNLOCK(&in_ifa_tracker);
821 		break;
822 
823 	case PRC_IFUP:
824 		IN_IFADDR_RLOCK(&in_ifa_tracker);
825 		CK_STAILQ_FOREACH(ia, &V_in_ifaddrhead, ia_link) {
826 			if (ia->ia_ifa.ifa_addr == sa)
827 				break;
828 		}
829 		if (ia == NULL || (ia->ia_flags & IFA_ROUTE)) {
830 			IN_IFADDR_RUNLOCK(&in_ifa_tracker);
831 			return;
832 		}
833 		ifa_ref(&ia->ia_ifa);
834 		IN_IFADDR_RUNLOCK(&in_ifa_tracker);
835 		flags = RTF_UP;
836 		ifp = ia->ia_ifa.ifa_ifp;
837 
838 		if ((ifp->if_flags & IFF_LOOPBACK)
839 		    || (ifp->if_flags & IFF_POINTOPOINT))
840 			flags |= RTF_HOST;
841 
842 		err = ifa_del_loopback_route((struct ifaddr *)ia, sa);
843 
844 		err = rtinit(&ia->ia_ifa, RTM_ADD, flags);
845 		if (err == 0)
846 			ia->ia_flags |= IFA_ROUTE;
847 
848 		err = ifa_add_loopback_route((struct ifaddr *)ia, sa);
849 
850 		ifa_free(&ia->ia_ifa);
851 		break;
852 	}
853 }
854 
855 static int
856 rip_attach(struct socket *so, int proto, struct thread *td)
857 {
858 	struct inpcb *inp;
859 	int error;
860 
861 	inp = sotoinpcb(so);
862 	KASSERT(inp == NULL, ("rip_attach: inp != NULL"));
863 
864 	error = priv_check(td, PRIV_NETINET_RAW);
865 	if (error)
866 		return (error);
867 	if (proto >= IPPROTO_MAX || proto < 0)
868 		return EPROTONOSUPPORT;
869 	error = soreserve(so, rip_sendspace, rip_recvspace);
870 	if (error)
871 		return (error);
872 	INP_INFO_WLOCK(&V_ripcbinfo);
873 	error = in_pcballoc(so, &V_ripcbinfo);
874 	if (error) {
875 		INP_INFO_WUNLOCK(&V_ripcbinfo);
876 		return (error);
877 	}
878 	inp = (struct inpcb *)so->so_pcb;
879 	inp->inp_vflag |= INP_IPV4;
880 	inp->inp_ip_p = proto;
881 	inp->inp_ip_ttl = V_ip_defttl;
882 	rip_inshash(inp);
883 	INP_INFO_WUNLOCK(&V_ripcbinfo);
884 	INP_WUNLOCK(inp);
885 	return (0);
886 }
887 
888 static void
889 rip_detach(struct socket *so)
890 {
891 	struct inpcb *inp;
892 
893 	inp = sotoinpcb(so);
894 	KASSERT(inp != NULL, ("rip_detach: inp == NULL"));
895 	KASSERT(inp->inp_faddr.s_addr == INADDR_ANY,
896 	    ("rip_detach: not closed"));
897 
898 	INP_INFO_WLOCK(&V_ripcbinfo);
899 	INP_WLOCK(inp);
900 	rip_delhash(inp);
901 	if (so == V_ip_mrouter && ip_mrouter_done)
902 		ip_mrouter_done();
903 	if (ip_rsvp_force_done)
904 		ip_rsvp_force_done(so);
905 	if (so == V_ip_rsvpd)
906 		ip_rsvp_done();
907 	in_pcbdetach(inp);
908 	in_pcbfree(inp);
909 	INP_INFO_WUNLOCK(&V_ripcbinfo);
910 }
911 
912 static void
913 rip_dodisconnect(struct socket *so, struct inpcb *inp)
914 {
915 	struct inpcbinfo *pcbinfo;
916 
917 	pcbinfo = inp->inp_pcbinfo;
918 	INP_INFO_WLOCK(pcbinfo);
919 	INP_WLOCK(inp);
920 	rip_delhash(inp);
921 	inp->inp_faddr.s_addr = INADDR_ANY;
922 	rip_inshash(inp);
923 	SOCK_LOCK(so);
924 	so->so_state &= ~SS_ISCONNECTED;
925 	SOCK_UNLOCK(so);
926 	INP_WUNLOCK(inp);
927 	INP_INFO_WUNLOCK(pcbinfo);
928 }
929 
930 static void
931 rip_abort(struct socket *so)
932 {
933 	struct inpcb *inp;
934 
935 	inp = sotoinpcb(so);
936 	KASSERT(inp != NULL, ("rip_abort: inp == NULL"));
937 
938 	rip_dodisconnect(so, inp);
939 }
940 
941 static void
942 rip_close(struct socket *so)
943 {
944 	struct inpcb *inp;
945 
946 	inp = sotoinpcb(so);
947 	KASSERT(inp != NULL, ("rip_close: inp == NULL"));
948 
949 	rip_dodisconnect(so, inp);
950 }
951 
952 static int
953 rip_disconnect(struct socket *so)
954 {
955 	struct inpcb *inp;
956 
957 	if ((so->so_state & SS_ISCONNECTED) == 0)
958 		return (ENOTCONN);
959 
960 	inp = sotoinpcb(so);
961 	KASSERT(inp != NULL, ("rip_disconnect: inp == NULL"));
962 
963 	rip_dodisconnect(so, inp);
964 	return (0);
965 }
966 
967 static int
968 rip_bind(struct socket *so, struct sockaddr *nam, struct thread *td)
969 {
970 	struct sockaddr_in *addr = (struct sockaddr_in *)nam;
971 	struct inpcb *inp;
972 	int error;
973 
974 	if (nam->sa_len != sizeof(*addr))
975 		return (EINVAL);
976 
977 	error = prison_check_ip4(td->td_ucred, &addr->sin_addr);
978 	if (error != 0)
979 		return (error);
980 
981 	inp = sotoinpcb(so);
982 	KASSERT(inp != NULL, ("rip_bind: inp == NULL"));
983 
984 	if (CK_STAILQ_EMPTY(&V_ifnet) ||
985 	    (addr->sin_family != AF_INET && addr->sin_family != AF_IMPLINK) ||
986 	    (addr->sin_addr.s_addr &&
987 	     (inp->inp_flags & INP_BINDANY) == 0 &&
988 	     ifa_ifwithaddr_check((struct sockaddr *)addr) == 0))
989 		return (EADDRNOTAVAIL);
990 
991 	INP_INFO_WLOCK(&V_ripcbinfo);
992 	INP_WLOCK(inp);
993 	rip_delhash(inp);
994 	inp->inp_laddr = addr->sin_addr;
995 	rip_inshash(inp);
996 	INP_WUNLOCK(inp);
997 	INP_INFO_WUNLOCK(&V_ripcbinfo);
998 	return (0);
999 }
1000 
1001 static int
1002 rip_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
1003 {
1004 	struct sockaddr_in *addr = (struct sockaddr_in *)nam;
1005 	struct inpcb *inp;
1006 
1007 	if (nam->sa_len != sizeof(*addr))
1008 		return (EINVAL);
1009 	if (CK_STAILQ_EMPTY(&V_ifnet))
1010 		return (EADDRNOTAVAIL);
1011 	if (addr->sin_family != AF_INET && addr->sin_family != AF_IMPLINK)
1012 		return (EAFNOSUPPORT);
1013 
1014 	inp = sotoinpcb(so);
1015 	KASSERT(inp != NULL, ("rip_connect: inp == NULL"));
1016 
1017 	INP_INFO_WLOCK(&V_ripcbinfo);
1018 	INP_WLOCK(inp);
1019 	rip_delhash(inp);
1020 	inp->inp_faddr = addr->sin_addr;
1021 	rip_inshash(inp);
1022 	soisconnected(so);
1023 	INP_WUNLOCK(inp);
1024 	INP_INFO_WUNLOCK(&V_ripcbinfo);
1025 	return (0);
1026 }
1027 
1028 static int
1029 rip_shutdown(struct socket *so)
1030 {
1031 	struct inpcb *inp;
1032 
1033 	inp = sotoinpcb(so);
1034 	KASSERT(inp != NULL, ("rip_shutdown: inp == NULL"));
1035 
1036 	INP_WLOCK(inp);
1037 	socantsendmore(so);
1038 	INP_WUNLOCK(inp);
1039 	return (0);
1040 }
1041 
1042 static int
1043 rip_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *nam,
1044     struct mbuf *control, struct thread *td)
1045 {
1046 	struct inpcb *inp;
1047 	u_long dst;
1048 
1049 	inp = sotoinpcb(so);
1050 	KASSERT(inp != NULL, ("rip_send: inp == NULL"));
1051 
1052 	/*
1053 	 * Note: 'dst' reads below are unlocked.
1054 	 */
1055 	if (so->so_state & SS_ISCONNECTED) {
1056 		if (nam) {
1057 			m_freem(m);
1058 			return (EISCONN);
1059 		}
1060 		dst = inp->inp_faddr.s_addr;	/* Unlocked read. */
1061 	} else {
1062 		if (nam == NULL) {
1063 			m_freem(m);
1064 			return (ENOTCONN);
1065 		}
1066 		dst = ((struct sockaddr_in *)nam)->sin_addr.s_addr;
1067 	}
1068 	return (rip_output(m, so, dst));
1069 }
1070 #endif /* INET */
1071 
1072 static int
1073 rip_pcblist(SYSCTL_HANDLER_ARGS)
1074 {
1075 	struct xinpgen xig;
1076 	struct epoch_tracker et;
1077 	struct inpcb *inp;
1078 	int error;
1079 
1080 	if (req->newptr != 0)
1081 		return (EPERM);
1082 
1083 	if (req->oldptr == 0) {
1084 		int n;
1085 
1086 		n = V_ripcbinfo.ipi_count;
1087 		n += imax(n / 8, 10);
1088 		req->oldidx = 2 * (sizeof xig) + n * sizeof(struct xinpcb);
1089 		return (0);
1090 	}
1091 
1092 	if ((error = sysctl_wire_old_buffer(req, 0)) != 0)
1093 		return (error);
1094 
1095 	bzero(&xig, sizeof(xig));
1096 	xig.xig_len = sizeof xig;
1097 	xig.xig_count = V_ripcbinfo.ipi_count;
1098 	xig.xig_gen = V_ripcbinfo.ipi_gencnt;
1099 	xig.xig_sogen = so_gencnt;
1100 	error = SYSCTL_OUT(req, &xig, sizeof xig);
1101 	if (error)
1102 		return (error);
1103 
1104 	NET_EPOCH_ENTER(et);
1105 	for (inp = CK_LIST_FIRST(V_ripcbinfo.ipi_listhead);
1106 	    inp != NULL;
1107 	    inp = CK_LIST_NEXT(inp, inp_list)) {
1108 		INP_RLOCK(inp);
1109 		if (inp->inp_gencnt <= xig.xig_gen &&
1110 		    cr_canseeinpcb(req->td->td_ucred, inp) == 0) {
1111 			struct xinpcb xi;
1112 
1113 			in_pcbtoxinpcb(inp, &xi);
1114 			INP_RUNLOCK(inp);
1115 			error = SYSCTL_OUT(req, &xi, sizeof xi);
1116 			if (error)
1117 				break;
1118 		} else
1119 			INP_RUNLOCK(inp);
1120 	}
1121 	NET_EPOCH_EXIT(et);
1122 
1123 	if (!error) {
1124 		/*
1125 		 * Give the user an updated idea of our state.  If the
1126 		 * generation differs from what we told her before, she knows
1127 		 * that something happened while we were processing this
1128 		 * request, and it might be necessary to retry.
1129 		 */
1130 		xig.xig_gen = V_ripcbinfo.ipi_gencnt;
1131 		xig.xig_sogen = so_gencnt;
1132 		xig.xig_count = V_ripcbinfo.ipi_count;
1133 		error = SYSCTL_OUT(req, &xig, sizeof xig);
1134 	}
1135 
1136 	return (error);
1137 }
1138 
1139 SYSCTL_PROC(_net_inet_raw, OID_AUTO/*XXX*/, pcblist,
1140     CTLTYPE_OPAQUE | CTLFLAG_RD, NULL, 0,
1141     rip_pcblist, "S,xinpcb", "List of active raw IP sockets");
1142 
1143 #ifdef INET
1144 struct pr_usrreqs rip_usrreqs = {
1145 	.pru_abort =		rip_abort,
1146 	.pru_attach =		rip_attach,
1147 	.pru_bind =		rip_bind,
1148 	.pru_connect =		rip_connect,
1149 	.pru_control =		in_control,
1150 	.pru_detach =		rip_detach,
1151 	.pru_disconnect =	rip_disconnect,
1152 	.pru_peeraddr =		in_getpeeraddr,
1153 	.pru_send =		rip_send,
1154 	.pru_shutdown =		rip_shutdown,
1155 	.pru_sockaddr =		in_getsockaddr,
1156 	.pru_sosetlabel =	in_pcbsosetlabel,
1157 	.pru_close =		rip_close,
1158 };
1159 #endif /* INET */
1160