This repository has been archived by the owner on Jan 30, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 11
/
ip.c
1536 lines (1328 loc) · 55.3 KB
/
ip.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
/*
* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
*
* http://www.ntop.org
*
* Copyright (C) 1998-2012 Luca Deri <[email protected]>
*
* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#include "ntop.h"
/* ***************************************** */
static u_char ethBroadcast[] = { 255, 255, 255, 255, 255, 255 };
/* ***************************************** */
/* *****************************************
*
* Fragment handling code courtesy of
* Andreas Pfaller <[email protected]>
*
* NOTE:
* the code below has a small (neglictable) limitation
* as described below.
*
* Subject: ntop 1.3.2: Fragment handling
* Date: Mon, 7 Aug 2000 16:05:45 +0200
* From: [email protected] (Andreas Pfaller)
* To: [email protected] (Luca Deri)
*
* I have also had a look at the code you added to handle
* overlapping fragments. It again assumes specific package
* ordering (either 1,2,..,n or n,n-1,..,1) which the IP protocol
* does not guarantee. The above assumptions are probably true
* for most users but in some setups they are nearly never true.
* Consider two host connected by multiple network cards
*
* e.g.:
* +--------+ eth0 eth0 +--------+
* | |-------------------| |
* | HOST A | | HOST B |
* | |-------------------| |
* +--------+ eth1 eth1 +--------+
*
* which distribute traffic on this interfaces to achive better
* throughput (Called bonding in Linux, Etherchannel by Cisco or
* trunking by Sun). A simple algorithm simple uses the interfaces
* in a cyclic way. Since packets are not always the same length
* or the interfaces my have different speeds more complicated
* ones use other methods to try to achive maximum throughput.
* In such an environment you have very high probability for
* out of order packets.
*
* ***************************************** */
#ifdef FRAGMENT_DEBUG
static void dumpFragmentData(IpFragment *fragment) {
printf("FRAGMENT_DEBUG: IPFragment: (%p)\n", fragment);
printf(" %s:%d->%s:%d\n",
fragment->src->hostResolvedName, fragment->sport,
fragment->dest->hostResolvedName, fragment->dport);
printf(" FragmentId=%d\n", fragment->fragmentId);
printf(" lastOffset=%d, totalPacketLength=%d\n",
fragment->lastOffset, fragment->totalPacketLength);
printf(" totalDataLength=%d, expectedDataLength=%d\n",
fragment->totalDataLength, fragment->expectedDataLength);
fflush(stdout);
}
#endif
/* ************************************ */
static IpFragment *searchFragment(HostTraffic *srcHost,
HostTraffic *dstHost,
u_int fragmentId,
int actualDeviceId) {
IpFragment *fragment = myGlobals.device[actualDeviceId].fragmentList;
while ((fragment != NULL)
&& ((fragment->src != srcHost)
|| (fragment->dest != dstHost)
|| (fragment->fragmentId != fragmentId)))
fragment = fragment->next;
return(fragment);
}
/* ************************************ */
void deleteFragment(IpFragment *fragment, int actualDeviceId) {
if(fragment->prev == NULL)
myGlobals.device[actualDeviceId].fragmentList = fragment->next;
else
fragment->prev->next = fragment->next;
free(fragment);
myGlobals.num_queued_fragments--;
}
/* ************************************ */
/* Courtesy of Andreas Pfaller <[email protected]> */
static void checkFragmentOverlap(HostTraffic *srcHost,
HostTraffic *dstHost,
IpFragment *fragment,
u_int fragmentOffset,
u_int dataLength,
int actualDeviceId,
const struct pcap_pkthdr *h, const u_char *p) {
if(fragment->fragmentOrder == FLAG_UNKNOWN_FRAGMENT_ORDER) {
if(fragment->lastOffset > fragmentOffset)
fragment->fragmentOrder = FLAG_DECREASING_FRAGMENT_ORDER;
else
fragment->fragmentOrder = FLAG_INCREASING_FRAGMENT_ORDER;
}
if((fragment->fragmentOrder == FLAG_INCREASING_FRAGMENT_ORDER
&& fragment->lastOffset+fragment->lastDataLength > fragmentOffset)
||
(fragment->fragmentOrder == FLAG_DECREASING_FRAGMENT_ORDER
&& fragment->lastOffset < fragmentOffset+dataLength)) {
if(myGlobals.runningPref.enableSuspiciousPacketDump) {
char buf[LEN_GENERAL_WORK_BUFFER];
safe_snprintf(__FILE__, __LINE__, buf, LEN_GENERAL_WORK_BUFFER,
"Detected overlapping packet fragment [%s->%s]: "
"fragment id=%d, actual offset=%d, previous offset=%d\n",
fragment->src->hostResolvedName,
fragment->dest->hostResolvedName,
fragment->fragmentId, fragmentOffset,
fragment->lastOffset);
dumpSuspiciousPacket(actualDeviceId, h, p);
}
allocateSecurityHostPkts(fragment->src); allocateSecurityHostPkts(fragment->dest);
incrementUsageCounter(&fragment->src->secHostPkts->overlappingFragmentSent,
dstHost, actualDeviceId);
incrementUsageCounter(&fragment->dest->secHostPkts->overlappingFragmentRcvd,
srcHost, actualDeviceId);
incrementTrafficCounter(&myGlobals.device[actualDeviceId].securityPkts.overlappingFragment, 1);
}
}
/* ************************************ */
static u_int handleFragment(HostTraffic *srcHost,
HostTraffic *dstHost,
u_short *sport,
u_short *dport,
u_int fragmentId,
u_int off,
u_int packetLength,
u_int dataLength,
int actualDeviceId,
const struct pcap_pkthdr *h, const u_char *p) {
IpFragment *fragment;
u_int fragmentOffset, length;
if(!myGlobals.enableFragmentHandling)
return(0);
accessMutex(&myGlobals.fragmentMutex, "handleFragment");
fragmentOffset = (off & 0x1FFF)*8;
fragment = searchFragment(srcHost, dstHost, fragmentId, actualDeviceId);
if(fragment == NULL) {
/* new fragment */
fragment = (IpFragment*)calloc(1, sizeof(IpFragment));
if(fragment == NULL) return(0); /* out of memory, not much we can do */
memset(fragment, 0, sizeof(IpFragment));
fragment->src = srcHost, fragment->dest = dstHost;
fragment->fragmentId = fragmentId, fragment->firstSeen = myGlobals.actTime;
fragment->fragmentOrder = FLAG_UNKNOWN_FRAGMENT_ORDER;
fragment->next = myGlobals.device[actualDeviceId].fragmentList, fragment->prev = NULL;
if(fragment->next) fragment->next->prev = fragment;
myGlobals.device[actualDeviceId].fragmentList = fragment;
myGlobals.num_queued_fragments++;
} else
checkFragmentOverlap(srcHost, dstHost, fragment,
fragmentOffset, dataLength,
actualDeviceId, h, p);
fragment->lastOffset = fragmentOffset;
fragment->totalPacketLength += packetLength;
fragment->totalDataLength += dataLength;
fragment->lastDataLength = dataLength;
if(fragmentOffset == 0) {
/* first fragment contains port numbers */
fragment->sport = *sport;
fragment->dport = *dport;
} else if(!(off & IP_MF)) /* last fragment->we know the total data size */
fragment->expectedDataLength = fragmentOffset+dataLength;
#ifdef FRAGMENT_DEBUG
dumpFragmentData(fragment);
#endif
/* Now check if we have all the data needed for the statistics */
if((fragment->sport != 0) && (fragment->dport != 0) /* first fragment rcvd */
/* last fragment rcvd */
&& (fragment->expectedDataLength != 0)
/* probably all fragments rcvd */
&& (fragment->totalDataLength >= fragment->expectedDataLength)) {
*sport = fragment->sport;
*dport = fragment->dport;
length = fragment->totalPacketLength;
deleteFragment(fragment, actualDeviceId);
} else {
*sport = 0;
*dport = 0;
length = 0;
}
releaseMutex(&myGlobals.fragmentMutex);
return length;
}
/* ************************************ */
void purgeOldFragmentEntries(int actualDeviceId) {
IpFragment *fragment, *next;
#ifdef FRAGMENT_DEBUG
u_int fragcnt=0, expcnt=0;
#endif
accessMutex(&myGlobals.fragmentMutex, "purgeOldFragmentEntries");
fragment = myGlobals.device[actualDeviceId].fragmentList;
while(fragment != NULL) {
#ifdef FRAGMENT_DEBUG
fragcnt++;
#endif
next = fragment->next;
if((fragment->firstSeen + 30 /* sec */) < myGlobals.actTime) {
#ifdef FRAGMENT_DEBUG
expcnt++;
dumpFragmentData(fragment);
#endif
if(fragment->prev) fragment->prev = next;
if(next) next->prev = fragment->prev;
deleteFragment(fragment, actualDeviceId);
}
fragment = next;
}
releaseMutex(&myGlobals.fragmentMutex);
#ifdef FRAGMENT_DEBUG
if(fragcnt) {
printf("FRAGMENT_DEBUG: fragcnt=%d, expcnt=%d\n", fragcnt, expcnt);
fflush(stdout);
}
#endif
}
/* ************************************ */
/*
Fingerprint code courtesy of ettercap
http://ettercap.sourceforge.net
*/
static u_char TTL_PREDICTOR(u_char x) /* coded by awgn <[email protected]> */
{ /* round the TTL to the nearest power of 2 (ceiling) */
register u_char i = x;
register u_char j = 1;
register u_char c = 0;
do {
c += i & 1;
j <<= 1;
} while ( i >>= 1 );
if( c == 1 )
return x;
else
return ( j ? j : 0xff );
}
/* ************************************ */
static void updateRoutedTraffic(HostTraffic *router, Counter bytes) {
if(router != NULL) {
if(router->routedTraffic == NULL) {
int mallocLen = sizeof(RoutingCounter);
router->routedTraffic = (RoutingCounter*)malloc(mallocLen);
if(router->routedTraffic == NULL) return;
memset(router->routedTraffic, 0, mallocLen);
}
if(router->routedTraffic != NULL) { /* malloc() didn't fail */
incrementTrafficCounter(&router->routedTraffic->routedPkts, 1);
incrementTrafficCounter(&router->routedTraffic->routedBytes, bytes);
}
}
}
/* ************************************ */
static void updateDevicePacketTTLStats(u_int ttl, int actualDeviceId) {
if(ttl <= 32) incrementTrafficCounter(&myGlobals.device[actualDeviceId].rcvdPktTTLStats.upTo32, 1);
else if(ttl <= 64) incrementTrafficCounter(&myGlobals.device[actualDeviceId].rcvdPktTTLStats.upTo64, 1);
else if(ttl <= 96) incrementTrafficCounter(&myGlobals.device[actualDeviceId].rcvdPktTTLStats.upTo96, 1);
else if(ttl <= 128) incrementTrafficCounter(&myGlobals.device[actualDeviceId].rcvdPktTTLStats.upTo128, 1);
else if(ttl <= 160) incrementTrafficCounter(&myGlobals.device[actualDeviceId].rcvdPktTTLStats.upTo160, 1);
else if(ttl <= 192) incrementTrafficCounter(&myGlobals.device[actualDeviceId].rcvdPktTTLStats.upTo192, 1);
else if(ttl <= 224) incrementTrafficCounter(&myGlobals.device[actualDeviceId].rcvdPktTTLStats.upTo224, 1);
else incrementTrafficCounter(&myGlobals.device[actualDeviceId].rcvdPktTTLStats.upTo255, 1);
}
/* ************************************ */
static void checkNetworkRouter(HostTraffic *srcHost, HostTraffic *dstHost,
u_char *ether_dst, int actualDeviceId,
Counter bytes,
const struct pcap_pkthdr *h, const u_char *p) {
if(ether_dst == NULL) return;
if((subnetLocalHost(srcHost) && (!subnetLocalHost(dstHost))
&& (!broadcastHost(dstHost)) && (!multicastHost(dstHost)))
|| (subnetLocalHost(dstHost) && (!subnetLocalHost(srcHost))
&& (!broadcastHost(srcHost)) && (!multicastHost(srcHost)))) {
HostTraffic *router = lookupHost(NULL, ether_dst, srcHost->vlanId, 0, 0, actualDeviceId, h, p);
if(router == NULL) return;
if(((router->hostNumIpAddress[0] != '\0')
&& (broadcastHost(router)
|| multicastHost(router)
|| (!subnetLocalHost(router)) /* No IP: is this a special Multicast address ? */))
|| (addrcmp(&router->hostIpAddress,&dstHost->hostIpAddress) == 0)
|| (memcmp(router->ethAddress, dstHost->ethAddress, LEN_ETHERNET_ADDRESS) == 0)
)
return;
#ifdef DEBUG
traceEvent(CONST_TRACE_INFO, "(%s/%s/%s) -> (%s/%s/%s) routed by [%s/%s/%s]",
srcHost->ethAddressString, srcHost->hostNumIpAddress, srcHost->hostResolvedName,
dstHost->ethAddressString, dstHost->hostNumIpAddress, dstHost->hostResolvedName,
router->ethAddressString,
router->hostNumIpAddress,
router->hostResolvedName);
#endif
setHostFlag(FLAG_GATEWAY_HOST, router);
updateRoutedTraffic(router, bytes);
}
}
/* ************************************ */
void processIpPkt(const u_char *bp, /* Pointer to IP */
const struct pcap_pkthdr *h,
const u_char *p, /* Original packet */
u_int ip_offset, u_int length,
u_char *ether_src,
u_char *ether_dst,
int actualDeviceId,
int vlanId) {
u_short sport=0, dport=0;
struct ip ip;
struct ip6_hdr *ip6;
struct icmp6_hdr icmp6Pkt;
u_int advance = 0;
u_char *cp = NULL;
u_char *snapend = NULL;
u_int icmp6len = 0;
u_int nh;
int fragmented = 0;
struct tcphdr tp;
struct udphdr up;
struct icmp icmpPkt;
u_int hlen, ip_len, tcpDataLength, udpDataLength, off=0, tcpUdpLen, idx;
HostTraffic *srcHost=NULL, *dstHost=NULL;
HostAddr srcAddr, dstAddr; /* Protocol Independent addresses */
u_char forceUsingIPaddress = 0;
struct timeval tvstrct;
u_char *theData, found = 0;
TrafficCounter ctr;
ProtocolsList *protoList;
u_short newSession = 0;
u_short nonFullyRemoteSession = 1;
/* Need to copy this over in case bp isn't properly aligned.
* This occurs on SunOS 4.x at least.
*
* Paul D. Smith <[email protected]>
*/
memcpy(&ip, bp, sizeof(struct ip));
/* TODO: isipv6 = (ip.ip_v == 6)?1:0; */
if(ip.ip_v == 6) {
/* handle IPv6 packets */
ip6 = (struct ip6_hdr *)bp;
} else
ip6 = NULL;
if(ip6)
hlen = sizeof(struct ip6_hdr);
else
hlen = (u_int)ip.ip_hl * 4;
incrementTrafficCounter(&myGlobals.device[actualDeviceId].ipPkts, 1);
/*
Fix below courtesy of Christian Hammers <[email protected]>
*/
if(ip6)
incrementTrafficCounter(&myGlobals.device[actualDeviceId].ipv6Bytes, length /* ntohs(ip.ip_len) */);
else
incrementTrafficCounter(&myGlobals.device[actualDeviceId].ipv4Bytes, length /* ntohs(ip.ip_len) */);
if(ip6 == NULL) {
if(ip.ip_p == CONST_GRE_PROTOCOL_TYPE) {
/*
Cisco GRE (Generic Routing Encapsulation) Tunnels (RFC 1701, 1702)
*/
GreTunnel tunnel;
PPPTunnelHeader pppTHeader;
memcpy(&tunnel, bp+hlen, sizeof(GreTunnel));
switch(ntohs(tunnel.protocol)) {
case CONST_PPP_PROTOCOL_TYPE:
memcpy(&pppTHeader, bp+hlen+sizeof(GreTunnel), sizeof(PPPTunnelHeader));
if(ntohs(pppTHeader.protocol) == 0x21 /* IP */) {
memcpy(&ip, bp+hlen+sizeof(GreTunnel)+sizeof(PPPTunnelHeader), sizeof(struct ip));
hlen = (u_int)ip.ip_hl * 4;
ether_src = NULL, ether_dst = NULL;
}
break;
case ETHERTYPE_IP:
memcpy(&ip, bp+hlen+4 /* 4 is the size of the GRE header */, sizeof(struct ip));
hlen = (u_int)ip.ip_hl * 4;
ether_src = NULL, ether_dst = NULL;
break;
}
}
}
if((ether_src == NULL) && (ether_dst == NULL)) {
/* Ethernet-less protocols (e.g. PPP/RAW IP) */
forceUsingIPaddress = 1;
}
if(ip6) {
addrput(AF_INET6, &srcAddr, &ip6->ip6_src);
addrput(AF_INET6, &dstAddr, &ip6->ip6_dst);
} else {
NTOHL(ip.ip_dst.s_addr); NTOHL(ip.ip_src.s_addr);
addrput(AF_INET, &srcAddr,&ip.ip_src.s_addr);
addrput(AF_INET, &dstAddr,&ip.ip_dst.s_addr);
}
if(ip6 == NULL) {
if(isBroadcastAddress(&dstAddr, NULL, NULL)
&& (ether_src != NULL) && (ether_dst != NULL) /* PPP has no ethernet */
&& (memcmp(ether_dst, ethBroadcast, 6) != 0)) {
/* forceUsingIPaddress = 1; */
srcHost = lookupHost(NULL, ether_src, vlanId, 0, 0, actualDeviceId, h, p);
if(srcHost != NULL) {
if(vlanId != NO_VLAN) srcHost->vlanId = vlanId;
if(myGlobals.runningPref.enableSuspiciousPacketDump && (!hasWrongNetmask(srcHost))) {
/* Dump the first packet only */
char etherbuf[LEN_ETHERNET_ADDRESS_DISPLAY];
traceEvent(CONST_TRACE_WARNING, "Host %s has a wrong netmask",
etheraddr_string(ether_src, etherbuf));
dumpSuspiciousPacket(actualDeviceId, h, p);
}
setHostFlag(FLAG_HOST_WRONG_NETMASK, srcHost);
}
}
}
/*
IMPORTANT:
do NOT change the order of the lines below (see isBroadcastAddress call)
*/
dstHost = lookupHost(&dstAddr, ether_dst, vlanId, 1 , 0, actualDeviceId, h, p);
if(dstHost == NULL) {
/* Sanity check */
lowMemory();
return;
}
srcHost = lookupHost(&srcAddr, ether_src, vlanId,
/*
Don't check for multihoming when
the destination address is a broadcast address
*/
(!isBroadcastAddress(&dstAddr, NULL, NULL)),
forceUsingIPaddress, actualDeviceId, h, p);
if(srcHost == NULL) {
/* Sanity check */
lowMemory();
return; /* It might be that there's not enough memory that that
dstHost = lookupHost(&ip.ip_dst, ether_dst) caused
srcHost to be freed */
}
if(vlanId != NO_VLAN) { srcHost->vlanId = vlanId; dstHost->vlanId = vlanId; }
#ifdef DEBUG
if(myGlobals.runningPref.rFileName != NULL) {
static int numPkt=1;
traceEvent(CONST_TRACE_INFO, "%d) %s -> %s",
numPkt++,
srcHost->hostNumIpAddress,
dstHost->hostNumIpAddress);
fflush(stdout);
}
#endif
/* ****************** */
if(ip6) {
updateDevicePacketTTLStats(ip6->ip6_hlim, actualDeviceId);
if(ip6->ip6_hlim != 255) {
if((srcHost->minTTL == 0) || (ip6->ip6_hlim < srcHost->minTTL)) srcHost->minTTL = ip6->ip6_hlim;
if((ip6->ip6_hlim > srcHost->maxTTL)) srcHost->maxTTL = ip6->ip6_hlim;
}
} else {
updateDevicePacketTTLStats(ip.ip_ttl, actualDeviceId);
if(ip.ip_ttl != 255) {
/*
TTL can be calculated only when the packet
is originated by the sender
*/
if((srcHost->minTTL == 0) || (ip.ip_ttl < srcHost->minTTL)) srcHost->minTTL = ip.ip_ttl;
if((ip.ip_ttl > srcHost->maxTTL)) srcHost->maxTTL = ip.ip_ttl;
}
}
ctr.value = h->len;
updatePacketCount(srcHost, dstHost, ctr, 1, actualDeviceId);
if(!myGlobals.device[actualDeviceId].dummyDevice) {
checkNetworkRouter(srcHost, dstHost, ether_dst, actualDeviceId, length, h, p);
ctr.value = length;
}
if(ip6) {
incrementHostTrafficCounter(srcHost, ipv6BytesSent, length);
incrementHostTrafficCounter(dstHost, ipv6BytesRcvd, length);
} else {
incrementHostTrafficCounter(srcHost, ipv4BytesSent, length);
incrementHostTrafficCounter(dstHost, ipv4BytesRcvd, length);
}
if(subnetPseudoLocalHost(srcHost)) {
if(subnetPseudoLocalHost(dstHost)) {
incrementHostTrafficCounter(srcHost, bytesSentLoc, length);
incrementHostTrafficCounter(dstHost, bytesRcvdLoc, length);
} else {
incrementHostTrafficCounter(srcHost, bytesSentRem, length);
incrementHostTrafficCounter(dstHost, bytesRcvdLoc, length);
}
} else {
/* srcHost is remote */
if(subnetPseudoLocalHost(dstHost)) {
incrementHostTrafficCounter(srcHost, bytesSentLoc, length);
incrementHostTrafficCounter(dstHost, bytesRcvdFromRem, length);
} else {
incrementHostTrafficCounter(srcHost, bytesSentRem, length);
incrementHostTrafficCounter(dstHost, bytesRcvdFromRem, length);
}
}
if(ip6) {
if(ip6->ip6_nxt == IPPROTO_FRAGMENT) {
fragmented = 1;
nh = ip6->ip6_nxt;
}
} else {
off = ntohs(ip.ip_off);
if(off & 0x3fff) {
fragmented = 1;
nh = ip.ip_p;
}
}
/*
This is a fragment: fragment handling is handled by handleFragment()
called below.
Courtesy of Andreas Pfaller
*/
if(fragmented) {
incrementTrafficCounter(&myGlobals.device[actualDeviceId].fragmentedIpBytes, length);
switch(nh) {
case IPPROTO_TCP:
incrementHostTrafficCounter(srcHost, tcpFragmentsSent, length);
incrementHostTrafficCounter(dstHost, tcpFragmentsRcvd, length);
break;
case IPPROTO_UDP:
incrementHostTrafficCounter(srcHost, udpFragmentsSent, length);
incrementHostTrafficCounter(dstHost, udpFragmentsRcvd, length);
break;
case IPPROTO_ICMP:
incrementHostTrafficCounter(srcHost, icmpFragmentsSent, length);
incrementHostTrafficCounter(dstHost, icmpFragmentsRcvd, length);
break;
case IPPROTO_GRE:
incrementHostTrafficCounter(srcHost, greSent, length);
incrementHostTrafficCounter(dstHost, greRcvd, length);
incrementTrafficCounter(&myGlobals.device[actualDeviceId].greBytes, length);
break;
case IPPROTO_IPSEC_ESP:
case IPPROTO_IPSEC_AH:
incrementHostTrafficCounter(srcHost, ipsecSent, length);
incrementHostTrafficCounter(dstHost, ipsecRcvd, length);
incrementTrafficCounter(&myGlobals.device[actualDeviceId].ipsecBytes, length);
break;
case IPPROTO_ICMPV6:
incrementHostTrafficCounter(srcHost, icmp6FragmentsSent, length);
incrementHostTrafficCounter(dstHost, icmp6FragmentsRcvd, length);
break;
}
}
if(ip6) {
advance = sizeof(struct ip6_hdr);
cp = (unsigned char *) ip6;
snapend = (unsigned char *)(bp+length);
nh = ip6->ip6_nxt;
ip_len = ntohs(ip6->ip6_plen);
tcpUdpLen = ip_len;
} else {
nh = ip.ip_p;
ip_len = ntohs(ip.ip_len);
tcpUdpLen = ip_len - hlen;
}
loop:
if(ip6)
cp +=advance;
switch(nh) {
case IPPROTO_FRAGMENT:
if(ip6) {
advance = sizeof(struct ip6_frag);
if(snapend <= cp+advance) goto end;
nh = *cp;
goto loop;
}
/* If it's no IPv6 we continue */
case IPPROTO_TCP:
incrementTrafficCounter(&myGlobals.device[actualDeviceId].tcpBytes, length);
if(tcpUdpLen < sizeof(struct tcphdr)) {
if(myGlobals.runningPref.enableSuspiciousPacketDump) {
traceEvent(CONST_TRACE_WARNING, "Malformed TCP pkt %s->%s detected (packet too short)",
srcHost->hostResolvedName,
dstHost->hostResolvedName);
dumpSuspiciousPacket(actualDeviceId, h, p);
allocateSecurityHostPkts(srcHost); allocateSecurityHostPkts(dstHost);
incrementUsageCounter(&srcHost->secHostPkts->malformedPktsSent, dstHost, actualDeviceId);
incrementUsageCounter(&dstHost->secHostPkts->malformedPktsRcvd, srcHost, actualDeviceId);
incrementTrafficCounter(&myGlobals.device[actualDeviceId].securityPkts.malformedPkts, 1);
}
} else {
memcpy(&tp, bp+hlen, sizeof(struct tcphdr));
/* Sanity check */
if(tcpUdpLen >= (tp.th_off * 4)) {
int diff;
/* Real lenght if we captured the full packet */
tcpDataLength = tcpUdpLen - (tp.th_off * 4);
/* Actual lenght scaled with caplen */
diff = h->caplen - (h->len - tcpDataLength);
if(diff > 0) {
tcpDataLength = diff;
theData = (u_char*)(bp+hlen+(tp.th_off * 4));
} else {
tcpDataLength = 0;
theData = NULL;
}
} else {
tcpDataLength = 0;
theData = NULL;
}
sport = ntohs(tp.th_sport);
dport = ntohs(tp.th_dport);
/*
Don't move this code on top as it is supposed to stay here
as it modifies sport/sport
Courtesy of Andreas Pfaller
*/
if(myGlobals.enableFragmentHandling && (fragmented)) {
/* Handle fragmented packets */
if(ip6)
length = handleFragment(srcHost, dstHost, &sport, &dport,
(u_short)(ip6->ip6_flow & 0xffff),fragmented,
length,ntohs(ip6->ip6_plen),
actualDeviceId, h, p);
else
length = handleFragment(srcHost, dstHost, &sport, &dport,
ntohs(ip.ip_id), off, length,
ip_len - hlen, actualDeviceId, h, p);
}
if(srcHost->fingerprint == NULL) {
char fingerprint[64] = { 0 } ;
int WIN=0, MSS=-1, WS=-1, S=0, N=0, D=0, T=0;
int ttl;
char WSS[3] = { 0 }, _MSS[5] = { 0 };
struct tcphdr *tcp = (struct tcphdr*)(bp+hlen);
u_char *tcp_opt = (u_char *)(bp + hlen + 1);
u_char *tcp_data = (u_char *)(bp + hlen + tp.th_off * 4);
if(tcp->th_flags & TH_SYN) { /* only SYN or SYN-2ACK packets */
if(tcpUdpLen > 0) {
if(ip6) {
if(!fragmented) D = 1;
} else
if(ntohs(ip.ip_off) & IP_DF) D = 1; /* don't fragment bit is set */
WIN = ntohs(tcp->th_win); /* TCP window size */
if(tcp_data != tcp_opt) { /* there are some tcp_option to be parsed */
u_char *opt_start = tcp_opt, *opt_end = tcp_data;
u_short num_loops = 0;
while(opt_start < opt_end) {
switch(opt_start[0]) {
case TCPOPT_EOL: /* end option: exit */
opt_start = opt_end;
break;
case TCPOPT_NOP:
N = 1;
opt_start++;
break;
case TCPOPT_SACKOK:
S = 1;
opt_start += 2;
break;
case TCPOPT_MAXSEG:
opt_start += 2;
MSS = ntohs(ptohs(opt_start));
opt_start += 2;
break;
case TCPOPT_WSCALE:
opt_start += 2;
WS = *opt_start;
opt_start++;
break;
case TCPOPT_TIMESTAMP:
T = 1;
opt_start++;
opt_start += (*opt_start - 1);
break;
default:
opt_start++;
if(*opt_start > 0)
opt_start += (*opt_start - 1);
break;
}
num_loops++;
if(num_loops > 16) {
/* Suspicious packet: maybe the TCP options are wrong */
break;
}
}
}
if(WS == -1)
safe_snprintf(__FILE__, __LINE__, WSS, sizeof(WSS), "WS");
else
safe_snprintf(__FILE__, __LINE__, WSS, sizeof(WSS), "%02X", WS & 0xFFFF);
if(MSS == -1)
safe_snprintf(__FILE__, __LINE__, _MSS, sizeof(_MSS), "_MSS");
else
safe_snprintf(__FILE__, __LINE__, _MSS, sizeof(_MSS), "%04X", MSS & 0xFFFFFFFF);
safe_snprintf(__FILE__, __LINE__, fingerprint, sizeof(fingerprint),
"%04X:%s:%02X:%s:%d:%d:%d:%d:%c:%02X",
WIN, _MSS, ttl = TTL_PREDICTOR(ip.ip_ttl), WSS , S, N, D, T,
(tcp->th_flags & TH_ACK) ? 'A' : 'S', tcpUdpLen);
#if 0
traceEvent(CONST_TRACE_INFO, "[%s][%s]", srcHost->hostNumIpAddress, fingerprint);
#endif
srcHost->fingerprint = strdup(fingerprint);
}
}
}
if((sport > 0) || (dport > 0)) {
/* It might be that tcpDataLength is 0 when
the rcvd packet is fragmented and the main
packet has not yet been rcvd */
updateInterfacePorts(actualDeviceId, sport, dport, length);
if(tcpDataLength > 0) /* Don't update ports for all packets */
updateUsedPorts(srcHost, dstHost, sport, dport, tcpDataLength);
if(subnetPseudoLocalHost(srcHost)) {
if(subnetPseudoLocalHost(dstHost)) {
incrementHostTrafficCounter(srcHost, tcpSentLoc, length);
incrementHostTrafficCounter(dstHost, tcpRcvdLoc, length);
incrementTrafficCounter(&myGlobals.device[actualDeviceId].tcpGlobalTrafficStats.local,
length);
} else {
incrementHostTrafficCounter(srcHost, tcpSentRem, length);
incrementHostTrafficCounter(dstHost, tcpRcvdLoc, length);
incrementTrafficCounter(&myGlobals.device[actualDeviceId].tcpGlobalTrafficStats.local2remote,
length);
}
} else {
/* srcHost is remote */
if(subnetPseudoLocalHost(dstHost)) {
incrementHostTrafficCounter(srcHost, tcpSentLoc, length);
incrementHostTrafficCounter(dstHost, tcpRcvdFromRem, length);
incrementTrafficCounter(&myGlobals.device[actualDeviceId].tcpGlobalTrafficStats.remote2local,
length);
} else {
incrementHostTrafficCounter(srcHost, tcpSentRem, length);
incrementHostTrafficCounter(dstHost, tcpRcvdFromRem, length);
incrementTrafficCounter(&myGlobals.device[actualDeviceId].tcpGlobalTrafficStats.remote,
length);
nonFullyRemoteSession = 0;
}
}
if(nonFullyRemoteSession) {
if(ip6)
handleSession(h, p, nh, fragmented, tp.th_win,
srcHost, sport, dstHost,
dport, ntohs(ip6->ip6_plen), 0,
ip_offset, &tp, tcpDataLength,
theData, actualDeviceId, &newSession,
IPOQUE_PROTOCOL_UNKNOWN, 1);
else
handleSession(h, p, nh, (off & 0x3fff), tp.th_win,
srcHost, sport, dstHost,
dport, ip_len, 0,
ip_offset, &tp, tcpDataLength,
theData, actualDeviceId, &newSession,
IPOQUE_PROTOCOL_UNKNOWN, 1);
}
}
}
if(ip6)
goto end;
else
break;
case IPPROTO_UDP:
incrementTrafficCounter(&myGlobals.device[actualDeviceId].udpBytes, length);
incrementTrafficCounter(&myGlobals.device[actualDeviceId].udpGlobalTrafficStats.totalFlows, 1);
if(tcpUdpLen < sizeof(struct udphdr)) {
if(myGlobals.runningPref.enableSuspiciousPacketDump) {
traceEvent(CONST_TRACE_WARNING, "Malformed UDP pkt %s->%s detected (packet too short)",
srcHost->hostResolvedName,
dstHost->hostResolvedName);
dumpSuspiciousPacket(actualDeviceId, h, p);
allocateSecurityHostPkts(srcHost); allocateSecurityHostPkts(dstHost);
incrementUsageCounter(&srcHost->secHostPkts->malformedPktsSent, dstHost, actualDeviceId);
incrementUsageCounter(&dstHost->secHostPkts->malformedPktsRcvd, srcHost, actualDeviceId);
incrementTrafficCounter(&myGlobals.device[actualDeviceId].securityPkts.malformedPkts, 1);
}
} else {
udpDataLength = (u_int)(tcpUdpLen - sizeof(struct udphdr));
memcpy(&up, bp+hlen, sizeof(struct udphdr));
sport = ntohs(up.uh_sport);
dport = ntohs(up.uh_dport);
if(!(fragmented)) {
/* Not fragmented */
if(((sport == 53) || (dport == 53) /* domain */)
|| ((sport == 5353) && (dport == 5353)) /* Multicast DNS */) {
short isRequest = 0, positiveReply = 0;
u_int16_t transactionId = 0;
if(myGlobals.runningPref.enablePacketDecoding
&& (bp != NULL) /* packet long enough */) {
/* The DNS chain will be checked here */
transactionId = processDNSPacket(srcHost, sport, bp+hlen+sizeof(struct udphdr),
udpDataLength, &isRequest, &positiveReply);
#ifdef DNS_SNIFF_DEBUG
traceEvent(CONST_TRACE_INFO, "DNS_SNIFF_DEBUG: %s:%d->%s:%d [request: %d][positive reply: %d]",
srcHost->hostResolvedName, sport,
dstHost->hostResolvedName, dport,
isRequest, positiveReply);
#endif
allocHostTrafficCounterMemory(srcHost, protocolInfo, sizeof(ProtocolInfo));
allocHostTrafficCounterMemory(dstHost, protocolInfo, sizeof(ProtocolInfo));
if((srcHost->protocolInfo == NULL) || (dstHost->protocolInfo == NULL)) return;
allocHostTrafficCounterMemory(srcHost, protocolInfo->dnsStats, sizeof(ServiceStats));
if(srcHost->protocolInfo->dnsStats == NULL) return;
allocHostTrafficCounterMemory(dstHost, protocolInfo->dnsStats, sizeof(ServiceStats));
if(dstHost->protocolInfo->dnsStats == NULL) return;
allocHostTrafficCounterMemory(srcHost, protocolInfo, sizeof(ProtocolInfo));
allocHostTrafficCounterMemory(srcHost, protocolInfo->dnsStats, sizeof(ServiceStats));
allocHostTrafficCounterMemory(dstHost, protocolInfo, sizeof(ProtocolInfo));
allocHostTrafficCounterMemory(dstHost, protocolInfo->dnsStats, sizeof(ServiceStats));
if(isRequest) {
/* to be 64bit-proof we have to copy the elements */
tvstrct.tv_sec = h->ts.tv_sec;
tvstrct.tv_usec = h->ts.tv_usec;
addTimeMapping(transactionId, tvstrct);
if(subnetLocalHost(dstHost)) {
incrementHostTrafficCounter(srcHost, protocolInfo->dnsStats->numLocalReqSent, 1);
} else {
incrementHostTrafficCounter(srcHost, protocolInfo->dnsStats->numRemReqSent, 1);
}
if(subnetLocalHost(srcHost)) {
incrementHostTrafficCounter(dstHost, protocolInfo->dnsStats->numLocalReqRcvd, 1);
} else {
incrementHostTrafficCounter(dstHost, protocolInfo->dnsStats->numRemReqRcvd, 1);
}
} else {
time_t microSecTimeDiff;
/* to be 64bit-safe we have to copy the elements */
tvstrct.tv_sec = h->ts.tv_sec;
tvstrct.tv_usec = h->ts.tv_usec;
microSecTimeDiff = getTimeMapping(transactionId, tvstrct);
if(microSecTimeDiff > 0) {
#ifdef DEBUG
traceEvent(CONST_TRACE_INFO, "TransactionId=0x%X [%.1f ms]",
transactionId, ((float)microSecTimeDiff)/1000);
#endif
if(microSecTimeDiff > 0) {
if(subnetLocalHost(dstHost)) {
if((srcHost->protocolInfo->dnsStats->fastestMicrosecLocalReqServed == 0)
|| (microSecTimeDiff < srcHost->protocolInfo->dnsStats->fastestMicrosecLocalReqServed))
srcHost->protocolInfo->dnsStats->fastestMicrosecLocalReqServed = microSecTimeDiff;
if(microSecTimeDiff > srcHost->protocolInfo->dnsStats->slowestMicrosecLocalReqServed)
srcHost->protocolInfo->dnsStats->slowestMicrosecLocalReqServed = microSecTimeDiff;
} else {
if((srcHost->protocolInfo->dnsStats->fastestMicrosecRemReqServed == 0)
|| (microSecTimeDiff < srcHost->protocolInfo->dnsStats->fastestMicrosecRemReqServed))
srcHost->protocolInfo->dnsStats->fastestMicrosecRemReqServed = microSecTimeDiff;
if(microSecTimeDiff > srcHost->protocolInfo->dnsStats->slowestMicrosecRemReqServed)
srcHost->protocolInfo->dnsStats->slowestMicrosecRemReqServed = microSecTimeDiff;