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