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