forked from irino/softflowd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
softflowd.c
2305 lines (2059 loc) · 70.7 KB
/
softflowd.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 2002 Damien Miller <djm@mindrot.org> 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.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
*/
/*
* This is software implementation of Cisco's NetFlow(tm) traffic
* reporting system. It operates by listening (via libpcap) on a
* promiscuous interface and tracking traffic flows.
*
* Traffic flows are recorded by source/destination/protocol
* IP address or, in the case of TCP and UDP, by
* src_addr:src_port/dest_addr:dest_port/protocol
*
* Flows expire automatically after a period of inactivity (default: 1
* hour) They may also be evicted (in order of age) in situations where
* there are more flows than slots available.
*
* Netflow compatible packets are sent to a specified target host upon
* flow expiry.
*
* As this implementation watches traffic promiscuously, it is likely to
* place significant load on hosts or gateways on which it is installed.
*/
#include "common.h"
#include "sys-tree.h"
#include "convtime.h"
#include "softflowd.h"
#include "treetype.h"
#include "freelist.h"
#include "log.h"
#include "psamp.h"
#include <pcap.h>
/* Global variables */
static int verbose_flag = 0; /* Debugging flag */
static u_int16_t if_index = 0; /* "manual" interface index */
static int track_level;
static int snaplen = 0;
#ifdef ENABLE_PTHREAD
pthread_mutex_t read_mutex;
pthread_cond_t read_cond;
int use_thread;
u_char packet_data[1500];
struct pcap_pkthdr packet_header;
struct FLOW *send_expired_flows;
#endif /* ENABLE_PTHREAD */
/* Signal handler flags */
static volatile sig_atomic_t graceful_shutdown_request = 0;
/* Context for libpcap callback functions */
struct CB_CTXT {
struct FLOWTRACK *ft;
struct NETFLOW_TARGET *target;
int linktype;
int fatal;
int want_v6;
};
/* Describes a datalink header and how to extract v4/v6 frames from it */
struct DATALINK {
int dlt; /* BPF datalink type */
int skiplen; /* Number of bytes to skip datalink header */
int ft_off; /* Datalink frametype offset */
int ft_len; /* Datalink frametype length */
int ft_is_be; /* Set if frametype is big-endian */
u_int32_t ft_mask; /* Mask applied to frametype */
u_int32_t ft_v4; /* IPv4 frametype */
u_int32_t ft_v6; /* IPv6 frametype */
};
/* Datalink types that we know about */
static const struct DATALINK lt[] = {
{DLT_EN10MB, 14, 12, 2, 1, 0xffffffff, 0x0800, 0x86dd},
{DLT_PPP, 5, 3, 2, 1, 0xffffffff, 0x0021, 0x0057},
#ifdef DLT_LINUX_SLL
{DLT_LINUX_SLL, 16, 14, 2, 1, 0xffffffff, 0x0800, 0x86dd},
#endif
{DLT_RAW, 0, 0, 1, 1, 0x000000f0, 0x0040, 0x0060},
{DLT_NULL, 4, 0, 4, 0, 0xffffffff, AF_INET, AF_INET6},
#ifdef DLT_LOOP
{DLT_LOOP, 4, 0, 4, 1, 0xffffffff, AF_INET, AF_INET6},
#endif
#ifdef DLT_PFLOG
{DLT_PFLOG, 48, 1, 1, 0, 0x000000ff, AF_INET, AF_INET6},
#endif
{-1, -1, -1, -1, -1, 0x00000000, 0xffff, 0xffff},
};
/* Netflow send functions */
typedef int (netflow_send_func_t) (struct SENDPARAMETER);
struct NETFLOW_SENDER {
int version;
netflow_send_func_t *func;
netflow_send_func_t *bidir_func;
int v6_capable;
};
/* Array of NetFlow export function that we know of. NB. nf[0] is default */
static const struct NETFLOW_SENDER nf[] = {
{5, send_netflow_v5, NULL, 0},
{1, send_netflow_v1, NULL, 0},
#ifdef LEGACY_NF9_IMPL
{9, send_netflow_v9, NULL, 1},
#else /* LEGACY_NF9_IMPL */
{9, send_nflow9, NULL, 1},
#endif /* LEGACY_NF9_IMPL */
{10, send_ipfix, send_ipfix_bi, 1},
{-1, NULL, NULL, 0},
};
/* Describes a location where we send NetFlow packets to */
struct NETFLOW_TARGET {
int num_destinations;
struct DESTINATION destinations[SOFTFLOWD_MAX_DESTINATIONS];
const struct NETFLOW_SENDER *dialect;
};
/* Signal handlers */
static void
sighand_graceful_shutdown (int signum) {
graceful_shutdown_request = signum;
}
static void
sighand_other (int signum) {
/* XXX: this may not be completely safe */
logit (LOG_WARNING, "Exiting immediately on unexpected signal %d", signum);
_exit (0);
}
/*
* This is the flow comparison function.
*/
static int
flow_compare (struct FLOW *a, struct FLOW *b) {
/* Be careful to avoid signed vs unsigned issues here */
int r;
if (track_level == TRACK_FULL_VLAN || track_level == TRACK_FULL_VLAN_ETHER) {
if (a->vlanid[0] != b->vlanid[0])
return (a->vlanid[0] > b->vlanid[0] ? 1 : -1);
if (a->vlanid[1] != b->vlanid[1])
return (a->vlanid[1] > b->vlanid[1] ? 1 : -1);
}
if (track_level == TRACK_FULL_VLAN_ETHER) {
if ((r = memcmp (&a->ethermac[0], &b->ethermac[0], 6)) != 0)
return (r > 0 ? 1 : -1);
if ((r = memcmp (&a->ethermac[1], &b->ethermac[1], 6)) != 0)
return (r > 0 ? 1 : -1);
}
if (a->af != b->af)
return (a->af > b->af ? 1 : -1);
if ((r = memcmp (&a->addr[0], &b->addr[0], sizeof (a->addr[0]))) != 0)
return (r > 0 ? 1 : -1);
if ((r = memcmp (&a->addr[1], &b->addr[1], sizeof (a->addr[1]))) != 0)
return (r > 0 ? 1 : -1);
#ifdef notyet
if (a->ip6_flowlabel[0] != 0 && b->ip6_flowlabel[0] != 0 &&
a->ip6_flowlabel[0] != b->ip6_flowlabel[0])
return (a->ip6_flowlabel[0] > b->ip6_flowlabel[0] ? 1 : -1);
if (a->ip6_flowlabel[1] != 0 && b->ip6_flowlabel[1] != 0 &&
a->ip6_flowlabel[1] != b->ip6_flowlabel[1])
return (a->ip6_flowlabel[1] > b->ip6_flowlabel[1] ? 1 : -1);
#endif
if (a->protocol != b->protocol)
return (a->protocol > b->protocol ? 1 : -1);
if (a->port[0] != b->port[0])
return (ntohs (a->port[0]) > ntohs (b->port[0]) ? 1 : -1);
if (a->port[1] != b->port[1])
return (ntohs (a->port[1]) > ntohs (b->port[1]) ? 1 : -1);
return (0);
}
/* Generate functions for flow tree */
FLOW_PROTOTYPE (FLOWS, FLOW, trp, flow_compare);
FLOW_GENERATE (FLOWS, FLOW, trp, flow_compare);
/*
* This is the expiry comparison function.
*/
static int
expiry_compare (struct EXPIRY *a, struct EXPIRY *b) {
if (a->expires_at != b->expires_at)
return (a->expires_at > b->expires_at ? 1 : -1);
/* Make expiry entries unique by comparing flow sequence */
if (a->flow->flow_seq != b->flow->flow_seq)
return (a->flow->flow_seq > b->flow->flow_seq ? 1 : -1);
return (0);
}
/* Generate functions for flow tree */
EXPIRY_PROTOTYPE (EXPIRIES, EXPIRY, trp, expiry_compare);
EXPIRY_GENERATE (EXPIRIES, EXPIRY, trp, expiry_compare);
static struct FLOW *
flow_get (struct FLOWTRACK *ft) {
return freelist_get (&ft->flow_freelist);
}
static void
flow_put (struct FLOWTRACK *ft, struct FLOW *flow) {
return freelist_put (&ft->flow_freelist, flow);
}
static struct EXPIRY *
expiry_get (struct FLOWTRACK *ft) {
return freelist_get (&ft->expiry_freelist);
}
static void
expiry_put (struct FLOWTRACK *ft, struct EXPIRY *expiry) {
return freelist_put (&ft->expiry_freelist, expiry);
}
#if 0
/* Dump a packet */
static void
dump_packet (const u_int8_t * p, int len) {
char buf[1024], tmp[3];
int i;
for (*buf = '\0', i = 0; i < len; i++) {
snprintf (tmp, sizeof (tmp), "%02x%s", p[i], i % 2 ? " " : "");
if (strlcat (buf, tmp, sizeof (buf) - 4) >= sizeof (buf) - 4) {
strlcat (buf, "...", sizeof (buf));
break;
}
}
logit (LOG_INFO, "packet len %d: %s", len, buf);
}
#endif
/* Format a time in an ISOish format */
static const char *
format_time (time_t t) {
struct tm *tm;
static char buf[32];
tm = gmtime (&t);
strftime (buf, sizeof (buf), "%Y-%m-%dT%H:%M:%S", tm);
return (buf);
}
static const char *
format_ethermac (uint8_t ethermac[6]) {
static char buf[1024];
snprintf (buf, sizeof (buf), "%.2x:%.2x:%.2x:%.2x:%.2x:%.2x",
ethermac[0], ethermac[1], ethermac[2], ethermac[3],
ethermac[4], ethermac[5]);
return buf;
}
/* Format a flow in a verbose and ugly way */
static const char *
format_flow (struct FLOW *flow) {
char addr1[64], addr2[64], start_time[32], fin_time[32];
static char buf[1024];
inet_ntop (flow->af, &flow->addr[0], addr1, sizeof (addr1));
inet_ntop (flow->af, &flow->addr[1], addr2, sizeof (addr2));
snprintf (start_time, sizeof (start_time), "%s",
format_time (flow->flow_start.tv_sec));
snprintf (fin_time, sizeof (fin_time), "%s",
format_time (flow->flow_last.tv_sec));
snprintf (buf, sizeof (buf),
"seq:%" PRIu64 " [%s]:%hu <> [%s]:%hu proto:%u "
"octets>:%u packets>:%u octets<:%u packets<:%u "
"start:%s.%03ld finish:%s.%03ld tcp>:%02x tcp<:%02x "
"flowlabel>:%08x flowlabel<:%08x "
"vlan>:%u vlan<:%u ether:%s <> %s", flow->flow_seq, addr1,
ntohs (flow->port[0]), addr2, ntohs (flow->port[1]),
(int) flow->protocol, flow->octets[0], flow->packets[0],
flow->octets[1], flow->packets[1], start_time,
(flow->flow_start.tv_usec + 500) / 1000, fin_time,
(flow->flow_last.tv_usec + 500) / 1000, flow->tcp_flags[0],
flow->tcp_flags[1], flow->ip6_flowlabel[0],
flow->ip6_flowlabel[1], flow->vlanid[0], flow->vlanid[1],
format_ethermac (flow->ethermac[0]),
format_ethermac (flow->ethermac[1]));
return (buf);
}
/* Format a flow in a brief way */
static const char *
format_flow_brief (struct FLOW *flow) {
char addr1[64], addr2[64];
static char buf[1024];
inet_ntop (flow->af, &flow->addr[0], addr1, sizeof (addr1));
inet_ntop (flow->af, &flow->addr[1], addr2, sizeof (addr2));
snprintf (buf, sizeof (buf),
"seq:%" PRIu64 " [%s]:%hu <> [%s]:%hu proto:%u "
"vlan>:%u vlan<:%u ether:%s <> %s ",
flow->flow_seq,
addr1, ntohs (flow->port[0]), addr2, ntohs (flow->port[1]),
(int) flow->protocol, flow->vlanid[0], flow->vlanid[1],
format_ethermac (flow->ethermac[0]),
format_ethermac (flow->ethermac[1]));
return (buf);
}
/* Fill in transport-layer (tcp/udp) portions of flow record */
static int
transport_to_flowrec (struct FLOW *flow, const u_int8_t * pkt,
const size_t caplen, int isfrag, int protocol, int ndx)
{
const struct tcphdr *tcp = (const struct tcphdr *) pkt;
const struct udphdr *udp = (const struct udphdr *) pkt;
const struct icmp *icmp = (const struct icmp *) pkt;
/*
* XXX to keep flow in proper canonical format, it may be necessary to
* swap the array slots based on the order of the port numbers does
* this matter in practice??? I don't think so - return flows will
* always match, because of their symmetrical addr/ports
*/
switch (protocol) {
case IPPROTO_TCP:
/* Check for runt packet, but don't error out on short frags */
if (caplen < sizeof (*tcp))
return (isfrag ? 0 : 1);
flow->port[ndx] = tcp->th_sport;
flow->port[ndx ^ 1] = tcp->th_dport;
flow->tcp_flags[ndx] |= tcp->th_flags;
break;
case IPPROTO_UDP:
/* Check for runt packet, but don't error out on short frags */
if (caplen < sizeof (*udp))
return (isfrag ? 0 : 1);
flow->port[ndx] = udp->uh_sport;
flow->port[ndx ^ 1] = udp->uh_dport;
break;
case IPPROTO_ICMP:
case IPPROTO_ICMPV6:
/*
* Encode ICMP type * 256 + code into dest port like
* Cisco routers
*/
flow->port[ndx] = 0;
flow->port[ndx ^ 1] = htons (icmp->icmp_type * 256 + icmp->icmp_code);
break;
}
return (0);
}
static int
make_ndx_ipv4 (const struct ip *ip, size_t caplen) {
if (caplen < 20 || caplen < ip->ip_hl * 4)
return (-1); /* Runt packet */
if (ip->ip_v != 4)
return (-1); /* Unsupported IP version */
/* Prepare to store flow in canonical format */
return (memcmp (&ip->ip_src, &ip->ip_dst, sizeof (ip->ip_src)) > 0 ? 1 : 0);
}
/* Convert a IPv4 packet to a partial flow record (used for comparison) */
static int
ipv4_to_flowrec (struct FLOW *flow, const u_int8_t * pkt, size_t caplen,
size_t len, int *isfrag, int af, int ndx) {
const struct ip *ip = (const struct ip *) pkt;
//int ndx = make_ndx_ipv4 (ip, caplen);
if (ndx < 0)
return (-1);
flow->af = af;
flow->addr[ndx].v4 = ip->ip_src;
flow->addr[ndx ^ 1].v4 = ip->ip_dst;
flow->protocol = ip->ip_p;
flow->octets[ndx] = len;
flow->packets[ndx] = 1;
flow->tos[ndx] = ip->ip_tos;
*isfrag = (ntohs (ip->ip_off) & (IP_OFFMASK | IP_MF)) ? 1 : 0;
/* Don't try to examine higher level headers if not first fragment */
if (*isfrag && (ntohs (ip->ip_off) & IP_OFFMASK) != 0)
return (0);
return (transport_to_flowrec (flow, pkt + (ip->ip_hl * 4),
caplen - (ip->ip_hl * 4), *isfrag, ip->ip_p,
ndx));
}
static int
make_ndx_ipv6 (const struct ip6_hdr *ip6, size_t caplen) {
if (caplen < sizeof (*ip6))
return (-1); /* Runt packet */
if ((ip6->ip6_vfc & IPV6_VERSION_MASK) != IPV6_VERSION)
return (-1); /* Unsupported IPv6 version */
/* Prepare to store flow in canonical format */
return (memcmp (&ip6->ip6_src, &ip6->ip6_dst,
sizeof (ip6->ip6_src)) > 0 ? 1 : 0);
}
/* Convert a IPv6 packet to a partial flow record (used for comparison) */
static int
ipv6_to_flowrec (struct FLOW *flow, const u_int8_t * pkt, size_t caplen,
size_t len, int *isfrag, int af, int ndx) {
const struct ip6_hdr *ip6 = (const struct ip6_hdr *) pkt;
const struct ip6_ext *eh6;
const struct ip6_frag *fh6;
int nxt;
if (ndx < 0)
return (-1);
flow->af = af;
flow->ip6_flowlabel[ndx] = ip6->ip6_flow & IPV6_FLOWLABEL_MASK;
flow->addr[ndx].v6 = ip6->ip6_src;
flow->addr[ndx ^ 1].v6 = ip6->ip6_dst;
flow->octets[ndx] = len;
flow->packets[ndx] = 1;
flow->tos[ndx] = (ntohl (ip6->ip6_flow) & ntohl (0x0ff00000)) >> 20;
*isfrag = 0;
nxt = ip6->ip6_nxt;
pkt += sizeof (*ip6);
caplen -= sizeof (*ip6);
/* Now loop through headers, looking for transport header */
for (;;) {
eh6 = (const struct ip6_ext *) pkt;
if (nxt == IPPROTO_HOPOPTS ||
nxt == IPPROTO_ROUTING || nxt == IPPROTO_DSTOPTS) {
if (caplen < sizeof (*eh6) || caplen < (eh6->ip6e_len + 1) << 3)
return (1); /* Runt */
nxt = eh6->ip6e_nxt;
pkt += (eh6->ip6e_len + 1) << 3;
caplen -= (eh6->ip6e_len + 1) << 3;
} else if (nxt == IPPROTO_FRAGMENT) {
*isfrag = 1;
fh6 = (const struct ip6_frag *) eh6;
if (caplen < sizeof (*fh6))
return (1); /* Runt */
/*
* Don't try to examine higher level headers if
* not first fragment
*/
if ((fh6->ip6f_offlg & IP6F_OFF_MASK) != 0)
return (0);
nxt = fh6->ip6f_nxt;
pkt += sizeof (*fh6);
caplen -= sizeof (*fh6);
} else
break;
}
flow->protocol = nxt;
return (transport_to_flowrec (flow, pkt, caplen, *isfrag, nxt, ndx));
}
static int
vlan_to_flowrec (struct FLOW *flow, u_int16_t vlanid, int ndx) {
if (ndx < 0)
return (-1);
return (flow->vlanid[ndx] = vlanid);
}
static int
ether_to_flowrec (struct FLOW *flow, struct ether_header *ether, int ndx) {
if (ndx < 0)
return (-1);
if (ether == NULL)
return (-1);
memcpy (flow->ethermac[ndx], ether->ether_shost, ETH_ALEN);
memcpy (flow->ethermac[ndx ^ 1], ether->ether_dhost, ETH_ALEN);
return (1);
}
static void
flow_update_expiry (struct FLOWTRACK *ft, struct FLOW *flow) {
EXPIRY_REMOVE (EXPIRIES, &ft->expiries, flow->expiry);
/* Flows over 2 GiB traffic */
if (flow->octets[0] > (1U << 31) || flow->octets[1] > (1U << 31)) {
flow->expiry->expires_at = 0;
flow->expiry->reason = R_OVERBYTES;
goto out;
}
/* Flows over maximum life seconds */
if (ft->param.maximum_lifetime != 0 &&
flow->flow_last.tv_sec - flow->flow_start.tv_sec >
ft->param.maximum_lifetime) {
flow->expiry->expires_at = 0;
flow->expiry->reason = R_MAXLIFE;
goto out;
}
if (flow->protocol == IPPROTO_TCP) {
/* Reset TCP flows */
if (ft->param.tcp_rst_timeout != 0 &&
((flow->tcp_flags[0] & TH_RST) || (flow->tcp_flags[1] & TH_RST))) {
flow->expiry->expires_at = flow->flow_last.tv_sec +
ft->param.tcp_rst_timeout;
flow->expiry->reason = R_TCP_RST;
goto out;
}
/* Finished TCP flows */
if (ft->param.tcp_fin_timeout != 0 &&
((flow->tcp_flags[0] & TH_FIN) && (flow->tcp_flags[1] & TH_FIN))) {
flow->expiry->expires_at = flow->flow_last.tv_sec +
ft->param.tcp_fin_timeout;
flow->expiry->reason = R_TCP_FIN;
goto out;
}
/* TCP flows */
if (ft->param.tcp_timeout != 0) {
flow->expiry->expires_at = flow->flow_last.tv_sec +
ft->param.tcp_timeout;
flow->expiry->reason = R_TCP;
goto out;
}
}
if (ft->param.udp_timeout != 0 && flow->protocol == IPPROTO_UDP) {
/* UDP flows */
flow->expiry->expires_at = flow->flow_last.tv_sec + ft->param.udp_timeout;
flow->expiry->reason = R_UDP;
goto out;
}
if (ft->param.icmp_timeout != 0 &&
((flow->af == AF_INET && flow->protocol == IPPROTO_ICMP) ||
((flow->af == AF_INET6 && flow->protocol == IPPROTO_ICMPV6)))) {
/* ICMP flows */
flow->expiry->expires_at = flow->flow_last.tv_sec +
ft->param.icmp_timeout;
flow->expiry->reason = R_ICMP;
goto out;
}
/* Everything else */
flow->expiry->expires_at = flow->flow_last.tv_sec +
ft->param.general_timeout;
flow->expiry->reason = R_GENERAL;
out:
if (ft->param.maximum_lifetime != 0 && flow->expiry->expires_at != 0) {
flow->expiry->expires_at = MIN (flow->expiry->expires_at,
flow->flow_start.tv_sec +
ft->param.maximum_lifetime);
}
EXPIRY_INSERT (EXPIRIES, &ft->expiries, flow->expiry);
}
/* Return values from process_packet */
#define PP_OK 0
#define PP_BAD_PACKET -2
#define PP_MALLOC_FAIL -3
/*
* Main per-packet processing function. Take a packet (provided by
* libpcap) and attempt to find a matching flow. If no such flow exists,
* then create one.
*
* Also marks flows for fast expiry, based on flow or packet attributes
* (the actual expiry is performed elsewhere)
*/
static int
process_packet (struct FLOWTRACK *ft, const u_int8_t * pkt, int af,
const u_int32_t caplen, const u_int32_t len,
struct ether_header *ether, u_int16_t vlanid,
const struct timeval *received_time) {
struct FLOW tmp, *flow;
int frag, ndx;
/* Convert the IP packet to a flow identity */
memset (&tmp, 0, sizeof (tmp));
switch (af) {
case AF_INET:
ndx = make_ndx_ipv4 ((const struct ip *) pkt, caplen);
if (ipv4_to_flowrec (&tmp, pkt, caplen, len, &frag, af, ndx) == -1)
goto bad;
break;
case AF_INET6:
ndx = make_ndx_ipv6 ((const struct ip6_hdr *) pkt, caplen);
if (ipv6_to_flowrec (&tmp, pkt, caplen, len, &frag, af, ndx) == -1)
goto bad;
break;
default:
bad:
ft->param.bad_packets++;
return (PP_BAD_PACKET);
}
if (frag)
ft->param.frag_packets++;
/* Zero out bits of the flow that aren't relevant to tracking level */
switch (ft->param.track_level) {
case TRACK_IP_ONLY:
tmp.protocol = 0;
/* FALLTHROUGH */
case TRACK_IP_PROTO:
tmp.port[0] = tmp.port[1] = 0;
tmp.tcp_flags[0] = tmp.tcp_flags[1] = 0;
/* FALLTHROUGH */
case TRACK_FULL:
tmp.vlanid[0] = tmp.vlanid[1] = 0;
break;
case TRACK_FULL_VLAN_ETHER:
ether_to_flowrec (&tmp, ether, ndx);
/* FALLTHROUGH */
case TRACK_FULL_VLAN:
vlan_to_flowrec (&tmp, vlanid, ndx);
break;
}
/* If a matching flow does not exist, create and insert one */
if ((flow = FLOW_FIND (FLOWS, &ft->flows, &tmp)) == NULL) {
/* Allocate and fill in the flow */
if ((flow = flow_get (ft)) == NULL) {
logit (LOG_ERR, "process_packet: flow_get failed", sizeof (*flow));
return (PP_MALLOC_FAIL);
}
memcpy (flow, &tmp, sizeof (*flow));
memcpy (&flow->flow_start, received_time, sizeof (flow->flow_start));
flow->flow_seq = ft->param.next_flow_seq++;
FLOW_INSERT (FLOWS, &ft->flows, flow);
/* Allocate and fill in the associated expiry event */
if ((flow->expiry = expiry_get (ft)) == NULL) {
logit (LOG_ERR, "process_packet: expiry_get failed",
sizeof (*flow->expiry));
return (PP_MALLOC_FAIL);
}
flow->expiry->flow = flow;
/* Must be non-zero (0 means expire immediately) */
flow->expiry->expires_at = 1;
flow->expiry->reason = R_GENERAL;
EXPIRY_INSERT (EXPIRIES, &ft->expiries, flow->expiry);
ft->param.num_flows++;
if (verbose_flag)
logit (LOG_DEBUG, "ADD FLOW %s", format_flow_brief (flow));
} else {
/* Update flow statistics */
flow->packets[0] += tmp.packets[0];
flow->octets[0] += tmp.octets[0];
flow->tcp_flags[0] |= tmp.tcp_flags[0];
flow->packets[1] += tmp.packets[1];
flow->octets[1] += tmp.octets[1];
flow->tcp_flags[1] |= tmp.tcp_flags[1];
}
memcpy (&flow->flow_last, received_time, sizeof (flow->flow_last));
if (flow->expiry->expires_at != 0)
flow_update_expiry (ft, flow);
return (PP_OK);
}
/*
* Subtract two timevals. Returns (t1 - t2) in milliseconds.
*/
u_int32_t
timeval_sub_ms (const struct timeval * t1, const struct timeval * t2) {
struct timeval res;
res.tv_sec = t1->tv_sec - t2->tv_sec;
res.tv_usec = t1->tv_usec - t2->tv_usec;
if (res.tv_usec < 0) {
res.tv_usec += 1000000L;
res.tv_sec--;
}
return ((u_int32_t) res.tv_sec * 1000 + (u_int32_t) res.tv_usec / 1000);
}
int
send_multi_destinations (int num_destinations,
struct DESTINATION *destinations, u_int8_t * packet,
int size) {
struct DESTINATION *dest;
int i, err;
socklen_t errsz;
for (i = 0; i < num_destinations; i++) {
dest = &destinations[i];
errsz = sizeof (err);
getsockopt (dest->sock, SOL_SOCKET, SO_ERROR, &err, &errsz); // Clear ICMP errors
if (send (dest->sock, packet, (size_t) size, 0) == -1)
return (-1);
}
return i;
}
static void
update_statistic (struct STATISTIC *s, double new, double n) {
if (n == 1.0) {
s->min = s->mean = s->max = new;
return;
}
s->min = MIN (s->min, new);
s->max = MAX (s->max, new);
s->mean = s->mean + ((new - s->mean) / n);
}
/* Update global statistics */
static void
update_statistics (struct FLOWTRACK *ft, struct FLOW *flow) {
double tmp;
static double n = 1.0;
ft->param.flows_expired++;
ft->param.flows_pp[flow->protocol % 256]++;
tmp = (double) flow->flow_last.tv_sec +
((double) flow->flow_last.tv_usec / 1000000.0);
tmp -= (double) flow->flow_start.tv_sec +
((double) flow->flow_start.tv_usec / 1000000.0);
if (tmp < 0.0)
tmp = 0.0;
update_statistic (&ft->param.duration, tmp, n);
update_statistic (&ft->param.duration_pp[flow->protocol], tmp,
(double) ft->param.flows_pp[flow->protocol % 256]);
tmp = flow->octets[0] + flow->octets[1];
update_statistic (&ft->param.octets, tmp, n);
ft->param.octets_pp[flow->protocol % 256] += tmp;
tmp = flow->packets[0] + flow->packets[1];
update_statistic (&ft->param.packets, tmp, n);
ft->param.packets_pp[flow->protocol % 256] += tmp;
n++;
}
static void
update_expiry_stats (struct FLOWTRACK *ft, struct EXPIRY *e) {
switch (e->reason) {
case R_GENERAL:
ft->param.expired_general++;
break;
case R_TCP:
ft->param.expired_tcp++;
break;
case R_TCP_RST:
ft->param.expired_tcp_rst++;
break;
case R_TCP_FIN:
ft->param.expired_tcp_fin++;
break;
case R_UDP:
ft->param.expired_udp++;
break;
case R_ICMP:
ft->param.expired_icmp++;
break;
case R_MAXLIFE:
ft->param.expired_maxlife++;
break;
case R_OVERBYTES:
ft->param.expired_overbytes++;
break;
case R_OVERFLOWS:
ft->param.expired_maxflows++;
break;
case R_FLUSH:
ft->param.expired_flush++;
break;
}
}
/* How long before the next expiry event in millisecond */
static int
next_expire (struct FLOWTRACK *ft) {
struct EXPIRY *expiry;
struct timeval now;
u_int32_t expires_at, ret, fudge;
if (ft->param.adjust_time)
now = ft->param.last_packet_time;
else
gettimeofday (&now, NULL);
if ((expiry = EXPIRY_MIN (EXPIRIES, &ft->expiries)) == NULL)
return (-1); /* indefinite */
expires_at = expiry->expires_at;
/* Don't cluster urgent expiries */
if (expires_at == 0 && (expiry->reason == R_OVERBYTES ||
expiry->reason == R_OVERFLOWS
|| expiry->reason == R_FLUSH))
return (0); /* Now */
/* Cluster expiries by expiry_interval */
if (ft->param.expiry_interval > 1) {
if ((fudge = expires_at % ft->param.expiry_interval) > 0)
expires_at += ft->param.expiry_interval - fudge;
}
if (expires_at < now.tv_sec)
return (0); /* Now */
ret = 999 + (expires_at - now.tv_sec) * 1000;
return (ret);
}
/*
* Scan the tree of expiry events and process expired flows. If zap_all
* is set, then forcibly expire all flows.
*/
#define CE_EXPIRE_NORMAL 0 /* Normal expiry processing */
#define CE_EXPIRE_ALL -1 /* Expire all flows immediately */
#define CE_EXPIRE_FORCED 1 /* Only expire force-expired flows */
static int
check_expired (struct FLOWTRACK *ft, struct NETFLOW_TARGET *target, int ex) {
struct FLOW **expired_flows, **oldexp;
int num_expired, i, r;
struct timeval now;
struct EXPIRY *expiry, *nexpiry;
if (ft->param.adjust_time)
now = ft->param.last_packet_time;
else
gettimeofday (&now, NULL);
r = 0;
num_expired = 0;
expired_flows = NULL;
if (verbose_flag)
logit (LOG_DEBUG, "Starting expiry scan: mode %d", ex);
for (expiry = EXPIRY_MIN (EXPIRIES, &ft->expiries);
expiry != NULL; expiry = nexpiry) {
nexpiry = EXPIRY_NEXT (EXPIRIES, &ft->expiries, expiry);
if ((expiry->expires_at == 0) || (ex == CE_EXPIRE_ALL) ||
(ex != CE_EXPIRE_FORCED && (expiry->expires_at < now.tv_sec))) {
/* Flow has expired */
if (ft->param.maximum_lifetime != 0 &&
expiry->flow->flow_last.tv_sec -
expiry->flow->flow_start.tv_sec >= ft->param.maximum_lifetime)
expiry->reason = R_MAXLIFE;
if (verbose_flag)
logit (LOG_DEBUG,
"Queuing flow seq:%" PRIu64 " (%p) for expiry "
"reason %d", expiry->flow->flow_seq,
expiry->flow, expiry->reason);
/* Add to array of expired flows */
oldexp = expired_flows;
expired_flows = realloc (expired_flows,
sizeof (*expired_flows) * (num_expired + 1));
/* Don't fatal on realloc failures */
if (expired_flows == NULL)
expired_flows = oldexp;
else {
expired_flows[num_expired] = expiry->flow;
num_expired++;
}
if (ex == CE_EXPIRE_ALL)
expiry->reason = R_FLUSH;
update_expiry_stats (ft, expiry);
/* Remove from flow tree, destroy expiry event */
FLOW_REMOVE (FLOWS, &ft->flows, expiry->flow);
EXPIRY_REMOVE (EXPIRIES, &ft->expiries, expiry);
expiry->flow->expiry = NULL;
expiry_put (ft, expiry);
ft->param.num_flows--;
}
}
if (verbose_flag)
logit (LOG_DEBUG, "Finished scan %d flow(s) to be evicted", num_expired);
/* Processing for expired flows */
if (num_expired > 0) {
if (target != NULL) {
struct SENDPARAMETER sp =
{ expired_flows, num_expired, target->num_destinations,
target->destinations, if_index, &ft->param, verbose_flag
};
netflow_send_func_t *func =
ft->param.bidirection == 1 ?
target->dialect->bidir_func : target->dialect->func;
if (func == NULL) {
func = target->dialect->func;
}
#ifdef ENABLE_PTHREAD
if (use_thread) {
pthread_t write_thread = 0;
sp.flows = calloc (num_expired, sizeof (struct FLOW));
memcpy (sp.flows, expired_flows, sizeof (struct FLOW) * num_expired);
if (pthread_create (&write_thread, NULL, (void *) func, (void *) &sp)
< 0) {
perror ("pthread_create error");
exit (1);
}
if (pthread_detach (write_thread) != 0) {
perror ("pthread_detach error");
exit (1);
}
r = 1;
} else
#endif /* ENABLE_PTHREAD */
r = func (sp);
if (verbose_flag)
logit (LOG_DEBUG, "sent %d netflow packets", r);
if (r <= 0)
ft->param.flows_dropped += num_expired * 2; /* XXX what if r < num_expired * 2 ? */
}
for (i = 0; i < num_expired; i++) {
if (verbose_flag) {
logit (LOG_DEBUG, "EXPIRED: %s (%p)",
format_flow (expired_flows[i]), expired_flows[i]);
}
update_statistics (ft, expired_flows[i]);
flow_put (ft, expired_flows[i]);
}
free (expired_flows);
}
return (r == -1 ? -1 : num_expired);
}
/*
* Force expiry of num_to_expire flows (e.g. when flow table overfull)
*/
static void
force_expire (struct FLOWTRACK *ft, u_int32_t num_to_expire) {
struct EXPIRY *expiry, **expiryv;
int i;
/* XXX move all overflow processing here (maybe) */
if (verbose_flag)
logit (LOG_INFO, "Forcing expiry of %d flows", num_to_expire);
/*
* Do this in two steps, as it is dangerous to change a key on
* a tree entry without first removing it and then re-adding it.
* It is even worse when this has to be done during a FOREACH :)
* To get around this, we make a list of expired flows and _then_
* alter them
*/
if ((expiryv = calloc (num_to_expire, sizeof (*expiryv))) == NULL) {