xref: /xnu-11215/bsd/netinet/ip_input.c (revision 4f1223e8)
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) 1982, 1986, 1988, 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  *	@(#)ip_input.c	8.2 (Berkeley) 1/4/94
61  */
62 /*
63  * NOTICE: This file was modified by SPARTA, Inc. in 2007 to introduce
64  * support for mandatory and extensible security protections.  This notice
65  * is included in support of clause 2.2 (b) of the Apple Public License,
66  * Version 2.0.
67  */
68 
69 #define _IP_VHL
70 
71 #include <sys/param.h>
72 #include <sys/systm.h>
73 #include <sys/mbuf.h>
74 #include <sys/malloc.h>
75 #include <sys/domain.h>
76 #include <sys/protosw.h>
77 #include <sys/socket.h>
78 #include <sys/time.h>
79 #include <sys/kernel.h>
80 #include <sys/syslog.h>
81 #include <sys/sysctl.h>
82 #include <sys/mcache.h>
83 #include <sys/socketvar.h>
84 #include <sys/kdebug.h>
85 #include <mach/mach_time.h>
86 #include <mach/sdt.h>
87 
88 #include <machine/endian.h>
89 #include <dev/random/randomdev.h>
90 
91 #include <kern/queue.h>
92 #include <kern/locks.h>
93 #include <libkern/OSAtomic.h>
94 
95 #include <pexpert/pexpert.h>
96 
97 #include <net/if.h>
98 #include <net/if_var.h>
99 #include <net/if_dl.h>
100 #include <net/route.h>
101 #include <net/kpi_protocol.h>
102 #include <net/ntstat.h>
103 #include <net/dlil.h>
104 #include <net/classq/classq.h>
105 #include <net/net_perf.h>
106 #include <net/init.h>
107 #if PF
108 #include <net/pfvar.h>
109 #endif /* PF */
110 #include <net/if_ports_used.h>
111 #include <net/droptap.h>
112 
113 #include <netinet/in.h>
114 #include <netinet/in_systm.h>
115 #include <netinet/in_var.h>
116 #include <netinet/in_arp.h>
117 #include <netinet/ip.h>
118 #include <netinet/in_pcb.h>
119 #include <netinet/ip_var.h>
120 #include <netinet/ip_icmp.h>
121 #include <netinet/kpi_ipfilter_var.h>
122 #include <netinet/udp.h>
123 #include <netinet/udp_var.h>
124 #include <netinet/bootp.h>
125 
126 #if DUMMYNET
127 #include <netinet/ip_dummynet.h>
128 #endif /* DUMMYNET */
129 
130 #if IPSEC
131 #include <netinet6/ipsec.h>
132 #include <netkey/key.h>
133 #endif /* IPSEC */
134 
135 #include <net/sockaddr_utils.h>
136 
137 #include <os/log.h>
138 
139 extern struct inpcbinfo ripcbinfo;
140 
141 #define DBG_LAYER_BEG           NETDBG_CODE(DBG_NETIP, 0)
142 #define DBG_LAYER_END           NETDBG_CODE(DBG_NETIP, 2)
143 #define DBG_FNC_IP_INPUT        NETDBG_CODE(DBG_NETIP, (2 << 8))
144 
145 #if IPSEC
146 extern int ipsec_bypass;
147 #endif /* IPSEC */
148 
149 MBUFQ_HEAD(fq_head);
150 
151 static int frag_timeout_run;            /* frag timer is scheduled to run */
152 static void frag_timeout(void *);
153 static void frag_sched_timeout(void);
154 
155 static struct ipq *ipq_alloc(void);
156 static void ipq_free(struct ipq *);
157 static void ipq_updateparams(void);
158 static void ip_input_second_pass(struct mbuf *, struct ifnet *,
159     int, int, struct ip_fw_in_args *);
160 
161 static LCK_GRP_DECLARE(ipqlock_grp, "ipqlock");
162 static LCK_MTX_DECLARE(ipqlock, &ipqlock_grp);
163 
164 
165 /* Packet reassembly stuff */
166 #define IPREASS_NHASH_LOG2      6
167 #define IPREASS_NHASH           (1 << IPREASS_NHASH_LOG2)
168 #define IPREASS_HMASK           (IPREASS_NHASH - 1)
169 #define IPREASS_HASH(x, y) \
170 	(((((x) & 0xF) | ((((x) >> 8) & 0xF) << 4)) ^ (y)) & IPREASS_HMASK)
171 
172 /* IP fragment reassembly queues (protected by ipqlock) */
173 static TAILQ_HEAD(ipqhead, ipq) ipq[IPREASS_NHASH]; /* ip reassembly queues */
174 static int maxnipq;                     /* max packets in reass queues */
175 static u_int32_t maxfragsperpacket;     /* max frags/packet in reass queues */
176 static u_int32_t nipq;                  /* # of packets in reass queues */
177 static u_int32_t ipq_limit;             /* ipq allocation limit */
178 static u_int32_t ipq_count;             /* current # of allocated ipq's */
179 
180 static int sysctl_ipforwarding SYSCTL_HANDLER_ARGS;
181 static int sysctl_maxnipq SYSCTL_HANDLER_ARGS;
182 static int sysctl_maxfragsperpacket SYSCTL_HANDLER_ARGS;
183 
184 #if (DEBUG || DEVELOPMENT)
185 static int sysctl_reset_ip_input_stats SYSCTL_HANDLER_ARGS;
186 static int sysctl_ip_input_measure_bins SYSCTL_HANDLER_ARGS;
187 static int sysctl_ip_input_getperf SYSCTL_HANDLER_ARGS;
188 #endif /* (DEBUG || DEVELOPMENT) */
189 
190 int ipforwarding = 0;
191 SYSCTL_PROC(_net_inet_ip, IPCTL_FORWARDING, forwarding,
192     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED, &ipforwarding, 0,
193     sysctl_ipforwarding, "I", "Enable IP forwarding between interfaces");
194 
195 static int ipsendredirects = 1; /* XXX */
196 SYSCTL_INT(_net_inet_ip, IPCTL_SENDREDIRECTS, redirect,
197     CTLFLAG_RW | CTLFLAG_LOCKED, &ipsendredirects, 0,
198     "Enable sending IP redirects");
199 
200 int ip_defttl = IPDEFTTL;
201 SYSCTL_INT(_net_inet_ip, IPCTL_DEFTTL, ttl, CTLFLAG_RW | CTLFLAG_LOCKED,
202     &ip_defttl, 0, "Maximum TTL on IP packets");
203 
204 static int ip_dosourceroute = 0;
205 SYSCTL_INT(_net_inet_ip, IPCTL_SOURCEROUTE, sourceroute,
206     CTLFLAG_RW | CTLFLAG_LOCKED, &ip_dosourceroute, 0,
207     "Enable forwarding source routed IP packets");
208 
209 static int ip_acceptsourceroute = 0;
210 SYSCTL_INT(_net_inet_ip, IPCTL_ACCEPTSOURCEROUTE, accept_sourceroute,
211     CTLFLAG_RW | CTLFLAG_LOCKED, &ip_acceptsourceroute, 0,
212     "Enable accepting source routed IP packets");
213 
214 static int ip_sendsourcequench = 0;
215 SYSCTL_INT(_net_inet_ip, OID_AUTO, sendsourcequench,
216     CTLFLAG_RW | CTLFLAG_LOCKED, &ip_sendsourcequench, 0,
217     "Enable the transmission of source quench packets");
218 
219 SYSCTL_PROC(_net_inet_ip, OID_AUTO, maxfragpackets,
220     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED, &maxnipq, 0, sysctl_maxnipq,
221     "I", "Maximum number of IPv4 fragment reassembly queue entries");
222 
223 SYSCTL_UINT(_net_inet_ip, OID_AUTO, fragpackets, CTLFLAG_RD | CTLFLAG_LOCKED,
224     &nipq, 0, "Current number of IPv4 fragment reassembly queue entries");
225 
226 SYSCTL_PROC(_net_inet_ip, OID_AUTO, maxfragsperpacket,
227     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED, &maxfragsperpacket, 0,
228     sysctl_maxfragsperpacket, "I",
229     "Maximum number of IPv4 fragments allowed per packet");
230 
231 static uint32_t ip_adj_clear_hwcksum = 0;
232 SYSCTL_UINT(_net_inet_ip, OID_AUTO, adj_clear_hwcksum,
233     CTLFLAG_RW | CTLFLAG_LOCKED, &ip_adj_clear_hwcksum, 0,
234     "Invalidate hwcksum info when adjusting length");
235 
236 static uint32_t ip_adj_partial_sum = 1;
237 SYSCTL_UINT(_net_inet_ip, OID_AUTO, adj_partial_sum,
238     CTLFLAG_RW | CTLFLAG_LOCKED, &ip_adj_partial_sum, 0,
239     "Perform partial sum adjustment of trailing bytes at IP layer");
240 
241 /*
242  * ip_checkinterface controls the receive side of the models for multihoming
243  * that are discussed in RFC 1122.
244  *
245  * ip_checkinterface values are:
246  *  IP_CHECKINTERFACE_WEAK_ES:
247  *	This corresponds to the Weak End-System model where incoming packets from
248  *	any interface are accepted provided the destination address of the incoming packet
249  *	is assigned to some interface.
250  *
251  *  IP_CHECKINTERFACE_HYBRID_ES:
252  *	The Hybrid End-System model use the Strong End-System for tunnel interfaces
253  *	(ipsec and utun) and the weak End-System model for other interfaces families.
254  *	This prevents a rogue middle box to probe for signs of TCP connections
255  *	that use the tunnel interface.
256  *
257  *  IP_CHECKINTERFACE_STRONG_ES:
258  *	The Strong model model requires the packet arrived on an interface that
259  *	is assigned the destination address of the packet.
260  *
261  * Since the routing table and transmit implementation do not implement the Strong ES model,
262  * setting this to a value different from IP_CHECKINTERFACE_WEAK_ES may lead to unexpected results.
263  *
264  * When forwarding is enabled, the system reverts to the Weak ES model as a router
265  * is expected by design to receive packets from several interfaces to the same address.
266  *
267  * XXX - ip_checkinterface currently must be set to IP_CHECKINTERFACE_WEAK_ES if you use ipnat
268  * to translate the destination address to another local interface.
269  *
270  * XXX - ip_checkinterface must be set to IP_CHECKINTERFACE_WEAK_ES if you add IP aliases
271  * to the loopback interface instead of the interface where the
272  * packets for those addresses are received.
273  */
274 #define IP_CHECKINTERFACE_WEAK_ES       0
275 #define IP_CHECKINTERFACE_HYBRID_ES     1
276 #define IP_CHECKINTERFACE_STRONG_ES     2
277 
278 static int ip_checkinterface = IP_CHECKINTERFACE_HYBRID_ES;
279 
280 static int sysctl_ip_checkinterface SYSCTL_HANDLER_ARGS;
281 SYSCTL_PROC(_net_inet_ip, OID_AUTO, check_interface,
282     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED,
283     0, 0, sysctl_ip_checkinterface, "I", "Verify packet arrives on correct interface");
284 
285 #if (DEBUG || DEVELOPMENT)
286 #define IP_CHECK_IF_DEBUG 1
287 #else
288 #define IP_CHECK_IF_DEBUG 0
289 #endif /* (DEBUG || DEVELOPMENT) */
290 static int ip_checkinterface_debug = IP_CHECK_IF_DEBUG;
291 SYSCTL_INT(_net_inet_ip, OID_AUTO, checkinterface_debug, CTLFLAG_RW | CTLFLAG_LOCKED,
292     &ip_checkinterface_debug, IP_CHECK_IF_DEBUG, "");
293 
294 static int ip_chaining = 1;
295 SYSCTL_INT(_net_inet_ip, OID_AUTO, rx_chaining, CTLFLAG_RW | CTLFLAG_LOCKED,
296     &ip_chaining, 1, "Do receive side ip address based chaining");
297 
298 static int ip_chainsz = 6;
299 SYSCTL_INT(_net_inet_ip, OID_AUTO, rx_chainsz, CTLFLAG_RW | CTLFLAG_LOCKED,
300     &ip_chainsz, 1, "IP receive side max chaining");
301 
302 #if (DEBUG || DEVELOPMENT)
303 static int ip_input_measure = 0;
304 SYSCTL_PROC(_net_inet_ip, OID_AUTO, input_perf,
305     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED,
306     &ip_input_measure, 0, sysctl_reset_ip_input_stats, "I", "Do time measurement");
307 
308 static uint64_t ip_input_measure_bins = 0;
309 SYSCTL_PROC(_net_inet_ip, OID_AUTO, input_perf_bins,
310     CTLTYPE_QUAD | CTLFLAG_RW | CTLFLAG_LOCKED, &ip_input_measure_bins, 0,
311     sysctl_ip_input_measure_bins, "I",
312     "bins for chaining performance data histogram");
313 
314 static net_perf_t net_perf;
315 SYSCTL_PROC(_net_inet_ip, OID_AUTO, input_perf_data,
316     CTLTYPE_STRUCT | CTLFLAG_RD | CTLFLAG_LOCKED,
317     0, 0, sysctl_ip_input_getperf, "S,net_perf",
318     "IP input performance data (struct net_perf, net/net_perf.h)");
319 #endif /* (DEBUG || DEVELOPMENT) */
320 
321 #if DIAGNOSTIC
322 static int ipprintfs = 0;
323 #endif
324 
325 struct protosw *ip_protox[IPPROTO_MAX];
326 
327 static LCK_GRP_DECLARE(in_ifaddr_rwlock_grp, "in_ifaddr_rwlock");
328 LCK_RW_DECLARE(in_ifaddr_rwlock, &in_ifaddr_rwlock_grp);
329 
330 #define INADDR_NHASH    61
331 static uint32_t inaddr_nhash;                  /* hash table size */
332 static uint32_t inaddr_hashp;                  /* next largest prime */
333 
334 /* Protected by in_ifaddr_rwlock */
335 struct in_ifaddrhead in_ifaddrhead;     /* first inet address */
336 static struct in_ifaddrhashhead *__counted_by(inaddr_nhash) in_ifaddrhashtbl = NULL;  /* inet addr hash table  */
337 
338 static int ip_getstat SYSCTL_HANDLER_ARGS;
339 struct ipstat ipstat;
340 SYSCTL_PROC(_net_inet_ip, IPCTL_STATS, stats,
341     CTLTYPE_STRUCT | CTLFLAG_RD | CTLFLAG_LOCKED,
342     0, 0, ip_getstat, "S,ipstat",
343     "IP statistics (struct ipstat, netinet/ip_var.h)");
344 
345 #if IPCTL_DEFMTU
346 SYSCTL_INT(_net_inet_ip, IPCTL_DEFMTU, mtu, CTLFLAG_RW | CTLFLAG_LOCKED,
347     &ip_mtu, 0, "Default MTU");
348 #endif /* IPCTL_DEFMTU */
349 
350 #if IPSTEALTH
351 static int      ipstealth = 0;
352 SYSCTL_INT(_net_inet_ip, OID_AUTO, stealth, CTLFLAG_RW | CTLFLAG_LOCKED,
353     &ipstealth, 0, "");
354 #endif /* IPSTEALTH */
355 
356 #if DUMMYNET
357 ip_dn_io_t *ip_dn_io_ptr;
358 #endif /* DUMMYNET */
359 
360 SYSCTL_NODE(_net_inet_ip, OID_AUTO, linklocal,
361     CTLFLAG_RW | CTLFLAG_LOCKED, 0, "link local");
362 
363 struct ip_linklocal_stat ip_linklocal_stat;
364 SYSCTL_STRUCT(_net_inet_ip_linklocal, OID_AUTO, stat,
365     CTLFLAG_RD | CTLFLAG_LOCKED, &ip_linklocal_stat, ip_linklocal_stat,
366     "Number of link local packets with TTL less than 255");
367 
368 SYSCTL_NODE(_net_inet_ip_linklocal, OID_AUTO, in,
369     CTLFLAG_RW | CTLFLAG_LOCKED, 0, "link local input");
370 
371 int ip_linklocal_in_allowbadttl = 1;
372 SYSCTL_INT(_net_inet_ip_linklocal_in, OID_AUTO, allowbadttl,
373     CTLFLAG_RW | CTLFLAG_LOCKED, &ip_linklocal_in_allowbadttl, 0,
374     "Allow incoming link local packets with TTL less than 255");
375 
376 
377 /*
378  * We need to save the IP options in case a protocol wants to respond
379  * to an incoming packet over the same route if the packet got here
380  * using IP source routing.  This allows connection establishment and
381  * maintenance when the remote end is on a network that is not known
382  * to us.
383  */
384 static int      ip_nhops = 0;
385 static  struct ip_srcrt {
386 	struct  in_addr dst;                    /* final destination */
387 	char    nop;                            /* one NOP to align */
388 	char    srcopt[IPOPT_OFFSET + 1];       /* OPTVAL, OLEN and OFFSET */
389 	struct  in_addr route[MAX_IPOPTLEN / sizeof(struct in_addr)];
390 } ip_srcrt;
391 
392 static void in_ifaddrhashtbl_init(void);
393 static void save_rte(u_char *__indexable, struct in_addr);
394 static int ip_dooptions(struct mbuf *, int, struct sockaddr_in *);
395 static void ip_forward(struct mbuf *, int, struct sockaddr_in *);
396 static void frag_freef(struct ipqhead *, struct ipq *, drop_reason_t);
397 static struct mbuf *ip_reass(struct mbuf *);
398 static void ip_fwd_route_copyout(struct ifnet *, struct route *);
399 static void ip_fwd_route_copyin(struct ifnet *, struct route *);
400 static inline u_short ip_cksum(struct mbuf *, int);
401 
402 /*
403  * On platforms which require strict alignment (currently for anything but
404  * i386 or x86_64 or arm64), check if the IP header pointer is 32-bit aligned; if not,
405  * copy the contents of the mbuf chain into a new chain, and free the original
406  * one.  Create some head room in the first mbuf of the new chain, in case
407  * it's needed later on.
408  */
409 #if defined(__i386__) || defined(__x86_64__) || defined(__arm64__)
410 #define IP_HDR_ALIGNMENT_FIXUP(_m, _ifp, _action) do { } while (0)
411 #else /* !__i386__ && !__x86_64__ && !__arm64__ */
412 #define IP_HDR_ALIGNMENT_FIXUP(_m, _ifp, _action) do {                  \
413 	if (!IP_HDR_ALIGNED_P(mtod(_m, caddr_t))) {                     \
414 	        struct mbuf *_n;                                        \
415 	        struct ifnet *__ifp = (_ifp);                           \
416 	        os_atomic_inc(&(__ifp)->if_alignerrs, relaxed);         \
417 	        if (((_m)->m_flags & M_PKTHDR) &&                       \
418 	            (_m)->m_pkthdr.pkt_hdr != NULL)                     \
419 	                (_m)->m_pkthdr.pkt_hdr = NULL;                  \
420 	        _n = m_defrag_offset(_m, max_linkhdr, M_NOWAIT);        \
421 	        if (_n == NULL) {                                       \
422 	                os_atomic_inc(&ipstat.ips_toosmall, relaxed);   \
423 	                m_drop(_m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IP_TOO_SMALL, NULL, 0);\
424 	                (_m) = NULL;                                    \
425 	                _action;                                        \
426 	        } else {                                                \
427 	                VERIFY(_n != (_m));                             \
428 	                (_m) = _n;                                      \
429 	        }                                                       \
430 	}                                                               \
431 } while (0)
432 #endif /* !__i386__ && !__x86_64__ && !__arm64__ */
433 
434 
435 typedef enum ip_check_if_result {
436 	IP_CHECK_IF_NONE = 0,
437 	IP_CHECK_IF_OURS = 1,
438 	IP_CHECK_IF_DROP = 2,
439 	IP_CHECK_IF_FORWARD = 3
440 } ip_check_if_result_t;
441 
442 static ip_check_if_result_t ip_input_check_interface(struct mbuf **, struct ip *, struct ifnet *);
443 
444 /*
445  * GRE input handler function, settable via ip_gre_register_input() for PPTP.
446  */
447 static gre_input_func_t gre_input_func;
448 
449 static void
ip_init_delayed(void)450 ip_init_delayed(void)
451 {
452 	struct ifreq ifr;
453 	int error;
454 	struct sockaddr_in *__single sin;
455 
456 	bzero(&ifr, sizeof(ifr));
457 	strlcpy(ifr.ifr_name, "lo0", sizeof(ifr.ifr_name));
458 	sin = SIN(&ifr.ifr_addr);
459 	sin->sin_len = sizeof(struct sockaddr_in);
460 	sin->sin_family = AF_INET;
461 	sin->sin_addr.s_addr = htonl(INADDR_LOOPBACK);
462 	error = in_control(NULL, SIOCSIFADDR, (caddr_t)&ifr, lo_ifp, kernproc);
463 	if (error) {
464 		printf("%s: failed to initialise lo0's address, error=%d\n",
465 		    __func__, error);
466 	}
467 }
468 
469 /*
470  * IP initialization: fill in IP protocol switch table.
471  * All protocols not implemented in kernel go to raw IP protocol handler.
472  */
473 void
ip_init(struct protosw * pp,struct domain * dp)474 ip_init(struct protosw *pp, struct domain *dp)
475 {
476 	static int ip_initialized = 0;
477 	struct protosw *__single pr;
478 	struct timeval tv;
479 	int i;
480 
481 	domain_proto_mtx_lock_assert_held();
482 	VERIFY((pp->pr_flags & (PR_INITIALIZED | PR_ATTACHED)) == PR_ATTACHED);
483 
484 	/*
485 	 * Some ioctls (e.g. SIOCAIFADDR) use ifaliasreq struct, which is
486 	 * interchangeable with in_aliasreq; they must have the same size.
487 	 */
488 	_CASSERT(sizeof(struct ifaliasreq) == sizeof(struct in_aliasreq));
489 
490 	if (ip_initialized) {
491 		return;
492 	}
493 	ip_initialized = 1;
494 
495 	TAILQ_INIT(&in_ifaddrhead);
496 	in_ifaddrhashtbl_init();
497 
498 	ip_moptions_init();
499 
500 	pr = pffindproto_locked(PF_INET, IPPROTO_RAW, SOCK_RAW);
501 	if (pr == NULL) {
502 		panic("%s: Unable to find [PF_INET,IPPROTO_RAW,SOCK_RAW]",
503 		    __func__);
504 		/* NOTREACHED */
505 	}
506 
507 	/* Initialize the entire ip_protox[] array to IPPROTO_RAW. */
508 	for (i = 0; i < IPPROTO_MAX; i++) {
509 		ip_protox[i] = pr;
510 	}
511 	/*
512 	 * Cycle through IP protocols and put them into the appropriate place
513 	 * in ip_protox[], skipping protocols IPPROTO_{IP,RAW}.
514 	 */
515 	VERIFY(dp == inetdomain && dp->dom_family == PF_INET);
516 	TAILQ_FOREACH(pr, &dp->dom_protosw, pr_entry) {
517 		VERIFY(pr->pr_domain == dp);
518 		if (pr->pr_protocol != 0 && pr->pr_protocol != IPPROTO_RAW) {
519 			/* Be careful to only index valid IP protocols. */
520 			if (pr->pr_protocol < IPPROTO_MAX) {
521 				ip_protox[pr->pr_protocol] = pr;
522 			}
523 		}
524 	}
525 
526 	lck_mtx_lock(&ipqlock);
527 	/* Initialize IP reassembly queue. */
528 	for (i = 0; i < IPREASS_NHASH; i++) {
529 		TAILQ_INIT(&ipq[i]);
530 	}
531 
532 	maxnipq = nmbclusters / 32;
533 	maxfragsperpacket = 128; /* enough for 64k in 512 byte fragments */
534 	ipq_updateparams();
535 	lck_mtx_unlock(&ipqlock);
536 
537 	getmicrotime(&tv);
538 	ip_id = (u_short)(RandomULong() ^ tv.tv_usec);
539 
540 	PE_parse_boot_argn("ip_checkinterface", &i, sizeof(i));
541 	switch (i) {
542 	case IP_CHECKINTERFACE_WEAK_ES:
543 	case IP_CHECKINTERFACE_HYBRID_ES:
544 	case IP_CHECKINTERFACE_STRONG_ES:
545 		ip_checkinterface = i;
546 		break;
547 	default:
548 		break;
549 	}
550 
551 	net_init_add(ip_init_delayed);
552 }
553 
554 /*
555  * Initialize IPv4 source address hash table.
556  */
557 static void
in_ifaddrhashtbl_init(void)558 in_ifaddrhashtbl_init(void)
559 {
560 	int i, k, p;
561 	uint32_t nhash = 0;
562 	uint32_t hash_size;
563 
564 	if (in_ifaddrhashtbl != NULL) {
565 		return;
566 	}
567 
568 	PE_parse_boot_argn("inaddr_nhash", &nhash,
569 	    sizeof(inaddr_nhash));
570 	if (nhash == 0) {
571 		nhash = INADDR_NHASH;
572 	}
573 
574 	hash_size = nhash * sizeof(*in_ifaddrhashtbl);
575 
576 	in_ifaddrhashtbl = zalloc_permanent(
577 		hash_size,
578 		ZALIGN_PTR);
579 	inaddr_nhash = nhash;
580 
581 	/*
582 	 * Generate the next largest prime greater than inaddr_nhash.
583 	 */
584 	k = (inaddr_nhash % 2 == 0) ? inaddr_nhash + 1 : inaddr_nhash + 2;
585 	for (;;) {
586 		p = 1;
587 		for (i = 3; i * i <= k; i += 2) {
588 			if (k % i == 0) {
589 				p = 0;
590 			}
591 		}
592 		if (p == 1) {
593 			break;
594 		}
595 		k += 2;
596 	}
597 	inaddr_hashp = k;
598 }
599 
600 uint32_t
inaddr_hashval(uint32_t key)601 inaddr_hashval(uint32_t key)
602 {
603 	/*
604 	 * The hash index is the computed prime times the key modulo
605 	 * the hash size, as documented in "Introduction to Algorithms"
606 	 * (Cormen, Leiserson, Rivest).
607 	 */
608 	if (inaddr_nhash > 1) {
609 		return (key * inaddr_hashp) % inaddr_nhash;
610 	} else {
611 		return 0;
612 	}
613 }
614 
615 struct in_ifaddrhashhead *
inaddr_hashlookup(uint32_t key)616 inaddr_hashlookup(uint32_t key)
617 {
618 	return &in_ifaddrhashtbl[inaddr_hashval(key)];
619 }
620 
621 __private_extern__ void
ip_proto_dispatch_in(struct mbuf * m,int hlen,u_int8_t proto,ipfilter_t inject_ipfref)622 ip_proto_dispatch_in(struct mbuf *m, int hlen, u_int8_t proto,
623     ipfilter_t inject_ipfref)
624 {
625 	struct ipfilter *__single filter;
626 	int seen = (inject_ipfref == NULL);
627 	int     changed_header = 0;
628 	struct ip *ip;
629 	void (*pr_input)(struct mbuf *, int len);
630 
631 	if (!TAILQ_EMPTY(&ipv4_filters)) {
632 		ipf_ref();
633 		TAILQ_FOREACH(filter, &ipv4_filters, ipf_link) {
634 			if (seen == 0) {
635 				if ((struct ipfilter *)inject_ipfref == filter) {
636 					seen = 1;
637 				}
638 			} else if (filter->ipf_filter.ipf_input) {
639 				errno_t result;
640 
641 				if (changed_header == 0) {
642 					/*
643 					 * Perform IP header alignment fixup,
644 					 * if needed, before passing packet
645 					 * into filter(s).
646 					 */
647 					IP_HDR_ALIGNMENT_FIXUP(m,
648 					    m->m_pkthdr.rcvif, ipf_unref());
649 
650 					/* ipf_unref() already called */
651 					if (m == NULL) {
652 						return;
653 					}
654 
655 					changed_header = 1;
656 					ip = mtod(m, struct ip *);
657 					ip->ip_len = htons(ip->ip_len + (uint16_t)hlen);
658 					ip->ip_off = htons(ip->ip_off);
659 					ip->ip_sum = 0;
660 					ip->ip_sum = ip_cksum_hdr_in(m, hlen);
661 				}
662 				result = filter->ipf_filter.ipf_input(
663 					filter->ipf_filter.cookie, (mbuf_t *)&m,
664 					hlen, proto);
665 				if (result == EJUSTRETURN) {
666 					ipf_unref();
667 					return;
668 				}
669 				if (result != 0) {
670 					ipstat.ips_input_ipf_drop++;
671 					ipf_unref();
672 					m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IP_FILTER_DROP,
673 					    NULL, 0);
674 					return;
675 				}
676 			}
677 		}
678 		ipf_unref();
679 	}
680 
681 	/* Perform IP header alignment fixup (post-filters), if needed */
682 	IP_HDR_ALIGNMENT_FIXUP(m, m->m_pkthdr.rcvif, return );
683 
684 	ip = mtod(m, struct ip *);
685 
686 	if (changed_header) {
687 		ip->ip_len = ntohs(ip->ip_len) - (u_short)hlen;
688 		ip->ip_off = ntohs(ip->ip_off);
689 	}
690 
691 	/*
692 	 * If there isn't a specific lock for the protocol
693 	 * we're about to call, use the generic lock for AF_INET.
694 	 * otherwise let the protocol deal with its own locking
695 	 */
696 	if ((pr_input = ip_protox[ip->ip_p]->pr_input) == NULL) {
697 		ipstat.ips_input_no_proto++;
698 		m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IP_NO_PROTO,
699 		    NULL, 0);
700 	} else if (!(ip_protox[ip->ip_p]->pr_flags & PR_PROTOLOCK)) {
701 		lck_mtx_lock(inet_domain_mutex);
702 		pr_input(m, hlen);
703 		lck_mtx_unlock(inet_domain_mutex);
704 	} else {
705 		pr_input(m, hlen);
706 	}
707 }
708 
709 struct pktchain_elm {
710 	struct mbuf     *pkte_head;
711 	struct mbuf     *pkte_tail;
712 	struct in_addr  pkte_saddr;
713 	struct in_addr  pkte_daddr;
714 	uint16_t        pkte_npkts;
715 	uint16_t        pkte_proto;
716 	uint32_t        pkte_nbytes;
717 };
718 
719 typedef struct pktchain_elm pktchain_elm_t;
720 
721 /* Store upto PKTTBL_SZ unique flows on the stack */
722 #define PKTTBL_SZ       7
723 
724 static struct mbuf *
ip_chain_insert(struct mbuf * packet,pktchain_elm_t * __counted_by (PKTTBL_SZ)tbl)725 ip_chain_insert(struct mbuf *packet, pktchain_elm_t *__counted_by(PKTTBL_SZ) tbl)
726 {
727 	struct ip*      ip;
728 	int             pkttbl_idx = 0;
729 
730 	ip = mtod(packet, struct ip*);
731 
732 	/* reusing the hash function from inaddr_hashval */
733 	pkttbl_idx = inaddr_hashval(ntohl(ip->ip_src.s_addr)) % PKTTBL_SZ;
734 	if (tbl[pkttbl_idx].pkte_head == NULL) {
735 		tbl[pkttbl_idx].pkte_head = packet;
736 		tbl[pkttbl_idx].pkte_saddr.s_addr = ip->ip_src.s_addr;
737 		tbl[pkttbl_idx].pkte_daddr.s_addr = ip->ip_dst.s_addr;
738 		tbl[pkttbl_idx].pkte_proto = ip->ip_p;
739 	} else {
740 		if ((ip->ip_dst.s_addr == tbl[pkttbl_idx].pkte_daddr.s_addr) &&
741 		    (ip->ip_src.s_addr == tbl[pkttbl_idx].pkte_saddr.s_addr) &&
742 		    (ip->ip_p == tbl[pkttbl_idx].pkte_proto)) {
743 		} else {
744 			return packet;
745 		}
746 	}
747 	if (tbl[pkttbl_idx].pkte_tail != NULL) {
748 		mbuf_setnextpkt(tbl[pkttbl_idx].pkte_tail, packet);
749 	}
750 
751 	tbl[pkttbl_idx].pkte_tail = packet;
752 	tbl[pkttbl_idx].pkte_npkts += 1;
753 	tbl[pkttbl_idx].pkte_nbytes += packet->m_pkthdr.len;
754 	return NULL;
755 }
756 
757 /* args is a dummy variable here for backward compatibility */
758 static void
ip_input_second_pass_loop_tbl(pktchain_elm_t * __counted_by (PKTTBL_SZ)tbl,struct ip_fw_in_args * args)759 ip_input_second_pass_loop_tbl(pktchain_elm_t *__counted_by(PKTTBL_SZ) tbl, struct ip_fw_in_args *args)
760 {
761 	int i = 0;
762 
763 	for (i = 0; i < PKTTBL_SZ; i++) {
764 		if (tbl[i].pkte_head != NULL) {
765 			struct mbuf *m = tbl[i].pkte_head;
766 			ip_input_second_pass(m, m->m_pkthdr.rcvif,
767 			    tbl[i].pkte_npkts, tbl[i].pkte_nbytes, args);
768 
769 			if (tbl[i].pkte_npkts > 2) {
770 				ipstat.ips_rxc_chainsz_gt2++;
771 			}
772 			if (tbl[i].pkte_npkts > 4) {
773 				ipstat.ips_rxc_chainsz_gt4++;
774 			}
775 #if (DEBUG || DEVELOPMENT)
776 			if (ip_input_measure) {
777 				net_perf_histogram(&net_perf, tbl[i].pkte_npkts);
778 			}
779 #endif /* (DEBUG || DEVELOPMENT) */
780 			tbl[i].pkte_head = tbl[i].pkte_tail = NULL;
781 			tbl[i].pkte_npkts = 0;
782 			tbl[i].pkte_nbytes = 0;
783 			/* no need to initialize address and protocol in tbl */
784 		}
785 	}
786 }
787 
788 static void
ip_input_cpout_args(struct ip_fw_in_args * args,struct ip_fw_args * args1,boolean_t * done_init)789 ip_input_cpout_args(struct ip_fw_in_args *args, struct ip_fw_args *args1,
790     boolean_t *done_init)
791 {
792 	if (*done_init == FALSE) {
793 		bzero(args1, sizeof(struct ip_fw_args));
794 		*done_init = TRUE;
795 	}
796 	args1->fwa_pf_rule = args->fwai_pf_rule;
797 }
798 
799 static void
ip_input_cpin_args(struct ip_fw_args * args1,struct ip_fw_in_args * args)800 ip_input_cpin_args(struct ip_fw_args *args1, struct ip_fw_in_args *args)
801 {
802 	args->fwai_pf_rule = args1->fwa_pf_rule;
803 }
804 
805 typedef enum {
806 	IPINPUT_DOCHAIN = 0,
807 	IPINPUT_DONTCHAIN,
808 	IPINPUT_FREED,
809 	IPINPUT_DONE
810 } ipinput_chain_ret_t;
811 
812 static void
ip_input_update_nstat(struct ifnet * ifp,struct in_addr src_ip,u_int32_t packets,u_int32_t bytes)813 ip_input_update_nstat(struct ifnet *ifp, struct in_addr src_ip,
814     u_int32_t packets, u_int32_t bytes)
815 {
816 	if (nstat_collect) {
817 		struct rtentry *rt = ifnet_cached_rtlookup_inet(ifp,
818 		    src_ip);
819 		if (rt != NULL) {
820 			nstat_route_rx(rt, packets, bytes, 0);
821 			rtfree(rt);
822 		}
823 	}
824 }
825 
826 static void
ip_input_dispatch_chain(struct mbuf * m)827 ip_input_dispatch_chain(struct mbuf *m)
828 {
829 	mbuf_ref_t tmp_mbuf = m;
830 	mbuf_ref_t nxt_mbuf = NULL;
831 	struct ip *__single ip = NULL;
832 	unsigned int hlen;
833 
834 	ip = mtod(tmp_mbuf, struct ip *);
835 	hlen = IP_VHL_HL(ip->ip_vhl) << 2;
836 	while (tmp_mbuf != NULL) {
837 		nxt_mbuf = mbuf_nextpkt(tmp_mbuf);
838 		mbuf_setnextpkt(tmp_mbuf, NULL);
839 		ip_proto_dispatch_in(tmp_mbuf, hlen, ip->ip_p, 0);
840 		tmp_mbuf = nxt_mbuf;
841 		if (tmp_mbuf) {
842 			ip = mtod(tmp_mbuf, struct ip *);
843 			/* first mbuf of chain already has adjusted ip_len */
844 			hlen = IP_VHL_HL(ip->ip_vhl) << 2;
845 			ip->ip_len -= hlen;
846 		}
847 	}
848 }
849 
850 static void
ip_input_setdst_chain(struct mbuf * m,uint16_t ifindex,struct in_ifaddr * ia)851 ip_input_setdst_chain(struct mbuf *m, uint16_t ifindex, struct in_ifaddr *ia)
852 {
853 	mbuf_ref_t tmp_mbuf = m;
854 
855 	while (tmp_mbuf != NULL) {
856 		ip_setdstifaddr_info(tmp_mbuf, ifindex, ia);
857 		tmp_mbuf = mbuf_nextpkt(tmp_mbuf);
858 	}
859 }
860 
861 static void
ip_input_adjust(struct mbuf * m,struct ip * ip,struct ifnet * inifp)862 ip_input_adjust(struct mbuf *m, struct ip *ip, struct ifnet *inifp)
863 {
864 	boolean_t adjust = TRUE;
865 
866 	ASSERT(m_pktlen(m) > ip->ip_len);
867 
868 	/*
869 	 * Invalidate hardware checksum info if ip_adj_clear_hwcksum
870 	 * is set; useful to handle buggy drivers.  Note that this
871 	 * should not be enabled by default, as we may get here due
872 	 * to link-layer padding.
873 	 */
874 	if (ip_adj_clear_hwcksum &&
875 	    (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) &&
876 	    !(inifp->if_flags & IFF_LOOPBACK) &&
877 	    !(m->m_pkthdr.pkt_flags & PKTF_LOOP)) {
878 		m->m_pkthdr.csum_flags &= ~CSUM_DATA_VALID;
879 		m->m_pkthdr.csum_data = 0;
880 		ipstat.ips_adj_hwcsum_clr++;
881 	}
882 
883 	/*
884 	 * If partial checksum information is available, subtract
885 	 * out the partial sum of postpended extraneous bytes, and
886 	 * update the checksum metadata accordingly.  By doing it
887 	 * here, the upper layer transport only needs to adjust any
888 	 * prepended extraneous bytes (else it will do both.)
889 	 */
890 	if (ip_adj_partial_sum &&
891 	    (m->m_pkthdr.csum_flags & (CSUM_DATA_VALID | CSUM_PARTIAL)) ==
892 	    (CSUM_DATA_VALID | CSUM_PARTIAL)) {
893 		m->m_pkthdr.csum_rx_val = m_adj_sum16(m,
894 		    m->m_pkthdr.csum_rx_start, m->m_pkthdr.csum_rx_start,
895 		    (ip->ip_len - m->m_pkthdr.csum_rx_start),
896 		    m->m_pkthdr.csum_rx_val);
897 	} else if ((m->m_pkthdr.csum_flags &
898 	    (CSUM_DATA_VALID | CSUM_PARTIAL)) ==
899 	    (CSUM_DATA_VALID | CSUM_PARTIAL)) {
900 		/*
901 		 * If packet has partial checksum info and we decided not
902 		 * to subtract the partial sum of postpended extraneous
903 		 * bytes here (not the default case), leave that work to
904 		 * be handled by the other layers.  For now, only TCP, UDP
905 		 * layers are capable of dealing with this.  For all other
906 		 * protocols (including fragments), trim and ditch the
907 		 * partial sum as those layers might not implement partial
908 		 * checksumming (or adjustment) at all.
909 		 */
910 		if ((ip->ip_off & (IP_MF | IP_OFFMASK)) == 0 &&
911 		    (ip->ip_p == IPPROTO_TCP || ip->ip_p == IPPROTO_UDP)) {
912 			adjust = FALSE;
913 		} else {
914 			m->m_pkthdr.csum_flags &= ~CSUM_DATA_VALID;
915 			m->m_pkthdr.csum_data = 0;
916 			ipstat.ips_adj_hwcsum_clr++;
917 		}
918 	}
919 
920 	if (adjust) {
921 		ipstat.ips_adj++;
922 		if (m->m_len == m->m_pkthdr.len) {
923 			m->m_len = ip->ip_len;
924 			m->m_pkthdr.len = ip->ip_len;
925 		} else {
926 			m_adj(m, ip->ip_len - m->m_pkthdr.len);
927 		}
928 	}
929 }
930 
931 /*
932  * First pass does all essential packet validation and places on a per flow
933  * queue for doing operations that have same outcome for all packets of a flow.
934  */
935 static ipinput_chain_ret_t
ip_input_first_pass(struct mbuf * m,struct ip_fw_in_args * args,struct mbuf ** modm)936 ip_input_first_pass(struct mbuf *m, struct ip_fw_in_args *args, struct mbuf **modm)
937 {
938 	struct ip       *__single ip;
939 	ifnet_ref_t     inifp;
940 	unsigned int    hlen;
941 	int             retval = IPINPUT_DOCHAIN;
942 	int             len = 0;
943 	struct in_addr  src_ip;
944 #if DUMMYNET
945 	struct m_tag            *copy;
946 	struct m_tag            *p;
947 	boolean_t               delete = FALSE;
948 	struct ip_fw_args       args1;
949 	boolean_t               init = FALSE;
950 #endif /* DUMMYNET */
951 	ipfilter_t __single inject_filter_ref = NULL;
952 
953 	/* Check if the mbuf is still valid after interface filter processing */
954 	MBUF_INPUT_CHECK(m, m->m_pkthdr.rcvif);
955 	inifp = mbuf_pkthdr_rcvif(m);
956 	VERIFY(inifp != NULL);
957 
958 	/* Perform IP header alignment fixup, if needed */
959 	IP_HDR_ALIGNMENT_FIXUP(m, inifp, return );
960 
961 	m->m_pkthdr.pkt_flags &= ~PKTF_FORWARDED;
962 
963 #if DUMMYNET
964 	/*
965 	 * Don't bother searching for tag(s) if there's none.
966 	 */
967 	if (SLIST_EMPTY(&m->m_pkthdr.tags)) {
968 		goto ipfw_tags_done;
969 	}
970 
971 	/* Grab info from mtags prepended to the chain */
972 	p = m_tag_first(m);
973 	while (p) {
974 		if (p->m_tag_id == KERNEL_MODULE_TAG_ID) {
975 			if (p->m_tag_type == KERNEL_TAG_TYPE_DUMMYNET) {
976 				struct dn_pkt_tag *dn_tag;
977 
978 				dn_tag = (struct dn_pkt_tag *)(p->m_tag_data);
979 				args->fwai_pf_rule = dn_tag->dn_pf_rule;
980 				delete = TRUE;
981 			}
982 
983 			if (delete) {
984 				copy = p;
985 				p = m_tag_next(m, p);
986 				m_tag_delete(m, copy);
987 			} else {
988 				p = m_tag_next(m, p);
989 			}
990 		} else {
991 			p = m_tag_next(m, p);
992 		}
993 	}
994 
995 #if DIAGNOSTIC
996 	if (m == NULL || !(m->m_flags & M_PKTHDR)) {
997 		panic("ip_input no HDR");
998 	}
999 #endif
1000 
1001 	if (args->fwai_pf_rule) {
1002 		/* dummynet already filtered us */
1003 		ip = mtod(m, struct ip *);
1004 		hlen = IP_VHL_HL(ip->ip_vhl) << 2;
1005 		inject_filter_ref = ipf_get_inject_filter(m);
1006 		if (args->fwai_pf_rule) {
1007 			goto check_with_pf;
1008 		}
1009 	}
1010 ipfw_tags_done:
1011 #endif /* DUMMYNET */
1012 
1013 	/*
1014 	 * No need to process packet twice if we've already seen it.
1015 	 */
1016 	if (!SLIST_EMPTY(&m->m_pkthdr.tags)) {
1017 		inject_filter_ref = ipf_get_inject_filter(m);
1018 	}
1019 	if (inject_filter_ref != NULL) {
1020 		ip = mtod(m, struct ip *);
1021 		hlen = IP_VHL_HL(ip->ip_vhl) << 2;
1022 
1023 		DTRACE_IP6(receive, struct mbuf *, m, struct inpcb *, NULL,
1024 		    struct ip *, ip, struct ifnet *, inifp,
1025 		    struct ip *, ip, struct ip6_hdr *, NULL);
1026 
1027 		ip->ip_len = ntohs(ip->ip_len) - (u_short)hlen;
1028 		ip->ip_off = ntohs(ip->ip_off);
1029 		ip_proto_dispatch_in(m, hlen, ip->ip_p, inject_filter_ref);
1030 		return IPINPUT_DONE;
1031 	}
1032 
1033 	if (__improbable(m->m_pkthdr.pkt_flags & PKTF_WAKE_PKT)) {
1034 		if_ports_used_match_mbuf(inifp, PF_INET, m);
1035 	}
1036 
1037 	if (m->m_pkthdr.len < sizeof(struct ip)) {
1038 		OSAddAtomic(1, &ipstat.ips_total);
1039 		OSAddAtomic(1, &ipstat.ips_tooshort);
1040 		m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IP_TOO_SHORT,
1041 		    NULL, 0);
1042 		return IPINPUT_FREED;
1043 	}
1044 
1045 	if (m->m_len < sizeof(struct ip) &&
1046 	    (m = m_pullup(m, sizeof(struct ip))) == NULL) {
1047 		OSAddAtomic(1, &ipstat.ips_total);
1048 		OSAddAtomic(1, &ipstat.ips_toosmall);
1049 		return IPINPUT_FREED;
1050 	}
1051 
1052 	ip = mtod(m, struct ip *);
1053 	*modm = m;
1054 
1055 	KERNEL_DEBUG(DBG_LAYER_BEG, ip->ip_dst.s_addr, ip->ip_src.s_addr,
1056 	    ip->ip_p, ip->ip_off, ip->ip_len);
1057 
1058 	if (IP_VHL_V(ip->ip_vhl) != IPVERSION) {
1059 		OSAddAtomic(1, &ipstat.ips_total);
1060 		OSAddAtomic(1, &ipstat.ips_badvers);
1061 		KERNEL_DEBUG(DBG_LAYER_END, 0, 0, 0, 0, 0);
1062 		m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IP_BAD_VERSION,
1063 		    NULL, 0);
1064 		return IPINPUT_FREED;
1065 	}
1066 
1067 	hlen = IP_VHL_HL(ip->ip_vhl) << 2;
1068 	if (hlen < sizeof(struct ip)) {
1069 		OSAddAtomic(1, &ipstat.ips_total);
1070 		OSAddAtomic(1, &ipstat.ips_badhlen);
1071 		KERNEL_DEBUG(DBG_LAYER_END, 0, 0, 0, 0, 0);
1072 		m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IP_BAD_HDR_LENGTH,
1073 		    NULL, 0);
1074 		return IPINPUT_FREED;
1075 	}
1076 
1077 	if (hlen > m->m_len) {
1078 		if ((m = m_pullup(m, hlen)) == NULL) {
1079 			OSAddAtomic(1, &ipstat.ips_total);
1080 			OSAddAtomic(1, &ipstat.ips_badhlen);
1081 			KERNEL_DEBUG(DBG_LAYER_END, 0, 0, 0, 0, 0);
1082 			return IPINPUT_FREED;
1083 		}
1084 		ip = mtod(m, struct ip *);
1085 		*modm = m;
1086 	}
1087 
1088 	if ((ip->ip_tos & IPTOS_ECN_MASK) == IPTOS_ECN_ECT1) {
1089 		m->m_pkthdr.pkt_ext_flags |= PKTF_EXT_L4S;
1090 	}
1091 
1092 	/* 127/8 must not appear on wire - RFC1122 */
1093 	if ((ntohl(ip->ip_dst.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET ||
1094 	    (ntohl(ip->ip_src.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET) {
1095 		/*
1096 		 * Allow for the following exceptions:
1097 		 *
1098 		 *   1. If the packet was sent to loopback (i.e. rcvif
1099 		 *      would have been set earlier at output time.)
1100 		 *
1101 		 *   2. If the packet was sent out on loopback from a local
1102 		 *      source address which belongs to a non-loopback
1103 		 *      interface (i.e. rcvif may not necessarily be a
1104 		 *      loopback interface, hence the test for PKTF_LOOP.)
1105 		 *      Unlike IPv6, there is no interface scope ID, and
1106 		 *      therefore we don't care so much about PKTF_IFINFO.
1107 		 */
1108 		if (!(inifp->if_flags & IFF_LOOPBACK) &&
1109 		    !(m->m_pkthdr.pkt_flags & PKTF_LOOP)) {
1110 			OSAddAtomic(1, &ipstat.ips_total);
1111 			OSAddAtomic(1, &ipstat.ips_badaddr);
1112 			KERNEL_DEBUG(DBG_LAYER_END, 0, 0, 0, 0, 0);
1113 			m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IP_INVALID_ADDR,
1114 			    NULL, 0);
1115 			return IPINPUT_FREED;
1116 		}
1117 	}
1118 
1119 	/* IPv4 Link-Local Addresses as defined in RFC3927 */
1120 	if ((IN_LINKLOCAL(ntohl(ip->ip_dst.s_addr)) ||
1121 	    IN_LINKLOCAL(ntohl(ip->ip_src.s_addr)))) {
1122 		ip_linklocal_stat.iplls_in_total++;
1123 		if (ip->ip_ttl != MAXTTL) {
1124 			OSAddAtomic(1, &ip_linklocal_stat.iplls_in_badttl);
1125 			/* Silently drop link local traffic with bad TTL */
1126 			if (!ip_linklocal_in_allowbadttl) {
1127 				OSAddAtomic(1, &ipstat.ips_total);
1128 				KERNEL_DEBUG(DBG_LAYER_END, 0, 0, 0, 0, 0);
1129 				m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IP_BAD_TTL,
1130 				    NULL, 0);
1131 				return IPINPUT_FREED;
1132 			}
1133 		}
1134 	}
1135 
1136 	if (ip_cksum(m, hlen)) {
1137 		OSAddAtomic(1, &ipstat.ips_total);
1138 		KERNEL_DEBUG(DBG_LAYER_END, 0, 0, 0, 0, 0);
1139 		m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IP_BAD_CHECKSUM,
1140 		    NULL, 0);
1141 		return IPINPUT_FREED;
1142 	}
1143 
1144 	DTRACE_IP6(receive, struct mbuf *, m, struct inpcb *, NULL,
1145 	    struct ip *, ip, struct ifnet *, inifp,
1146 	    struct ip *, ip, struct ip6_hdr *, NULL);
1147 
1148 	/*
1149 	 * Convert fields to host representation.
1150 	 */
1151 #if BYTE_ORDER != BIG_ENDIAN
1152 	NTOHS(ip->ip_len);
1153 #endif
1154 
1155 	if (ip->ip_len < hlen) {
1156 		OSAddAtomic(1, &ipstat.ips_total);
1157 		OSAddAtomic(1, &ipstat.ips_badlen);
1158 		KERNEL_DEBUG(DBG_LAYER_END, 0, 0, 0, 0, 0);
1159 		m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IP_BAD_LENGTH,
1160 		    NULL, 0);
1161 		return IPINPUT_FREED;
1162 	}
1163 
1164 #if BYTE_ORDER != BIG_ENDIAN
1165 	NTOHS(ip->ip_off);
1166 #endif
1167 
1168 	/*
1169 	 * Check that the amount of data in the buffers
1170 	 * is as at least much as the IP header would have us expect.
1171 	 * Trim mbufs if longer than we expect.
1172 	 * Drop packet if shorter than we expect.
1173 	 */
1174 	if (m->m_pkthdr.len < ip->ip_len) {
1175 		OSAddAtomic(1, &ipstat.ips_total);
1176 		OSAddAtomic(1, &ipstat.ips_tooshort);
1177 		KERNEL_DEBUG(DBG_LAYER_END, 0, 0, 0, 0, 0);
1178 		m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IP_TOO_SHORT,
1179 		    NULL, 0);
1180 		return IPINPUT_FREED;
1181 	}
1182 
1183 	if (m->m_pkthdr.len > ip->ip_len) {
1184 		ip_input_adjust(m, ip, inifp);
1185 	}
1186 
1187 	/* for netstat route statistics */
1188 	src_ip = ip->ip_src;
1189 	len = m->m_pkthdr.len;
1190 
1191 #if DUMMYNET
1192 check_with_pf:
1193 #endif /* DUMMYNET */
1194 #if PF
1195 	/* Invoke inbound packet filter */
1196 	if (PF_IS_ENABLED) {
1197 		int error;
1198 		ip_input_cpout_args(args, &args1, &init);
1199 		ip = mtod(m, struct ip *);
1200 		src_ip = ip->ip_src;
1201 
1202 #if DUMMYNET
1203 		error = pf_af_hook(inifp, NULL, &m, AF_INET, TRUE, &args1);
1204 #else
1205 		error = pf_af_hook(inifp, NULL, &m, AF_INET, TRUE, NULL);
1206 #endif /* DUMMYNET */
1207 		if (error != 0 || m == NULL) {
1208 			if (m != NULL) {
1209 				panic("%s: unexpected packet %p",
1210 				    __func__, m);
1211 				/* NOTREACHED */
1212 			}
1213 			/* Already freed by callee */
1214 			ip_input_update_nstat(inifp, src_ip, 1, len);
1215 			KERNEL_DEBUG(DBG_LAYER_END, 0, 0, 0, 0, 0);
1216 			OSAddAtomic(1, &ipstat.ips_total);
1217 			return IPINPUT_FREED;
1218 		}
1219 		ip = mtod(m, struct ip *);
1220 		hlen = IP_VHL_HL(ip->ip_vhl) << 2;
1221 		*modm = m;
1222 		ip_input_cpin_args(&args1, args);
1223 	}
1224 #endif /* PF */
1225 
1226 #if IPSEC
1227 	if (ipsec_bypass == 0 && ipsec_get_history_count(m)) {
1228 		retval = IPINPUT_DONTCHAIN; /* XXX scope for chaining here? */
1229 		goto pass;
1230 	}
1231 #endif
1232 
1233 #if IPSEC
1234 pass:
1235 #endif
1236 	/*
1237 	 * Process options and, if not destined for us,
1238 	 * ship it on.  ip_dooptions returns 1 when an
1239 	 * error was detected (causing an icmp message
1240 	 * to be sent and the original packet to be freed).
1241 	 */
1242 	ip_nhops = 0;           /* for source routed packets */
1243 	if (hlen > sizeof(struct ip) && ip_dooptions(m, 0, NULL)) {
1244 		src_ip = ip->ip_src;
1245 		ip_input_update_nstat(inifp, src_ip, 1, len);
1246 		KERNEL_DEBUG(DBG_LAYER_END, 0, 0, 0, 0, 0);
1247 		OSAddAtomic(1, &ipstat.ips_total);
1248 		return IPINPUT_FREED;
1249 	}
1250 
1251 	/*
1252 	 * Don't chain fragmented packets
1253 	 */
1254 	if (ip->ip_off & ~(IP_DF | IP_RF)) {
1255 		return IPINPUT_DONTCHAIN;
1256 	}
1257 
1258 	/* Allow DHCP/BootP responses through */
1259 	if ((inifp->if_eflags & IFEF_AUTOCONFIGURING) &&
1260 	    hlen == sizeof(struct ip) && ip->ip_p == IPPROTO_UDP) {
1261 		struct udpiphdr *__single ui;
1262 
1263 		if (m->m_len < sizeof(struct udpiphdr) &&
1264 		    (m = m_pullup(m, sizeof(struct udpiphdr))) == NULL) {
1265 			OSAddAtomic(1, &udpstat.udps_hdrops);
1266 			KERNEL_DEBUG(DBG_LAYER_END, 0, 0, 0, 0, 0);
1267 			OSAddAtomic(1, &ipstat.ips_total);
1268 			return IPINPUT_FREED;
1269 		}
1270 		*modm = m;
1271 		ui = mtod(m, struct udpiphdr *);
1272 		if (ntohs(ui->ui_dport) == IPPORT_BOOTPC) {
1273 			ip_setdstifaddr_info(m, inifp->if_index, NULL);
1274 			return IPINPUT_DONTCHAIN;
1275 		}
1276 	}
1277 
1278 	/* Avoid chaining raw sockets as ipsec checks occur later for them */
1279 	if (ip_protox[ip->ip_p]->pr_flags & PR_LASTHDR) {
1280 		return IPINPUT_DONTCHAIN;
1281 	}
1282 
1283 	return retval;
1284 }
1285 
1286 /*
1287  * Because the call to m_pullup() may freem the mbuf, the function frees the mbuf packet
1288  * chain before it return IP_CHECK_IF_DROP
1289  */
1290 static ip_check_if_result_t
ip_input_check_interface(struct mbuf ** mp,struct ip * ip,struct ifnet * inifp)1291 ip_input_check_interface(struct mbuf **mp, struct ip *ip, struct ifnet *inifp)
1292 {
1293 	mbuf_ref_t m = *mp;
1294 	struct in_ifaddr *__single ia = NULL;
1295 	struct in_ifaddr *__single best_ia = NULL;
1296 	ifnet_ref_t match_ifp = NULL;
1297 	ip_check_if_result_t result = IP_CHECK_IF_NONE;
1298 
1299 	/*
1300 	 * Host broadcast and all network broadcast addresses are always a match
1301 	 */
1302 	if (ip->ip_dst.s_addr == (u_int32_t)INADDR_BROADCAST ||
1303 	    ip->ip_dst.s_addr == INADDR_ANY) {
1304 		ip_input_setdst_chain(m, inifp->if_index, NULL);
1305 		return IP_CHECK_IF_OURS;
1306 	}
1307 
1308 	/*
1309 	 * Check for a match in the hash bucket.
1310 	 */
1311 	lck_rw_lock_shared(&in_ifaddr_rwlock);
1312 	TAILQ_FOREACH(ia, INADDR_HASH(ip->ip_dst.s_addr), ia_hash) {
1313 		if (IA_SIN(ia)->sin_addr.s_addr == ip->ip_dst.s_addr) {
1314 			best_ia = ia;
1315 			match_ifp = best_ia->ia_ifp;
1316 
1317 			if (ia->ia_ifp == inifp || (inifp->if_flags & IFF_LOOPBACK) ||
1318 			    (m->m_pkthdr.pkt_flags & PKTF_LOOP)) {
1319 				/*
1320 				 * A locally originated packet or packet from the loopback
1321 				 * interface is always an exact interface address match
1322 				 */
1323 				match_ifp = inifp;
1324 				break;
1325 			}
1326 			/*
1327 			 * Continue the loop in case there's a exact match with another
1328 			 * interface
1329 			 */
1330 		}
1331 	}
1332 	if (best_ia != NULL) {
1333 		if (match_ifp != inifp && ipforwarding == 0 &&
1334 		    ((ip_checkinterface == IP_CHECKINTERFACE_HYBRID_ES &&
1335 		    (match_ifp->if_family == IFNET_FAMILY_IPSEC ||
1336 		    match_ifp->if_family == IFNET_FAMILY_UTUN)) ||
1337 		    ip_checkinterface == IP_CHECKINTERFACE_STRONG_ES)) {
1338 			/*
1339 			 * Drop when interface address check is strict and forwarding
1340 			 * is disabled
1341 			 */
1342 			result = IP_CHECK_IF_DROP;
1343 		} else {
1344 			result = IP_CHECK_IF_OURS;
1345 			ip_input_setdst_chain(m, 0, best_ia);
1346 		}
1347 	}
1348 	lck_rw_done(&in_ifaddr_rwlock);
1349 
1350 	if (result == IP_CHECK_IF_NONE && (inifp->if_flags & IFF_BROADCAST)) {
1351 		/*
1352 		 * Check for broadcast addresses.
1353 		 *
1354 		 * Only accept broadcast packets that arrive via the matching
1355 		 * interface.  Reception of forwarded directed broadcasts would be
1356 		 * handled via ip_forward() and ether_frameout() with the loopback
1357 		 * into the stack for SIMPLEX interfaces handled by ether_frameout().
1358 		 */
1359 		struct ifaddr *__single ifa;
1360 
1361 		ifnet_lock_shared(inifp);
1362 		TAILQ_FOREACH(ifa, &inifp->if_addrhead, ifa_link) {
1363 			if (ifa->ifa_addr->sa_family != AF_INET) {
1364 				continue;
1365 			}
1366 			ia = ifatoia(ifa);
1367 			if (satosin(&ia->ia_broadaddr)->sin_addr.s_addr == ip->ip_dst.s_addr ||
1368 			    ia->ia_netbroadcast.s_addr == ip->ip_dst.s_addr) {
1369 				ip_input_setdst_chain(m, 0, ia);
1370 				result = IP_CHECK_IF_OURS;
1371 				match_ifp = inifp;
1372 				break;
1373 			}
1374 		}
1375 		ifnet_lock_done(inifp);
1376 	}
1377 
1378 	/* Allow DHCP/BootP responses through */
1379 	if (result == IP_CHECK_IF_NONE && (inifp->if_eflags & IFEF_AUTOCONFIGURING) &&
1380 	    ip->ip_p == IPPROTO_UDP && (IP_VHL_HL(ip->ip_vhl) << 2) == sizeof(struct ip)) {
1381 		struct udpiphdr *__single ui;
1382 
1383 		if (m->m_len < sizeof(struct udpiphdr)) {
1384 			if ((m = m_pullup(m, sizeof(struct udpiphdr))) == NULL) {
1385 				OSAddAtomic(1, &udpstat.udps_hdrops);
1386 				*mp = NULL;
1387 				return IP_CHECK_IF_DROP;
1388 			}
1389 			/*
1390 			 * m_pullup can return a different mbuf
1391 			 */
1392 			*mp = m;
1393 			ip = mtod(m, struct ip *);
1394 		}
1395 		ui = mtod(m, struct udpiphdr *);
1396 		if (ntohs(ui->ui_dport) == IPPORT_BOOTPC) {
1397 			ip_input_setdst_chain(m, inifp->if_index, NULL);
1398 			result = IP_CHECK_IF_OURS;
1399 			match_ifp = inifp;
1400 		}
1401 	}
1402 
1403 	if (result == IP_CHECK_IF_NONE) {
1404 		if (ipforwarding == 0) {
1405 			result = IP_CHECK_IF_DROP;
1406 		} else {
1407 			result = IP_CHECK_IF_FORWARD;
1408 			ip_input_setdst_chain(m, inifp->if_index, NULL);
1409 		}
1410 	}
1411 
1412 	if (result == IP_CHECK_IF_OURS && match_ifp != inifp) {
1413 		ipstat.ips_rcv_if_weak_match++;
1414 
1415 		/*  Logging is too noisy when forwarding is enabled */
1416 		if (ip_checkinterface_debug != 0 && ipforwarding == 0) {
1417 			char src_str[MAX_IPv4_STR_LEN];
1418 			char dst_str[MAX_IPv4_STR_LEN];
1419 
1420 			inet_ntop(AF_INET, &ip->ip_src, src_str, sizeof(src_str));
1421 			inet_ntop(AF_INET, &ip->ip_dst, dst_str, sizeof(dst_str));
1422 			os_log_info(OS_LOG_DEFAULT,
1423 			    "%s: weak ES interface match to %s for packet from %s to %s proto %u received via %s",
1424 			    __func__, best_ia->ia_ifp->if_xname, src_str, dst_str, ip->ip_p, inifp->if_xname);
1425 		}
1426 	} else if (result == IP_CHECK_IF_DROP) {
1427 		if (ip_checkinterface_debug > 0) {
1428 			char src_str[MAX_IPv4_STR_LEN];
1429 			char dst_str[MAX_IPv4_STR_LEN];
1430 
1431 			inet_ntop(AF_INET, &ip->ip_src, src_str, sizeof(src_str));
1432 			inet_ntop(AF_INET, &ip->ip_dst, dst_str, sizeof(dst_str));
1433 			os_log(OS_LOG_DEFAULT,
1434 			    "%s: no interface match for packet from %s to %s proto %u received via %s",
1435 			    __func__, src_str, dst_str, ip->ip_p, inifp->if_xname);
1436 		}
1437 		mbuf_ref_t tmp_mbuf = m;
1438 		while (tmp_mbuf != NULL) {
1439 			ipstat.ips_rcv_if_no_match++;
1440 			tmp_mbuf = tmp_mbuf->m_nextpkt;
1441 		}
1442 		m_drop_list(m, NULL, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IP_RCV_IF_NO_MATCH, NULL, 0);
1443 		*mp = NULL;
1444 	}
1445 
1446 	return result;
1447 }
1448 
1449 static void
ip_input_second_pass(struct mbuf * m,struct ifnet * inifp,int npkts_in_chain,int bytes_in_chain,struct ip_fw_in_args * args)1450 ip_input_second_pass(struct mbuf *m, struct ifnet *inifp,
1451     int npkts_in_chain, int bytes_in_chain, struct ip_fw_in_args *args)
1452 {
1453 	struct mbuf             *tmp_mbuf = NULL;
1454 	unsigned int            hlen;
1455 
1456 #pragma unused (args)
1457 
1458 	struct ip *__single ip = mtod(m, struct ip *);
1459 	hlen = IP_VHL_HL(ip->ip_vhl) << 2;
1460 
1461 	OSAddAtomic(npkts_in_chain, &ipstat.ips_total);
1462 
1463 	/*
1464 	 * Naively assume we can attribute inbound data to the route we would
1465 	 * use to send to this destination. Asymmetric routing breaks this
1466 	 * assumption, but it still allows us to account for traffic from
1467 	 * a remote node in the routing table.
1468 	 * this has a very significant performance impact so we bypass
1469 	 * if nstat_collect is disabled. We may also bypass if the
1470 	 * protocol is tcp in the future because tcp will have a route that
1471 	 * we can use to attribute the data to. That does mean we would not
1472 	 * account for forwarded tcp traffic.
1473 	 */
1474 	ip_input_update_nstat(inifp, ip->ip_src, npkts_in_chain,
1475 	    bytes_in_chain);
1476 
1477 	/*
1478 	 * Check our list of addresses, to see if the packet is for us.
1479 	 * If we don't have any addresses, assume any unicast packet
1480 	 * we receive might be for us (and let the upper layers deal
1481 	 * with it).
1482 	 */
1483 	tmp_mbuf = m;
1484 	if (TAILQ_EMPTY(&in_ifaddrhead)) {
1485 		while (tmp_mbuf != NULL) {
1486 			if (!(tmp_mbuf->m_flags & (M_MCAST | M_BCAST))) {
1487 				ip_setdstifaddr_info(tmp_mbuf, inifp->if_index,
1488 				    NULL);
1489 			}
1490 			tmp_mbuf = mbuf_nextpkt(tmp_mbuf);
1491 		}
1492 		goto ours;
1493 	}
1494 
1495 	/*
1496 	 * Enable a consistency check between the destination address
1497 	 * and the arrival interface for a unicast packet (the RFC 1122
1498 	 * strong ES model) if IP forwarding is disabled and the packet
1499 	 * is not locally generated
1500 	 *
1501 	 * XXX - Checking also should be disabled if the destination
1502 	 * address is ipnat'ed to a different interface.
1503 	 *
1504 	 * XXX - Checking is incompatible with IP aliases added
1505 	 * to the loopback interface instead of the interface where
1506 	 * the packets are received.
1507 	 */
1508 	if (!IN_MULTICAST(ntohl(ip->ip_dst.s_addr))) {
1509 		ip_check_if_result_t ip_check_if_result = IP_CHECK_IF_NONE;
1510 
1511 		ip_check_if_result = ip_input_check_interface(&m, ip, inifp);
1512 		ASSERT(ip_check_if_result != IP_CHECK_IF_NONE);
1513 		if (ip_check_if_result == IP_CHECK_IF_OURS) {
1514 			goto ours;
1515 		} else if (ip_check_if_result == IP_CHECK_IF_DROP) {
1516 			KERNEL_DEBUG(DBG_LAYER_END, 0, 0, 0, 0, 0);
1517 			return;
1518 		}
1519 	} else {
1520 		struct in_multi *__single inm;
1521 		/*
1522 		 * See if we belong to the destination multicast group on the
1523 		 * arrival interface.
1524 		 */
1525 		in_multihead_lock_shared();
1526 		IN_LOOKUP_MULTI(&ip->ip_dst, inifp, inm);
1527 		in_multihead_lock_done();
1528 		if (inm == NULL) {
1529 			OSAddAtomic(npkts_in_chain, &ipstat.ips_notmember);
1530 			m_drop_list(m, NULL, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IP_UNKNOWN_MULTICAST_GROUP,
1531 			    NULL, 0);
1532 			KERNEL_DEBUG(DBG_LAYER_END, 0, 0, 0, 0, 0);
1533 			return;
1534 		}
1535 		ip_input_setdst_chain(m, inifp->if_index, NULL);
1536 		INM_REMREF(inm);
1537 		goto ours;
1538 	}
1539 
1540 	tmp_mbuf = m;
1541 	struct mbuf *__single nxt_mbuf = NULL;
1542 	while (tmp_mbuf != NULL) {
1543 		nxt_mbuf = mbuf_nextpkt(tmp_mbuf);
1544 		/*
1545 		 * Not for us; forward if possible and desirable.
1546 		 */
1547 		mbuf_setnextpkt(tmp_mbuf, NULL);
1548 		if (ipforwarding == 0) {
1549 			OSAddAtomic(1, &ipstat.ips_cantforward);
1550 			m_drop(tmp_mbuf, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IP_CANNOT_FORWARD,
1551 			    NULL, 0);
1552 		} else {
1553 			ip_forward(tmp_mbuf, 0, NULL);
1554 		}
1555 		tmp_mbuf = nxt_mbuf;
1556 	}
1557 	KERNEL_DEBUG(DBG_LAYER_END, 0, 0, 0, 0, 0);
1558 	return;
1559 ours:
1560 	ip = mtod(m, struct ip *); /* in case it changed */
1561 	/*
1562 	 * If offset is set, must reassemble.
1563 	 */
1564 	if (ip->ip_off & ~(IP_DF | IP_RF)) {
1565 		VERIFY(npkts_in_chain == 1);
1566 		m = ip_reass(m);
1567 		if (m == NULL) {
1568 			KERNEL_DEBUG(DBG_LAYER_END, 0, 0, 0, 0, 0);
1569 			return;
1570 		}
1571 		ip = mtod(m, struct ip *);
1572 		/* Get the header length of the reassembled packet */
1573 		hlen = IP_VHL_HL(ip->ip_vhl) << 2;
1574 	}
1575 
1576 	/*
1577 	 * Further protocols expect the packet length to be w/o the
1578 	 * IP header.
1579 	 */
1580 	ip->ip_len -= hlen;
1581 
1582 #if IPSEC
1583 	/*
1584 	 * enforce IPsec policy checking if we are seeing last header.
1585 	 * note that we do not visit this with protocols with pcb layer
1586 	 * code - like udp/tcp/raw ip.
1587 	 */
1588 	if (ipsec_bypass == 0 && (ip_protox[ip->ip_p]->pr_flags & PR_LASTHDR)) {
1589 		VERIFY(npkts_in_chain == 1);
1590 		if (ipsec4_in_reject(m, NULL)) {
1591 			IPSEC_STAT_INCREMENT(ipsecstat.in_polvio);
1592 			m_drop(tmp_mbuf, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IPSEC_REJECT,
1593 			    NULL, 0);
1594 			KERNEL_DEBUG(DBG_LAYER_END, 0, 0, 0, 0, 0);
1595 			return;
1596 		}
1597 	}
1598 #endif /* IPSEC */
1599 
1600 	/*
1601 	 * Switch out to protocol's input routine.
1602 	 */
1603 	OSAddAtomic(npkts_in_chain, &ipstat.ips_delivered);
1604 
1605 	ip_input_dispatch_chain(m);
1606 
1607 	KERNEL_DEBUG(DBG_LAYER_END, 0, 0, 0, 0, 0);
1608 	return;
1609 }
1610 
1611 void
ip_input_process_list(struct mbuf * packet_list)1612 ip_input_process_list(struct mbuf *packet_list)
1613 {
1614 	pktchain_elm_t  pktchain_tbl[PKTTBL_SZ];
1615 
1616 	mbuf_ref_t packet = NULL;
1617 	mbuf_ref_t modm = NULL; /* modified mbuf */
1618 	int             retval = 0;
1619 #if (DEBUG || DEVELOPMENT)
1620 	struct timeval start_tv;
1621 #endif /* (DEBUG || DEVELOPMENT) */
1622 	int     num_pkts = 0;
1623 	int chain = 0;
1624 	struct ip_fw_in_args       args;
1625 
1626 	if (ip_chaining == 0) {
1627 		mbuf_ref_t m = packet_list;
1628 #if (DEBUG || DEVELOPMENT)
1629 		if (ip_input_measure) {
1630 			net_perf_start_time(&net_perf, &start_tv);
1631 		}
1632 #endif /* (DEBUG || DEVELOPMENT) */
1633 
1634 		while (m) {
1635 			packet_list = mbuf_nextpkt(m);
1636 			mbuf_setnextpkt(m, NULL);
1637 			ip_input(m);
1638 			m = packet_list;
1639 			num_pkts++;
1640 		}
1641 #if (DEBUG || DEVELOPMENT)
1642 		if (ip_input_measure) {
1643 			net_perf_measure_time(&net_perf, &start_tv, num_pkts);
1644 		}
1645 #endif /* (DEBUG || DEVELOPMENT) */
1646 		return;
1647 	}
1648 #if (DEBUG || DEVELOPMENT)
1649 	if (ip_input_measure) {
1650 		net_perf_start_time(&net_perf, &start_tv);
1651 	}
1652 #endif /* (DEBUG || DEVELOPMENT) */
1653 
1654 	bzero(&pktchain_tbl, sizeof(pktchain_tbl));
1655 restart_list_process:
1656 	chain = 0;
1657 	for (packet = packet_list; packet; packet = packet_list) {
1658 		m_add_crumb(packet, PKT_CRUMB_IP_INPUT);
1659 
1660 		packet_list = mbuf_nextpkt(packet);
1661 		mbuf_setnextpkt(packet, NULL);
1662 
1663 		num_pkts++;
1664 		modm = NULL;
1665 		bzero(&args, sizeof(args));
1666 
1667 		retval = ip_input_first_pass(packet, &args, &modm);
1668 
1669 		if (retval == IPINPUT_DOCHAIN) {
1670 			if (modm) {
1671 				packet = modm;
1672 			}
1673 			packet = ip_chain_insert(packet, &pktchain_tbl[0]);
1674 			if (packet == NULL) {
1675 				ipstat.ips_rxc_chained++;
1676 				chain++;
1677 				if (chain > ip_chainsz) {
1678 					break;
1679 				}
1680 			} else {
1681 				ipstat.ips_rxc_collisions++;
1682 				break;
1683 			}
1684 		} else if (retval == IPINPUT_DONTCHAIN) {
1685 			/* in order to preserve order, exit from chaining */
1686 			if (modm) {
1687 				packet = modm;
1688 			}
1689 			ipstat.ips_rxc_notchain++;
1690 			break;
1691 		} else {
1692 			/* packet was freed or delivered, do nothing. */
1693 		}
1694 	}
1695 
1696 	/* do second pass here for pktchain_tbl */
1697 	if (chain) {
1698 		ip_input_second_pass_loop_tbl(&pktchain_tbl[0], &args);
1699 	}
1700 
1701 	if (packet) {
1702 		/*
1703 		 * equivalent update in chaining case if performed in
1704 		 * ip_input_second_pass_loop_tbl().
1705 		 */
1706 #if (DEBUG || DEVELOPMENT)
1707 		if (ip_input_measure) {
1708 			net_perf_histogram(&net_perf, 1);
1709 		}
1710 #endif /* (DEBUG || DEVELOPMENT) */
1711 		ip_input_second_pass(packet, packet->m_pkthdr.rcvif,
1712 		    1, packet->m_pkthdr.len, &args);
1713 	}
1714 
1715 	if (packet_list) {
1716 		goto restart_list_process;
1717 	}
1718 
1719 #if (DEBUG || DEVELOPMENT)
1720 	if (ip_input_measure) {
1721 		net_perf_measure_time(&net_perf, &start_tv, num_pkts);
1722 	}
1723 #endif /* (DEBUG || DEVELOPMENT) */
1724 }
1725 /*
1726  * Ip input routine.  Checksum and byte swap header.  If fragmented
1727  * try to reassemble.  Process options.  Pass to next level.
1728  */
1729 void
ip_input(struct mbuf * m)1730 ip_input(struct mbuf *m)
1731 {
1732 	struct ip *__single ip;
1733 	unsigned int hlen;
1734 	u_short sum = 0;
1735 #if DUMMYNET
1736 	struct ip_fw_args args;
1737 	struct m_tag    *__single tag;
1738 #endif
1739 	ipfilter_t __single inject_filter_ref = NULL;
1740 	ifnet_ref_t inifp;
1741 
1742 	/* Check if the mbuf is still valid after interface filter processing */
1743 	MBUF_INPUT_CHECK(m, m->m_pkthdr.rcvif);
1744 	inifp = m->m_pkthdr.rcvif;
1745 	VERIFY(inifp != NULL);
1746 
1747 	m_add_crumb(m, PKT_CRUMB_IP_INPUT);
1748 
1749 	ipstat.ips_rxc_notlist++;
1750 
1751 	/* Perform IP header alignment fixup, if needed */
1752 	IP_HDR_ALIGNMENT_FIXUP(m, inifp, return );
1753 
1754 	m->m_pkthdr.pkt_flags &= ~PKTF_FORWARDED;
1755 
1756 #if DUMMYNET
1757 	bzero(&args, sizeof(struct ip_fw_args));
1758 
1759 	/*
1760 	 * Don't bother searching for tag(s) if there's none.
1761 	 */
1762 	if (SLIST_EMPTY(&m->m_pkthdr.tags)) {
1763 		goto ipfw_tags_done;
1764 	}
1765 
1766 	/* Grab info from mtags prepended to the chain */
1767 	if ((tag = m_tag_locate(m, KERNEL_MODULE_TAG_ID,
1768 	    KERNEL_TAG_TYPE_DUMMYNET)) != NULL) {
1769 		struct dn_pkt_tag *__single dn_tag;
1770 
1771 		dn_tag = (struct dn_pkt_tag *)(tag->m_tag_data);
1772 		args.fwa_pf_rule = dn_tag->dn_pf_rule;
1773 
1774 		m_tag_delete(m, tag);
1775 	}
1776 
1777 #if DIAGNOSTIC
1778 	if (m == NULL || !(m->m_flags & M_PKTHDR)) {
1779 		panic("ip_input no HDR");
1780 	}
1781 #endif
1782 
1783 	if (args.fwa_pf_rule) {
1784 		/* dummynet already filtered us */
1785 		ip = mtod(m, struct ip *);
1786 		hlen = IP_VHL_HL(ip->ip_vhl) << 2;
1787 		inject_filter_ref = ipf_get_inject_filter(m);
1788 		if (args.fwa_pf_rule) {
1789 			goto check_with_pf;
1790 		}
1791 	}
1792 ipfw_tags_done:
1793 #endif /* DUMMYNET */
1794 
1795 	/*
1796 	 * No need to process packet twice if we've already seen it.
1797 	 */
1798 	if (!SLIST_EMPTY(&m->m_pkthdr.tags)) {
1799 		inject_filter_ref = ipf_get_inject_filter(m);
1800 	}
1801 	if (inject_filter_ref != NULL) {
1802 		ip = mtod(m, struct ip *);
1803 		hlen = IP_VHL_HL(ip->ip_vhl) << 2;
1804 
1805 		DTRACE_IP6(receive, struct mbuf *, m, struct inpcb *, NULL,
1806 		    struct ip *, ip, struct ifnet *, inifp,
1807 		    struct ip *, ip, struct ip6_hdr *, NULL);
1808 
1809 		ip->ip_len = ntohs(ip->ip_len) - (u_short)hlen;
1810 		ip->ip_off = ntohs(ip->ip_off);
1811 		ip_proto_dispatch_in(m, hlen, ip->ip_p, inject_filter_ref);
1812 		return;
1813 	}
1814 
1815 	if (__improbable(m->m_pkthdr.pkt_flags & PKTF_WAKE_PKT)) {
1816 		if_ports_used_match_mbuf(inifp, PF_INET, m);
1817 	}
1818 
1819 	OSAddAtomic(1, &ipstat.ips_total);
1820 	if (m->m_pkthdr.len < sizeof(struct ip)) {
1821 		goto tooshort;
1822 	}
1823 
1824 	if (m->m_len < sizeof(struct ip) &&
1825 	    (m = m_pullup(m, sizeof(struct ip))) == NULL) {
1826 		OSAddAtomic(1, &ipstat.ips_toosmall);
1827 		return;
1828 	}
1829 	ip = mtod(m, struct ip *);
1830 
1831 	KERNEL_DEBUG(DBG_LAYER_BEG, ip->ip_dst.s_addr, ip->ip_src.s_addr,
1832 	    ip->ip_p, ip->ip_off, ip->ip_len);
1833 
1834 	if (IP_VHL_V(ip->ip_vhl) != IPVERSION) {
1835 		OSAddAtomic(1, &ipstat.ips_badvers);
1836 		m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IP_BAD_VERSION,
1837 		    NULL, 0);
1838 		goto bad;
1839 	}
1840 
1841 	hlen = IP_VHL_HL(ip->ip_vhl) << 2;
1842 	if (hlen < sizeof(struct ip)) {         /* minimum header length */
1843 		OSAddAtomic(1, &ipstat.ips_badhlen);
1844 		m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IP_BAD_HDR_LENGTH,
1845 		    NULL, 0);
1846 		goto bad;
1847 	}
1848 	if (hlen > m->m_len) {
1849 		if ((m = m_pullup(m, hlen)) == NULL) {
1850 			OSAddAtomic(1, &ipstat.ips_badhlen);
1851 			return;
1852 		}
1853 		ip = mtod(m, struct ip *);
1854 	}
1855 
1856 	/* 127/8 must not appear on wire - RFC1122 */
1857 	if ((ntohl(ip->ip_dst.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET ||
1858 	    (ntohl(ip->ip_src.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET) {
1859 		/*
1860 		 * Allow for the following exceptions:
1861 		 *
1862 		 *   1. If the packet was sent to loopback (i.e. rcvif
1863 		 *	would have been set earlier at output time.)
1864 		 *
1865 		 *   2. If the packet was sent out on loopback from a local
1866 		 *	source address which belongs to a non-loopback
1867 		 *	interface (i.e. rcvif may not necessarily be a
1868 		 *	loopback interface, hence the test for PKTF_LOOP.)
1869 		 *	Unlike IPv6, there is no interface scope ID, and
1870 		 *	therefore we don't care so much about PKTF_IFINFO.
1871 		 */
1872 		if (!(inifp->if_flags & IFF_LOOPBACK) &&
1873 		    !(m->m_pkthdr.pkt_flags & PKTF_LOOP)) {
1874 			OSAddAtomic(1, &ipstat.ips_badaddr);
1875 			m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IP_INVALID_ADDR,
1876 			    NULL, 0);
1877 			goto bad;
1878 		}
1879 	}
1880 
1881 	/* IPv4 Link-Local Addresses as defined in RFC3927 */
1882 	if ((IN_LINKLOCAL(ntohl(ip->ip_dst.s_addr)) ||
1883 	    IN_LINKLOCAL(ntohl(ip->ip_src.s_addr)))) {
1884 		ip_linklocal_stat.iplls_in_total++;
1885 		if (ip->ip_ttl != MAXTTL) {
1886 			OSAddAtomic(1, &ip_linklocal_stat.iplls_in_badttl);
1887 			/* Silently drop link local traffic with bad TTL */
1888 			if (!ip_linklocal_in_allowbadttl) {
1889 				m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IP_BAD_TTL,
1890 				    NULL, 0);
1891 				goto bad;
1892 			}
1893 		}
1894 	}
1895 
1896 	sum = ip_cksum(m, hlen);
1897 	if (sum) {
1898 		m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IP_BAD_CHECKSUM,
1899 		    NULL, 0);
1900 		goto bad;
1901 	}
1902 
1903 	DTRACE_IP6(receive, struct mbuf *, m, struct inpcb *, NULL,
1904 	    struct ip *, ip, struct ifnet *, inifp,
1905 	    struct ip *, ip, struct ip6_hdr *, NULL);
1906 
1907 	/*
1908 	 * Naively assume we can attribute inbound data to the route we would
1909 	 * use to send to this destination. Asymmetric routing breaks this
1910 	 * assumption, but it still allows us to account for traffic from
1911 	 * a remote node in the routing table.
1912 	 * this has a very significant performance impact so we bypass
1913 	 * if nstat_collect is disabled. We may also bypass if the
1914 	 * protocol is tcp in the future because tcp will have a route that
1915 	 * we can use to attribute the data to. That does mean we would not
1916 	 * account for forwarded tcp traffic.
1917 	 */
1918 	if (nstat_collect) {
1919 		rtentry_ref_t rt = ifnet_cached_rtlookup_inet(inifp, ip->ip_src);
1920 		if (rt != NULL) {
1921 			nstat_route_rx(rt, 1, m->m_pkthdr.len, 0);
1922 			rtfree(rt);
1923 		}
1924 	}
1925 
1926 	/*
1927 	 * Convert fields to host representation.
1928 	 */
1929 #if BYTE_ORDER != BIG_ENDIAN
1930 	NTOHS(ip->ip_len);
1931 #endif
1932 
1933 	if (ip->ip_len < hlen) {
1934 		OSAddAtomic(1, &ipstat.ips_badlen);
1935 		m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IP_BAD_LENGTH,
1936 		    NULL, 0);
1937 		goto bad;
1938 	}
1939 
1940 #if BYTE_ORDER != BIG_ENDIAN
1941 	NTOHS(ip->ip_off);
1942 #endif
1943 	/*
1944 	 * Check that the amount of data in the buffers
1945 	 * is as at least much as the IP header would have us expect.
1946 	 * Trim mbufs if longer than we expect.
1947 	 * Drop packet if shorter than we expect.
1948 	 */
1949 	if (m->m_pkthdr.len < ip->ip_len) {
1950 tooshort:
1951 		OSAddAtomic(1, &ipstat.ips_tooshort);
1952 		m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IP_TOO_SHORT,
1953 		    NULL, 0);
1954 		goto bad;
1955 	}
1956 	if (m->m_pkthdr.len > ip->ip_len) {
1957 		ip_input_adjust(m, ip, inifp);
1958 	}
1959 
1960 #if DUMMYNET
1961 check_with_pf:
1962 #endif
1963 #if PF
1964 	/* Invoke inbound packet filter */
1965 	if (PF_IS_ENABLED) {
1966 		int error;
1967 #if DUMMYNET
1968 		error = pf_af_hook(inifp, NULL, &m, AF_INET, TRUE, &args);
1969 #else
1970 		error = pf_af_hook(inifp, NULL, &m, AF_INET, TRUE, NULL);
1971 #endif /* DUMMYNET */
1972 		if (error != 0 || m == NULL) {
1973 			if (m != NULL) {
1974 				panic("%s: unexpected packet %p",
1975 				    __func__, m);
1976 				/* NOTREACHED */
1977 			}
1978 			/* Already freed by callee */
1979 			return;
1980 		}
1981 		ip = mtod(m, struct ip *);
1982 		hlen = IP_VHL_HL(ip->ip_vhl) << 2;
1983 	}
1984 #endif /* PF */
1985 
1986 #if IPSEC
1987 	if (ipsec_bypass == 0 && ipsec_get_history_count(m)) {
1988 		goto pass;
1989 	}
1990 #endif
1991 
1992 pass:
1993 	/*
1994 	 * Process options and, if not destined for us,
1995 	 * ship it on.  ip_dooptions returns 1 when an
1996 	 * error was detected (causing an icmp message
1997 	 * to be sent and the original packet to be freed).
1998 	 */
1999 	ip_nhops = 0;           /* for source routed packets */
2000 	if (hlen > sizeof(struct ip) && ip_dooptions(m, 0, NULL)) {
2001 		return;
2002 	}
2003 
2004 	/*
2005 	 * Check our list of addresses, to see if the packet is for us.
2006 	 * If we don't have any addresses, assume any unicast packet
2007 	 * we receive might be for us (and let the upper layers deal
2008 	 * with it).
2009 	 */
2010 	if (TAILQ_EMPTY(&in_ifaddrhead) && !(m->m_flags & (M_MCAST | M_BCAST))) {
2011 		ip_setdstifaddr_info(m, inifp->if_index, NULL);
2012 		goto ours;
2013 	}
2014 
2015 	/*
2016 	 * Enable a consistency check between the destination address
2017 	 * and the arrival interface for a unicast packet (the RFC 1122
2018 	 * strong ES model) if IP forwarding is disabled and the packet
2019 	 * is not locally generated and the packet is not subject to
2020 	 * 'ipfw fwd'.
2021 	 *
2022 	 * XXX - Checking also should be disabled if the destination
2023 	 * address is ipnat'ed to a different interface.
2024 	 *
2025 	 * XXX - Checking is incompatible with IP aliases added
2026 	 * to the loopback interface instead of the interface where
2027 	 * the packets are received.
2028 	 */
2029 	if (!IN_MULTICAST(ntohl(ip->ip_dst.s_addr))) {
2030 		ip_check_if_result_t check_if_result = IP_CHECK_IF_NONE;
2031 
2032 		check_if_result = ip_input_check_interface(&m, ip, inifp);
2033 		ASSERT(check_if_result != IP_CHECK_IF_NONE);
2034 		if (check_if_result == IP_CHECK_IF_OURS) {
2035 			goto ours;
2036 		} else if (check_if_result == IP_CHECK_IF_DROP) {
2037 			return;
2038 		}
2039 	} else {
2040 		struct in_multi *__single inm;
2041 		/*
2042 		 * See if we belong to the destination multicast group on the
2043 		 * arrival interface.
2044 		 */
2045 		in_multihead_lock_shared();
2046 		IN_LOOKUP_MULTI(&ip->ip_dst, inifp, inm);
2047 		in_multihead_lock_done();
2048 		if (inm == NULL) {
2049 			OSAddAtomic(1, &ipstat.ips_notmember);
2050 			HTONS(ip->ip_len);
2051 			HTONS(ip->ip_off);
2052 			m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING,
2053 			    DROP_REASON_IP_UNKNOWN_MULTICAST_GROUP, NULL, 0);
2054 			return;
2055 		}
2056 		ip_setdstifaddr_info(m, inifp->if_index, NULL);
2057 		INM_REMREF(inm);
2058 		goto ours;
2059 	}
2060 
2061 	/*
2062 	 * Not for us; forward if possible and desirable.
2063 	 */
2064 	if (ipforwarding == 0) {
2065 		OSAddAtomic(1, &ipstat.ips_cantforward);
2066 		m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IP_UNKNOWN_MULTICAST_GROUP,
2067 		    NULL, 0);
2068 	} else {
2069 		ip_forward(m, 0, NULL);
2070 	}
2071 	return;
2072 
2073 ours:
2074 	/*
2075 	 * If offset or IP_MF are set, must reassemble.
2076 	 */
2077 	if (ip->ip_off & ~(IP_DF | IP_RF)) {
2078 		m = ip_reass(m);
2079 		if (m == NULL) {
2080 			return;
2081 		}
2082 		ip = mtod(m, struct ip *);
2083 		/* Get the header length of the reassembled packet */
2084 		hlen = IP_VHL_HL(ip->ip_vhl) << 2;
2085 	}
2086 
2087 	/*
2088 	 * Further protocols expect the packet length to be w/o the
2089 	 * IP header.
2090 	 */
2091 	ip->ip_len -= hlen;
2092 
2093 
2094 #if IPSEC
2095 	/*
2096 	 * enforce IPsec policy checking if we are seeing last header.
2097 	 * note that we do not visit this with protocols with pcb layer
2098 	 * code - like udp/tcp/raw ip.
2099 	 */
2100 	if (ipsec_bypass == 0 && (ip_protox[ip->ip_p]->pr_flags & PR_LASTHDR)) {
2101 		if (ipsec4_in_reject(m, NULL)) {
2102 			IPSEC_STAT_INCREMENT(ipsecstat.in_polvio);
2103 			m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IPSEC_REJECT,
2104 			    NULL, 0);
2105 			goto bad;
2106 		}
2107 	}
2108 #endif /* IPSEC */
2109 
2110 	/*
2111 	 * Switch out to protocol's input routine.
2112 	 */
2113 	OSAddAtomic(1, &ipstat.ips_delivered);
2114 
2115 	ip_proto_dispatch_in(m, hlen, ip->ip_p, 0);
2116 bad:
2117 	KERNEL_DEBUG(DBG_LAYER_END, 0, 0, 0, 0, 0);
2118 }
2119 
2120 static void
ipq_updateparams(void)2121 ipq_updateparams(void)
2122 {
2123 	LCK_MTX_ASSERT(&ipqlock, LCK_MTX_ASSERT_OWNED);
2124 	/*
2125 	 * -1 for unlimited allocation.
2126 	 */
2127 	if (maxnipq < 0) {
2128 		ipq_limit = 0;
2129 	}
2130 	/*
2131 	 * Positive number for specific bound.
2132 	 */
2133 	if (maxnipq > 0) {
2134 		ipq_limit = maxnipq;
2135 	}
2136 	/*
2137 	 * Zero specifies no further fragment queue allocation -- set the
2138 	 * bound very low, but rely on implementation elsewhere to actually
2139 	 * prevent allocation and reclaim current queues.
2140 	 */
2141 	if (maxnipq == 0) {
2142 		ipq_limit = 1;
2143 	}
2144 	/*
2145 	 * Arm the purge timer if not already and if there's work to do
2146 	 */
2147 	frag_sched_timeout();
2148 }
2149 
2150 static int
2151 sysctl_maxnipq SYSCTL_HANDLER_ARGS
2152 {
2153 #pragma unused(arg1, arg2)
2154 	int error, i;
2155 
2156 	lck_mtx_lock(&ipqlock);
2157 	i = maxnipq;
2158 	error = sysctl_handle_int(oidp, &i, 0, req);
2159 	if (error || req->newptr == USER_ADDR_NULL) {
2160 		goto done;
2161 	}
2162 	/* impose bounds */
2163 	if (i < -1 || i > (nmbclusters / 4)) {
2164 		error = EINVAL;
2165 		goto done;
2166 	}
2167 	maxnipq = i;
2168 	ipq_updateparams();
2169 done:
2170 	lck_mtx_unlock(&ipqlock);
2171 	return error;
2172 }
2173 
2174 static int
2175 sysctl_maxfragsperpacket SYSCTL_HANDLER_ARGS
2176 {
2177 #pragma unused(arg1, arg2)
2178 	int error, i;
2179 
2180 	lck_mtx_lock(&ipqlock);
2181 	i = maxfragsperpacket;
2182 	error = sysctl_handle_int(oidp, &i, 0, req);
2183 	if (error || req->newptr == USER_ADDR_NULL) {
2184 		goto done;
2185 	}
2186 	maxfragsperpacket = i;
2187 	ipq_updateparams();     /* see if we need to arm timer */
2188 done:
2189 	lck_mtx_unlock(&ipqlock);
2190 	return error;
2191 }
2192 
2193 /*
2194  * Take incoming datagram fragment and try to reassemble it into
2195  * whole datagram.  If a chain for reassembly of this datagram already
2196  * exists, then it is given as fp; otherwise have to make a chain.
2197  *
2198  * The IP header is *NOT* adjusted out of iplen (but in host byte order).
2199  */
2200 static struct mbuf *
ip_reass(struct mbuf * m)2201 ip_reass(struct mbuf *m)
2202 {
2203 	struct ip *__single ip;
2204 	mbuf_ref_t p, q, nq, t;
2205 	struct ipq *__single fp = NULL;
2206 	struct ipqhead *__single head;
2207 	int i, hlen, next;
2208 	u_int8_t ecn, ecn0;
2209 	uint32_t csum, csum_flags;
2210 	uint16_t hash;
2211 	struct fq_head dfq;
2212 
2213 	MBUFQ_INIT(&dfq);       /* for deferred frees */
2214 
2215 	/* If maxnipq or maxfragsperpacket is 0, never accept fragments. */
2216 	if (maxnipq == 0 || maxfragsperpacket == 0) {
2217 		ipstat.ips_fragments++;
2218 		ipstat.ips_fragdropped++;
2219 		m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IP_FRAG_NOT_ACCEPTED,
2220 		    NULL, 0);
2221 		if (nipq > 0) {
2222 			lck_mtx_lock(&ipqlock);
2223 			frag_sched_timeout();   /* purge stale fragments */
2224 			lck_mtx_unlock(&ipqlock);
2225 		}
2226 		return NULL;
2227 	}
2228 
2229 	ip = mtod(m, struct ip *);
2230 	hlen = IP_VHL_HL(ip->ip_vhl) << 2;
2231 
2232 	lck_mtx_lock(&ipqlock);
2233 
2234 	hash = IPREASS_HASH(ip->ip_src.s_addr, ip->ip_id);
2235 	head = &ipq[hash];
2236 
2237 	/*
2238 	 * Look for queue of fragments
2239 	 * of this datagram.
2240 	 */
2241 	TAILQ_FOREACH(fp, head, ipq_list) {
2242 		if (ip->ip_id == fp->ipq_id &&
2243 		    ip->ip_src.s_addr == fp->ipq_src.s_addr &&
2244 		    ip->ip_dst.s_addr == fp->ipq_dst.s_addr &&
2245 		    ip->ip_p == fp->ipq_p) {
2246 			goto found;
2247 		}
2248 	}
2249 
2250 	fp = NULL;
2251 
2252 	/*
2253 	 * Attempt to trim the number of allocated fragment queues if it
2254 	 * exceeds the administrative limit.
2255 	 */
2256 	if ((nipq > (unsigned)maxnipq) && (maxnipq > 0)) {
2257 		/*
2258 		 * drop something from the tail of the current queue
2259 		 * before proceeding further
2260 		 */
2261 		struct ipq *__single fq = TAILQ_LAST(head, ipqhead);
2262 		if (fq == NULL) {   /* gak */
2263 			for (i = 0; i < IPREASS_NHASH; i++) {
2264 				struct ipq *__single r = TAILQ_LAST(&ipq[i], ipqhead);
2265 				if (r) {
2266 					ipstat.ips_fragdropped += r->ipq_nfrags;
2267 					frag_freef(&ipq[i], r, DROP_REASON_IP_FRAG_TOO_MANY);
2268 					break;
2269 				}
2270 			}
2271 		} else {
2272 			ipstat.ips_fragdropped += fq->ipq_nfrags;
2273 			frag_freef(head, fq, DROP_REASON_IP_FRAG_TOO_MANY);
2274 		}
2275 	}
2276 
2277 found:
2278 	/*
2279 	 * Leverage partial checksum offload for IP fragments.  Narrow down
2280 	 * the scope to cover only UDP without IP options, as that is the
2281 	 * most common case.
2282 	 *
2283 	 * Perform 1's complement adjustment of octets that got included/
2284 	 * excluded in the hardware-calculated checksum value.  Ignore cases
2285 	 * where the value includes the entire IPv4 header span, as the sum
2286 	 * for those octets would already be 0 by the time we get here; IP
2287 	 * has already performed its header checksum validation.  Also take
2288 	 * care of any trailing bytes and subtract out their partial sum.
2289 	 */
2290 	if (ip->ip_p == IPPROTO_UDP && hlen == sizeof(struct ip) &&
2291 	    (m->m_pkthdr.csum_flags &
2292 	    (CSUM_DATA_VALID | CSUM_PARTIAL | CSUM_PSEUDO_HDR)) ==
2293 	    (CSUM_DATA_VALID | CSUM_PARTIAL)) {
2294 		uint32_t start = m->m_pkthdr.csum_rx_start;
2295 		int32_t trailer = (m_pktlen(m) - ip->ip_len);
2296 		uint32_t swbytes = (uint32_t)trailer;
2297 
2298 		csum = m->m_pkthdr.csum_rx_val;
2299 
2300 		ASSERT(trailer >= 0);
2301 		if ((start != 0 && start != hlen) || trailer != 0) {
2302 			uint32_t datalen = ip->ip_len - hlen;
2303 
2304 #if BYTE_ORDER != BIG_ENDIAN
2305 			if (start < hlen) {
2306 				HTONS(ip->ip_len);
2307 				HTONS(ip->ip_off);
2308 			}
2309 #endif /* BYTE_ORDER != BIG_ENDIAN */
2310 			/* callee folds in sum */
2311 			csum = m_adj_sum16(m, start, hlen, datalen, csum);
2312 			if (hlen > start) {
2313 				swbytes += (hlen - start);
2314 			} else {
2315 				swbytes += (start - hlen);
2316 			}
2317 #if BYTE_ORDER != BIG_ENDIAN
2318 			if (start < hlen) {
2319 				NTOHS(ip->ip_off);
2320 				NTOHS(ip->ip_len);
2321 			}
2322 #endif /* BYTE_ORDER != BIG_ENDIAN */
2323 		}
2324 		csum_flags = m->m_pkthdr.csum_flags;
2325 
2326 		if (swbytes != 0) {
2327 			udp_in_cksum_stats(swbytes);
2328 		}
2329 		if (trailer != 0) {
2330 			m_adj(m, -trailer);
2331 		}
2332 	} else {
2333 		csum = 0;
2334 		csum_flags = 0;
2335 	}
2336 
2337 	/* Invalidate checksum */
2338 	m->m_pkthdr.csum_flags &= ~CSUM_DATA_VALID;
2339 
2340 	ipstat.ips_fragments++;
2341 
2342 	/*
2343 	 * Adjust ip_len to not reflect header,
2344 	 * convert offset of this to bytes.
2345 	 */
2346 	ip->ip_len -= hlen;
2347 	if (ip->ip_off & IP_MF) {
2348 		/*
2349 		 * Make sure that fragments have a data length
2350 		 * that's a non-zero multiple of 8 bytes.
2351 		 */
2352 		if (ip->ip_len == 0 || (ip->ip_len & 0x7) != 0) {
2353 			OSAddAtomic(1, &ipstat.ips_toosmall);
2354 			/*
2355 			 * Reassembly queue may have been found if previous
2356 			 * fragments were valid; given that this one is bad,
2357 			 * we need to drop it.  Make sure to set fp to NULL
2358 			 * if not already, since we don't want to decrement
2359 			 * ipq_nfrags as it doesn't include this packet.
2360 			 */
2361 			fp = NULL;
2362 			goto dropfrag;
2363 		}
2364 		m->m_flags |= M_FRAG;
2365 	} else {
2366 		/* Clear the flag in case packet comes from loopback */
2367 		m->m_flags &= ~M_FRAG;
2368 	}
2369 	ip->ip_off = (u_short)(ip->ip_off << 3);
2370 
2371 	m->m_pkthdr.pkt_hdr = ip;
2372 
2373 	/* Previous ip_reass() started here. */
2374 	/*
2375 	 * Presence of header sizes in mbufs
2376 	 * would confuse code below.
2377 	 */
2378 	m->m_data += hlen;
2379 	m->m_len -= hlen;
2380 
2381 	/*
2382 	 * If first fragment to arrive, create a reassembly queue.
2383 	 */
2384 	if (fp == NULL) {
2385 		fp = ipq_alloc();
2386 		if (fp == NULL) {
2387 			goto dropfrag;
2388 		}
2389 		TAILQ_INSERT_HEAD(head, fp, ipq_list);
2390 		nipq++;
2391 		fp->ipq_nfrags = 1;
2392 		fp->ipq_ttl = IPFRAGTTL;
2393 		fp->ipq_p = ip->ip_p;
2394 		fp->ipq_id = ip->ip_id;
2395 		fp->ipq_src = ip->ip_src;
2396 		fp->ipq_dst = ip->ip_dst;
2397 		fp->ipq_frags = m;
2398 		m->m_nextpkt = NULL;
2399 		/*
2400 		 * If the first fragment has valid checksum offload
2401 		 * info, the rest of fragments are eligible as well.
2402 		 */
2403 		if (csum_flags != 0) {
2404 			fp->ipq_csum = csum;
2405 			fp->ipq_csum_flags = csum_flags;
2406 		}
2407 		m = NULL;       /* nothing to return */
2408 		goto done;
2409 	} else {
2410 		fp->ipq_nfrags++;
2411 	}
2412 
2413 #define GETIP(m)        ((struct ip *)((m)->m_pkthdr.pkt_hdr))
2414 
2415 	/*
2416 	 * Handle ECN by comparing this segment with the first one;
2417 	 * if CE is set, do not lose CE.
2418 	 * drop if CE and not-ECT are mixed for the same packet.
2419 	 */
2420 	ecn = ip->ip_tos & IPTOS_ECN_MASK;
2421 	ecn0 = GETIP(fp->ipq_frags)->ip_tos & IPTOS_ECN_MASK;
2422 	if (ecn == IPTOS_ECN_CE) {
2423 		if (ecn0 == IPTOS_ECN_NOTECT) {
2424 			goto dropfrag;
2425 		}
2426 		if (ecn0 != IPTOS_ECN_CE) {
2427 			GETIP(fp->ipq_frags)->ip_tos |= IPTOS_ECN_CE;
2428 		}
2429 	}
2430 	if (ecn == IPTOS_ECN_NOTECT && ecn0 != IPTOS_ECN_NOTECT) {
2431 		goto dropfrag;
2432 	}
2433 
2434 	/*
2435 	 * Find a segment which begins after this one does.
2436 	 */
2437 	for (p = NULL, q = fp->ipq_frags; q; p = q, q = q->m_nextpkt) {
2438 		if (GETIP(q)->ip_off > ip->ip_off) {
2439 			break;
2440 		}
2441 	}
2442 
2443 	/*
2444 	 * If there is a preceding segment, it may provide some of
2445 	 * our data already.  If so, drop the data from the incoming
2446 	 * segment.  If it provides all of our data, drop us, otherwise
2447 	 * stick new segment in the proper place.
2448 	 *
2449 	 * If some of the data is dropped from the preceding
2450 	 * segment, then it's checksum is invalidated.
2451 	 */
2452 	if (p) {
2453 		i = GETIP(p)->ip_off + GETIP(p)->ip_len - ip->ip_off;
2454 		if (i > 0) {
2455 			if (i >= ip->ip_len) {
2456 				goto dropfrag;
2457 			}
2458 			m_adj(m, i);
2459 			fp->ipq_csum_flags = 0;
2460 			ip->ip_off += i;
2461 			ip->ip_len -= i;
2462 		}
2463 		m->m_nextpkt = p->m_nextpkt;
2464 		p->m_nextpkt = m;
2465 	} else {
2466 		m->m_nextpkt = fp->ipq_frags;
2467 		fp->ipq_frags = m;
2468 	}
2469 
2470 	/*
2471 	 * While we overlap succeeding segments trim them or,
2472 	 * if they are completely covered, dequeue them.
2473 	 */
2474 	for (; q != NULL && ip->ip_off + ip->ip_len > GETIP(q)->ip_off;
2475 	    q = nq) {
2476 		i = (ip->ip_off + ip->ip_len) - GETIP(q)->ip_off;
2477 		if (i < GETIP(q)->ip_len) {
2478 			GETIP(q)->ip_len -= i;
2479 			GETIP(q)->ip_off += i;
2480 			m_adj(q, i);
2481 			fp->ipq_csum_flags = 0;
2482 			break;
2483 		}
2484 		nq = q->m_nextpkt;
2485 		m->m_nextpkt = nq;
2486 		ipstat.ips_fragdropped++;
2487 		fp->ipq_nfrags--;
2488 		/* defer freeing until after lock is dropped */
2489 		MBUFQ_ENQUEUE(&dfq, q);
2490 	}
2491 
2492 	/*
2493 	 * If this fragment contains similar checksum offload info
2494 	 * as that of the existing ones, accumulate checksum.  Otherwise,
2495 	 * invalidate checksum offload info for the entire datagram.
2496 	 */
2497 	if (csum_flags != 0 && csum_flags == fp->ipq_csum_flags) {
2498 		fp->ipq_csum += csum;
2499 	} else if (fp->ipq_csum_flags != 0) {
2500 		fp->ipq_csum_flags = 0;
2501 	}
2502 
2503 
2504 	/*
2505 	 * Check for complete reassembly and perform frag per packet
2506 	 * limiting.
2507 	 *
2508 	 * Frag limiting is performed here so that the nth frag has
2509 	 * a chance to complete the packet before we drop the packet.
2510 	 * As a result, n+1 frags are actually allowed per packet, but
2511 	 * only n will ever be stored. (n = maxfragsperpacket.)
2512 	 *
2513 	 */
2514 	next = 0;
2515 	for (p = NULL, q = fp->ipq_frags; q; p = q, q = q->m_nextpkt) {
2516 		if (GETIP(q)->ip_off != next) {
2517 			if (fp->ipq_nfrags > maxfragsperpacket) {
2518 				ipstat.ips_fragdropped += fp->ipq_nfrags;
2519 				frag_freef(head, fp, DROP_REASON_IP_FRAG_TOO_MANY);
2520 			}
2521 			m = NULL;       /* nothing to return */
2522 			goto done;
2523 		}
2524 		next += GETIP(q)->ip_len;
2525 	}
2526 	/* Make sure the last packet didn't have the IP_MF flag */
2527 	if (p->m_flags & M_FRAG) {
2528 		if (fp->ipq_nfrags > maxfragsperpacket) {
2529 			ipstat.ips_fragdropped += fp->ipq_nfrags;
2530 			frag_freef(head, fp, DROP_REASON_IP_FRAG_TOO_MANY);
2531 		}
2532 		m = NULL;               /* nothing to return */
2533 		goto done;
2534 	}
2535 
2536 	/*
2537 	 * Reassembly is complete.  Make sure the packet is a sane size.
2538 	 */
2539 	q = fp->ipq_frags;
2540 	ip = GETIP(q);
2541 	if (next + (IP_VHL_HL(ip->ip_vhl) << 2) > IP_MAXPACKET) {
2542 		ipstat.ips_toolong++;
2543 		ipstat.ips_fragdropped += fp->ipq_nfrags;
2544 		frag_freef(head, fp, DROP_REASON_IP_FRAG_TOO_LONG);
2545 		m = NULL;               /* nothing to return */
2546 		goto done;
2547 	}
2548 
2549 	/*
2550 	 * Concatenate fragments.
2551 	 */
2552 	m = q;
2553 	t = m->m_next;
2554 	m->m_next = NULL;
2555 	m_cat(m, t);
2556 	nq = q->m_nextpkt;
2557 	q->m_nextpkt = NULL;
2558 	for (q = nq; q != NULL; q = nq) {
2559 		nq = q->m_nextpkt;
2560 		q->m_nextpkt = NULL;
2561 		m_cat(m, q);
2562 	}
2563 
2564 	/*
2565 	 * Store partial hardware checksum info from the fragment queue;
2566 	 * the receive start offset is set to 20 bytes (see code at the
2567 	 * top of this routine.)
2568 	 */
2569 	if (fp->ipq_csum_flags != 0) {
2570 		csum = fp->ipq_csum;
2571 
2572 		ADDCARRY(csum);
2573 
2574 		m->m_pkthdr.csum_rx_val = (uint16_t)csum;
2575 		m->m_pkthdr.csum_rx_start = sizeof(struct ip);
2576 		m->m_pkthdr.csum_flags = fp->ipq_csum_flags;
2577 	} else if ((m->m_pkthdr.rcvif->if_flags & IFF_LOOPBACK) ||
2578 	    (m->m_pkthdr.pkt_flags & PKTF_LOOP)) {
2579 		/* loopback checksums are always OK */
2580 		m->m_pkthdr.csum_data = 0xffff;
2581 		m->m_pkthdr.csum_flags =
2582 		    CSUM_DATA_VALID | CSUM_PSEUDO_HDR |
2583 		    CSUM_IP_CHECKED | CSUM_IP_VALID;
2584 	}
2585 
2586 	/*
2587 	 * Create header for new ip packet by modifying header of first
2588 	 * packet; dequeue and discard fragment reassembly header.
2589 	 * Make header visible.
2590 	 */
2591 	ip->ip_len = (u_short)((IP_VHL_HL(ip->ip_vhl) << 2) + next);
2592 	ip->ip_src = fp->ipq_src;
2593 	ip->ip_dst = fp->ipq_dst;
2594 
2595 	fp->ipq_frags = NULL;   /* return to caller as 'm' */
2596 	frag_freef(head, fp, DROP_REASON_UNSPECIFIED);
2597 	fp = NULL;
2598 
2599 	m->m_len += (IP_VHL_HL(ip->ip_vhl) << 2);
2600 	m->m_data -= (IP_VHL_HL(ip->ip_vhl) << 2);
2601 	/* some debugging cruft by sklower, below, will go away soon */
2602 	if (m->m_flags & M_PKTHDR) {    /* XXX this should be done elsewhere */
2603 		m_fixhdr(m);
2604 	}
2605 	ipstat.ips_reassembled++;
2606 
2607 	/* arm the purge timer if not already and if there's work to do */
2608 	frag_sched_timeout();
2609 	lck_mtx_unlock(&ipqlock);
2610 	/* perform deferred free (if needed) now that lock is dropped */
2611 	if (!MBUFQ_EMPTY(&dfq)) {
2612 		MBUFQ_DRAIN(&dfq);
2613 	}
2614 	VERIFY(MBUFQ_EMPTY(&dfq));
2615 	return m;
2616 
2617 done:
2618 	VERIFY(m == NULL);
2619 	/* arm the purge timer if not already and if there's work to do */
2620 	frag_sched_timeout();
2621 	lck_mtx_unlock(&ipqlock);
2622 	/* perform deferred free (if needed) */
2623 	if (!MBUFQ_EMPTY(&dfq)) {
2624 		MBUFQ_DRAIN(&dfq);
2625 	}
2626 	VERIFY(MBUFQ_EMPTY(&dfq));
2627 	return NULL;
2628 
2629 dropfrag:
2630 	ipstat.ips_fragdropped++;
2631 	if (fp != NULL) {
2632 		fp->ipq_nfrags--;
2633 	}
2634 	/* arm the purge timer if not already and if there's work to do */
2635 	frag_sched_timeout();
2636 	lck_mtx_unlock(&ipqlock);
2637 	m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IP_FRAG_DROPPED,
2638 	    NULL, 0);
2639 	/* perform deferred free (if needed) */
2640 	if (!MBUFQ_EMPTY(&dfq)) {
2641 		MBUFQ_DRAIN(&dfq);
2642 	}
2643 	VERIFY(MBUFQ_EMPTY(&dfq));
2644 	return NULL;
2645 #undef GETIP
2646 }
2647 
2648 /*
2649  * Free a fragment reassembly header and all
2650  * associated datagrams.
2651  */
2652 static void
frag_freef(struct ipqhead * fhp,struct ipq * fp,drop_reason_t drop_reason)2653 frag_freef(struct ipqhead *fhp, struct ipq *fp, drop_reason_t drop_reason)
2654 {
2655 	LCK_MTX_ASSERT(&ipqlock, LCK_MTX_ASSERT_OWNED);
2656 
2657 	fp->ipq_nfrags = 0;
2658 	if (fp->ipq_frags != NULL) {
2659 		if (drop_reason == DROP_REASON_UNSPECIFIED) {
2660 			m_freem_list(fp->ipq_frags);
2661 		} else {
2662 			m_drop_list(fp->ipq_frags, NULL, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, drop_reason, NULL, 0);
2663 		}
2664 		fp->ipq_frags = NULL;
2665 	}
2666 	TAILQ_REMOVE(fhp, fp, ipq_list);
2667 	nipq--;
2668 	ipq_free(fp);
2669 }
2670 
2671 /*
2672  * IP reassembly timer processing
2673  */
2674 static void
frag_timeout(void * arg)2675 frag_timeout(void *arg)
2676 {
2677 #pragma unused(arg)
2678 	struct ipq *__single fp;
2679 	int i;
2680 
2681 	/*
2682 	 * Update coarse-grained networking timestamp (in sec.); the idea
2683 	 * is to piggy-back on the timeout callout to update the counter
2684 	 * returnable via net_uptime().
2685 	 */
2686 	net_update_uptime();
2687 
2688 	lck_mtx_lock(&ipqlock);
2689 	for (i = 0; i < IPREASS_NHASH; i++) {
2690 		for (fp = TAILQ_FIRST(&ipq[i]); fp;) {
2691 			struct ipq *__single fpp;
2692 
2693 			fpp = fp;
2694 			fp = TAILQ_NEXT(fp, ipq_list);
2695 			if (--fpp->ipq_ttl == 0) {
2696 				ipstat.ips_fragtimeout += fpp->ipq_nfrags;
2697 				frag_freef(&ipq[i], fpp, DROP_REASON_IP_FRAG_TIMEOUT);
2698 			}
2699 		}
2700 	}
2701 	/*
2702 	 * If we are over the maximum number of fragments
2703 	 * (due to the limit being lowered), drain off
2704 	 * enough to get down to the new limit.
2705 	 */
2706 	if (maxnipq >= 0 && nipq > (unsigned)maxnipq) {
2707 		for (i = 0; i < IPREASS_NHASH; i++) {
2708 			while (nipq > (unsigned)maxnipq &&
2709 			    !TAILQ_EMPTY(&ipq[i])) {
2710 				ipstat.ips_fragdropped +=
2711 				    TAILQ_FIRST(&ipq[i])->ipq_nfrags;
2712 				frag_freef(&ipq[i], TAILQ_FIRST(&ipq[i]), DROP_REASON_IP_FRAG_DROPPED);
2713 			}
2714 		}
2715 	}
2716 	/* re-arm the purge timer if there's work to do */
2717 	frag_timeout_run = 0;
2718 	frag_sched_timeout();
2719 	lck_mtx_unlock(&ipqlock);
2720 }
2721 
2722 static void
frag_sched_timeout(void)2723 frag_sched_timeout(void)
2724 {
2725 	LCK_MTX_ASSERT(&ipqlock, LCK_MTX_ASSERT_OWNED);
2726 
2727 	if (!frag_timeout_run && nipq > 0) {
2728 		frag_timeout_run = 1;
2729 		timeout(frag_timeout, NULL, hz);
2730 	}
2731 }
2732 
2733 /*
2734  * Drain off all datagram fragments.
2735  */
2736 static void
frag_drain(void)2737 frag_drain(void)
2738 {
2739 	int i;
2740 
2741 	lck_mtx_lock(&ipqlock);
2742 	for (i = 0; i < IPREASS_NHASH; i++) {
2743 		while (!TAILQ_EMPTY(&ipq[i])) {
2744 			ipstat.ips_fragdropped +=
2745 			    TAILQ_FIRST(&ipq[i])->ipq_nfrags;
2746 			frag_freef(&ipq[i], TAILQ_FIRST(&ipq[i]), DROP_REASON_IP_FRAG_DRAINED);
2747 		}
2748 	}
2749 	lck_mtx_unlock(&ipqlock);
2750 }
2751 
2752 static struct ipq *
ipq_alloc(void)2753 ipq_alloc(void)
2754 {
2755 	struct ipq *__single fp;
2756 
2757 	/*
2758 	 * See comments in ipq_updateparams().  Keep the count separate
2759 	 * from nipq since the latter represents the elements already
2760 	 * in the reassembly queues.
2761 	 */
2762 	if (ipq_limit > 0 && ipq_count > ipq_limit) {
2763 		return NULL;
2764 	}
2765 
2766 	fp = kalloc_type(struct ipq, Z_NOWAIT | Z_ZERO);
2767 	if (fp != NULL) {
2768 		os_atomic_inc(&ipq_count, relaxed);
2769 	}
2770 	return fp;
2771 }
2772 
2773 static void
ipq_free(struct ipq * fp)2774 ipq_free(struct ipq *fp)
2775 {
2776 	kfree_type(struct ipq, fp);
2777 	os_atomic_dec(&ipq_count, relaxed);
2778 }
2779 
2780 /*
2781  * Drain callback
2782  */
2783 void
ip_drain(void)2784 ip_drain(void)
2785 {
2786 	frag_drain();           /* fragments */
2787 	in_rtqdrain();          /* protocol cloned routes */
2788 	in_arpdrain(NULL);      /* cloned routes: ARP */
2789 }
2790 
2791 /*
2792  * Do option processing on a datagram,
2793  * possibly discarding it if bad options are encountered,
2794  * or forwarding it if source-routed.
2795  * The pass argument is used when operating in the IPSTEALTH
2796  * mode to tell what options to process:
2797  * [LS]SRR (pass 0) or the others (pass 1).
2798  * The reason for as many as two passes is that when doing IPSTEALTH,
2799  * non-routing options should be processed only if the packet is for us.
2800  * Returns 1 if packet has been forwarded/freed,
2801  * 0 if the packet should be processed further.
2802  */
2803 static int
ip_dooptions(struct mbuf * m,int pass,struct sockaddr_in * next_hop)2804 ip_dooptions(struct mbuf *m, int pass, struct sockaddr_in *next_hop)
2805 {
2806 #pragma unused(pass)
2807 	struct ip *ip = mtod(m, struct ip *);
2808 	u_char *cp;
2809 	struct ip_timestamp *__single ipt;
2810 	struct in_ifaddr *__single ia;
2811 	int opt, optlen, cnt, off, type = ICMP_PARAMPROB, forward = 0;
2812 	uint8_t code = 0;
2813 	struct in_addr *__single sin, dst;
2814 	u_int32_t ntime;
2815 	struct sockaddr_in ipaddr = {
2816 		.sin_len = sizeof(ipaddr),
2817 		.sin_family = AF_INET,
2818 		.sin_port = 0,
2819 		.sin_addr = { .s_addr = 0 },
2820 		.sin_zero = { 0, }
2821 	};
2822 
2823 	/* Expect 32-bit aligned data pointer on strict-align platforms */
2824 	MBUF_STRICT_DATA_ALIGNMENT_CHECK_32(m);
2825 
2826 	dst = ip->ip_dst;
2827 	cp = (u_char *)(ip + 1);
2828 	cnt = (IP_VHL_HL(ip->ip_vhl) << 2) - sizeof(struct ip);
2829 	for (; cnt > 0; cnt -= optlen, cp += optlen) {
2830 		opt = cp[IPOPT_OPTVAL];
2831 		if (opt == IPOPT_EOL) {
2832 			break;
2833 		}
2834 		if (opt == IPOPT_NOP) {
2835 			optlen = 1;
2836 		} else {
2837 			if (cnt < IPOPT_OLEN + sizeof(*cp)) {
2838 				code = (uint8_t)(&cp[IPOPT_OLEN] - (u_char *)ip);
2839 				goto bad;
2840 			}
2841 			optlen = cp[IPOPT_OLEN];
2842 			if (optlen < IPOPT_OLEN + sizeof(*cp) ||
2843 			    optlen > cnt) {
2844 				code = (uint8_t)(&cp[IPOPT_OLEN] - (u_char *)ip);
2845 				goto bad;
2846 			}
2847 		}
2848 		switch (opt) {
2849 		default:
2850 			break;
2851 
2852 		/*
2853 		 * Source routing with record.
2854 		 * Find interface with current destination address.
2855 		 * If none on this machine then drop if strictly routed,
2856 		 * or do nothing if loosely routed.
2857 		 * Record interface address and bring up next address
2858 		 * component.  If strictly routed make sure next
2859 		 * address is on directly accessible net.
2860 		 */
2861 		case IPOPT_LSRR:
2862 		case IPOPT_SSRR:
2863 			if (optlen < IPOPT_OFFSET + sizeof(*cp)) {
2864 				code = (uint8_t)(&cp[IPOPT_OLEN] - (u_char *)ip);
2865 				goto bad;
2866 			}
2867 			if ((off = cp[IPOPT_OFFSET]) < IPOPT_MINOFF) {
2868 				code = (uint8_t)(&cp[IPOPT_OFFSET] - (u_char *)ip);
2869 				goto bad;
2870 			}
2871 			ipaddr.sin_addr = ip->ip_dst;
2872 			ia = ifatoia(ifa_ifwithaddr(SA(&ipaddr)));
2873 			if (ia == NULL) {
2874 				if (opt == IPOPT_SSRR) {
2875 					type = ICMP_UNREACH;
2876 					code = ICMP_UNREACH_SRCFAIL;
2877 					goto bad;
2878 				}
2879 				if (!ip_dosourceroute) {
2880 					goto nosourcerouting;
2881 				}
2882 				/*
2883 				 * Loose routing, and not at next destination
2884 				 * yet; nothing to do except forward.
2885 				 */
2886 				break;
2887 			} else {
2888 				ifa_remref(&ia->ia_ifa);
2889 				ia = NULL;
2890 			}
2891 			off--;                  /* 0 origin */
2892 			if (off > optlen - (int)sizeof(struct in_addr)) {
2893 				/*
2894 				 * End of source route.  Should be for us.
2895 				 */
2896 				if (!ip_acceptsourceroute) {
2897 					goto nosourcerouting;
2898 				}
2899 				save_rte(cp, ip->ip_src);
2900 				break;
2901 			}
2902 
2903 			if (!ip_dosourceroute) {
2904 				if (ipforwarding) {
2905 					char buf[MAX_IPv4_STR_LEN];
2906 					char buf2[MAX_IPv4_STR_LEN];
2907 					/*
2908 					 * Acting as a router, so generate ICMP
2909 					 */
2910 nosourcerouting:
2911 					log(LOG_WARNING,
2912 					    "attempted source route from %s "
2913 					    "to %s\n",
2914 					    inet_ntop(AF_INET, &ip->ip_src,
2915 					    buf, sizeof(buf)),
2916 					    inet_ntop(AF_INET, &ip->ip_dst,
2917 					    buf2, sizeof(buf2)));
2918 					type = ICMP_UNREACH;
2919 					code = ICMP_UNREACH_SRCFAIL;
2920 					goto bad;
2921 				} else {
2922 					/*
2923 					 * Not acting as a router,
2924 					 * so silently drop.
2925 					 */
2926 					OSAddAtomic(1, &ipstat.ips_cantforward);
2927 					m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IP_CANNOT_FORWARD,
2928 					    NULL, 0);
2929 					return 1;
2930 				}
2931 			}
2932 
2933 			/*
2934 			 * locate outgoing interface
2935 			 */
2936 			(void) memcpy(&ipaddr.sin_addr, cp + off,
2937 			    sizeof(ipaddr.sin_addr));
2938 
2939 			if (opt == IPOPT_SSRR) {
2940 #define INA     struct in_ifaddr *
2941 				if ((ia = (INA)ifa_ifwithdstaddr(
2942 					    SA(&ipaddr))) == NULL) {
2943 					ia = (INA)ifa_ifwithnet(SA(&ipaddr));
2944 				}
2945 			} else {
2946 				ia = ip_rtaddr(ipaddr.sin_addr);
2947 			}
2948 			if (ia == NULL) {
2949 				type = ICMP_UNREACH;
2950 				code = ICMP_UNREACH_SRCFAIL;
2951 				goto bad;
2952 			}
2953 			ip->ip_dst = ipaddr.sin_addr;
2954 			IFA_LOCK(&ia->ia_ifa);
2955 			(void) memcpy(cp + off, &(IA_SIN(ia)->sin_addr),
2956 			    sizeof(struct in_addr));
2957 			IFA_UNLOCK(&ia->ia_ifa);
2958 			ifa_remref(&ia->ia_ifa);
2959 			ia = NULL;
2960 			cp[IPOPT_OFFSET] += sizeof(struct in_addr);
2961 			/*
2962 			 * Let ip_intr's mcast routing check handle mcast pkts
2963 			 */
2964 			forward = !IN_MULTICAST(ntohl(ip->ip_dst.s_addr));
2965 			break;
2966 
2967 		case IPOPT_RR:
2968 			if (optlen < IPOPT_OFFSET + sizeof(*cp)) {
2969 				code = (uint8_t)(&cp[IPOPT_OFFSET] - (u_char *)ip);
2970 				goto bad;
2971 			}
2972 			if ((off = cp[IPOPT_OFFSET]) < IPOPT_MINOFF) {
2973 				code = (uint8_t)(&cp[IPOPT_OFFSET] - (u_char *)ip);
2974 				goto bad;
2975 			}
2976 			/*
2977 			 * If no space remains, ignore.
2978 			 */
2979 			off--;                  /* 0 origin */
2980 			if (off > optlen - (int)sizeof(struct in_addr)) {
2981 				break;
2982 			}
2983 			(void) memcpy(&ipaddr.sin_addr, &ip->ip_dst,
2984 			    sizeof(ipaddr.sin_addr));
2985 			/*
2986 			 * locate outgoing interface; if we're the destination,
2987 			 * use the incoming interface (should be same).
2988 			 */
2989 			if ((ia = (INA)ifa_ifwithaddr(SA(&ipaddr))) == NULL) {
2990 				if ((ia = ip_rtaddr(ipaddr.sin_addr)) == NULL) {
2991 					type = ICMP_UNREACH;
2992 					code = ICMP_UNREACH_HOST;
2993 					goto bad;
2994 				}
2995 			}
2996 			IFA_LOCK(&ia->ia_ifa);
2997 			(void) memcpy(cp + off, &(IA_SIN(ia)->sin_addr),
2998 			    sizeof(struct in_addr));
2999 			IFA_UNLOCK(&ia->ia_ifa);
3000 			ifa_remref(&ia->ia_ifa);
3001 			ia = NULL;
3002 			cp[IPOPT_OFFSET] += sizeof(struct in_addr);
3003 			break;
3004 
3005 		case IPOPT_TS:
3006 			code = (uint8_t)(cp - (u_char *)ip);
3007 			ipt = (struct ip_timestamp *)(void *)cp;
3008 			if (ipt->ipt_len < 4 || ipt->ipt_len > 40) {
3009 				code = (uint8_t)((u_char *)&ipt->ipt_len -
3010 				    (u_char *)ip);
3011 				goto bad;
3012 			}
3013 			if (ipt->ipt_ptr < 5) {
3014 				code = (uint8_t)((u_char *)&ipt->ipt_ptr -
3015 				    (u_char *)ip);
3016 				goto bad;
3017 			}
3018 			if (ipt->ipt_ptr >
3019 			    ipt->ipt_len - (int)sizeof(int32_t)) {
3020 				if (++ipt->ipt_oflw == 0) {
3021 					code = (uint8_t)((u_char *)&ipt->ipt_ptr -
3022 					    (u_char *)ip);
3023 					goto bad;
3024 				}
3025 				break;
3026 			}
3027 			sin = (struct in_addr *)(void *)(cp + ipt->ipt_ptr - 1);
3028 			switch (ipt->ipt_flg) {
3029 			case IPOPT_TS_TSONLY:
3030 				break;
3031 
3032 			case IPOPT_TS_TSANDADDR:
3033 				if (ipt->ipt_ptr - 1 + sizeof(n_time) +
3034 				    sizeof(struct in_addr) > ipt->ipt_len) {
3035 					code = (uint8_t)((u_char *)&ipt->ipt_ptr -
3036 					    (u_char *)ip);
3037 					goto bad;
3038 				}
3039 				ipaddr.sin_addr = dst;
3040 				ia = (INA)ifaof_ifpforaddr(SA(&ipaddr),
3041 				    m->m_pkthdr.rcvif);
3042 				if (ia == NULL) {
3043 					continue;
3044 				}
3045 				IFA_LOCK(&ia->ia_ifa);
3046 				(void) memcpy(sin, &IA_SIN(ia)->sin_addr,
3047 				    sizeof(struct in_addr));
3048 				IFA_UNLOCK(&ia->ia_ifa);
3049 				ipt->ipt_ptr += sizeof(struct in_addr);
3050 				ifa_remref(&ia->ia_ifa);
3051 				ia = NULL;
3052 				break;
3053 
3054 			case IPOPT_TS_PRESPEC:
3055 				if (ipt->ipt_ptr - 1 + sizeof(n_time) +
3056 				    sizeof(struct in_addr) > ipt->ipt_len) {
3057 					code = (uint8_t)((u_char *)&ipt->ipt_ptr -
3058 					    (u_char *)ip);
3059 					goto bad;
3060 				}
3061 				(void) memcpy(&ipaddr.sin_addr, sin,
3062 				    sizeof(struct in_addr));
3063 				if ((ia = ifatoia(ifa_ifwithaddr(
3064 					    SA(&ipaddr)))) == NULL) {
3065 					continue;
3066 				}
3067 				ifa_remref(&ia->ia_ifa);
3068 				ia = NULL;
3069 				ipt->ipt_ptr += sizeof(struct in_addr);
3070 				break;
3071 
3072 			default:
3073 				/* XXX can't take &ipt->ipt_flg */
3074 				code = (uint8_t)((u_char *)&ipt->ipt_ptr -
3075 				    (u_char *)ip + 1);
3076 				goto bad;
3077 			}
3078 			ntime = iptime();
3079 			(void) memcpy(cp + ipt->ipt_ptr - 1, &ntime,
3080 			    sizeof(n_time));
3081 			ipt->ipt_ptr += sizeof(n_time);
3082 		}
3083 	}
3084 	if (forward && ipforwarding) {
3085 		ip_forward(m, 1, next_hop);
3086 		return 1;
3087 	}
3088 	return 0;
3089 bad:
3090 	icmp_error(m, type, code, 0, 0);
3091 	OSAddAtomic(1, &ipstat.ips_badoptions);
3092 	return 1;
3093 }
3094 
3095 /*
3096  * Check for the presence of the IP Router Alert option [RFC2113]
3097  * in the header of an IPv4 datagram.
3098  *
3099  * This call is not intended for use from the forwarding path; it is here
3100  * so that protocol domains may check for the presence of the option.
3101  * Given how FreeBSD's IPv4 stack is currently structured, the Router Alert
3102  * option does not have much relevance to the implementation, though this
3103  * may change in future.
3104  * Router alert options SHOULD be passed if running in IPSTEALTH mode and
3105  * we are not the endpoint.
3106  * Length checks on individual options should already have been peformed
3107  * by ip_dooptions() therefore they are folded under DIAGNOSTIC here.
3108  *
3109  * Return zero if not present or options are invalid, non-zero if present.
3110  */
3111 int
ip_checkrouteralert(struct mbuf * m)3112 ip_checkrouteralert(struct mbuf *m)
3113 {
3114 	struct ip *ip = mtod(m, struct ip *);
3115 	u_char *cp;
3116 	int opt, optlen, cnt, found_ra;
3117 
3118 	found_ra = 0;
3119 	cp = (u_char *)(ip + 1);
3120 	cnt = (IP_VHL_HL(ip->ip_vhl) << 2) - sizeof(struct ip);
3121 	for (; cnt > 0; cnt -= optlen, cp += optlen) {
3122 		opt = cp[IPOPT_OPTVAL];
3123 		if (opt == IPOPT_EOL) {
3124 			break;
3125 		}
3126 		if (opt == IPOPT_NOP) {
3127 			optlen = 1;
3128 		} else {
3129 #ifdef DIAGNOSTIC
3130 			if (cnt < IPOPT_OLEN + sizeof(*cp)) {
3131 				break;
3132 			}
3133 #endif
3134 			optlen = cp[IPOPT_OLEN];
3135 #ifdef DIAGNOSTIC
3136 			if (optlen < IPOPT_OLEN + sizeof(*cp) || optlen > cnt) {
3137 				break;
3138 			}
3139 #endif
3140 		}
3141 		switch (opt) {
3142 		case IPOPT_RA:
3143 #ifdef DIAGNOSTIC
3144 			if (optlen != IPOPT_OFFSET + sizeof(uint16_t) ||
3145 			    (*((uint16_t *)(void *)&cp[IPOPT_OFFSET]) != 0)) {
3146 				break;
3147 			} else
3148 #endif
3149 			found_ra = 1;
3150 			break;
3151 		default:
3152 			break;
3153 		}
3154 	}
3155 
3156 	return found_ra;
3157 }
3158 
3159 /*
3160  * Given address of next destination (final or next hop),
3161  * return internet address info of interface to be used to get there.
3162  */
3163 struct in_ifaddr *
ip_rtaddr(struct in_addr dst)3164 ip_rtaddr(struct in_addr dst)
3165 {
3166 	struct sockaddr_in *__single sin;
3167 	struct ifaddr *__single rt_ifa;
3168 	struct route ro;
3169 
3170 	bzero(&ro, sizeof(ro));
3171 	sin = SIN(&ro.ro_dst);
3172 	sin->sin_family = AF_INET;
3173 	sin->sin_len = sizeof(*sin);
3174 	sin->sin_addr = dst;
3175 
3176 	rtalloc_ign(&ro, RTF_PRCLONING);
3177 	if (ro.ro_rt == NULL) {
3178 		ROUTE_RELEASE(&ro);
3179 		return NULL;
3180 	}
3181 
3182 	RT_LOCK(ro.ro_rt);
3183 	if ((rt_ifa = ro.ro_rt->rt_ifa) != NULL) {
3184 		ifa_addref(rt_ifa);
3185 	}
3186 	RT_UNLOCK(ro.ro_rt);
3187 	ROUTE_RELEASE(&ro);
3188 
3189 	return ifatoia(rt_ifa);
3190 }
3191 
3192 /*
3193  * Save incoming source route for use in replies,
3194  * to be picked up later by ip_srcroute if the receiver is interested.
3195  */
3196 static void
save_rte(u_char * __indexable option,struct in_addr dst)3197 save_rte(u_char *__indexable option, struct in_addr dst)
3198 {
3199 	unsigned olen;
3200 
3201 	olen = option[IPOPT_OLEN];
3202 #if DIAGNOSTIC
3203 	if (ipprintfs) {
3204 		printf("save_rte: olen %d\n", olen);
3205 	}
3206 #endif
3207 	if (olen > sizeof(ip_srcrt) - (1 + sizeof(dst))) {
3208 		return;
3209 	}
3210 	bcopy(option, ip_srcrt.srcopt, olen);
3211 	ip_nhops = (olen - IPOPT_OFFSET - 1) / sizeof(struct in_addr);
3212 	ip_srcrt.dst = dst;
3213 }
3214 
3215 /*
3216  * Retrieve incoming source route for use in replies,
3217  * in the same form used by setsockopt.
3218  * The first hop is placed before the options, will be removed later.
3219  */
3220 struct mbuf *
ip_srcroute(void)3221 ip_srcroute(void)
3222 {
3223 	struct in_addr *p, *q;
3224 	struct mbuf *m;
3225 
3226 	if (ip_nhops == 0) {
3227 		return NULL;
3228 	}
3229 
3230 	m = m_get(M_DONTWAIT, MT_HEADER);
3231 	if (m == NULL) {
3232 		return NULL;
3233 	}
3234 
3235 #define OPTSIZ  (sizeof (ip_srcrt.nop) + sizeof (ip_srcrt.srcopt))
3236 
3237 	/* length is (nhops+1)*sizeof(addr) + sizeof(nop + srcrt header) */
3238 	m->m_len = ip_nhops * sizeof(struct in_addr) +
3239 	    sizeof(struct in_addr) + OPTSIZ;
3240 #if DIAGNOSTIC
3241 	if (ipprintfs) {
3242 		printf("ip_srcroute: nhops %d mlen %d", ip_nhops, m->m_len);
3243 	}
3244 #endif
3245 
3246 	/*
3247 	 * Notes: to the astute reader:
3248 	 * 1. The code is sequenced in the order
3249 	 *    of writing to the mbuf contents.
3250 	 * 2. The order of addresses in `ip_srcrt.route`
3251 	 *    is the reverse of the order in the wire format.
3252 	 */
3253 	/*
3254 	 * First save first hop for return route
3255 	 */
3256 	p = &ip_srcrt.route[ip_nhops - 1];
3257 	*(mtod(m, struct in_addr *)) = *p;
3258 #if DIAGNOSTIC
3259 	if (ipprintfs) {
3260 		printf(" hops %lx",
3261 		    (u_int32_t)ntohl(mtod(m, struct in_addr *)->s_addr));
3262 	}
3263 #endif
3264 
3265 	/*
3266 	 * Copy option fields and padding (nop) to mbuf.
3267 	 */
3268 	ip_srcrt.nop = IPOPT_NOP;
3269 	ip_srcrt.srcopt[IPOPT_OFFSET] = IPOPT_MINOFF;
3270 	(void) __nochk_memcpy(mtod(m, caddr_t) + sizeof(struct in_addr),
3271 	    (caddr_t)&ip_srcrt + sizeof(struct in_addr), OPTSIZ);
3272 	q = (struct in_addr *)(void *)(mtod(m, caddr_t) +
3273 	    sizeof(struct in_addr) + OPTSIZ);
3274 #undef OPTSIZ
3275 	/*
3276 	 * If multiple return addresses were provided,
3277 	 * record the return path as an IP source route,
3278 	 * reversing the path.
3279 	 */
3280 	for (int i = 0; i < (ip_nhops - 1); i++) {
3281 		q[i] = ip_srcrt.route[ip_nhops - (i + 2)];
3282 #if DIAGNOSTIC
3283 		if (ipprintfs) {
3284 			printf(" %lx", (u_int32_t)ntohl(q[i].s_addr));
3285 		}
3286 #endif
3287 	}
3288 	/*
3289 	 * Last hop goes to final destination.
3290 	 */
3291 	q[ip_nhops - 1] = ip_srcrt.dst;
3292 #if DIAGNOSTIC
3293 	if (ipprintfs) {
3294 		printf(" %lx\n", (u_int32_t)ntohl(q[ip_nhops - 1].s_addr));
3295 	}
3296 #endif
3297 	return m;
3298 }
3299 
3300 /*
3301  * Strip out IP options, at higher level protocol in the kernel.
3302  */
3303 void
ip_stripoptions(struct mbuf * m)3304 ip_stripoptions(struct mbuf *m)
3305 {
3306 	int i;
3307 	struct ip *ip = mtod(m, struct ip *);
3308 	caddr_t opts;
3309 	int olen;
3310 
3311 	/* Expect 32-bit aligned data pointer on strict-align platforms */
3312 	MBUF_STRICT_DATA_ALIGNMENT_CHECK_32(m);
3313 
3314 	/* use bcopy() since it supports overlapping range */
3315 	olen = (IP_VHL_HL(ip->ip_vhl) << 2) - sizeof(struct ip);
3316 	opts = (caddr_t)(ip + 1);
3317 	i = m->m_len - (sizeof(struct ip) + olen);
3318 	bcopy(opts + olen, opts, (unsigned)i);
3319 	m->m_len -= olen;
3320 	if (m->m_flags & M_PKTHDR) {
3321 		m->m_pkthdr.len -= olen;
3322 	}
3323 	ip->ip_vhl = IP_MAKE_VHL(IPVERSION, sizeof(struct ip) >> 2);
3324 
3325 	/*
3326 	 * We expect ip_{off,len} to be in host order by now, and
3327 	 * that the original IP header length has been subtracted
3328 	 * out from ip_len.  Temporarily adjust ip_len for checksum
3329 	 * recalculation, and restore it afterwards.
3330 	 */
3331 	ip->ip_len += sizeof(struct ip);
3332 
3333 	/* recompute checksum now that IP header is smaller */
3334 #if BYTE_ORDER != BIG_ENDIAN
3335 	HTONS(ip->ip_len);
3336 	HTONS(ip->ip_off);
3337 #endif /* BYTE_ORDER != BIG_ENDIAN */
3338 	ip->ip_sum = in_cksum_hdr(ip);
3339 #if BYTE_ORDER != BIG_ENDIAN
3340 	NTOHS(ip->ip_off);
3341 	NTOHS(ip->ip_len);
3342 #endif /* BYTE_ORDER != BIG_ENDIAN */
3343 
3344 	ip->ip_len -= sizeof(struct ip);
3345 
3346 	/*
3347 	 * Given that we've just stripped IP options from the header,
3348 	 * we need to adjust the start offset accordingly if this
3349 	 * packet had gone thru partial checksum offload.
3350 	 */
3351 	if ((m->m_pkthdr.csum_flags & (CSUM_DATA_VALID | CSUM_PARTIAL)) ==
3352 	    (CSUM_DATA_VALID | CSUM_PARTIAL)) {
3353 		if (m->m_pkthdr.csum_rx_start >= (sizeof(struct ip) + olen)) {
3354 			/* most common case */
3355 			m->m_pkthdr.csum_rx_start -= olen;
3356 		} else {
3357 			/* compute checksum in software instead */
3358 			m->m_pkthdr.csum_flags &= ~CSUM_DATA_VALID;
3359 			m->m_pkthdr.csum_data = 0;
3360 			ipstat.ips_adj_hwcsum_clr++;
3361 		}
3362 	}
3363 }
3364 
3365 u_char inetctlerrmap[PRC_NCMDS] = {
3366 	0, 0, 0, 0,
3367 	0, EMSGSIZE, EHOSTDOWN, EHOSTUNREACH,
3368 	ENETUNREACH, EHOSTUNREACH, ECONNREFUSED, ECONNREFUSED,
3369 	EMSGSIZE, EHOSTUNREACH, 0, 0,
3370 	0, 0, EHOSTUNREACH, 0,
3371 	ENOPROTOOPT, ECONNREFUSED
3372 };
3373 
3374 static int
3375 sysctl_ipforwarding SYSCTL_HANDLER_ARGS
3376 {
3377 #pragma unused(arg1, arg2)
3378 	int i, was_ipforwarding = ipforwarding;
3379 
3380 	i = sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2, req);
3381 	if (i != 0 || req->newptr == USER_ADDR_NULL) {
3382 		return i;
3383 	}
3384 
3385 	if (was_ipforwarding && !ipforwarding) {
3386 		/* clean up IPv4 forwarding cached routes */
3387 		ifnet_head_lock_shared();
3388 		for (i = 0; i <= if_index; i++) {
3389 			ifnet_ref_t ifp = ifindex2ifnet[i];
3390 			if (ifp != NULL) {
3391 				lck_mtx_lock(&ifp->if_cached_route_lock);
3392 				ROUTE_RELEASE(&ifp->if_fwd_route);
3393 				bzero(&ifp->if_fwd_route,
3394 				    sizeof(ifp->if_fwd_route));
3395 				lck_mtx_unlock(&ifp->if_cached_route_lock);
3396 			}
3397 		}
3398 		ifnet_head_done();
3399 	}
3400 
3401 	return 0;
3402 }
3403 
3404 /*
3405  * Similar to inp_route_{copyout,copyin} routines except that these copy
3406  * out the cached IPv4 forwarding route from struct ifnet instead of the
3407  * inpcb.  See comments for those routines for explanations.
3408  */
3409 static void
ip_fwd_route_copyout(struct ifnet * ifp,struct route * dst)3410 ip_fwd_route_copyout(struct ifnet *ifp, struct route *dst)
3411 {
3412 	struct route *src = &ifp->if_fwd_route;
3413 
3414 	lck_mtx_lock_spin(&ifp->if_cached_route_lock);
3415 	lck_mtx_convert_spin(&ifp->if_cached_route_lock);
3416 
3417 	/* Minor sanity check */
3418 	if (src->ro_rt != NULL && rt_key(src->ro_rt)->sa_family != AF_INET) {
3419 		panic("%s: wrong or corrupted route: %p", __func__, src);
3420 	}
3421 
3422 	route_copyout(dst, src, sizeof(*dst));
3423 
3424 	lck_mtx_unlock(&ifp->if_cached_route_lock);
3425 }
3426 
3427 static void
ip_fwd_route_copyin(struct ifnet * ifp,struct route * src)3428 ip_fwd_route_copyin(struct ifnet *ifp, struct route *src)
3429 {
3430 	struct route *dst = &ifp->if_fwd_route;
3431 
3432 	lck_mtx_lock_spin(&ifp->if_cached_route_lock);
3433 	lck_mtx_convert_spin(&ifp->if_cached_route_lock);
3434 
3435 	/* Minor sanity check */
3436 	if (src->ro_rt != NULL && rt_key(src->ro_rt)->sa_family != AF_INET) {
3437 		panic("%s: wrong or corrupted route: %p", __func__, src);
3438 	}
3439 
3440 	if (ifp->if_fwd_cacheok) {
3441 		route_copyin(src, dst, sizeof(*src));
3442 	}
3443 
3444 	lck_mtx_unlock(&ifp->if_cached_route_lock);
3445 }
3446 
3447 /*
3448  * Forward a packet.  If some error occurs return the sender
3449  * an icmp packet.  Note we can't always generate a meaningful
3450  * icmp message because icmp doesn't have a large enough repertoire
3451  * of codes and types.
3452  *
3453  * If not forwarding, just drop the packet.  This could be confusing
3454  * if ipforwarding was zero but some routing protocol was advancing
3455  * us as a gateway to somewhere.  However, we must let the routing
3456  * protocol deal with that.
3457  *
3458  * The srcrt parameter indicates whether the packet is being forwarded
3459  * via a source route.
3460  */
3461 static void
ip_forward(struct mbuf * m,int srcrt,struct sockaddr_in * next_hop)3462 ip_forward(struct mbuf *m, int srcrt, struct sockaddr_in *next_hop)
3463 {
3464 #pragma unused(next_hop)
3465 	struct ip *__single ip = mtod(m, struct ip *);
3466 	struct sockaddr_in *__single sin;
3467 	rtentry_ref_t rt;
3468 	struct route fwd_rt;
3469 	int error, type = 0, code = 0;
3470 	mbuf_ref_t mcopy;
3471 	n_long dest;
3472 	struct in_addr pkt_dst;
3473 	u_int32_t nextmtu = 0, len;
3474 	struct ip_out_args ipoa;
3475 	struct ifnet *__single rcvifp = m->m_pkthdr.rcvif;
3476 
3477 	bzero(&ipoa, sizeof(ipoa));
3478 	ipoa.ipoa_boundif = IFSCOPE_NONE;
3479 	ipoa.ipoa_sotc = SO_TC_UNSPEC;
3480 	ipoa.ipoa_netsvctype = _NET_SERVICE_TYPE_UNSPEC;
3481 
3482 #if IPSEC
3483 	struct secpolicy *sp = NULL;
3484 	int ipsecerror;
3485 #endif /* IPSEC */
3486 #if PF
3487 	struct pf_mtag *pf_mtag;
3488 #endif /* PF */
3489 
3490 	dest = 0;
3491 	pkt_dst = ip->ip_dst;
3492 
3493 #if DIAGNOSTIC
3494 	if (ipprintfs) {
3495 		printf("forward: src %lx dst %lx ttl %x\n",
3496 		    (u_int32_t)ip->ip_src.s_addr, (u_int32_t)pkt_dst.s_addr,
3497 		    ip->ip_ttl);
3498 	}
3499 #endif
3500 
3501 	if (m->m_flags & (M_BCAST | M_MCAST) || !in_canforward(pkt_dst)) {
3502 		OSAddAtomic(1, &ipstat.ips_cantforward);
3503 		m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IP_CANNOT_FORWARD,
3504 		    NULL, 0);
3505 		return;
3506 	}
3507 #if IPSTEALTH
3508 	if (!ipstealth) {
3509 #endif /* IPSTEALTH */
3510 	if (ip->ip_ttl <= IPTTLDEC) {
3511 		icmp_error(m, ICMP_TIMXCEED, ICMP_TIMXCEED_INTRANS,
3512 		    dest, 0);
3513 		return;
3514 	}
3515 #if IPSTEALTH
3516 }
3517 #endif /* IPSTEALTH */
3518 
3519 #if PF
3520 	pf_mtag = pf_find_mtag(m);
3521 	if (pf_mtag != NULL && pf_mtag->pftag_rtableid != IFSCOPE_NONE) {
3522 		ipoa.ipoa_boundif = pf_mtag->pftag_rtableid;
3523 		ipoa.ipoa_flags |= IPOAF_BOUND_IF;
3524 	}
3525 #endif /* PF */
3526 
3527 	ip_fwd_route_copyout(rcvifp, &fwd_rt);
3528 
3529 	sin = SIN(&fwd_rt.ro_dst);
3530 	if (ROUTE_UNUSABLE(&fwd_rt) || pkt_dst.s_addr != sin->sin_addr.s_addr) {
3531 		ROUTE_RELEASE(&fwd_rt);
3532 
3533 		sin->sin_family = AF_INET;
3534 		sin->sin_len = sizeof(*sin);
3535 		sin->sin_addr = pkt_dst;
3536 
3537 		rtalloc_scoped_ign(&fwd_rt, RTF_PRCLONING, ipoa.ipoa_boundif);
3538 		if (fwd_rt.ro_rt == NULL) {
3539 			icmp_error(m, ICMP_UNREACH, ICMP_UNREACH_HOST, dest, 0);
3540 			goto done;
3541 		}
3542 	}
3543 	rt = fwd_rt.ro_rt;
3544 
3545 	/*
3546 	 * Save the IP header and at most 8 bytes of the payload,
3547 	 * in case we need to generate an ICMP message to the src.
3548 	 *
3549 	 * We don't use m_copy() because it might return a reference
3550 	 * to a shared cluster. Both this function and ip_output()
3551 	 * assume exclusive access to the IP header in `m', so any
3552 	 * data in a cluster may change before we reach icmp_error().
3553 	 */
3554 	MGET(mcopy, M_DONTWAIT, m->m_type);
3555 	if (mcopy != NULL && m_dup_pkthdr(mcopy, m, M_DONTWAIT) == 0) {
3556 		mcopy->m_len = imin((IP_VHL_HL(ip->ip_vhl) << 2) + 8,
3557 		    (int)ip->ip_len);
3558 		m_copydata(m, 0, mcopy->m_len, mtod(mcopy, caddr_t));
3559 	}
3560 
3561 #if IPSTEALTH
3562 	if (!ipstealth) {
3563 #endif /* IPSTEALTH */
3564 	ip->ip_ttl -= IPTTLDEC;
3565 #if IPSTEALTH
3566 }
3567 #endif /* IPSTEALTH */
3568 
3569 	/*
3570 	 * If forwarding packet using same interface that it came in on,
3571 	 * perhaps should send a redirect to sender to shortcut a hop.
3572 	 * Only send redirect if source is sending directly to us,
3573 	 * and if packet was not source routed (or has any options).
3574 	 * Also, don't send redirect if forwarding using a default route
3575 	 * or a route modified by a redirect.
3576 	 */
3577 	RT_LOCK_SPIN(rt);
3578 	if (rt->rt_ifp == m->m_pkthdr.rcvif &&
3579 	    !(rt->rt_flags & (RTF_DYNAMIC | RTF_MODIFIED)) &&
3580 	    satosin(rt_key(rt))->sin_addr.s_addr != INADDR_ANY &&
3581 	    ipsendredirects && !srcrt && rt->rt_ifa != NULL) {
3582 		struct in_ifaddr *ia = ifatoia(rt->rt_ifa);
3583 		u_int32_t src = ntohl(ip->ip_src.s_addr);
3584 
3585 		/* Become a regular mutex */
3586 		RT_CONVERT_LOCK(rt);
3587 		IFA_LOCK_SPIN(&ia->ia_ifa);
3588 		if ((src & ia->ia_subnetmask) == ia->ia_subnet) {
3589 			if (rt->rt_flags & RTF_GATEWAY) {
3590 				dest = satosin(rt->rt_gateway)->sin_addr.s_addr;
3591 			} else {
3592 				dest = pkt_dst.s_addr;
3593 			}
3594 			/*
3595 			 * Router requirements says to only send
3596 			 * host redirects.
3597 			 */
3598 			type = ICMP_REDIRECT;
3599 			code = ICMP_REDIRECT_HOST;
3600 #if DIAGNOSTIC
3601 			if (ipprintfs) {
3602 				printf("redirect (%d) to %lx\n", code,
3603 				    (u_int32_t)dest);
3604 			}
3605 #endif
3606 		}
3607 		IFA_UNLOCK(&ia->ia_ifa);
3608 	}
3609 	RT_UNLOCK(rt);
3610 
3611 
3612 	/* Mark this packet as being forwarded from another interface */
3613 	m->m_pkthdr.pkt_flags |= PKTF_FORWARDED;
3614 	len = m_pktlen(m);
3615 
3616 	error = ip_output(m, NULL, &fwd_rt, IP_FORWARDING | IP_OUTARGS,
3617 	    NULL, &ipoa);
3618 
3619 	/* Refresh rt since the route could have changed while in IP */
3620 	rt = fwd_rt.ro_rt;
3621 
3622 	if (error != 0) {
3623 		OSAddAtomic(1, &ipstat.ips_cantforward);
3624 	} else {
3625 		/*
3626 		 * Increment stats on the source interface; the ones
3627 		 * for destination interface has been taken care of
3628 		 * during output above by virtue of PKTF_FORWARDED.
3629 		 */
3630 		rcvifp->if_fpackets++;
3631 		rcvifp->if_fbytes += len;
3632 
3633 		OSAddAtomic(1, &ipstat.ips_forward);
3634 		if (type != 0) {
3635 			OSAddAtomic(1, &ipstat.ips_redirectsent);
3636 		} else {
3637 			if (mcopy != NULL) {
3638 				/*
3639 				 * If we didn't have to go thru ipflow and
3640 				 * the packet was successfully consumed by
3641 				 * ip_output, the mcopy is rather a waste;
3642 				 * this could be further optimized.
3643 				 */
3644 				m_freem(mcopy);
3645 			}
3646 			goto done;
3647 		}
3648 	}
3649 	if (mcopy == NULL) {
3650 		goto done;
3651 	}
3652 
3653 	switch (error) {
3654 	case 0:                         /* forwarded, but need redirect */
3655 		/* type, code set above */
3656 		break;
3657 
3658 	case ENETUNREACH:               /* shouldn't happen, checked above */
3659 	case EHOSTUNREACH:
3660 	case ENETDOWN:
3661 	case EHOSTDOWN:
3662 	default:
3663 		type = ICMP_UNREACH;
3664 		code = ICMP_UNREACH_HOST;
3665 		break;
3666 
3667 	case EMSGSIZE:
3668 		type = ICMP_UNREACH;
3669 		code = ICMP_UNREACH_NEEDFRAG;
3670 
3671 		if (rt == NULL) {
3672 			break;
3673 		} else {
3674 			RT_LOCK_SPIN(rt);
3675 			if (rt->rt_ifp != NULL) {
3676 				nextmtu = rt->rt_ifp->if_mtu;
3677 			}
3678 			RT_UNLOCK(rt);
3679 		}
3680 #ifdef IPSEC
3681 		if (ipsec_bypass) {
3682 			break;
3683 		}
3684 
3685 		/*
3686 		 * If the packet is routed over IPsec tunnel, tell the
3687 		 * originator the tunnel MTU.
3688 		 *	tunnel MTU = if MTU - sizeof(IP) - ESP/AH hdrsiz
3689 		 * XXX quickhack!!!
3690 		 */
3691 		sp = ipsec4_getpolicybyaddr(mcopy, IPSEC_DIR_OUTBOUND,
3692 		    IP_FORWARDING, &ipsecerror);
3693 
3694 		if (sp == NULL) {
3695 			break;
3696 		}
3697 
3698 		/*
3699 		 * find the correct route for outer IPv4
3700 		 * header, compute tunnel MTU.
3701 		 */
3702 		nextmtu = 0;
3703 
3704 		if (sp->req != NULL &&
3705 		    sp->req->saidx.mode == IPSEC_MODE_TUNNEL) {
3706 			struct secasindex saidx;
3707 			struct secasvar *__single sav;
3708 			struct route *__single ro;
3709 			struct ip *__single ipm;
3710 			size_t ipsechdr;
3711 
3712 			/* count IPsec header size */
3713 			ipsechdr = ipsec_hdrsiz(sp);
3714 
3715 			ipm = mtod(mcopy, struct ip *);
3716 			bcopy(&sp->req->saidx, &saidx, sizeof(saidx));
3717 			saidx.mode = sp->req->saidx.mode;
3718 			saidx.reqid = sp->req->saidx.reqid;
3719 			sin = SIN(&saidx.src);
3720 			if (sin->sin_len == 0) {
3721 				sin->sin_len = sizeof(*sin);
3722 				sin->sin_family = AF_INET;
3723 				sin->sin_port = IPSEC_PORT_ANY;
3724 				bcopy(&ipm->ip_src, &sin->sin_addr,
3725 				    sizeof(sin->sin_addr));
3726 			}
3727 			sin = SIN(&saidx.dst);
3728 			if (sin->sin_len == 0) {
3729 				sin->sin_len = sizeof(*sin);
3730 				sin->sin_family = AF_INET;
3731 				sin->sin_port = IPSEC_PORT_ANY;
3732 				bcopy(&ipm->ip_dst, &sin->sin_addr,
3733 				    sizeof(sin->sin_addr));
3734 			}
3735 			sav = key_allocsa_policy(&saidx);
3736 			if (sav != NULL) {
3737 				lck_mtx_lock(sadb_mutex);
3738 				if (sav->sah != NULL) {
3739 					ro = (struct route *)&sav->sah->sa_route;
3740 					if (ro->ro_rt != NULL) {
3741 						RT_LOCK(ro->ro_rt);
3742 						if (ro->ro_rt->rt_ifp != NULL) {
3743 							nextmtu = ro->ro_rt->
3744 							    rt_ifp->if_mtu;
3745 							nextmtu -= ipsechdr;
3746 						}
3747 						RT_UNLOCK(ro->ro_rt);
3748 					}
3749 				}
3750 				key_freesav(sav, KEY_SADB_LOCKED);
3751 				lck_mtx_unlock(sadb_mutex);
3752 			}
3753 		}
3754 		key_freesp(sp, KEY_SADB_UNLOCKED);
3755 #endif /* IPSEC */
3756 		break;
3757 
3758 	case ENOBUFS:
3759 		/*
3760 		 * A router should not generate ICMP_SOURCEQUENCH as
3761 		 * required in RFC1812 Requirements for IP Version 4 Routers.
3762 		 * Source quench could be a big problem under DoS attacks,
3763 		 * or if the underlying interface is rate-limited.
3764 		 * Those who need source quench packets may re-enable them
3765 		 * via the net.inet.ip.sendsourcequench sysctl.
3766 		 */
3767 		if (ip_sendsourcequench == 0) {
3768 			m_freem(mcopy);
3769 			goto done;
3770 		} else {
3771 			type = ICMP_SOURCEQUENCH;
3772 			code = 0;
3773 		}
3774 		break;
3775 
3776 	case EACCES:
3777 		m_freem(mcopy);
3778 		goto done;
3779 	}
3780 
3781 	if (type == ICMP_UNREACH && code == ICMP_UNREACH_NEEDFRAG) {
3782 		OSAddAtomic(1, &ipstat.ips_cantfrag);
3783 	}
3784 
3785 	icmp_error(mcopy, type, code, dest, nextmtu);
3786 done:
3787 	ip_fwd_route_copyin(rcvifp, &fwd_rt);
3788 }
3789 
3790 int
ip_savecontrol(struct inpcb * inp,struct mbuf ** mp,struct ip * ip,struct mbuf * m)3791 ip_savecontrol(struct inpcb *inp, struct mbuf **mp, struct ip *ip,
3792     struct mbuf *m)
3793 {
3794 	*mp = NULL;
3795 	if (inp->inp_socket->so_options & SO_TIMESTAMP) {
3796 		struct timeval tv;
3797 
3798 		getmicrotime(&tv);
3799 		mp = sbcreatecontrol_mbuf((caddr_t)&tv, sizeof(tv),
3800 		    SCM_TIMESTAMP, SOL_SOCKET, mp);
3801 		if (*mp == NULL) {
3802 			goto no_mbufs;
3803 		}
3804 	}
3805 	if (inp->inp_socket->so_options & SO_TIMESTAMP_MONOTONIC) {
3806 		uint64_t time;
3807 
3808 		time = mach_absolute_time();
3809 		mp = sbcreatecontrol_mbuf((caddr_t)&time, sizeof(time),
3810 		    SCM_TIMESTAMP_MONOTONIC, SOL_SOCKET, mp);
3811 		if (*mp == NULL) {
3812 			goto no_mbufs;
3813 		}
3814 	}
3815 	if (inp->inp_socket->so_options & SO_TIMESTAMP_CONTINUOUS) {
3816 		uint64_t time;
3817 
3818 		time = mach_continuous_time();
3819 		mp = sbcreatecontrol_mbuf((caddr_t)&time, sizeof(time),
3820 		    SCM_TIMESTAMP_CONTINUOUS, SOL_SOCKET, mp);
3821 		if (*mp == NULL) {
3822 			goto no_mbufs;
3823 		}
3824 	}
3825 	if (inp->inp_socket->so_flags & SOF_RECV_TRAFFIC_CLASS) {
3826 		int tc = m_get_traffic_class(m);
3827 
3828 		mp = sbcreatecontrol_mbuf((caddr_t)&tc, sizeof(tc),
3829 		    SO_TRAFFIC_CLASS, SOL_SOCKET, mp);
3830 		if (*mp == NULL) {
3831 			goto no_mbufs;
3832 		}
3833 	}
3834 	if ((inp->inp_socket->so_flags & SOF_RECV_WAKE_PKT) &&
3835 	    (m->m_pkthdr.pkt_flags & PKTF_WAKE_PKT)) {
3836 		int flag = 1;
3837 
3838 		mp = sbcreatecontrol_mbuf((caddr_t)&flag, sizeof(flag),
3839 		    SO_RECV_WAKE_PKT, SOL_SOCKET, mp);
3840 		if (*mp == NULL) {
3841 			goto no_mbufs;
3842 		}
3843 	}
3844 
3845 	if (inp->inp_flags & INP_RECVDSTADDR || SOFLOW_ENABLED(inp->inp_socket)) {
3846 		mp = sbcreatecontrol_mbuf((caddr_t)&ip->ip_dst,
3847 		    sizeof(struct in_addr), IP_RECVDSTADDR, IPPROTO_IP, mp);
3848 		if (*mp == NULL) {
3849 			goto no_mbufs;
3850 		}
3851 	}
3852 #ifdef notyet
3853 	/*
3854 	 * XXX
3855 	 * Moving these out of udp_input() made them even more broken
3856 	 * than they already were.
3857 	 */
3858 	/* options were tossed already */
3859 	if (inp->inp_flags & INP_RECVOPTS) {
3860 		mp = sbcreatecontrol_mbuf((caddr_t)opts_deleted_above,
3861 		    sizeof(struct in_addr), IP_RECVOPTS, IPPROTO_IP, mp);
3862 		if (*mp == NULL) {
3863 			goto no_mbufs;
3864 		}
3865 	}
3866 	/* ip_srcroute doesn't do what we want here, need to fix */
3867 	if (inp->inp_flags & INP_RECVRETOPTS) {
3868 		mp = sbcreatecontrol_mbuf((caddr_t)ip_srcroute(),
3869 		    sizeof(struct in_addr), IP_RECVRETOPTS, IPPROTO_IP, mp);
3870 		if (*mp == NULL) {
3871 			goto no_mbufs;
3872 		}
3873 	}
3874 #endif /* notyet */
3875 	if (inp->inp_flags & INP_RECVIF) {
3876 		ifnet_ref_t ifp;
3877 		uint8_t sdlbuf[SOCK_MAXADDRLEN + 1];
3878 		struct sockaddr_dl *sdl2 = SDL(sdlbuf);
3879 
3880 		/*
3881 		 * Make sure to accomodate the largest possible
3882 		 * size of SA(if_lladdr)->sa_len.
3883 		 */
3884 		_CASSERT(sizeof(sdlbuf) == (SOCK_MAXADDRLEN + 1));
3885 
3886 		ifnet_head_lock_shared();
3887 		if ((ifp = m->m_pkthdr.rcvif) != NULL &&
3888 		    ifp->if_index && IF_INDEX_IN_RANGE(ifp->if_index)) {
3889 			struct ifaddr *__single ifa = ifnet_addrs[ifp->if_index - 1];
3890 			struct sockaddr_dl *sdp;
3891 
3892 			if (!ifa || !ifa->ifa_addr) {
3893 				goto makedummy;
3894 			}
3895 
3896 			IFA_LOCK_SPIN(ifa);
3897 			sdp = SDL(ifa->ifa_addr);
3898 			/*
3899 			 * Change our mind and don't try copy.
3900 			 */
3901 			if (sdp->sdl_family != AF_LINK) {
3902 				IFA_UNLOCK(ifa);
3903 				goto makedummy;
3904 			}
3905 			/* the above _CASSERT ensures sdl_len fits in sdlbuf */
3906 			SOCKADDR_COPY(sdp, sdl2, sdp->sdl_len);
3907 			IFA_UNLOCK(ifa);
3908 		} else {
3909 makedummy:
3910 			sdl2->sdl_len =
3911 			    offsetof(struct sockaddr_dl, sdl_data[0]);
3912 			sdl2->sdl_family = AF_LINK;
3913 			sdl2->sdl_index = 0;
3914 			sdl2->sdl_nlen = sdl2->sdl_alen = sdl2->sdl_slen = 0;
3915 		}
3916 		ifnet_head_done();
3917 		mp = sbcreatecontrol_mbuf((caddr_t)SA_BYTES(sdl2), sdl2->sdl_len,
3918 		    IP_RECVIF, IPPROTO_IP, mp);
3919 		if (*mp == NULL) {
3920 			goto no_mbufs;
3921 		}
3922 	}
3923 	if (inp->inp_flags & INP_RECVTTL) {
3924 		mp = sbcreatecontrol_mbuf((caddr_t)&ip->ip_ttl,
3925 		    sizeof(ip->ip_ttl), IP_RECVTTL, IPPROTO_IP, mp);
3926 		if (*mp == NULL) {
3927 			goto no_mbufs;
3928 		}
3929 	}
3930 	if (inp->inp_flags & INP_PKTINFO) {
3931 		struct in_pktinfo pi;
3932 
3933 		bzero(&pi, sizeof(struct in_pktinfo));
3934 		bcopy(&ip->ip_dst, &pi.ipi_addr, sizeof(struct in_addr));
3935 		pi.ipi_ifindex = (m != NULL && m->m_pkthdr.rcvif != NULL) ?
3936 		    m->m_pkthdr.rcvif->if_index : 0;
3937 
3938 		mp = sbcreatecontrol_mbuf((caddr_t)&pi,
3939 		    sizeof(struct in_pktinfo), IP_RECVPKTINFO, IPPROTO_IP, mp);
3940 		if (*mp == NULL) {
3941 			goto no_mbufs;
3942 		}
3943 	}
3944 	if (inp->inp_flags & INP_RECVTOS) {
3945 		mp = sbcreatecontrol_mbuf((caddr_t)&ip->ip_tos,
3946 		    sizeof(u_char), IP_RECVTOS, IPPROTO_IP, mp);
3947 		if (*mp == NULL) {
3948 			goto no_mbufs;
3949 		}
3950 	}
3951 	return 0;
3952 
3953 no_mbufs:
3954 	ipstat.ips_pktdropcntrl++;
3955 	return ENOBUFS;
3956 }
3957 
3958 static inline u_short
ip_cksum(struct mbuf * m,int hlen)3959 ip_cksum(struct mbuf *m, int hlen)
3960 {
3961 	u_short sum;
3962 
3963 	if (m->m_pkthdr.csum_flags & CSUM_IP_CHECKED) {
3964 		sum = !(m->m_pkthdr.csum_flags & CSUM_IP_VALID);
3965 	} else if (!(m->m_pkthdr.rcvif->if_flags & IFF_LOOPBACK) &&
3966 	    !(m->m_pkthdr.pkt_flags & PKTF_LOOP)) {
3967 		/*
3968 		 * The packet arrived on an interface which isn't capable
3969 		 * of performing IP header checksum; compute it now.
3970 		 */
3971 		sum = ip_cksum_hdr_in(m, hlen);
3972 	} else {
3973 		sum = 0;
3974 		m->m_pkthdr.csum_flags |= (CSUM_DATA_VALID | CSUM_PSEUDO_HDR |
3975 		    CSUM_IP_CHECKED | CSUM_IP_VALID);
3976 		m->m_pkthdr.csum_data = 0xffff;
3977 	}
3978 
3979 	if (sum != 0) {
3980 		OSAddAtomic(1, &ipstat.ips_badsum);
3981 	}
3982 
3983 	return sum;
3984 }
3985 
3986 static int
3987 ip_getstat SYSCTL_HANDLER_ARGS
3988 {
3989 #pragma unused(oidp, arg1, arg2)
3990 	if (req->oldptr == USER_ADDR_NULL) {
3991 		req->oldlen = (size_t)sizeof(struct ipstat);
3992 	}
3993 
3994 	return SYSCTL_OUT(req, &ipstat, MIN(sizeof(ipstat), req->oldlen));
3995 }
3996 
3997 void
ip_setsrcifaddr_info(struct mbuf * m,uint16_t src_idx,struct in_ifaddr * ia)3998 ip_setsrcifaddr_info(struct mbuf *m, uint16_t src_idx, struct in_ifaddr *ia)
3999 {
4000 	VERIFY(m->m_flags & M_PKTHDR);
4001 
4002 	/*
4003 	 * If the source ifaddr is specified, pick up the information
4004 	 * from there; otherwise just grab the passed-in ifindex as the
4005 	 * caller may not have the ifaddr available.
4006 	 */
4007 	if (ia != NULL) {
4008 		m->m_pkthdr.pkt_flags |= PKTF_IFAINFO;
4009 		m->m_pkthdr.src_ifindex = ia->ia_ifp->if_index;
4010 	} else {
4011 		m->m_pkthdr.src_ifindex = src_idx;
4012 		if (src_idx != 0) {
4013 			m->m_pkthdr.pkt_flags |= PKTF_IFAINFO;
4014 		}
4015 	}
4016 }
4017 
4018 void
ip_setdstifaddr_info(struct mbuf * m,uint16_t dst_idx,struct in_ifaddr * ia)4019 ip_setdstifaddr_info(struct mbuf *m, uint16_t dst_idx, struct in_ifaddr *ia)
4020 {
4021 	VERIFY(m->m_flags & M_PKTHDR);
4022 
4023 	/*
4024 	 * If the destination ifaddr is specified, pick up the information
4025 	 * from there; otherwise just grab the passed-in ifindex as the
4026 	 * caller may not have the ifaddr available.
4027 	 */
4028 	if (ia != NULL) {
4029 		m->m_pkthdr.pkt_flags |= PKTF_IFAINFO;
4030 		m->m_pkthdr.dst_ifindex = ia->ia_ifp->if_index;
4031 	} else {
4032 		m->m_pkthdr.dst_ifindex = dst_idx;
4033 		if (dst_idx != 0) {
4034 			m->m_pkthdr.pkt_flags |= PKTF_IFAINFO;
4035 		}
4036 	}
4037 }
4038 
4039 int
ip_getsrcifaddr_info(struct mbuf * m,uint32_t * src_idx,uint32_t * iaf)4040 ip_getsrcifaddr_info(struct mbuf *m, uint32_t *src_idx, uint32_t *iaf)
4041 {
4042 	VERIFY(m->m_flags & M_PKTHDR);
4043 
4044 	if (!(m->m_pkthdr.pkt_flags & PKTF_IFAINFO)) {
4045 		return -1;
4046 	}
4047 
4048 	if (src_idx != NULL) {
4049 		*src_idx = m->m_pkthdr.src_ifindex;
4050 	}
4051 
4052 	if (iaf != NULL) {
4053 		*iaf = 0;
4054 	}
4055 
4056 	return 0;
4057 }
4058 
4059 int
ip_getdstifaddr_info(struct mbuf * m,uint32_t * dst_idx,uint32_t * iaf)4060 ip_getdstifaddr_info(struct mbuf *m, uint32_t *dst_idx, uint32_t *iaf)
4061 {
4062 	VERIFY(m->m_flags & M_PKTHDR);
4063 
4064 	if (!(m->m_pkthdr.pkt_flags & PKTF_IFAINFO)) {
4065 		return -1;
4066 	}
4067 
4068 	if (dst_idx != NULL) {
4069 		*dst_idx = m->m_pkthdr.dst_ifindex;
4070 	}
4071 
4072 	if (iaf != NULL) {
4073 		*iaf = 0;
4074 	}
4075 
4076 	return 0;
4077 }
4078 
4079 /*
4080  * Protocol input handler for IPPROTO_GRE.
4081  */
4082 void
gre_input(struct mbuf * m,int off)4083 gre_input(struct mbuf *m, int off)
4084 {
4085 	gre_input_func_t fn = gre_input_func;
4086 
4087 	/*
4088 	 * If there is a registered GRE input handler, pass mbuf to it.
4089 	 */
4090 	if (fn != NULL) {
4091 		lck_mtx_unlock(inet_domain_mutex);
4092 		m = fn(m, off, (mtod(m, struct ip *))->ip_p);
4093 		lck_mtx_lock(inet_domain_mutex);
4094 	}
4095 
4096 	/*
4097 	 * If no matching tunnel that is up is found, we inject
4098 	 * the mbuf to raw ip socket to see if anyone picks it up.
4099 	 */
4100 	if (m != NULL) {
4101 		rip_input(m, off);
4102 	}
4103 }
4104 
4105 /*
4106  * Private KPI for PPP/PPTP.
4107  */
4108 int
ip_gre_register_input(gre_input_func_t fn)4109 ip_gre_register_input(gre_input_func_t fn)
4110 {
4111 	lck_mtx_lock(inet_domain_mutex);
4112 	gre_input_func = fn;
4113 	lck_mtx_unlock(inet_domain_mutex);
4114 
4115 	return 0;
4116 }
4117 
4118 #if (DEBUG || DEVELOPMENT)
4119 static int
4120 sysctl_reset_ip_input_stats SYSCTL_HANDLER_ARGS
4121 {
4122 #pragma unused(arg1, arg2)
4123 	int error, i;
4124 
4125 	i = ip_input_measure;
4126 	error = sysctl_handle_int(oidp, &i, 0, req);
4127 	if (error || req->newptr == USER_ADDR_NULL) {
4128 		goto done;
4129 	}
4130 	/* impose bounds */
4131 	if (i < 0 || i > 1) {
4132 		error = EINVAL;
4133 		goto done;
4134 	}
4135 	if (ip_input_measure != i && i == 1) {
4136 		net_perf_initialize(&net_perf, ip_input_measure_bins);
4137 	}
4138 	ip_input_measure = i;
4139 done:
4140 	return error;
4141 }
4142 
4143 static int
4144 sysctl_ip_input_measure_bins SYSCTL_HANDLER_ARGS
4145 {
4146 #pragma unused(arg1, arg2)
4147 	int error;
4148 	uint64_t i;
4149 
4150 	i = ip_input_measure_bins;
4151 	error = sysctl_handle_quad(oidp, &i, 0, req);
4152 	if (error || req->newptr == USER_ADDR_NULL) {
4153 		goto done;
4154 	}
4155 	/* validate data */
4156 	if (!net_perf_validate_bins(i)) {
4157 		error = EINVAL;
4158 		goto done;
4159 	}
4160 	ip_input_measure_bins = i;
4161 done:
4162 	return error;
4163 }
4164 
4165 static int
4166 sysctl_ip_input_getperf SYSCTL_HANDLER_ARGS
4167 {
4168 #pragma unused(oidp, arg1, arg2)
4169 	if (req->oldptr == USER_ADDR_NULL) {
4170 		req->oldlen = (size_t)sizeof(struct ipstat);
4171 	}
4172 
4173 	return SYSCTL_OUT(req, &net_perf, MIN(sizeof(net_perf), req->oldlen));
4174 }
4175 #endif /* (DEBUG || DEVELOPMENT) */
4176 
4177 static int
4178 sysctl_ip_checkinterface SYSCTL_HANDLER_ARGS
4179 {
4180 #pragma unused(arg1, arg2)
4181 	int error, i;
4182 
4183 	i = ip_checkinterface;
4184 	error = sysctl_handle_int(oidp, &i, 0, req);
4185 	if (error != 0 || req->newptr == USER_ADDR_NULL) {
4186 		return error;
4187 	}
4188 
4189 	switch (i) {
4190 	case IP_CHECKINTERFACE_WEAK_ES:
4191 	case IP_CHECKINTERFACE_HYBRID_ES:
4192 	case IP_CHECKINTERFACE_STRONG_ES:
4193 		if (ip_checkinterface != i) {
4194 			ip_checkinterface = i;
4195 			os_log(OS_LOG_DEFAULT, "%s: ip_checkinterface is now %d\n",
4196 			    __func__, ip_checkinterface);
4197 		}
4198 		break;
4199 	default:
4200 		error = EINVAL;
4201 		break;
4202 	}
4203 	return error;
4204 }
4205