-
Notifications
You must be signed in to change notification settings - Fork 46
/
nprobe.c
4037 lines (3412 loc) · 137 KB
/
nprobe.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
/*
* nProbe - a Netflow v5/v9/IPFIX probe for IPv4/v6
*
* Copyright (C) 2002-11 Luca Deri <[email protected]>
*
* http://www.ntop.org/
*
* 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.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
/* ************************************************************************
History:
1.0 [06/02] Initial release
1.3 [07/02] First public release
************************************************************************ */
#include "nprobe.h"
#define BLANK_SPACES " "
/* #define NETFLOW_DEBUG */
/* #define HASH_DEBUG */
/* #define TIME_PROTECTION */
#define MAX_SAMPLE_RATE ((u_short)-1)
/* *************************************** */
/*
#define OPTION_TEMPLATE "%SYSTEM_ID %SAMPLING_INTERVAL %SAMPLING_ALGORITHM %TOTAL_BYTES_EXP %TOTAL_PKTS_EXP %TOTAL_FLOWS_EXP %FLOW_ACTIVE_TIMEOUT %FLOW_INACTIVE_TIMEOUT"
*/
#define V9_OPTION_TEMPLATE "%TOTAL_FLOWS_EXP %TOTAL_PKTS_EXP"
/* IMPORTANT: when you modify it please also change exportBucketToNetflowV5 */
#define DEFAULT_V9_IPV4_TEMPLATE "%IPV4_SRC_ADDR %IPV4_DST_ADDR %IPV4_NEXT_HOP %INPUT_SNMP %OUTPUT_SNMP %IN_PKTS %IN_BYTES %FIRST_SWITCHED " \
"%LAST_SWITCHED %L4_SRC_PORT %L4_DST_PORT %TCP_FLAGS %PROTOCOL %SRC_TOS %SRC_AS %DST_AS %IPV4_SRC_MASK %IPV4_DST_MASK"
#define DEFAULT_V9_OPTION_TEMPLATE_ID (DEFAULT_TEMPLATE_ID+1)
#define TEMPLATE_PACKETS_DELTA 10
/* *********** Globals ******************* */
#ifdef HAVE_PF_RING
#include "pro/pf_ring.c"
#endif
/* ****************************************************** */
/* Forward */
static void checkExportQueuedFlows(int forceExport);
static void printStats(int force);
static void shutdown_nprobe(void);
static pthread_t *packetProcessThread;
static int parseOptions(int argc, char* argv[], u_int8_t reparse_options);
static void compileTemplates(u_int8_t reloadTemplate);
static int argc_;
static char **argv_;
#ifdef HAVE_OPTRESET
extern int optreset; /* defined by BSD, but not others */
#endif
static const struct option long_options[] = {
{ "all-collectors", required_argument, NULL, 'a' },
{ "as-list", required_argument, NULL, 'A' },
{ "verbose", required_argument, NULL, 'b' },
{ "count-delay", required_argument, NULL, 'B' },
{ "local-hosts-only", no_argument, NULL, 'c' },
{ "flow-lock", required_argument, NULL, 'C' },
{ "idle-timeout", required_argument, NULL, 'd' },
{ "dump-format", required_argument, NULL, 'D' },
{ "flow-delay", required_argument, NULL, 'e' },
{ "netflow-engine", required_argument, NULL, 'E' },
{ "bpf-filter", required_argument, NULL, 'f' },
{ "dump-frequency", required_argument, NULL, 'F' },
{ "pid-file", required_argument, NULL, 'g' },
#ifndef WIN32
{ "daemon-mode", no_argument, NULL, 'G' },
#endif
{ "help", no_argument, NULL, 'h' },
{ "interface", required_argument, NULL, 'i' },
{ "syslog", required_argument, NULL, 'I' },
{ "queue-timeout", required_argument, NULL, 'l' },
{ "local-networks", required_argument, NULL, 'L' },
{ "min-num-flows", required_argument, NULL, 'm' },
{ "max-num-flows", required_argument, NULL, 'M' },
{ "collector", required_argument, NULL, 'n' },
{ "rebuild-hash", no_argument, NULL, 'N' },
{ "flows-intra-templ", required_argument, NULL, 'o' },
{ "num-threads", required_argument, NULL, 'O' },
{ "aggregation", required_argument, NULL, 'p' },
{ "dump-path", required_argument, NULL, 'P' },
#ifdef IP_HDRINCL
{ "sender-address", required_argument, NULL, 'q' },
#endif
{ "out-iface-idx", required_argument, NULL, 'Q' },
{ "local-traffic-direction", no_argument, NULL, 'r' },
{ "payload-length", required_argument, NULL, 'R' },
{ "scan-cycle", required_argument, NULL, 's' },
{ "sample-rate", required_argument, NULL, 'S' },
{ "lifetime-timeout", required_argument, NULL, 't' },
{ "flow-templ", required_argument, NULL, 'T' },
{ "in-iface-idx", required_argument, NULL, 'u' },
{ "flow-templ-id", required_argument, NULL, 'U' },
{ "hash-size", required_argument, NULL, 'w' },
{ "no-ipv6", no_argument, NULL, 'W' },
{ "payload-policy", required_argument, NULL, 'x' },
{ "version", no_argument, NULL, 'v' },
{ "flow-version", required_argument, NULL, 'V' },
{ "min-flow-size", required_argument, NULL, 'z' },
#ifdef HAVE_MYSQL
{ "mysql", required_argument, NULL, '0' /* ignored */},
{ "mysql-skip-db-creation", no_argument, NULL, '0' /* ignored */},
#endif
{ "if-networks", required_argument, NULL, '1' },
{ "count", required_argument, NULL, '2' },
{ "collector-port", required_argument, NULL, '3' },
#ifdef linux
{ "cpu-affinity", required_argument, NULL, '4' },
#endif
{ "tunnel", no_argument, NULL, '5' },
/* Handled by the plugin */
{ "no-promisc", no_argument, NULL, '6' },
{ "smart-udp-frags", no_argument, NULL, '7' },
{ "ipsec-auth-data-len", required_argument, NULL, '8' },
{ "dump-stats", required_argument, NULL, '9' },
{ "black-list", required_argument, NULL, '!' },
{ "vlanid-as-iface-idx", no_argument, NULL, '@' },
{ "pcap-file-list", required_argument, NULL, '$' },
{ "csv-separator", required_argument, NULL, '^' },
{ "city-list", required_argument, NULL, ',' },
#ifdef HAVE_FASTBIT
{ "fastbit", required_argument, NULL, '[' },
{ "fastbit-rotation", required_argument, NULL, ']' },
{ "fastbit-template", required_argument, NULL, '(' },
#ifndef WIN32
{ "fastbit-index", required_argument, NULL, ')' },
#endif
{ "fastbit-exec", required_argument, NULL, '#' },
#endif
{ "dont-drop-privileges", no_argument, NULL, '\\' },
{ "bi-directional", no_argument, NULL, '{' },
{ "account-l2", no_argument, NULL, '}' },
{ "dump-metadata", required_argument, NULL, '=' },
{ "event-log", required_argument, NULL, '+' },
/*
Options for plugins. These options are not handled by the main
program but it's important to have them defined here otherwise we
get a warning from the probe
*/
{ "dont-hash-cookies", no_argument, NULL, 251 /* dummy */ },
{ "dont-nest-dump-dirs", no_argument, NULL, 251 /* dummy */ },
{ "max-http-log-lines", required_argument, NULL, 252 /* dummy */ },
{ "http-dump-dir", required_argument, NULL, 252 /* dummy */ },
{ "http-exec-cmd", required_argument, NULL, 252 /* dummy */ },
{ "max-mysql-log-lines", required_argument, NULL, 252 /* dummy */ },
{ "mysql-dump-dir", required_argument, NULL, 252 /* dummy */ },
{ "http-exec-cmd", required_argument, NULL, 252 /* dummy */ },
{ "dns-dump-dir", required_argument, NULL, 253 /* dummy */ },
{ "ntop-ng", required_argument, NULL, 254 /* dummy */ },
{ "bgp-port", required_argument, NULL, 255 /* dummy */ },
/* End of probe options */
{ NULL, no_argument, NULL, 0 }
};
/* ****************************************************** */
void printPcapStats(pcap_t *pcapPtr) {
struct pcap_stat pcapStat;
if(pcap_stats(pcapPtr, &pcapStat) >= 0) {
u_long rcvd_diff, drop_diff;
char msg[256];
/* Some pcap implementations resetthe stats at each call */
if(pcapStat.ps_recv >= readWriteGlobals->last_ps_recv) {
rcvd_diff = pcapStat.ps_recv-readWriteGlobals->last_ps_recv;
drop_diff = pcapStat.ps_drop-readWriteGlobals->last_ps_drop;
} else {
rcvd_diff = pcapStat.ps_recv, drop_diff = pcapStat.ps_drop;
}
snprintf(msg, sizeof(msg), "Packet stats: "
"%u/%u pkts rcvd/dropped [%.1f%%] [Last %lu/%lu pkts rcvd/dropped]",
pcapStat.ps_recv, pcapStat.ps_drop,
pcapStat.ps_recv > 0 ?
(float)(pcapStat.ps_drop*100)/(float)pcapStat.ps_recv : 0,
rcvd_diff, drop_diff);
traceEvent(TRACE_INFO, "%s", msg);
if(drop_diff > 0) dumpLogEvent(packet_drop, severity_warning, msg);
readWriteGlobals->last_ps_recv = pcapStat.ps_recv, readWriteGlobals->last_ps_drop = pcapStat.ps_drop;
} else {
#ifdef DEBUG
traceEvent(TRACE_WARNING, "Unable to read pcap statistics: %s",
pcap_geterr(pcapPtr));
#endif
}
}
/* ****************************************************** */
#ifndef WIN32
void reloadCLI(int signo) {
traceEvent(TRACE_NORMAL, "Received signal %d: reloading CLI options", signo);
parseOptions(argc_, argv_, 1);
}
/* ****************************************************** */
void cleanup(int signo) {
static u_char statsPrinted = 0;
if(!nprobe_up) exit(0);
if(!statsPrinted) {
statsPrinted = 1;
if(readOnlyGlobals.pcapPtr != NULL) {
printPcapStats(readOnlyGlobals.pcapPtr);
}
}
shutdown_nprobe();
/* exit(0); */
}
#endif
/* ****************************************************** */
#ifndef WIN32
void brokenPipe(int signo) {
#ifdef DEBUG
traceEvent(TRACE_WARNING, "Broken pipe (socket %d closed) ?\n", currSock);
#endif
signal(SIGPIPE, brokenPipe);
}
#endif
/* ****************************************************** */
void decodePacket(struct pcap_pkthdr *h, const u_char *p,
u_int8_t sampledPacket,
u_short numPkts, int input_index, int output_index,
u_int32_t flow_sender_ip) {
struct eth_header ehdr;
u_int caplen = h->caplen, length = h->len, offset = 0;
u_short eth_type, off=0;
u_int8_t tcpFlags = 0, proto = 0;
u_int32_t tunnel_id = 0, tcpSeqNum = 0;
struct ip ip = { 0 };
#ifndef IPV4_ONLY
struct ip6_hdr ipv6;
struct ip6_ext ipv6ext;
#endif
struct tcphdr tp = { 0 };
struct udphdr up = { 0 };
struct icmp_hdr icmpPkt = { 0 };
u_int16_t payload_shift = 0;
int originalPayloadLen = 0, payloadLen = 0; /* Do not set it to unsigned */
IpAddress src = { 0 }, dst = { 0 };
IpAddress untunneled_src = { 0 }, untunneled_dst = { 0 };
u_int16_t untunneled_sport = 0, untunneled_dport = 0;
u_int8_t untunneled_proto = 0;
u_short numFragments = 0;
u_int ehshift = 0;
#ifdef DEBUG
traceEvent(TRACE_INFO, ".");
#endif
if(readWriteGlobals->stopPacketCapture) return;
if(readOnlyGlobals.initialSniffTime.tv_sec == 0) {
/* Set it with the first incoming packet */
memcpy(&readOnlyGlobals.initialSniffTime, &h->ts, sizeof(struct timeval));
}
readWriteGlobals->now = h->ts.tv_sec;
if(caplen >= sizeof(struct eth_header)) {
u_int plen, hlen = 0, ip_len = 0;
u_short sport, dport, numMplsLabels = 0, tcp_len;
u_char mplsLabels[MAX_NUM_MPLS_LABELS][MPLS_LABEL_LEN];
u_int32_t null_type;
struct ppp_header ppphdr;
if(readOnlyGlobals.numProcessThreads > 1) pthread_rwlock_wrlock(&readWriteGlobals->statsRwLock);
readWriteGlobals->accumulateStats.pkts++, readWriteGlobals->accumulateStats.bytes += length;
readWriteGlobals->currentPkts++, readWriteGlobals->currentBytes += length;
if(readOnlyGlobals.numProcessThreads > 1) pthread_rwlock_unlock(&readWriteGlobals->statsRwLock);
// traceEvent(TRACE_INFO, "Datalink: %d", datalink);
switch(readOnlyGlobals.datalink) {
case DLT_ANY: /* Linux 'any' device */
eth_type = DLT_ANY;
memset(&ehdr, 0, sizeof(struct eth_header));
break;
case DLT_RAW: /* Raw packet data */
if(((p[0] & 0xF0) >> 4) == 4)
eth_type = ETHERTYPE_IP;
else
eth_type = ETHERTYPE_IPV6;
ehshift = 0;
break;
case DLT_NULL: /* loopaback interface */
ehshift = 4;
memcpy(&null_type, p, sizeof(u_int32_t));
//null_type = ntohl(null_type);
/* All this crap is due to the old little/big endian story... */
/* FIX !!!! */
switch(null_type) {
case BSD_AF_INET:
eth_type = ETHERTYPE_IP;
break;
case BSD_AF_INET6_BSD:
case BSD_AF_INET6_FREEBSD:
case BSD_AF_INET6_DARWIN:
eth_type = ETHERTYPE_IPV6;
break;
default:
return; /* Any other non IP protocol */
}
memset(&ehdr, 0, sizeof(struct eth_header));
break;
case DLT_PPP:
memcpy(&ppphdr, p, sizeof(struct ppp_header));
if(ntohs(ppphdr.proto) == 0x0021 /* IP */)
eth_type = ETHERTYPE_IP, ehshift = sizeof(struct ppp_header);
else
return;
break;
default:
ehshift = sizeof(struct eth_header);
memcpy(&ehdr, p, ehshift);
eth_type = ntohs(ehdr.ether_type);
break;
}
if((eth_type == ETHERTYPE_IP)
|| (eth_type == ETHERTYPE_IPV6)
|| (eth_type == ETHERTYPE_VLAN) /* Courtesy of Mikael Cam <[email protected]> - 2002/08/28 */
|| (eth_type == ETHERTYPE_MPLS)
|| (eth_type == ETHERTYPE_PPPoE)
|| (eth_type == DLT_NULL)
|| (eth_type == DLT_ANY)
|| (eth_type == 16385 /* MacOSX loopback */)
|| (eth_type == 16390 /* MacOSX loopback */)
) {
u_short vlanId = 0;
u_int estimatedLen = 0;
if(eth_type == ETHERTYPE_MPLS) {
char bos; /* bottom_of_stack */
memset(mplsLabels, 0, sizeof(mplsLabels));
bos = 0;
while(bos == 0) {
memcpy(&mplsLabels[numMplsLabels], p+ehshift, MPLS_LABEL_LEN);
bos = (mplsLabels[numMplsLabels][2] & 0x1), ehshift += 4, numMplsLabels++;
if((ehshift > caplen) || (numMplsLabels >= MAX_NUM_MPLS_LABELS))
return; /* bad packet */
}
eth_type = ETHERTYPE_IP;
} else if((eth_type == ETHERTYPE_IP) || (eth_type == ETHERTYPE_IPV6)) {
if((ehshift == 0) && (readOnlyGlobals.datalink != DLT_RAW)) /* still not set (used to handle the DLT_NULL case) */
ehshift = sizeof(struct eth_header);
} else if(eth_type == ETHERTYPE_PPPoE) {
eth_type = ETHERTYPE_IP, ehshift += 8;
} else if(eth_type == ETHERTYPE_VLAN) {
Ether80211q qType;
while(eth_type == ETHERTYPE_VLAN) {
memcpy(&qType, p+ehshift, sizeof(Ether80211q));
vlanId = ntohs(qType.vlanId) & 0xFFF;
eth_type = ntohs(qType.protoType);
ehshift += sizeof(qType);
/* printf("VlanId: %d\n", vlanId); <<<== NOT USED YET */
}
if(eth_type == 0x0800) {
/* Sanity check */
if(p[ehshift] == 0x60)
eth_type = ETHERTYPE_IPV6;
}
} else if(eth_type == DLT_ANY) {
ehshift += sizeof(AnyHeader);
eth_type = ntohs(((AnyHeader*)p)->protoType);
} else
ehshift += NULL_HDRLEN;
parse_ip:
if(eth_type == ETHERTYPE_IP) {
u_short ip_ip_len;
memcpy(&ip, p+ehshift, sizeof(struct ip));
if(ip.ip_v != 4) return; /* IP v4 only */
/* blacklist check */
if(isBlacklistedAddress(&ip.ip_src) || isBlacklistedAddress(&ip.ip_dst)) return;
ip_ip_len = htons(ip.ip_len);
ip_len = ((u_short)ip.ip_hl * 4);
estimatedLen = ehshift + ip_ip_len;
hlen = ip_len;
payloadLen = htons(ip.ip_len)-ip_len;
if(readOnlyGlobals.roundPacketLenWithIPHeaderLen)
length = estimatedLen;
src.ipVersion = 4, dst.ipVersion = 4;
if(readOnlyGlobals.ignoreIP || (readOnlyGlobals.setAllNonLocalHostsToZero && (!isLocalAddress(&ip.ip_src))))
src.ipType.ipv4 = 0; /* 0.0.0.0 */
else
src.ipType.ipv4 = ntohl(ip.ip_src.s_addr);
if(readOnlyGlobals.ignoreIP || (readOnlyGlobals.setAllNonLocalHostsToZero && (!isLocalAddress(&ip.ip_dst))))
dst.ipType.ipv4 = 0; /* 0.0.0.0 */
else
dst.ipType.ipv4 = ntohl(ip.ip_dst.s_addr);
proto = ip.ip_p;
off = ntohs(ip.ip_off) & 0x3fff;
numFragments = off ? 1 : 0;
#ifndef IPV4_ONLY
} else if(eth_type == ETHERTYPE_IPV6) {
u_short ipv6_ip_len;
if(readOnlyGlobals.disableIPv6) return;
memcpy(&ipv6, p+ehshift, sizeof(struct ip6_hdr));
if(((ipv6.ip6_vfc >> 4) & 0x0f) != 6) return; /* IP v6 only */
ipv6_ip_len = htons(ipv6.ip6_plen);
estimatedLen = sizeof(struct ip6_hdr)+ehshift+ipv6_ip_len;
if(readOnlyGlobals.roundPacketLenWithIPHeaderLen)
length = estimatedLen;
hlen = sizeof(struct ip6_hdr);
src.ipVersion = 6, dst.ipVersion = 6;
payloadLen = ipv6_ip_len - hlen;
/* FIX: blacklist check for IPv6 */
/* FIX: isLocalAddress doesn't work with IPv6 */
if(readOnlyGlobals.ignoreIP)
memset(&src.ipType.ipv6, 0, sizeof(struct in6_addr));
else
memcpy(&src.ipType.ipv6, &ipv6.ip6_src, sizeof(struct in6_addr));
if(readOnlyGlobals.ignoreIP)
memset(&dst.ipType.ipv6, 0, sizeof(struct in6_addr));
else
memcpy(&dst.ipType.ipv6, &ipv6.ip6_dst, sizeof(struct in6_addr));
proto = ipv6.ip6_nxt; /* next header (protocol) */
if(proto == 0) {
/* IPv6 hop-by-hop option */
memcpy(&ipv6ext, p+ehshift+sizeof(struct ip6_hdr), sizeof(struct ip6_ext));
hlen += (ipv6ext.ip6e_len+1)*8;
proto = ipv6ext.ip6e_nxt;
}
#endif
} else
return; /* Anything else that's not IPv4/v6 */
originalPayloadLen = payloadLen;
plen = length-ehshift;
if(caplen > estimatedLen) caplen = estimatedLen;
payloadLen -= (estimatedLen-caplen);
sport = dport = 0; /* default */
offset = ehshift+hlen;
if(readOnlyGlobals.tunnel_mode) {
switch(proto) {
case IPPROTO_ESP:
/* http://www.unixwiz.net/techtips/iguide-ipsec.html */
if(payloadLen > readOnlyGlobals.ipsec_auth_data_len) {
proto = p[offset+payloadLen-readOnlyGlobals.ipsec_auth_data_len-1];
offset += 8;
}
break;
case IPPROTO_GRE:
{
struct gre_header gre;
memcpy(&gre, &p[offset], sizeof(gre));
gre.flags_and_version = ntohs(gre.flags_and_version);
gre.proto = ntohs(gre.proto);
offset += sizeof(struct gre_header);
if(gre.flags_and_version & GRE_HEADER_CHECKSUM) offset += 4;
if(gre.flags_and_version & GRE_HEADER_ROUTING) offset += 4;
if(gre.flags_and_version & GRE_HEADER_KEY) offset += 4;
if(gre.flags_and_version & GRE_HEADER_SEQ_NUM) offset += 4;
eth_type = gre.proto;
if(eth_type == 0x8881 /* CDMA2000 */) {
offset++; /* PPP in HDLC-Like Framing */
memcpy(&ppphdr, &p[offset], sizeof(struct ppp_header));
if(ntohs(ppphdr.proto) == 0x0021 /* IP */)
eth_type = ETHERTYPE_IP;
ehshift = sizeof(struct ppp_header)+offset;
} else
ehshift = offset;
memcpy(&untunneled_src, &src, sizeof(IpAddress)), memcpy(&untunneled_dst, &dst, sizeof(IpAddress));
untunneled_proto = proto, untunneled_sport = sport, untunneled_dport = dport;
goto parse_ip;
break;
}
}
}
switch(proto) {
case IPPROTO_TCP:
if(plen < (hlen+sizeof(struct tcphdr))) return; /* packet too short */
memcpy(&tp, p+offset, sizeof(struct tcphdr));
if(!readOnlyGlobals.ignorePorts) sport = ntohs(tp.th_sport);
if(!readOnlyGlobals.ignorePorts) dport = ntohs(tp.th_dport);
tcpFlags = tp.th_flags, tcpSeqNum = ntohl(tp.th_seq);
tcp_len = (tp.th_off * 4);
payloadLen -= tcp_len, originalPayloadLen -= tcp_len;
if(payloadLen > 0)
payload_shift = offset+tcp_len;
else {
payloadLen = 0;
payload_shift = 0;
}
break;
case IPPROTO_UDP:
if(plen < (hlen+sizeof(struct udphdr))) return; /* packet too short */
memcpy(&up, p+offset, sizeof(struct udphdr));
if(!readOnlyGlobals.ignorePorts) sport = ntohs(up.uh_sport);
if(!readOnlyGlobals.ignorePorts) dport = ntohs(up.uh_dport);
originalPayloadLen = payloadLen = ntohs(up.uh_ulen)-sizeof(struct udphdr);
if(payloadLen > 0)
payload_shift = offset+sizeof(struct udphdr);
else {
payloadLen = 0;
payload_shift = 0;
}
if((readOnlyGlobals.tunnel_mode) && (payloadLen > sizeof(struct gtp_header))) {
if(dport == GTP_DATA_PORT) {
struct gtp_header *gtp = (struct gtp_header*)&p[payload_shift];
u_int gtp_header_len = 8 /* min size of struct gtp_header */;
if(((gtp->flags & 0x30) == 0x30) /* GTPv1 */
&& (ntohs(gtp->total_length) >= (payloadLen-gtp_header_len))) {
tunnel_id = ntohl(gtp->tunnel_id);
/* Now compute gtp_header_len precisely */
if(gtp->flags & 0x04) gtp_header_len += 1; /* next_ext_header is present */
if(gtp->flags & 0x02) gtp_header_len += 2; /* sequence_number is present */
if(gtp->flags & 0x01) gtp_header_len += 1; /* pdu_number is present */
payload_shift += gtp_header_len;
ehshift = payload_shift;
if(p[payload_shift] == 0x60)
eth_type = ETHERTYPE_IPV6;
else
eth_type = ETHERTYPE_IP;
memcpy(&untunneled_src, &src, sizeof(IpAddress)), memcpy(&untunneled_dst, &dst, sizeof(IpAddress));
untunneled_proto = proto, untunneled_sport = sport, untunneled_dport = dport;
goto parse_ip;
}
}
}
#ifdef NETFLOW_DEBUG
if((payloadLen > 0)
&& (numFragments == 0) && (off == 0) /* Do not process fragmented packets */
&& ((dport == 2055)
|| (dport == 2057)
|| (dport == 9999)
|| (dport == 3000)
|| (dport == 6000)
)) {
/* traceEvent(TRACE_NORMAL, "Dissecting flow packets (%d bytes)", payloadLen); */
dissectNetFlow(0, (char*)&p[payload_shift], payloadLen);
return;
}
#endif
break;
case IPPROTO_ICMP:
case IPPROTO_ICMPV6:
if(plen < (hlen+sizeof(struct icmp_hdr))) return; /* packet too short */
memcpy(&icmpPkt, p+offset, sizeof(struct icmp_hdr));
payloadLen = caplen - offset- sizeof(struct icmp_hdr);
//traceEvent(TRACE_ERROR, "[icmp_type=%d][icmp_code=%d]", icmpPkt.icmp_type, icmpPkt.icmp_code);
if(!(readOnlyGlobals.ignorePorts || readOnlyGlobals.ignorePorts)) {
if(readOnlyGlobals.usePortsForICMP)
sport = 0, dport = (icmpPkt.icmp_type * 256) + icmpPkt.icmp_code;
}
if(payloadLen > 0) {
payload_shift = offset;
if(proto == IPPROTO_ICMP)
payload_shift += sizeof(struct icmp_hdr);
else
payload_shift += 64; /* ICMPv6 */
} else {
payloadLen = 0;
payload_shift = 0;
}
break;
default:
payloadLen = 0;
}
/* ************************************************ */
/* Is this is a fragment ?
NOTE: IPv6 doesn't have the concept of fragments
*/
if(readOnlyGlobals.handleFragments && (numFragments > 0)) {
u_short fragmentOffset = (off & 0x1FFF)*8, fragmentId = ntohs(ip.ip_id);
u_short fragment_list_idx = (src.ipType.ipv4 + dst.ipType.ipv4) % NUM_FRAGMENT_LISTS;
IpV4Fragment *list, *prev = NULL;
if((readOnlyGlobals.smart_udp_frags_mode == 0) || (proto != IPPROTO_UDP)) {
pthread_mutex_lock(&readWriteGlobals->fragmentMutex[fragment_list_idx]);
list = readWriteGlobals->fragmentsList[fragment_list_idx];
while(list != NULL) {
if((list->src == src.ipType.ipv4)
&& (list->dst == dst.ipType.ipv4)
&& (list->fragmentId == fragmentId))
break;
else {
if((h->ts.tv_sec-list->firstSeen) > 30 /* sec */) {
/* Purge expired fragment */
IpV4Fragment *next = list->next;
if(prev == NULL)
readWriteGlobals->fragmentsList[fragment_list_idx] = next;
else
prev->next = next;
free(list);
readWriteGlobals->fragmentListLen[fragment_list_idx]--;
list = next;
} else {
prev = list;
list = list->next;
}
}
}
if(list == NULL) {
/* Fragment not found */
IpV4Fragment *frag = (IpV4Fragment*)malloc(sizeof(IpV4Fragment));
/* We have enough memory */
if(frag != NULL) {
memset(frag, 0, sizeof(IpV4Fragment));
frag->next = readWriteGlobals->fragmentsList[fragment_list_idx];
readWriteGlobals->fragmentsList[fragment_list_idx] = frag;
frag->src = src.ipType.ipv4, frag->dst = dst.ipType.ipv4;
frag->fragmentId = fragmentId;
frag->firstSeen = h->ts.tv_sec;
list = frag, prev = NULL;;
readWriteGlobals->fragmentListLen[fragment_list_idx]++;
} else
traceEvent(TRACE_ERROR, "Not enough memory?");
}
if(list != NULL) {
if(fragmentOffset == 0)
list->sport = sport, list->dport = dport;
list->len += plen, list->numPkts++;
if(!(off & IP_MF)) {
/* last fragment->we know the total data size */
IpV4Fragment *next = list->next;
sport = list->sport, dport = list->dport;
plen = list->len, numPkts = list->numPkts;
/* We can now free the fragment */
if(prev == NULL)
readWriteGlobals->fragmentsList[fragment_list_idx] = next;
else
prev->next = next;
readWriteGlobals->fragmentListLen[fragment_list_idx]--;
free(list);
pthread_mutex_unlock(&readWriteGlobals->fragmentMutex[fragment_list_idx]);
numFragments = numPkts;
} else {
pthread_mutex_unlock(&readWriteGlobals->fragmentMutex[fragment_list_idx]);
/* More fragments: we'll handle the packet later */
return;
}
}
} else {
if(fragmentOffset > 0) {
/*
Ignore fragments that do not have the initial
fragmented packet info
*/
return;
} else {
/*
We use 2* because we want to be as precise as possible given
that we have at least two fragments, we account twice the
IP packt header
*/
plen = ntohs(up.uh_ulen)+2*ip_len, numPkts = 2;
}
}
}
/* ************************************************ */
#ifdef DEBUG
{
char buf[256], buf1[256];
printf("%2d) %s:%d -> %s:%d [len=%d][payloadLen=%d]\n",
ip.ip_p, _intoaV4(ip.ip_src.s_addr, buf, sizeof(buf)), sport,
_intoaV4(ip.ip_dst.s_addr, buf1, sizeof(buf1)), dport,
plen, payloadLen);
}
#endif
if((src.ipVersion == 4) && (src.ipType.ipv4 == 0)
&& (dst.ipType.ipv4 == 0) && (!(readOnlyGlobals.ignoreIP)))
return; /* Flow to skip */
queueParsedPkt(proto, numFragments, sampledPacket,
numPkts, ip.ip_tos,
vlanId, tunnel_id, &ehdr, &src, sport, &dst, dport,
untunneled_proto, &untunneled_src, untunneled_sport, &untunneled_dst, untunneled_dport,
readOnlyGlobals.accountL2Traffic ? h->len : plen,
tcpFlags, tcpSeqNum,
((proto == IPPROTO_ICMP) || (proto == IPPROTO_ICMPV6)) ? icmpPkt.icmp_type : 0,
((proto == IPPROTO_ICMP) || (proto == IPPROTO_ICMPV6)) ? icmpPkt.icmp_code : 0,
numMplsLabels, mplsLabels,
input_index, output_index,
(struct pcap_pkthdr*)h, (u_char*)p,
payload_shift, payloadLen,
originalPayloadLen, 0,
0, 0, 0, 0, 0 /* flow_sender_ip */);
}
#ifdef DEBUG
else {
if(traceMode)
traceEvent(TRACE_WARNING, "Unknown ethernet type: 0x%X (%d)",
eth_type, eth_type);
}
#endif
}
}
/* ****************************************************** */
void dummyProcessPacket(u_char *_deviceId,
const struct pcap_pkthdr *h,
const u_char *p) {
// traceEvent(TRACE_NORMAL, "Got %d bytes packet", h->len);
decodePacket((struct pcap_pkthdr*)h, p,
0 /* sampledPacket */, 1 /* numPkts */,
NO_INTERFACE_INDEX, NO_INTERFACE_INDEX,
0 /* flow_sender_ip */);
}
/* ****************************************************** */
void allocateHostHash(void) {
if(readOnlyGlobals.enableHostStats) {
readWriteGlobals->theHostHash =
(HostHashBucket**)calloc(readOnlyGlobals.hostHashSize, sizeof(HostHashBucket*));
if(readWriteGlobals->theHostHash == NULL) {
traceEvent(TRACE_ERROR, "Not enough memory");
exit(-1);
}
}
}
/* ****************************************************** */
void freeHostHash(void) {
if(readOnlyGlobals.enableHostStats) {
traceEvent(TRACE_INFO, "MISSING implement freeHostHash()");
}
}
/* ****************************************************** */
/* There's 1 dequeue thread per queue */
void* dequeuePackets(void* notused) {
u_long num, queue_id = (long)notused; /* Range 0..readOnlyGlobals.numProcessThreads */
PacketQueue *queue = &readWriteGlobals->packetQueue[queue_id];
traceEvent(TRACE_INFO, "Started dequeue packets thread id %d...\n", queue_id);
while(!readWriteGlobals->shutdownInProgress) {
QueuedPacket *slot = &queue->queue[queue->remove_idx];
/* Wait for packets */
while((num = queuedPkts(queue)) == 0) {
if(readWriteGlobals->shutdownInProgress) break;
if(0)
traceEvent(TRACE_ERROR, "No queued packets [num=%d][queue_id=%d][queued=%u/dequeued=%u]",
num, queue_id, queue->num_queued_pkts, queue->num_dequeued_pkts);
waitCondvar(&queue->dequeue_condvar);
}
if(readWriteGlobals->shutdownInProgress) break;
if(0) traceEvent(TRACE_ERROR, "packet dequeued[queue_id=%d][num_queued=%d]", queue_id, queuedPkts(queue));
processFlowPacket(slot->idx, queue_id,
slot->proto, slot->numFragments,
slot->sampledPacket,
slot->numPkts, slot->tos,
slot->vlanId, slot->tunnel_id,
&slot->ehdr,
&slot->src, slot->sport,
&slot->dst, slot->dport,
slot->untunneled_proto,
&slot->untunneled_src, slot->untunneled_sport,
&slot->untunneled_dst, slot->untunneled_dport,
slot->len, slot->tcpFlags,
slot->tcpSeqNum,
slot->icmpType, slot->icmpCode,
slot->numMplsLabels,
slot->mplsLabels,
slot->if_input, slot->if_output,
&slot->h, slot->p,
slot->payload_shift, slot->payloadLen,
slot->originalPayloadLen, slot->_firstSeen,
slot->src_as, slot->dst_as,
slot->src_mask, slot->dst_mask,
slot->flow_sender_ip);
queue->num_dequeued_pkts++,
queue->remove_idx = (queue->remove_idx + 1) % queue->queue_capacity;
signalCondvar(&queue->queue_condvar, 0);
}
traceEvent(TRACE_INFO, "Dequeue packets thread id %d is over...\n", queue_id);
return(NULL);
}
/* ****************************************************** */
void allocateFlowHash(int idx) {
u_int mallocSize = sizeof(FlowHashBucket*)*readOnlyGlobals.flowHashSize;
readWriteGlobals->theFlowHash[idx] = (FlowHashBucket**)calloc(1, mallocSize);
if(readWriteGlobals->theFlowHash[idx] == NULL) {
traceEvent(TRACE_ERROR, "Not enough memory");
exit(-1);
}
}
/* ****************************************************** */
static void msecSleep(u_int msSleep) {
#ifndef WIN32
struct timespec timeout;
timeout.tv_sec = 0, timeout.tv_nsec = 1000000*msSleep;
while((nanosleep(&timeout, &timeout) == -1) && (errno == EINTR))
; /* Do nothing */
#else
waitForNextEvent(msSleep);
#endif
}
/* ****************************************************** */
/*
From the tests carried on, the very best approach
is to have a periodic thread that scans for expired
flows.
*/
void* hashWalker(void* notused) {
u_short sleep_time, msSleep = 100;
long idx;
/* Wait until all the data structures have been allocated */
while(readWriteGlobals->theFlowHash[readOnlyGlobals.numProcessThreads-1] == NULL) ntop_sleep(1);
/* Align to the scan cycle */
sleep_time = readOnlyGlobals.scanCycle - (time(NULL) % readOnlyGlobals.scanCycle);
if(readOnlyGlobals.traceMode == 2)
traceEvent(TRACE_INFO, "Sleeping %d sec before walking hash for the first time", sleep_time);
ntop_sleep(sleep_time);
while((readWriteGlobals->shutdownInProgress == 0)
&& (readWriteGlobals->stopPacketCapture == 0)) {
struct timeval begin, end;
u_int msDiff;
gettimeofday(&begin, NULL);
for(idx=0; idx<readOnlyGlobals.numProcessThreads; idx++) {
if(readOnlyGlobals.rebuild_hash) {
int i;
traceEvent(TRACE_INFO, "[%d] Rebuilding hash...", idx);
/* stop all activities and create a new hash */
for(i=0; i<MAX_HASH_MUTEXES; i++) pthread_rwlock_wrlock(&readWriteGlobals->flowHashRwLock[idx][i]);
readWriteGlobals->thePrevFlowHash[idx] = readWriteGlobals->theFlowHash[idx];
allocateFlowHash(idx);
allocateHostHash();
for(i=0; i<MAX_HASH_MUTEXES; i++) pthread_rwlock_unlock(&readWriteGlobals->flowHashRwLock[idx][i]);
traceEvent(TRACE_INFO, "The hash has been rebuilt.");
}
walkHash(idx, readOnlyGlobals.rebuild_hash);
if(readWriteGlobals->thePrevFlowHash[idx] != NULL) {
free(readWriteGlobals->thePrevFlowHash[idx]);
readWriteGlobals->thePrevFlowHash[idx] = NULL;
}
#ifndef WIN32
sched_yield();
#endif
/* Relax a bit */
gettimeofday(&end, NULL);
msDiff = msTimeDiff(&end, &begin);
if(msSleep > msDiff) {
u_int diff = msSleep-msDiff;
/* traceEvent(TRACE_NORMAL, "Sleeping %u msec", diff); */
msecSleep(diff);
}
} /* for */
/* End of scan */
printStats(0);
checkNetFlowExport(0);
if(readOnlyGlobals.traceMode == 2)
traceEvent(TRACE_INFO, "Sleeping %d sec before walking hash...", readOnlyGlobals.scanCycle);