This repository has been archived by the owner on May 22, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
ip_input.c
4174 lines (3741 loc) · 109 KB
/
ip_input.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2000-2020 Apple Inc. All rights reserved.
*
* @APPLE_OSREFERENCE_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apple Public Source License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. The rights granted to you under the License
* may not be used to create, or enable the creation or redistribution of,
* unlawful or unlicensed copies of an Apple operating system, or to
* circumvent, violate, or enable the circumvention or violation of, any
* terms of an Apple operating system software license agreement.
*
* Please obtain a copy of the License at
* http://www.opensource.apple.com/apsl/ and read it before using this file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPLE_OSREFERENCE_LICENSE_HEADER_END@
*/
/*
* Copyright (c) 1982, 1986, 1988, 1993
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* @(#)ip_input.c 8.2 (Berkeley) 1/4/94
*/
/*
* NOTICE: This file was modified by SPARTA, Inc. in 2007 to introduce
* support for mandatory and extensible security protections. This notice
* is included in support of clause 2.2 (b) of the Apple Public License,
* Version 2.0.
*/
#define _IP_VHL
#include <sys/param.h>
#include <sys/systm.h>
#include <sys/mbuf.h>
#include <sys/malloc.h>
#include <sys/domain.h>
#include <sys/protosw.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <sys/kernel.h>
#include <sys/syslog.h>
#include <sys/sysctl.h>
#include <sys/mcache.h>
#include <sys/socketvar.h>
#include <sys/kdebug.h>
#include <mach/mach_time.h>
#include <mach/sdt.h>
#include <machine/endian.h>
#include <dev/random/randomdev.h>
#include <kern/queue.h>
#include <kern/locks.h>
#include <libkern/OSAtomic.h>
#include <pexpert/pexpert.h>
#include <net/if.h>
#include <net/if_var.h>
#include <net/if_dl.h>
#include <net/route.h>
#include <net/kpi_protocol.h>
#include <net/ntstat.h>
#include <net/dlil.h>
#include <net/classq/classq.h>
#include <net/net_perf.h>
#include <net/init.h>
#if PF
#include <net/pfvar.h>
#endif /* PF */
#include <netinet/in.h>
#include <netinet/in_systm.h>
#include <netinet/in_var.h>
#include <netinet/in_arp.h>
#include <netinet/ip.h>
#include <netinet/in_pcb.h>
#include <netinet/ip_var.h>
#include <netinet/ip_icmp.h>
#include <netinet/kpi_ipfilter_var.h>
#include <netinet/udp.h>
#include <netinet/udp_var.h>
#include <netinet/bootp.h>
#if DUMMYNET
#include <netinet/ip_dummynet.h>
#endif /* DUMMYNET */
#if IPSEC
#include <netinet6/ipsec.h>
#include <netkey/key.h>
#endif /* IPSEC */
#include <os/log.h>
#define DBG_LAYER_BEG NETDBG_CODE(DBG_NETIP, 0)
#define DBG_LAYER_END NETDBG_CODE(DBG_NETIP, 2)
#define DBG_FNC_IP_INPUT NETDBG_CODE(DBG_NETIP, (2 << 8))
#if IPSEC
extern int ipsec_bypass;
extern lck_mtx_t *sadb_mutex;
lck_grp_t *sadb_stat_mutex_grp;
lck_grp_attr_t *sadb_stat_mutex_grp_attr;
lck_attr_t *sadb_stat_mutex_attr;
decl_lck_mtx_data(, sadb_stat_mutex_data);
lck_mtx_t *sadb_stat_mutex = &sadb_stat_mutex_data;
#endif /* IPSEC */
MBUFQ_HEAD(fq_head);
static int frag_timeout_run; /* frag timer is scheduled to run */
static void frag_timeout(void *);
static void frag_sched_timeout(void);
static struct ipq *ipq_alloc(int);
static void ipq_free(struct ipq *);
static void ipq_updateparams(void);
static void ip_input_second_pass(struct mbuf *, struct ifnet *,
int, int, struct ip_fw_in_args *);
decl_lck_mtx_data(static, ipqlock);
static lck_attr_t *ipqlock_attr;
static lck_grp_t *ipqlock_grp;
static lck_grp_attr_t *ipqlock_grp_attr;
/* Packet reassembly stuff */
#define IPREASS_NHASH_LOG2 6
#define IPREASS_NHASH (1 << IPREASS_NHASH_LOG2)
#define IPREASS_HMASK (IPREASS_NHASH - 1)
#define IPREASS_HASH(x, y) \
(((((x) & 0xF) | ((((x) >> 8) & 0xF) << 4)) ^ (y)) & IPREASS_HMASK)
/* IP fragment reassembly queues (protected by ipqlock) */
static TAILQ_HEAD(ipqhead, ipq) ipq[IPREASS_NHASH]; /* ip reassembly queues */
static int maxnipq; /* max packets in reass queues */
static u_int32_t maxfragsperpacket; /* max frags/packet in reass queues */
static u_int32_t nipq; /* # of packets in reass queues */
static u_int32_t ipq_limit; /* ipq allocation limit */
static u_int32_t ipq_count; /* current # of allocated ipq's */
static int sysctl_ipforwarding SYSCTL_HANDLER_ARGS;
static int sysctl_maxnipq SYSCTL_HANDLER_ARGS;
static int sysctl_maxfragsperpacket SYSCTL_HANDLER_ARGS;
#if (DEBUG || DEVELOPMENT)
static int sysctl_reset_ip_input_stats SYSCTL_HANDLER_ARGS;
static int sysctl_ip_input_measure_bins SYSCTL_HANDLER_ARGS;
static int sysctl_ip_input_getperf SYSCTL_HANDLER_ARGS;
#endif /* (DEBUG || DEVELOPMENT) */
int ipforwarding = 0;
SYSCTL_PROC(_net_inet_ip, IPCTL_FORWARDING, forwarding,
CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED, &ipforwarding, 0,
sysctl_ipforwarding, "I", "Enable IP forwarding between interfaces");
static int ipsendredirects = 1; /* XXX */
SYSCTL_INT(_net_inet_ip, IPCTL_SENDREDIRECTS, redirect,
CTLFLAG_RW | CTLFLAG_LOCKED, &ipsendredirects, 0,
"Enable sending IP redirects");
int ip_defttl = IPDEFTTL;
SYSCTL_INT(_net_inet_ip, IPCTL_DEFTTL, ttl, CTLFLAG_RW | CTLFLAG_LOCKED,
&ip_defttl, 0, "Maximum TTL on IP packets");
static int ip_dosourceroute = 0;
SYSCTL_INT(_net_inet_ip, IPCTL_SOURCEROUTE, sourceroute,
CTLFLAG_RW | CTLFLAG_LOCKED, &ip_dosourceroute, 0,
"Enable forwarding source routed IP packets");
static int ip_acceptsourceroute = 0;
SYSCTL_INT(_net_inet_ip, IPCTL_ACCEPTSOURCEROUTE, accept_sourceroute,
CTLFLAG_RW | CTLFLAG_LOCKED, &ip_acceptsourceroute, 0,
"Enable accepting source routed IP packets");
static int ip_sendsourcequench = 0;
SYSCTL_INT(_net_inet_ip, OID_AUTO, sendsourcequench,
CTLFLAG_RW | CTLFLAG_LOCKED, &ip_sendsourcequench, 0,
"Enable the transmission of source quench packets");
SYSCTL_PROC(_net_inet_ip, OID_AUTO, maxfragpackets,
CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED, &maxnipq, 0, sysctl_maxnipq,
"I", "Maximum number of IPv4 fragment reassembly queue entries");
SYSCTL_UINT(_net_inet_ip, OID_AUTO, fragpackets, CTLFLAG_RD | CTLFLAG_LOCKED,
&nipq, 0, "Current number of IPv4 fragment reassembly queue entries");
SYSCTL_PROC(_net_inet_ip, OID_AUTO, maxfragsperpacket,
CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED, &maxfragsperpacket, 0,
sysctl_maxfragsperpacket, "I",
"Maximum number of IPv4 fragments allowed per packet");
static uint32_t ip_adj_clear_hwcksum = 0;
SYSCTL_UINT(_net_inet_ip, OID_AUTO, adj_clear_hwcksum,
CTLFLAG_RW | CTLFLAG_LOCKED, &ip_adj_clear_hwcksum, 0,
"Invalidate hwcksum info when adjusting length");
static uint32_t ip_adj_partial_sum = 1;
SYSCTL_UINT(_net_inet_ip, OID_AUTO, adj_partial_sum,
CTLFLAG_RW | CTLFLAG_LOCKED, &ip_adj_partial_sum, 0,
"Perform partial sum adjustment of trailing bytes at IP layer");
/*
* ip_checkinterface controls the receive side of the models for multihoming
* that are discussed in RFC 1122.
*
* ip_checkinterface values are:
* IP_CHECKINTERFACE_WEAK_ES:
* This corresponds to the Weak End-System model where incoming packets from
* any interface are accepted provided the destination address of the incoming packet
* is assigned to some interface.
*
* IP_CHECKINTERFACE_HYBRID_ES:
* The Hybrid End-System model use the Strong End-System for tunnel interfaces
* (ipsec and utun) and the weak End-System model for other interfaces families.
* This prevents a rogue middle box to probe for signs of TCP connections
* that use the tunnel interface.
*
* IP_CHECKINTERFACE_STRONG_ES:
* The Strong model model requires the packet arrived on an interface that
* is assigned the destination address of the packet.
*
* Since the routing table and transmit implementation do not implement the Strong ES model,
* setting this to a value different from IP_CHECKINTERFACE_WEAK_ES may lead to unexpected results.
*
* When forwarding is enabled, the system reverts to the Weak ES model as a router
* is expected by design to receive packets from several interfaces to the same address.
*
* XXX - ip_checkinterface currently must be set to IP_CHECKINTERFACE_WEAK_ES if you use ipnat
* to translate the destination address to another local interface.
*
* XXX - ip_checkinterface must be set to IP_CHECKINTERFACE_WEAK_ES if you add IP aliases
* to the loopback interface instead of the interface where the
* packets for those addresses are received.
*/
#define IP_CHECKINTERFACE_WEAK_ES 0
#define IP_CHECKINTERFACE_HYBRID_ES 1
#define IP_CHECKINTERFACE_STRONG_ES 2
static int ip_checkinterface = IP_CHECKINTERFACE_HYBRID_ES;
static int sysctl_ip_checkinterface SYSCTL_HANDLER_ARGS;
SYSCTL_PROC(_net_inet_ip, OID_AUTO, check_interface,
CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED,
0, 0, sysctl_ip_checkinterface, "I", "Verify packet arrives on correct interface");
#if (DEBUG || DEVELOPMENT)
#define IP_CHECK_IF_DEBUG 1
#else
#define IP_CHECK_IF_DEBUG 0
#endif /* (DEBUG || DEVELOPMENT) */
static int ip_checkinterface_debug = IP_CHECK_IF_DEBUG;
SYSCTL_INT(_net_inet_ip, OID_AUTO, checkinterface_debug, CTLFLAG_RW | CTLFLAG_LOCKED,
&ip_checkinterface_debug, IP_CHECK_IF_DEBUG, "");
static int ip_chaining = 1;
SYSCTL_INT(_net_inet_ip, OID_AUTO, rx_chaining, CTLFLAG_RW | CTLFLAG_LOCKED,
&ip_chaining, 1, "Do receive side ip address based chaining");
static int ip_chainsz = 6;
SYSCTL_INT(_net_inet_ip, OID_AUTO, rx_chainsz, CTLFLAG_RW | CTLFLAG_LOCKED,
&ip_chainsz, 1, "IP receive side max chaining");
#if (DEBUG || DEVELOPMENT)
static int ip_input_measure = 0;
SYSCTL_PROC(_net_inet_ip, OID_AUTO, input_perf,
CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED,
&ip_input_measure, 0, sysctl_reset_ip_input_stats, "I", "Do time measurement");
static uint64_t ip_input_measure_bins = 0;
SYSCTL_PROC(_net_inet_ip, OID_AUTO, input_perf_bins,
CTLTYPE_QUAD | CTLFLAG_RW | CTLFLAG_LOCKED, &ip_input_measure_bins, 0,
sysctl_ip_input_measure_bins, "I",
"bins for chaining performance data histogram");
static net_perf_t net_perf;
SYSCTL_PROC(_net_inet_ip, OID_AUTO, input_perf_data,
CTLTYPE_STRUCT | CTLFLAG_RD | CTLFLAG_LOCKED,
0, 0, sysctl_ip_input_getperf, "S,net_perf",
"IP input performance data (struct net_perf, net/net_perf.h)");
#endif /* (DEBUG || DEVELOPMENT) */
#if DIAGNOSTIC
static int ipprintfs = 0;
#endif
struct protosw *ip_protox[IPPROTO_MAX];
static lck_grp_attr_t *in_ifaddr_rwlock_grp_attr;
static lck_grp_t *in_ifaddr_rwlock_grp;
static lck_attr_t *in_ifaddr_rwlock_attr;
decl_lck_rw_data(, in_ifaddr_rwlock_data);
lck_rw_t *in_ifaddr_rwlock = &in_ifaddr_rwlock_data;
/* Protected by in_ifaddr_rwlock */
struct in_ifaddrhead in_ifaddrhead; /* first inet address */
struct in_ifaddrhashhead *in_ifaddrhashtbl; /* inet addr hash table */
#define INADDR_NHASH 61
static u_int32_t inaddr_nhash; /* hash table size */
static u_int32_t inaddr_hashp; /* next largest prime */
static int ip_getstat SYSCTL_HANDLER_ARGS;
struct ipstat ipstat;
SYSCTL_PROC(_net_inet_ip, IPCTL_STATS, stats,
CTLTYPE_STRUCT | CTLFLAG_RD | CTLFLAG_LOCKED,
0, 0, ip_getstat, "S,ipstat",
"IP statistics (struct ipstat, netinet/ip_var.h)");
#if IPCTL_DEFMTU
SYSCTL_INT(_net_inet_ip, IPCTL_DEFMTU, mtu, CTLFLAG_RW | CTLFLAG_LOCKED,
&ip_mtu, 0, "Default MTU");
#endif /* IPCTL_DEFMTU */
#if IPSTEALTH
static int ipstealth = 0;
SYSCTL_INT(_net_inet_ip, OID_AUTO, stealth, CTLFLAG_RW | CTLFLAG_LOCKED,
&ipstealth, 0, "");
#endif /* IPSTEALTH */
#if DUMMYNET
ip_dn_io_t *ip_dn_io_ptr;
#endif /* DUMMYNET */
SYSCTL_NODE(_net_inet_ip, OID_AUTO, linklocal,
CTLFLAG_RW | CTLFLAG_LOCKED, 0, "link local");
struct ip_linklocal_stat ip_linklocal_stat;
SYSCTL_STRUCT(_net_inet_ip_linklocal, OID_AUTO, stat,
CTLFLAG_RD | CTLFLAG_LOCKED, &ip_linklocal_stat, ip_linklocal_stat,
"Number of link local packets with TTL less than 255");
SYSCTL_NODE(_net_inet_ip_linklocal, OID_AUTO, in,
CTLFLAG_RW | CTLFLAG_LOCKED, 0, "link local input");
int ip_linklocal_in_allowbadttl = 1;
SYSCTL_INT(_net_inet_ip_linklocal_in, OID_AUTO, allowbadttl,
CTLFLAG_RW | CTLFLAG_LOCKED, &ip_linklocal_in_allowbadttl, 0,
"Allow incoming link local packets with TTL less than 255");
/*
* We need to save the IP options in case a protocol wants to respond
* to an incoming packet over the same route if the packet got here
* using IP source routing. This allows connection establishment and
* maintenance when the remote end is on a network that is not known
* to us.
*/
static int ip_nhops = 0;
static struct ip_srcrt {
struct in_addr dst; /* final destination */
char nop; /* one NOP to align */
char srcopt[IPOPT_OFFSET + 1]; /* OPTVAL, OLEN and OFFSET */
struct in_addr route[MAX_IPOPTLEN / sizeof(struct in_addr)];
} ip_srcrt;
static void in_ifaddrhashtbl_init(void);
static void save_rte(u_char *, struct in_addr);
static int ip_dooptions(struct mbuf *, int, struct sockaddr_in *);
static void ip_forward(struct mbuf *, int, struct sockaddr_in *);
static void frag_freef(struct ipqhead *, struct ipq *);
static struct mbuf *ip_reass(struct mbuf *);
static void ip_fwd_route_copyout(struct ifnet *, struct route *);
static void ip_fwd_route_copyin(struct ifnet *, struct route *);
static inline u_short ip_cksum(struct mbuf *, int);
int ip_use_randomid = 1;
SYSCTL_INT(_net_inet_ip, OID_AUTO, random_id, CTLFLAG_RW | CTLFLAG_LOCKED,
&ip_use_randomid, 0, "Randomize IP packets IDs");
/*
* On platforms which require strict alignment (currently for anything but
* i386 or x86_64), check if the IP header pointer is 32-bit aligned; if not,
* copy the contents of the mbuf chain into a new chain, and free the original
* one. Create some head room in the first mbuf of the new chain, in case
* it's needed later on.
*/
#if defined(__i386__) || defined(__x86_64__)
#define IP_HDR_ALIGNMENT_FIXUP(_m, _ifp, _action) do { } while (0)
#else /* !__i386__ && !__x86_64__ */
#define IP_HDR_ALIGNMENT_FIXUP(_m, _ifp, _action) do { \
if (!IP_HDR_ALIGNED_P(mtod(_m, caddr_t))) { \
struct mbuf *_n; \
struct ifnet *__ifp = (_ifp); \
atomic_add_64(&(__ifp)->if_alignerrs, 1); \
if (((_m)->m_flags & M_PKTHDR) && \
(_m)->m_pkthdr.pkt_hdr != NULL) \
(_m)->m_pkthdr.pkt_hdr = NULL; \
_n = m_defrag_offset(_m, max_linkhdr, M_NOWAIT); \
if (_n == NULL) { \
atomic_add_32(&ipstat.ips_toosmall, 1); \
m_freem(_m); \
(_m) = NULL; \
_action; \
} else { \
VERIFY(_n != (_m)); \
(_m) = _n; \
} \
} \
} while (0)
#endif /* !__i386__ && !__x86_64__ */
typedef enum ip_check_if_result {
IP_CHECK_IF_NONE = 0,
IP_CHECK_IF_OURS = 1,
IP_CHECK_IF_DROP = 2,
IP_CHECK_IF_FORWARD = 3
} ip_check_if_result_t;
static ip_check_if_result_t ip_input_check_interface(struct mbuf **, struct ip *, struct ifnet *);
/*
* GRE input handler function, settable via ip_gre_register_input() for PPTP.
*/
static gre_input_func_t gre_input_func;
static void
ip_init_delayed(void)
{
struct ifreq ifr;
int error;
struct sockaddr_in *sin;
bzero(&ifr, sizeof(ifr));
strlcpy(ifr.ifr_name, "lo0", sizeof(ifr.ifr_name));
sin = (struct sockaddr_in *)(void *)&ifr.ifr_addr;
sin->sin_len = sizeof(struct sockaddr_in);
sin->sin_family = AF_INET;
sin->sin_addr.s_addr = htonl(INADDR_LOOPBACK);
error = in_control(NULL, SIOCSIFADDR, (caddr_t)&ifr, lo_ifp, kernproc);
if (error) {
printf("%s: failed to initialise lo0's address, error=%d\n",
__func__, error);
}
}
/*
* IP initialization: fill in IP protocol switch table.
* All protocols not implemented in kernel go to raw IP protocol handler.
*/
void
ip_init(struct protosw *pp, struct domain *dp)
{
static int ip_initialized = 0;
struct protosw *pr;
struct timeval tv;
int i;
domain_proto_mtx_lock_assert_held();
VERIFY((pp->pr_flags & (PR_INITIALIZED | PR_ATTACHED)) == PR_ATTACHED);
/* ipq_alloc() uses mbufs for IP fragment queue structures */
_CASSERT(sizeof(struct ipq) <= _MLEN);
/*
* Some ioctls (e.g. SIOCAIFADDR) use ifaliasreq struct, which is
* interchangeable with in_aliasreq; they must have the same size.
*/
_CASSERT(sizeof(struct ifaliasreq) == sizeof(struct in_aliasreq));
if (ip_initialized) {
return;
}
ip_initialized = 1;
in_ifaddr_init();
in_ifaddr_rwlock_grp_attr = lck_grp_attr_alloc_init();
in_ifaddr_rwlock_grp = lck_grp_alloc_init("in_ifaddr_rwlock",
in_ifaddr_rwlock_grp_attr);
in_ifaddr_rwlock_attr = lck_attr_alloc_init();
lck_rw_init(in_ifaddr_rwlock, in_ifaddr_rwlock_grp,
in_ifaddr_rwlock_attr);
TAILQ_INIT(&in_ifaddrhead);
in_ifaddrhashtbl_init();
ip_moptions_init();
pr = pffindproto_locked(PF_INET, IPPROTO_RAW, SOCK_RAW);
if (pr == NULL) {
panic("%s: Unable to find [PF_INET,IPPROTO_RAW,SOCK_RAW]\n",
__func__);
/* NOTREACHED */
}
/* Initialize the entire ip_protox[] array to IPPROTO_RAW. */
for (i = 0; i < IPPROTO_MAX; i++) {
ip_protox[i] = pr;
}
/*
* Cycle through IP protocols and put them into the appropriate place
* in ip_protox[], skipping protocols IPPROTO_{IP,RAW}.
*/
VERIFY(dp == inetdomain && dp->dom_family == PF_INET);
TAILQ_FOREACH(pr, &dp->dom_protosw, pr_entry) {
VERIFY(pr->pr_domain == dp);
if (pr->pr_protocol != 0 && pr->pr_protocol != IPPROTO_RAW) {
/* Be careful to only index valid IP protocols. */
if (pr->pr_protocol < IPPROTO_MAX) {
ip_protox[pr->pr_protocol] = pr;
}
}
}
/* IP fragment reassembly queue lock */
ipqlock_grp_attr = lck_grp_attr_alloc_init();
ipqlock_grp = lck_grp_alloc_init("ipqlock", ipqlock_grp_attr);
ipqlock_attr = lck_attr_alloc_init();
lck_mtx_init(&ipqlock, ipqlock_grp, ipqlock_attr);
lck_mtx_lock(&ipqlock);
/* Initialize IP reassembly queue. */
for (i = 0; i < IPREASS_NHASH; i++) {
TAILQ_INIT(&ipq[i]);
}
maxnipq = nmbclusters / 32;
maxfragsperpacket = 128; /* enough for 64k in 512 byte fragments */
ipq_updateparams();
lck_mtx_unlock(&ipqlock);
getmicrotime(&tv);
ip_id = RandomULong() ^ tv.tv_usec;
ip_initid();
ipf_init();
PE_parse_boot_argn("ip_checkinterface", &i, sizeof(i));
switch (i) {
case IP_CHECKINTERFACE_WEAK_ES:
case IP_CHECKINTERFACE_HYBRID_ES:
case IP_CHECKINTERFACE_STRONG_ES:
ip_checkinterface = i;
break;
default:
break;
}
#if IPSEC
sadb_stat_mutex_grp_attr = lck_grp_attr_alloc_init();
sadb_stat_mutex_grp = lck_grp_alloc_init("sadb_stat",
sadb_stat_mutex_grp_attr);
sadb_stat_mutex_attr = lck_attr_alloc_init();
lck_mtx_init(sadb_stat_mutex, sadb_stat_mutex_grp,
sadb_stat_mutex_attr);
#endif
arp_init();
net_init_add(ip_init_delayed);
}
/*
* Initialize IPv4 source address hash table.
*/
static void
in_ifaddrhashtbl_init(void)
{
int i, k, p;
if (in_ifaddrhashtbl != NULL) {
return;
}
PE_parse_boot_argn("inaddr_nhash", &inaddr_nhash,
sizeof(inaddr_nhash));
if (inaddr_nhash == 0) {
inaddr_nhash = INADDR_NHASH;
}
MALLOC(in_ifaddrhashtbl, struct in_ifaddrhashhead *,
inaddr_nhash * sizeof(*in_ifaddrhashtbl),
M_IFADDR, M_WAITOK | M_ZERO);
if (in_ifaddrhashtbl == NULL) {
panic("in_ifaddrhashtbl_init allocation failed");
}
/*
* Generate the next largest prime greater than inaddr_nhash.
*/
k = (inaddr_nhash % 2 == 0) ? inaddr_nhash + 1 : inaddr_nhash + 2;
for (;;) {
p = 1;
for (i = 3; i * i <= k; i += 2) {
if (k % i == 0) {
p = 0;
}
}
if (p == 1) {
break;
}
k += 2;
}
inaddr_hashp = k;
}
u_int32_t
inaddr_hashval(u_int32_t key)
{
/*
* The hash index is the computed prime times the key modulo
* the hash size, as documented in "Introduction to Algorithms"
* (Cormen, Leiserson, Rivest).
*/
if (inaddr_nhash > 1) {
return (key * inaddr_hashp) % inaddr_nhash;
} else {
return 0;
}
}
__private_extern__ void
ip_proto_dispatch_in(struct mbuf *m, int hlen, u_int8_t proto,
ipfilter_t inject_ipfref)
{
struct ipfilter *filter;
int seen = (inject_ipfref == NULL);
int changed_header = 0;
struct ip *ip;
void (*pr_input)(struct mbuf *, int len);
if (!TAILQ_EMPTY(&ipv4_filters)) {
ipf_ref();
TAILQ_FOREACH(filter, &ipv4_filters, ipf_link) {
if (seen == 0) {
if ((struct ipfilter *)inject_ipfref == filter) {
seen = 1;
}
} else if (filter->ipf_filter.ipf_input) {
errno_t result;
if (changed_header == 0) {
/*
* Perform IP header alignment fixup,
* if needed, before passing packet
* into filter(s).
*/
IP_HDR_ALIGNMENT_FIXUP(m,
m->m_pkthdr.rcvif, ipf_unref());
/* ipf_unref() already called */
if (m == NULL) {
return;
}
changed_header = 1;
ip = mtod(m, struct ip *);
ip->ip_len = htons(ip->ip_len + hlen);
ip->ip_off = htons(ip->ip_off);
ip->ip_sum = 0;
ip->ip_sum = ip_cksum_hdr_in(m, hlen);
}
result = filter->ipf_filter.ipf_input(
filter->ipf_filter.cookie, (mbuf_t *)&m,
hlen, proto);
if (result == EJUSTRETURN) {
ipf_unref();
return;
}
if (result != 0) {
ipf_unref();
m_freem(m);
return;
}
}
}
ipf_unref();
}
/* Perform IP header alignment fixup (post-filters), if needed */
IP_HDR_ALIGNMENT_FIXUP(m, m->m_pkthdr.rcvif, return );
ip = mtod(m, struct ip *);
if (changed_header) {
ip->ip_len = ntohs(ip->ip_len) - hlen;
ip->ip_off = ntohs(ip->ip_off);
}
/*
* If there isn't a specific lock for the protocol
* we're about to call, use the generic lock for AF_INET.
* otherwise let the protocol deal with its own locking
*/
if ((pr_input = ip_protox[ip->ip_p]->pr_input) == NULL) {
m_freem(m);
} else if (!(ip_protox[ip->ip_p]->pr_flags & PR_PROTOLOCK)) {
lck_mtx_lock(inet_domain_mutex);
pr_input(m, hlen);
lck_mtx_unlock(inet_domain_mutex);
} else {
pr_input(m, hlen);
}
}
struct pktchain_elm {
struct mbuf *pkte_head;
struct mbuf *pkte_tail;
struct in_addr pkte_saddr;
struct in_addr pkte_daddr;
uint16_t pkte_npkts;
uint16_t pkte_proto;
uint32_t pkte_nbytes;
};
typedef struct pktchain_elm pktchain_elm_t;
/* Store upto PKTTBL_SZ unique flows on the stack */
#define PKTTBL_SZ 7
static struct mbuf *
ip_chain_insert(struct mbuf *packet, pktchain_elm_t *tbl)
{
struct ip* ip;
int pkttbl_idx = 0;
ip = mtod(packet, struct ip*);
/* reusing the hash function from inaddr_hashval */
pkttbl_idx = inaddr_hashval(ntohs(ip->ip_src.s_addr)) % PKTTBL_SZ;
if (tbl[pkttbl_idx].pkte_head == NULL) {
tbl[pkttbl_idx].pkte_head = packet;
tbl[pkttbl_idx].pkte_saddr.s_addr = ip->ip_src.s_addr;
tbl[pkttbl_idx].pkte_daddr.s_addr = ip->ip_dst.s_addr;
tbl[pkttbl_idx].pkte_proto = ip->ip_p;
} else {
if ((ip->ip_dst.s_addr == tbl[pkttbl_idx].pkte_daddr.s_addr) &&
(ip->ip_src.s_addr == tbl[pkttbl_idx].pkte_saddr.s_addr) &&
(ip->ip_p == tbl[pkttbl_idx].pkte_proto)) {
} else {
return packet;
}
}
if (tbl[pkttbl_idx].pkte_tail != NULL) {
mbuf_setnextpkt(tbl[pkttbl_idx].pkte_tail, packet);
}
tbl[pkttbl_idx].pkte_tail = packet;
tbl[pkttbl_idx].pkte_npkts += 1;
tbl[pkttbl_idx].pkte_nbytes += packet->m_pkthdr.len;
return NULL;
}
/* args is a dummy variable here for backward compatibility */
static void
ip_input_second_pass_loop_tbl(pktchain_elm_t *tbl, struct ip_fw_in_args *args)
{
int i = 0;
for (i = 0; i < PKTTBL_SZ; i++) {
if (tbl[i].pkte_head != NULL) {
struct mbuf *m = tbl[i].pkte_head;
ip_input_second_pass(m, m->m_pkthdr.rcvif,
tbl[i].pkte_npkts, tbl[i].pkte_nbytes, args);
if (tbl[i].pkte_npkts > 2) {
ipstat.ips_rxc_chainsz_gt2++;
}
if (tbl[i].pkte_npkts > 4) {
ipstat.ips_rxc_chainsz_gt4++;
}
#if (DEBUG || DEVELOPMENT)
if (ip_input_measure) {
net_perf_histogram(&net_perf, tbl[i].pkte_npkts);
}
#endif /* (DEBUG || DEVELOPMENT) */
tbl[i].pkte_head = tbl[i].pkte_tail = NULL;
tbl[i].pkte_npkts = 0;
tbl[i].pkte_nbytes = 0;
/* no need to initialize address and protocol in tbl */
}
}
}
static void
ip_input_cpout_args(struct ip_fw_in_args *args, struct ip_fw_args *args1,
boolean_t *done_init)
{
if (*done_init == FALSE) {
bzero(args1, sizeof(struct ip_fw_args));
*done_init = TRUE;
}
args1->fwa_pf_rule = args->fwai_pf_rule;
}
static void
ip_input_cpin_args(struct ip_fw_args *args1, struct ip_fw_in_args *args)
{
args->fwai_pf_rule = args1->fwa_pf_rule;
}
typedef enum {
IPINPUT_DOCHAIN = 0,
IPINPUT_DONTCHAIN,
IPINPUT_FREED,
IPINPUT_DONE
} ipinput_chain_ret_t;
static void
ip_input_update_nstat(struct ifnet *ifp, struct in_addr src_ip,
u_int32_t packets, u_int32_t bytes)
{
if (nstat_collect) {
struct rtentry *rt = ifnet_cached_rtlookup_inet(ifp,
src_ip);
if (rt != NULL) {
nstat_route_rx(rt, packets, bytes, 0);
rtfree(rt);
}
}
}
static void
ip_input_dispatch_chain(struct mbuf *m)
{
struct mbuf *tmp_mbuf = m;
struct mbuf *nxt_mbuf = NULL;
struct ip *ip = NULL;
unsigned int hlen;
ip = mtod(tmp_mbuf, struct ip *);
hlen = IP_VHL_HL(ip->ip_vhl) << 2;
while (tmp_mbuf != NULL) {
nxt_mbuf = mbuf_nextpkt(tmp_mbuf);
mbuf_setnextpkt(tmp_mbuf, NULL);
ip_proto_dispatch_in(tmp_mbuf, hlen, ip->ip_p, 0);
tmp_mbuf = nxt_mbuf;
if (tmp_mbuf) {
ip = mtod(tmp_mbuf, struct ip *);
/* first mbuf of chain already has adjusted ip_len */
hlen = IP_VHL_HL(ip->ip_vhl) << 2;
ip->ip_len -= hlen;
}
}
}
static void
ip_input_setdst_chain(struct mbuf *m, uint32_t ifindex, struct in_ifaddr *ia)
{
struct mbuf *tmp_mbuf = m;
while (tmp_mbuf != NULL) {
ip_setdstifaddr_info(tmp_mbuf, ifindex, ia);
tmp_mbuf = mbuf_nextpkt(tmp_mbuf);
}
}
static void
ip_input_adjust(struct mbuf *m, struct ip *ip, struct ifnet *inifp)
{
boolean_t adjust = TRUE;
ASSERT(m_pktlen(m) > ip->ip_len);
/*
* Invalidate hardware checksum info if ip_adj_clear_hwcksum
* is set; useful to handle buggy drivers. Note that this
* should not be enabled by default, as we may get here due
* to link-layer padding.
*/
if (ip_adj_clear_hwcksum &&
(m->m_pkthdr.csum_flags & CSUM_DATA_VALID) &&
!(inifp->if_flags & IFF_LOOPBACK) &&
!(m->m_pkthdr.pkt_flags & PKTF_LOOP)) {
m->m_pkthdr.csum_flags &= ~CSUM_DATA_VALID;
m->m_pkthdr.csum_data = 0;
ipstat.ips_adj_hwcsum_clr++;
}
/*
* If partial checksum information is available, subtract
* out the partial sum of postpended extraneous bytes, and
* update the checksum metadata accordingly. By doing it
* here, the upper layer transport only needs to adjust any
* prepended extraneous bytes (else it will do both.)
*/
if (ip_adj_partial_sum &&
(m->m_pkthdr.csum_flags & (CSUM_DATA_VALID | CSUM_PARTIAL)) ==
(CSUM_DATA_VALID | CSUM_PARTIAL)) {
m->m_pkthdr.csum_rx_val = m_adj_sum16(m,
m->m_pkthdr.csum_rx_start, m->m_pkthdr.csum_rx_start,
(ip->ip_len - m->m_pkthdr.csum_rx_start),
m->m_pkthdr.csum_rx_val);
} else if ((m->m_pkthdr.csum_flags &
(CSUM_DATA_VALID | CSUM_PARTIAL)) ==
(CSUM_DATA_VALID | CSUM_PARTIAL)) {
/*
* If packet has partial checksum info and we decided not
* to subtract the partial sum of postpended extraneous
* bytes here (not the default case), leave that work to
* be handled by the other layers. For now, only TCP, UDP
* layers are capable of dealing with this. For all other
* protocols (including fragments), trim and ditch the
* partial sum as those layers might not implement partial
* checksumming (or adjustment) at all.
*/
if ((ip->ip_off & (IP_MF | IP_OFFMASK)) == 0 &&
(ip->ip_p == IPPROTO_TCP || ip->ip_p == IPPROTO_UDP)) {
adjust = FALSE;
} else {
m->m_pkthdr.csum_flags &= ~CSUM_DATA_VALID;
m->m_pkthdr.csum_data = 0;
ipstat.ips_adj_hwcsum_clr++;
}
}
if (adjust) {
ipstat.ips_adj++;
if (m->m_len == m->m_pkthdr.len) {
m->m_len = ip->ip_len;
m->m_pkthdr.len = ip->ip_len;
} else {
m_adj(m, ip->ip_len - m->m_pkthdr.len);
}
}
}
/*
* First pass does all essential packet validation and places on a per flow
* queue for doing operations that have same outcome for all packets of a flow.
*/
static ipinput_chain_ret_t
ip_input_first_pass(struct mbuf *m, struct ip_fw_in_args *args, struct mbuf **modm)
{
struct ip *ip;
struct ifnet *inifp;
unsigned int hlen;
int retval = IPINPUT_DOCHAIN;
int len = 0;
struct in_addr src_ip;
#if DUMMYNET
struct m_tag *copy;
struct m_tag *p;
boolean_t delete = FALSE;
struct ip_fw_args args1;
boolean_t init = FALSE;
#endif /* DUMMYNET */
ipfilter_t inject_filter_ref = NULL;
/* Check if the mbuf is still valid after interface filter processing */
MBUF_INPUT_CHECK(m, m->m_pkthdr.rcvif);
inifp = mbuf_pkthdr_rcvif(m);
VERIFY(inifp != NULL);
/* Perform IP header alignment fixup, if needed */
IP_HDR_ALIGNMENT_FIXUP(m, inifp, goto bad);
m->m_pkthdr.pkt_flags &= ~PKTF_FORWARDED;
#if DUMMYNET
/*
* Don't bother searching for tag(s) if there's none.
*/
if (SLIST_EMPTY(&m->m_pkthdr.tags)) {
goto ipfw_tags_done;
}
/* Grab info from mtags prepended to the chain */
p = m_tag_first(m);