forked from HostSuki/fastnetmon
-
Notifications
You must be signed in to change notification settings - Fork 1
/
fastnetmon.cpp
2671 lines (2069 loc) · 95.8 KB
/
fastnetmon.cpp
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
/* Author: [email protected] */
/* License: GPLv2 */
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <time.h>
#include <math.h>
#include <sys/socket.h>
#include <sys/resource.h>
#include <sys/stat.h>
#include <arpa/inet.h>
#include <netinet/ip.h>
#include <netinet/tcp.h>
#include <netinet/udp.h>
#include <netinet/ip_icmp.h>
#include <netinet/if_ether.h>
#include <netinet/in.h>
#include <netdb.h>
#include "libpatricia/patricia.h"
#include "fastnetmon_types.h"
// Plugins
#include "sflow_plugin/sflow_collector.h"
#include "netflow_plugin/netflow_collector.h"
#include "pcap_plugin/pcap_collector.h"
#ifdef PF_RING
#include "pfring_plugin/pfring_collector.h"
#endif
// Yes, maybe it's not an good idea but with this we can guarantee working code in example plugin
#include "example_plugin/example_collector.h"
#include <algorithm>
#include <iostream>
#include <map>
#include <fstream>
#include <vector>
#include <utility>
#include <sstream>
#include <boost/thread.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/regex.hpp>
// log4cpp logging facility
#include "log4cpp/Category.hh"
#include "log4cpp/Appender.hh"
#include "log4cpp/FileAppender.hh"
#include "log4cpp/OstreamAppender.hh"
#include "log4cpp/Layout.hh"
#include "log4cpp/BasicLayout.hh"
#include "log4cpp/PatternLayout.hh"
#include "log4cpp/Priority.hh"
// Boost libs
#include <boost/algorithm/string.hpp>
#ifdef GEOIP
#include "GeoIP.h"
#endif
#ifdef REDIS
#include <hiredis/hiredis.h>
#endif
std::string global_config_path = "/etc/fastnetmon.conf";
boost::regex regular_expression_cidr_pattern("^\\d+\\.\\d+\\.\\d+\\.\\d+\\/\\d+$");
time_t last_call_of_traffic_recalculation;
// Variable with all data from main screen
std::string screen_data_stats = "";
// Global map with parsed config file
std::map<std::string, std::string> configuration_map;
/* Configuration block, we must move it to configuration file */
#ifdef REDIS
unsigned int redis_port = 6379;
std::string redis_host = "127.0.0.1";
// because it's additional and very specific feature we should disable it by default
bool redis_enabled = false;
#endif
bool enable_ban_for_pps = false;
bool enable_ban_for_bandwidth = false;
bool enable_ban_for_flows_per_second = false;
bool enable_conection_tracking = true;
bool enable_data_collection_from_mirror = true;
bool enable_sflow_collection = false;
bool enable_netflow_collection = false;
bool enable_pcap_collection = false;
// Time consumed by reaclculation for all IPs
struct timeval speed_calculation_time;
// Time consumed by drawing stats for all IPs
struct timeval drawing_thread_execution_time;
// Total number of hosts in our networks
// We need this as global variable because it's very important value for configuring data structures
unsigned int total_number_of_hosts_in_our_networks = 0;
#ifdef GEOIP
GeoIP * geo_ip = NULL;
#endif
patricia_tree_t *lookup_tree, *whitelist_tree;
bool DEBUG = 0;
// flag about dumping all packets to log
bool DEBUG_DUMP_ALL_PACKETS = false;
// Period for update screen for console version of tool
unsigned int check_period = 3;
// Standard ban time in seconds for all attacks but you can tune this value
int standard_ban_time = 1800;
// We calc average pps/bps for this time
double average_calculation_amount = 15;
// Show average or absolute value of speed
bool print_average_traffic_counts = true;
// Key used for sorting clients in output. Allowed sort params: packets/bytes
std::string sort_parameter = "packets";
// Path to notify script
std::string notify_script_path = "/usr/local/bin/notify_about_attack.sh";
// Number of lines in programm output
unsigned int max_ips_in_list = 7;
// We must ban IP if it exceeed this limit in PPS
unsigned int ban_threshold_pps = 20000;
// We must ban IP of it exceed this limit for number of flows in any direction
unsigned int ban_threshold_flows = 3500;
// We must ban client if it exceed 1GBps
unsigned int ban_threshold_mbps = 1000;
// Number of lines for sending ben attack details to email
unsigned int ban_details_records_count = 500;
// log file
log4cpp::Category& logger = log4cpp::Category::getRoot();
std::string log_file_path = "/var/log/fastnetmon.log";
std::string attack_details_folder = "/var/log/fastnetmon_attacks";
/* Configuration block ends */
/* Our data structs */
// Enum with availible sort by field
enum sort_type { PACKETS, BYTES, FLOWS };
enum direction {
INCOMING = 0,
OUTGOING,
INTERNAL,
OTHER
};
typedef struct {
uint64_t bytes;
uint64_t packets;
uint64_t flows;
} total_counter_element;
// We count total number of incoming/outgoing/internal and other traffic type packets/bytes
// And initilize by 0 all fields
total_counter_element total_counters[4];
total_counter_element total_speed_counters[4];
// Total amount of non parsed packets
uint64_t total_unparsed_packets = 0;
uint64_t incoming_total_flows_speed = 0;
uint64_t outgoing_total_flows_speed = 0;
typedef std::pair<uint32_t, uint32_t> subnet;
// main data structure for storing traffic and speed data for all our IPs
class map_element {
public:
map_element() : in_bytes(0), out_bytes(0), in_packets(0), out_packets(0), tcp_in_packets(0), tcp_out_packets(0), tcp_in_bytes(0), tcp_out_bytes(0),
udp_in_packets(0), udp_out_packets(0), udp_in_bytes(0), udp_out_bytes(0), in_flows(0), out_flows(0),
icmp_in_packets(0), icmp_out_packets(0), icmp_in_bytes(0), icmp_out_bytes(0)
{}
uint64_t in_bytes;
uint64_t out_bytes;
uint64_t in_packets;
uint64_t out_packets;
// Additional data for correct attack protocol detection
uint64_t tcp_in_packets;
uint64_t tcp_out_packets;
uint64_t tcp_in_bytes;
uint64_t tcp_out_bytes;
uint64_t udp_in_packets;
uint64_t udp_out_packets;
uint64_t udp_in_bytes;
uint64_t udp_out_bytes;
uint64_t icmp_in_packets;
uint64_t icmp_out_packets;
uint64_t icmp_in_bytes;
uint64_t icmp_out_bytes;
uint64_t in_flows;
uint64_t out_flows;
};
// structure with attack details
class attack_details : public map_element {
public:
attack_details() :
attack_protocol(0), attack_power(0), max_attack_power(0), average_in_bytes(0), average_out_bytes(0), average_in_packets(0), average_out_packets(0), average_in_flows(0), average_out_flows(0) {
}
direction attack_direction;
// first attackpower detected
uint64_t attack_power;
// max attack power
uint64_t max_attack_power;
unsigned int attack_protocol;
// Average counters
uint64_t average_in_bytes;
uint64_t average_out_bytes;
uint64_t average_in_packets;
uint64_t average_out_packets;
uint64_t average_in_flows;
uint64_t average_out_flows;
// time when we but this user
time_t ban_timestamp;
int ban_time; // seconds of the ban
};
typedef attack_details banlist_item;
// struct for save per direction and per protocol details for flow
typedef struct {
uint64_t bytes;
uint64_t packets;
// will be used for Garbage Collection
time_t last_update_time;
} conntrack_key_struct;
typedef uint64_t packed_session;
// Main mega structure for storing conntracks
// We should use class instead struct for correct std::map allocation
typedef std::map<packed_session, conntrack_key_struct> contrack_map_type;
class conntrack_main_struct {
public:
contrack_map_type in_tcp;
contrack_map_type in_udp;
contrack_map_type in_icmp;
contrack_map_type in_other;
contrack_map_type out_tcp;
contrack_map_type out_udp;
contrack_map_type out_icmp;
contrack_map_type out_other;
};
typedef std::map <uint32_t, map_element> map_for_counters;
typedef std::vector<map_element> vector_of_counters;
typedef std::map <unsigned long int, vector_of_counters> map_of_vector_counters;
map_of_vector_counters SubnetVectorMap;
// Flow tracking structures
typedef std::vector<conntrack_main_struct> vector_of_flow_counters;
typedef std::map <unsigned long int, vector_of_flow_counters> map_of_vector_counters_for_flow;
map_of_vector_counters_for_flow SubnetVectorMapFlow;
class packed_conntrack_hash {
public:
packed_conntrack_hash() : opposite_ip(0), src_port(0), dst_port(0) { }
// src or dst IP
uint32_t opposite_ip;
uint16_t src_port;
uint16_t dst_port;
};
// data structure for storing data in Vector
typedef std::pair<uint32_t, map_element> pair_of_map_elements;
/* End of our data structs */
boost::mutex data_counters_mutex;
boost::mutex speed_counters_mutex;
boost::mutex total_counters_mutex;
boost::mutex ban_list_details_mutex;
boost::mutex ban_list_mutex;
boost::mutex flow_counter;
#ifdef REDIS
redisContext *redis_context = NULL;
#endif
// map for flows
std::map<uint64_t, int> FlowCounter;
// Struct for string speed per IP
map_for_counters SpeedCounter;
// Struct for storing average speed per IP for specified interval
map_for_counters SpeedCounterAverage;
#ifdef GEOIP
map_for_counters GeoIpCounter;
#endif
// In ddos info we store attack power and direction
std::map<uint32_t, banlist_item> ban_list;
std::map<uint32_t, std::vector<simple_packet> > ban_list_details;
std::vector<subnet> our_networks;
std::vector<subnet> whitelist_networks;
// Ban enable/disable flag
bool we_do_real_ban = true;
bool process_incoming_traffic = true;
bool process_outgoing_traffic = true;
// Prototypes
#ifdef HWFILTER_LOCKING
void block_all_traffic_with_82599_hardware_filtering(std::string client_ip_as_string);
#endif
unsigned int get_max_used_protocol(uint64_t tcp, uint64_t udp, uint64_t icmp);
std::string get_printable_protocol_name(unsigned int protocol);
void print_attack_details_to_file(std::string details, std::string client_ip_as_string, attack_details current_attack);
bool folder_exists(std::string path);
std::string print_time_t_in_fastnetmon_format(time_t current_time);
std::string print_ban_thresholds();
bool load_configuration_file();
std::string print_flow_tracking_for_ip(conntrack_main_struct& conntrack_element, std::string client_ip);
void convert_integer_to_conntrack_hash_struct(packed_session* packed_connection_data, packed_conntrack_hash* unpacked_data);
uint64_t convert_conntrack_hash_struct_to_integer(packed_conntrack_hash* struct_value);
int timeval_subtract (struct timeval * result, struct timeval * x, struct timeval * y);
bool is_cidr_subnet(const char* subnet);
uint64_t MurmurHash64A (const void * key, int len, uint64_t seed);
void cleanup_ban_list();
std::string print_tcp_flags(uint8_t flag_value);
int extract_bit_value(uint8_t num, int bit);
std::string get_attack_description(uint32_t client_ip, attack_details& current_attack);
uint64_t convert_speed_to_mbps(uint64_t speed_in_bps);
void send_attack_details(uint32_t client_ip, attack_details current_attack_details);
std::string convert_timeval_to_date(struct timeval tv);
void free_up_all_resources();
unsigned int get_cidr_mask_from_network_as_string(std::string network_cidr_format);
std::string print_ddos_attack_details();
void execute_ip_ban(uint32_t client_ip, map_element new_speed_element, uint64_t in_pps, uint64_t out_pps, uint64_t in_bps, uint64_t out_bps, uint64_t in_flows, uint64_t out_flows, std::string flow_attack_details);
direction get_packet_direction(uint32_t src_ip, uint32_t dst_ip, unsigned long& subnet);
void recalculate_speed();
std::string print_channel_speed(std::string traffic_type, direction packet_direction);
void process_packet(simple_packet& current_packet);
void copy_networks_from_string_form_to_binary(std::vector<std::string> networks_list_as_string, std::vector<subnet>& our_networks);
bool file_exists(std::string path);
void traffic_draw_programm();
void ulog_main_loop();
void signal_handler(int signal_number);
uint32_t convert_cidr_to_binary_netmask(unsigned int cidr);
/* Class for custom comparison fields by different fields */
class TrafficComparatorClass {
private:
sort_type sort_field;
direction sort_direction;
public:
TrafficComparatorClass(direction sort_direction, sort_type sort_field) {
this->sort_field = sort_field;
this->sort_direction = sort_direction;
}
bool operator()(pair_of_map_elements a, pair_of_map_elements b) {
if (sort_field == FLOWS) {
if (sort_direction == INCOMING) {
return a.second.in_flows > b.second.in_flows;
} else if (sort_direction == OUTGOING) {
return a.second.out_flows > b.second.out_flows;
} else {
return false;
}
} else if (sort_field == PACKETS) {
if (sort_direction == INCOMING) {
return a.second.in_packets > b.second.in_packets;
} else if (sort_direction == OUTGOING) {
return a.second.out_packets > b.second.out_packets;
} else {
return false;
}
} else if (sort_field == BYTES) {
if (sort_direction == INCOMING) {
return a.second.in_bytes > b.second.in_bytes;
} else if (sort_direction == OUTGOING) {
return a.second.out_bytes > b.second.out_bytes;
} else {
return false;
}
} else {
return false;
}
}
};
std::string get_direction_name(direction direction_value) {
std::string direction_name;
switch (direction_value) {
case INCOMING: direction_name = "incoming"; break;
case OUTGOING: direction_name = "outgoing"; break;
case INTERNAL: direction_name = "internal"; break;
case OTHER: direction_name = "other"; break;
default: direction_name = "unknown"; break;
}
return direction_name;
}
uint32_t convert_ip_as_string_to_uint(std::string ip) {
struct in_addr ip_addr;
inet_aton(ip.c_str(), &ip_addr);
// in network byte order
return ip_addr.s_addr;
}
std::string convert_ip_as_uint_to_string(uint32_t ip_as_integer) {
struct in_addr ip_addr;
ip_addr.s_addr = ip_as_integer;
return (std::string)inet_ntoa(ip_addr);
}
// convert integer to string
std::string convert_int_to_string(int value) {
std::stringstream out;
out << value;
return out.str();
}
// convert string to integer
int convert_string_to_integer(std::string line) {
return atoi(line.c_str());
}
// exec command in shell
std::vector<std::string> exec(std::string cmd) {
std::vector<std::string> output_list;
FILE* pipe = popen(cmd.c_str(), "r");
if (!pipe) return output_list;
char buffer[256];
std::string result = "";
while(!feof(pipe)) {
if(fgets(buffer, 256, pipe) != NULL) {
size_t newbuflen = strlen(buffer);
// remove newline at the end
if (buffer[newbuflen - 1] == '\n') {
buffer[newbuflen - 1] = '\0';
}
output_list.push_back(buffer);
}
}
pclose(pipe);
return output_list;
}
// exec command and pass data to it stdin
bool exec_with_stdin_params(std::string cmd, std::string params) {
FILE* pipe = popen(cmd.c_str(), "w");
if (!pipe) {
logger<<log4cpp::Priority::ERROR<<"Can't execute programm "<<cmd<<" error code: "<<errno<<" error text: "<<strerror(errno);
return false;
}
if (fputs(params.c_str(), pipe)) {
fclose(pipe);
return true;
} else {
logger<<log4cpp::Priority::ERROR<<"Can't pass data to stdin of programm "<<cmd;
fclose(pipe);
return false;
}
}
#ifdef GEOIP
bool geoip_init() {
// load GeoIP ASN database to memory
geo_ip = GeoIP_open("/root/fastnetmon/GeoIPASNum.dat", GEOIP_MEMORY_CACHE);
if (geo_ip == NULL) {
return false;
} else {
return true;
}
}
#endif
#ifdef REDIS
bool redis_init_connection() {
struct timeval timeout = { 1, 500000 }; // 1.5 seconds
redis_context = redisConnectWithTimeout(redis_host.c_str(), redis_port, timeout);
if (redis_context->err) {
logger<<log4cpp::Priority::INFO<<"Connection error:"<<redis_context->errstr;
return false;
}
// We should check connection with ping because redis do not check connection
redisReply* reply = (redisReply*)redisCommand(redis_context, "PING");
if (reply) {
freeReplyObject(reply);
} else {
return false;
}
return true;
}
void update_traffic_in_redis(uint32_t ip, unsigned int traffic_bytes, direction my_direction) {
std::string ip_as_string = convert_ip_as_uint_to_string(ip);
redisReply *reply;
if (!redis_context) {
logger<< log4cpp::Priority::INFO<<"Please initialize Redis handle";
return;
}
std::string key_name = ip_as_string + "_" + get_direction_name(my_direction);
reply = (redisReply *)redisCommand(redis_context, "INCRBY %s %s", key_name.c_str(), convert_int_to_string(traffic_bytes).c_str());
// If we store data correctly ...
if (!reply) {
logger.error("Can't increment traffic in redis error_code: %d error_string: %s", redis_context->err, redis_context->errstr);
// Handle redis server restart corectly
if (redis_context->err == 1 or redis_context->err == 3) {
// Connection refused
redis_init_connection();
}
} else {
freeReplyObject(reply);
}
}
#endif
std::string draw_table(map_for_counters& my_map_packets, direction data_direction, bool do_redis_update, sort_type sort_item) {
std::vector<pair_of_map_elements> vector_for_sort;
std::stringstream output_buffer;
// Preallocate memory for sort vector
vector_for_sort.reserve(my_map_packets.size());
for( map_for_counters::iterator ii = my_map_packets.begin(); ii != my_map_packets.end(); ++ii) {
// store all elements into vector for sorting
vector_for_sort.push_back( std::make_pair((*ii).first, (*ii).second) );
}
if (data_direction == INCOMING or data_direction == OUTGOING) {
std::sort( vector_for_sort.begin(), vector_for_sort.end(), TrafficComparatorClass(data_direction, sort_item));
} else {
logger<< log4cpp::Priority::INFO<<"Unexpected bahaviour on sort function";
}
unsigned int element_number = 0;
for( std::vector<pair_of_map_elements>::iterator ii=vector_for_sort.begin(); ii!=vector_for_sort.end(); ++ii) {
uint32_t client_ip = (*ii).first;
std::string client_ip_as_string = convert_ip_as_uint_to_string((*ii).first);
uint64_t pps = 0;
uint64_t bps = 0;
uint64_t flows = 0;
uint64_t pps_average = 0;
uint64_t bps_average = 0;
uint64_t flows_average = 0;
// TODO: replace map by vector iteration
map_element* current_average_speed_element = &SpeedCounterAverage[client_ip];
map_element* current_speed_element = &SpeedCounter[client_ip];
// Create polymorphic pps, byte and flow counters
if (data_direction == INCOMING) {
pps = current_speed_element->in_packets;
bps = current_speed_element->in_bytes;
flows = current_speed_element->in_flows;
pps_average = current_average_speed_element->in_packets;
bps_average = current_average_speed_element->in_bytes;
flows_average = current_average_speed_element->in_flows;
} else if (data_direction == OUTGOING) {
pps = current_speed_element->out_packets;
bps = current_speed_element->out_bytes;
flows = current_speed_element->out_flows;
pps_average = current_average_speed_element->out_packets;
bps_average = current_average_speed_element->out_bytes;
flows_average = current_average_speed_element->out_flows;
}
uint64_t mbps = convert_speed_to_mbps(bps);
uint64_t mbps_average = convert_speed_to_mbps(bps_average);
// Print first max_ips_in_list elements in list, we will show top 20 "huge" channel loaders
if (element_number < max_ips_in_list) {
std::string is_banned = ban_list.count(client_ip) > 0 ? " *banned* " : "";
// We use setw for alignment
output_buffer<<client_ip_as_string << "\t\t";
if (print_average_traffic_counts) {
output_buffer<<std::setw(6)<<pps_average << " pps ";
output_buffer<<std::setw(6)<<mbps_average << " mbps ";
output_buffer<<std::setw(6)<<flows_average << " flows ";
} else {
output_buffer<<std::setw(6)<< pps <<" pps ";
output_buffer<<std::setw(6)<< mbps <<" mbps ";
output_buffer<<std::setw(6)<< flows <<" flows ";
}
output_buffer<< is_banned << std::endl;
}
#ifdef REDIS
if (redis_enabled && do_redis_update) {
update_traffic_in_redis( (*ii).first, (*ii).second.in_packets, INCOMING);
update_traffic_in_redis( (*ii).first, (*ii).second.out_packets, OUTGOING);
}
#endif
element_number++;
}
return output_buffer.str();
}
// check file existence
bool file_exists(std::string path) {
FILE* check_file = fopen(path.c_str(), "r");
if (check_file) {
fclose(check_file);
return true;
} else {
return false;
}
}
// read whole file to vector
std::vector<std::string> read_file_to_vector(std::string file_name) {
std::vector<std::string> data;
std::string line;
std::ifstream reading_file;
reading_file.open(file_name.c_str(), std::ifstream::in);
if (reading_file.is_open()) {
while ( getline(reading_file, line) ) {
data.push_back(line);
}
} else {
logger<< log4cpp::Priority::ERROR <<"Can't open file: "<<file_name;
}
return data;
}
// Load configuration
bool load_configuration_file() {
std::ifstream config_file (global_config_path.c_str());
std::string line;
if (!config_file.is_open()) {
logger<< log4cpp::Priority::ERROR<<"Can't open config file";
return false;
}
while ( getline(config_file, line) ) {
std::vector<std::string> parsed_config;
boost::split( parsed_config, line, boost::is_any_of(" ="), boost::token_compress_on );
if (parsed_config.size() == 2) {
configuration_map[ parsed_config[0] ] = parsed_config[1];
} else {
logger<< log4cpp::Priority::ERROR<<"Can't parse config line: "<<line;
}
}
if (configuration_map.count("enable_connection_tracking")) {
if (configuration_map["enable_connection_tracking"] == "on") {
enable_conection_tracking = true;
} else {
enable_conection_tracking = false;
}
}
if (configuration_map.count("ban_time") != 0) {
standard_ban_time = convert_string_to_integer(configuration_map["ban_time"]);
}
if (configuration_map.count("average_calculation_time") != 0) {
average_calculation_amount = convert_string_to_integer(configuration_map["average_calculation_time"]);
}
if (configuration_map.count("threshold_pps") != 0) {
ban_threshold_pps = convert_string_to_integer( configuration_map[ "threshold_pps" ] );
}
if (configuration_map.count("threshold_mbps") != 0) {
ban_threshold_mbps = convert_string_to_integer( configuration_map[ "threshold_mbps" ] );
}
if (configuration_map.count("threshold_flows") != 0) {
ban_threshold_flows = convert_string_to_integer( configuration_map[ "threshold_flows" ] );
}
if (configuration_map.count("enable_ban") != 0) {
if (configuration_map["enable_ban"] == "on") {
we_do_real_ban = true;
} else {
we_do_real_ban = false;
}
}
if (configuration_map.count("sflow") != 0) {
if (configuration_map[ "sflow" ] == "on") {
enable_sflow_collection = true;
} else {
enable_sflow_collection = false;
}
}
if (configuration_map.count("netflow") != 0) {
if (configuration_map[ "netflow" ] == "on") {
enable_netflow_collection = true;
} else {
enable_netflow_collection = false;
}
}
if (configuration_map.count("process_incoming_traffic") != 0) {
process_incoming_traffic = configuration_map[ "process_incoming_traffic" ] == "on" ? true : false;
}
if (configuration_map.count("process_outgoing_traffic") != 0) {
process_outgoing_traffic = configuration_map[ "process_outgoing_traffic" ] == "on" ? true : false;
}
if (configuration_map.count("mirror") != 0) {
if (configuration_map["mirror"] == "on") {
enable_data_collection_from_mirror = true;
} else {
enable_data_collection_from_mirror = false;
}
}
if (configuration_map.count("pcap") != 0) {
if (configuration_map["pcap"] == "on") {
enable_pcap_collection = true;
} else {
enable_pcap_collection = false;
}
}
if (configuration_map.count("ban_for_pps") != 0) {
if (configuration_map["ban_for_pps"] == "on") {
enable_ban_for_pps = true;
} else {
enable_ban_for_pps = false;
}
}
if (configuration_map.count("ban_for_bandwidth") != 0) {
if (configuration_map["ban_for_bandwidth"] == "on") {
enable_ban_for_bandwidth = true;
} else {
enable_ban_for_bandwidth = false;
}
}
if (configuration_map.count("ban_for_flows") != 0) {
if (configuration_map["ban_for_flows"] == "on") {
enable_ban_for_flows_per_second = true;
} else {
enable_ban_for_flows_per_second = false;
}
}
#ifdef REDIS
if (configuration_map.count("redis_port") != 0) {
redis_port = convert_string_to_integer(configuration_map[ "redis_port" ] );
}
if (configuration_map.count("redis_host") != 0) {
redis_host = configuration_map[ "redis_host" ];
}
if (configuration_map.count("redis_enabled") != 0) {
if (configuration_map[ "redis_enabled" ] == "yes") {
redis_enabled = true;
} else {
redis_enabled = false;
}
}
#endif
if (configuration_map.count("ban_details_records_count") != 0 ) {
ban_details_records_count = convert_string_to_integer( configuration_map[ "ban_details_records_count" ]);
}
if (configuration_map.count("check_period") != 0) {
check_period = convert_string_to_integer( configuration_map[ "check_period" ]);
}
if (configuration_map.count("sort_parameter") != 0) {
sort_parameter = configuration_map[ "sort_parameter" ];
}
if (configuration_map.count("max_ips_in_list") != 0) {
max_ips_in_list = convert_string_to_integer( configuration_map[ "max_ips_in_list" ]);
}
if (configuration_map.count("notify_script_path") != 0 ) {
notify_script_path = configuration_map[ "notify_script_path" ];
}
return true;
}
/* Enable core dumps for simplify debug tasks */
void enable_core_dumps() {
struct rlimit rlim;
int result = getrlimit(RLIMIT_CORE, &rlim);
if (result) {
logger<< log4cpp::Priority::ERROR<<"Can't get current rlimit for RLIMIT_CORE";
return;
} else {
rlim.rlim_cur = rlim.rlim_max;
setrlimit(RLIMIT_CORE, &rlim);
}
}
void subnet_vectors_allocator(prefix_t* prefix, void* data) {
// Network byte order
uint32_t subnet_as_integer = prefix->add.sin.s_addr;
u_short bitlen = prefix->bitlen;
double base = 2;
int network_size_in_ips = pow(base, 32-bitlen);
//logger<< log4cpp::Priority::INFO<<"Subnet: "<<prefix->add.sin.s_addr<<" network size: "<<network_size_in_ips;
logger<< log4cpp::Priority::INFO<<"I will allocate "<<network_size_in_ips<<" records for subnet "<<subnet_as_integer<<" cidr mask: "<<bitlen;
// Initialize map element
SubnetVectorMap[subnet_as_integer] = vector_of_counters(network_size_in_ips);
// Zeroify all vector elements
map_element zero_map_element;
memset(&zero_map_element, 0, sizeof(zero_map_element));
std::fill(SubnetVectorMap[subnet_as_integer].begin(), SubnetVectorMap[subnet_as_integer].end(), zero_map_element);
// Initilize map element
SubnetVectorMapFlow[subnet_as_integer] = vector_of_flow_counters(network_size_in_ips);
// On creating it initilizes by zeros
conntrack_main_struct zero_conntrack_main_struct;
std::fill(SubnetVectorMapFlow[subnet_as_integer].begin(), SubnetVectorMapFlow[subnet_as_integer].end(), zero_conntrack_main_struct);
}
void zeroify_all_counters() {
map_element zero_map_element;
memset(&zero_map_element, 0, sizeof(zero_map_element));
for (map_of_vector_counters::iterator itr = SubnetVectorMap.begin(); itr != SubnetVectorMap.end(); itr++) {
//logger<< log4cpp::Priority::INFO<<"Zeroify "<<itr->first;
std::fill(itr->second.begin(), itr->second.end(), zero_map_element);
}
}
void zeroify_all_flow_counters() {
// On creating it initilizes by zeros
conntrack_main_struct zero_conntrack_main_struct;
// Iterate over map
for (map_of_vector_counters_for_flow::iterator itr = SubnetVectorMapFlow.begin(); itr != SubnetVectorMapFlow.end(); itr++) {
// Iterate over vector
for (vector_of_flow_counters::iterator vector_iterator = itr->second.begin(); vector_iterator != itr->second.end(); vector_iterator++) {
// TODO: rewrite this monkey code
vector_iterator->in_tcp.clear();
vector_iterator->in_udp.clear();
vector_iterator->in_icmp.clear();
vector_iterator->in_other.clear();
vector_iterator->out_tcp.clear();
vector_iterator->out_udp.clear();
vector_iterator->out_icmp.clear();
vector_iterator->out_other.clear();
}
}
}
bool load_our_networks_list() {
if (file_exists("/etc/networks_whitelist")) {
std::vector<std::string> network_list_from_config = read_file_to_vector("/etc/networks_whitelist");
for( std::vector<std::string>::iterator ii=network_list_from_config.begin(); ii!=network_list_from_config.end(); ++ii) {
if (ii->length() > 0 && is_cidr_subnet(ii->c_str())) {
make_and_lookup(whitelist_tree, const_cast<char*>(ii->c_str()));
} else {
logger<<log4cpp::Priority::ERROR<<"Can't parse line from whitelist: "<<*ii;
}
}
logger<<log4cpp::Priority::INFO<<"We loaded "<<network_list_from_config.size()<< " networks from whitelist file";
}
std::vector<std::string> networks_list_as_string;
// We can bould "our subnets" automatically here
if (file_exists("/proc/vz/version")) {
logger<< log4cpp::Priority::INFO<<"We found OpenVZ";
// Add /32 CIDR mask for every IP here
std::vector<std::string> openvz_ips = read_file_to_vector("/proc/vz/veip");
for( std::vector<std::string>::iterator ii=openvz_ips.begin(); ii!=openvz_ips.end(); ++ii) {
// skip IPv6 addresses
if (strstr(ii->c_str(), ":") != NULL) {
continue;
}
// skip header
if (strstr(ii->c_str(), "Version") != NULL) {
continue;
}
std::vector<std::string> subnet_as_string;
split( subnet_as_string, *ii, boost::is_any_of(" "), boost::token_compress_on );
std::string openvz_subnet = subnet_as_string[1] + "/32";
networks_list_as_string.push_back(openvz_subnet);
}
logger<<log4cpp::Priority::INFO<<"We loaded "<<networks_list_as_string.size()<< " networks from /proc/vz/version";
}
if (file_exists("/etc/networks_list")) {
std::vector<std::string> network_list_from_config = read_file_to_vector("/etc/networks_list");
networks_list_as_string.insert(networks_list_as_string.end(), network_list_from_config.begin(), network_list_from_config.end());
logger<<log4cpp::Priority::INFO<<"We loaded "<<network_list_from_config.size()<< " networks from networks file";
}
// Some consistency checks
assert( convert_ip_as_string_to_uint("255.255.255.0") == convert_cidr_to_binary_netmask(24) );
assert( convert_ip_as_string_to_uint("255.255.255.255") == convert_cidr_to_binary_netmask(32) );
for( std::vector<std::string>::iterator ii=networks_list_as_string.begin(); ii!=networks_list_as_string.end(); ++ii) {
if (ii->length() > 0 && is_cidr_subnet(ii->c_str())) {
unsigned int cidr_mask = get_cidr_mask_from_network_as_string(*ii);
double base = 2;
total_number_of_hosts_in_our_networks += pow(base, 32-cidr_mask);
make_and_lookup(lookup_tree, const_cast<char*>(ii->c_str()));
} else {
logger<<log4cpp::Priority::ERROR<<"Can't parse line from subnet list: "<<*ii;
}
}