forked from pavel-odintsov/fastnetmon
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfastnetmon.cpp
More file actions
1676 lines (1310 loc) · 56.9 KB
/
fastnetmon.cpp
File metadata and controls
1676 lines (1310 loc) · 56.9 KB
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: pavel.odintsov@gmail.com */
/* 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 <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 "libpatricia/patricia.h"
#include "lru_cache/lru_cache.h"
#include <ncurses.h>
#include <algorithm>
#include <iostream>
#include <map>
#include <fstream>
#include <vector>
#include <utility>
#include <sstream>
#include <boost/thread.hpp>
#include <boost/thread/mutex.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 ULOG2
#include "libipulog.h"
#endif
#ifdef GEOIP
#include "GeoIP.h"
#endif
#ifdef PCAP
#include <pcap.h>
#endif
#ifdef REDIS
#include <hiredis/hiredis.h>
#endif
#ifdef PF_RING
#include "pfring.h"
#endif
using namespace std;
/* 802.1Q VLAN tags are 4 bytes long. */
#define VLAN_HDRLEN 4
/* Complete list of ethertypes: http://en.wikipedia.org/wiki/EtherType */
/* This is the decimal equivalent of the VLAN tag's ether frame type */
#define VLAN_ETHERTYPE 0x8100
#define IP_ETHERTYPE 0x0800
#define IP6_ETHERTYPE 0x86dd
#define ARP_ETHERTYPE 0x0806
// Interface name or interface list (delimitered by comma)
string work_on_interfaces = "";
time_t last_call_of_traffic_recalculation;
/* Configuration block, we must move it to configuration file */
#ifdef REDIS
int redis_port = 6379;
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
typedef LRUCache<uint32_t, bool> lpm_cache_t;
// Total number of hosts in our networks
// We need this as global variable because it's very important value for configuring data structures
int total_number_of_hosts_in_our_networks = 0;
// LPM cache
lpm_cache_t *lpm_cache = NULL;
#ifdef GEOIP
GeoIP * geo_ip = NULL;
#endif
patricia_tree_t *lookup_tree, *whitelist_tree;
#ifdef ULOG2
// netlink group number for listening for traffic
int ULOGD_NLGROUP_DEFAULT = 1;
/* Size of the socket receive memory. Should be at least the same size as the 'nlbufsiz' module loadtime
parameter of ipt_ULOG.o If you have _big_ in-kernel queues, you may have to increase this number. (
* --qthreshold 100 * 1500 bytes/packet = 150kB */
int ULOGD_RMEM_DEFAULT = 131071;
/* Size of the receive buffer for the netlink socket. Should be at least of RMEM_DEFAULT size. */
int ULOGD_BUFSIZE_DEFAULT = 150000;
#endif
int DEBUG = 0;
// flag about dumping all packets to console
bool DEBUG_DUMP_ALL_PACKETS = false;
// Period for recounting pps/traffic
int check_period = 3;
#ifdef PCAP
// Enlarge receive buffer for PCAP for minimize packet drops
int pcap_buffer_size_mbytes = 10;
#endif
// Key used for sorting clients in output. Allowed sort params: packets/bytes
string sort_parameter = "packets";
// Path to notify script
string notify_script_path = "/usr/local/bin/notify_about_attack.sh";
// Number of lines in programm output
int max_ips_in_list = 7;
// We must ban IP if it exceeed this limit in PPS
int ban_threshold = 20000;
// Number of lines for sending ben attack details to email
int ban_details_records_count = 500;
// log file
log4cpp::Category& logger = log4cpp::Category::getRoot();
string log_file_path = "/var/log/fastnetmon.log";
/* Configuration block ends */
/* Our data structs */
// Enum with availible sort by field
enum sort_type { PACKETS, BYTES };
enum direction {
INCOMING = 0,
OUTGOING,
INTERNAL,
OTHER
};
typedef struct {
int bytes;
int packets;
} 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];
// simplified packet struct for lightweight save into memory
struct simple_packet {
uint32_t src_ip;
uint32_t dst_ip;
uint16_t source_port;
uint16_t destination_port;
int protocol;
int length;
struct timeval ts;
};
typedef pair<int, direction> banlist_item;
typedef pair<uint32_t, uint32_t> subnet;
// main data structure for storing traffic data for all our IPs
typedef struct {
int in_bytes;
int out_bytes;
int in_packets;
int out_packets;
} map_element;
typedef struct {
uint16_t source_port;
uint16_t destination_port;
uint32_t src_ip;
uint32_t dst_ip;
} conntrack_key;
typedef std::map <uint32_t, map_element> map_for_counters;
// data structure for storing data in Vector
typedef 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;
#ifdef REDIS
redisContext *redis_context = NULL;
#endif
#ifdef ULOG2
// For counting number of communication errors via netlink
int netlink_error_counter = 0;
int netlink_packets_counter = 0;
#endif
#ifdef PCAP
// pcap handler, we want it as global variable beacuse it used in singnal handler
pcap_t* descr = NULL;
#endif
#ifdef PF_RING
pfring* pf_ring_descr = NULL;
#endif
// main map for storing traffic data
map_for_counters DataCounter;
// структура для сохранения мгновенных скоростей
map_for_counters SpeedCounter;
#ifdef GEOIP
map_for_counters GeoIpCounter;
#endif
// В информации о ддосе мы храним силу атаки и ее направление
map<uint32_t, banlist_item> ban_list;
map<uint32_t, vector<simple_packet> > ban_list_details;
// стандартно у нас смещение для типа DLT_EN10MB, Ethernet
int DATA_SHIFT_VALUE = 14;
// начальный размер unordered_map для хранения данных
int MAP_INITIAL_SIZE = 2048;
vector<subnet> our_networks;
vector<subnet> whitelist_networks;
/*
Тут кроется огромный баго-фич:
В случае прослушивания any интерфейсов мы ловим фичу-баг, вместо эзернет хидера у нас тип 113, который LINUX SLL,
а следовательно размер хидера не 14, а 16 байт!
Если мы сниффим один интерфейсе - у нас хидер эзернет, 14 байт, а если ANY, то хидер у нас 16 !!!
packetptr += 14; // Ethernet
packetptr += 16; // LINUX SLL, только в случае указания any интерфейса
Подробнее:
https://github.com/the-tcpdump-group/libpcap/issues/324
http://comments.gmane.org/gmane.network.tcpdump.devel/5043
http://www.tcpdump.org/linktypes/LINKTYPE_LINUX_SLL.html
https://github.com/the-tcpdump-group/libpcap/issues/163
*/
// prototypes
string convert_tiemval_to_date(struct timeval tv);
void free_up_all_resources();
void main_packet_process_task();
int get_cidr_mask_from_network_as_string(string network_cidr_format);
string send_ddos_attack_details();
void execute_ip_ban(uint32_t client_ip, int in_pps, int out_pps, int in_bps, int out_bps);
direction get_packet_direction(uint32_t src_ip, uint32_t dst_ip);
void recalculate_speed();
std::string print_channel_speed(string traffic_type, direction packet_direction);
void process_packet(simple_packet& current_packet);
void copy_networks_from_string_form_to_binary(vector<string> networks_list_as_string, vector<subnet>& our_networks);
bool file_exists(string path);
void calculation_programm();
void pcap_main_loop(const char* dev);
void pf_ring_main_loop(const char* dev);
void parse_packet(u_char *user, struct pcap_pkthdr *packethdr, const u_char *packetptr);
void ulog_main_loop();
void signal_handler(int signal_number);
uint32_t convert_cidr_to_binary_netmask(int cidr);
// Function for sorting Vector of pairs
bool compare_function_by_in_packets (pair_of_map_elements a, pair_of_map_elements b) {
return a.second.in_packets > b.second.in_packets;
}
bool compare_function_by_out_packets (pair_of_map_elements a, pair_of_map_elements b) {
return a.second.out_packets > b.second.out_packets;
}
bool compare_function_by_out_bytes (pair_of_map_elements a, pair_of_map_elements b) {
return a.second.out_bytes > b.second.out_bytes;
}
bool compare_function_by_in_bytes(pair_of_map_elements a, pair_of_map_elements b) {
return a.second.in_bytes > b.second.in_bytes;
}
string get_direction_name(direction direction_value) {
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(string ip) {
struct in_addr ip_addr;
inet_aton(ip.c_str(), &ip_addr);
// in network byte order
return ip_addr.s_addr;
}
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 (string)inet_ntoa(ip_addr);
}
// convert integer to string
string convert_int_to_string(int value) {
std::stringstream out;
out << value;
return out.str();
}
// convert string to integer
int convert_string_to_integer(string line) {
return atoi(line.c_str());
}
// exec command in shell
vector<string> exec(string cmd) {
vector<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(string cmd, string params) {
FILE* pipe = popen(cmd.c_str(), "w");
if (!pipe) return false;
if (fputs(params.c_str(), pipe)) {
fclose(pipe);
return true;
} else {
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;
}
// Нужно проверить соединение пингом, так как, по-моему, оно не првоеряет само подключение при коннекте
redisReply* reply = (redisReply*)redisCommand(redis_context, "PING");
if (reply) {
freeReplyObject(reply);
} else {
return false;
}
return true;
}
void update_traffic_in_redis(uint32_t ip, int traffic_bytes, direction my_direction) {
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;
}
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 (!reply) {
logger.info("Can't increment traffic in redis error_code: %d error_string: %s", redis_context->err, redis_context->errstr);
// Такое может быть в случае перезапуска redis, нам надо попробовать решить это без падения программы
if (redis_context->err == 1 or redis_context->err == 3) {
// Connection refused
redis_init_connection();
}
} else {
freeReplyObject(reply);
}
}
#endif
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;
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) {
// кладем все наши элементы в массив для последующей сортировки при отображении
//pair_of_map_elements current_pair = make_pair((*ii).first, (*ii).second);
vector_for_sort.push_back( make_pair((*ii).first, (*ii).second) );
}
if (sort_item == PACKETS) {
// используем разные сортировочные функции
if (data_direction == INCOMING) {
std::sort( vector_for_sort.begin(), vector_for_sort.end(), compare_function_by_in_packets);
} else if (data_direction == OUTGOING) {
std::sort( vector_for_sort.begin(), vector_for_sort.end(), compare_function_by_out_packets);
} else {
// unexpected
}
} else if (sort_item == BYTES) {
if (data_direction == INCOMING) {
std::sort( vector_for_sort.begin(), vector_for_sort.end(), compare_function_by_in_bytes);
} else if (data_direction == OUTGOING) {
std::sort( vector_for_sort.begin(), vector_for_sort.end(), compare_function_by_out_bytes);
}
} else {
logger<< log4cpp::Priority::INFO<<"Unexpected bahaviour on sort function";
}
int element_number = 0;
for( vector<pair_of_map_elements>::iterator ii=vector_for_sort.begin(); ii!=vector_for_sort.end(); ++ii) {
uint32_t client_ip = (*ii).first;
string client_ip_as_string = convert_ip_as_uint_to_string((*ii).first);
int pps = 0;
int bps = 0;
// делаем "полиморфную" полосу и ппс
if (data_direction == INCOMING) {
pps = SpeedCounter[client_ip].in_packets;
bps = SpeedCounter[client_ip].in_bytes;
} else if (data_direction == OUTGOING) {
pps = SpeedCounter[client_ip].out_packets;
bps = SpeedCounter[client_ip].out_bytes;
}
int mbps = int((double)bps / 1024 / 1024 * 8);
// Выводим первые max_ips_in_list элементов в списке, при нашей сортировке, будут выданы топ 10 самых грузящих клиентов
if (element_number < max_ips_in_list) {
string is_banned = ban_list.count(client_ip) > 0 ? " *banned* " : "";
output_buffer << client_ip_as_string << "\t\t" << pps << " pps " << mbps << " mbps" << is_banned << endl;
}
#ifdef REDIS
if (redis_enabled && do_redis_update) {
//cout<<"Start updating traffic in redis"<<endl;
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(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
vector<string> read_file_to_vector(string file_name) {
vector<string> data;
string line;
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::INFO <<"Can't open file: "<<file_name;
}
return data;
}
// Load configuration
void load_configuration_file() {
ifstream config_file ("/etc/fastnetmon.conf");
string line;
map<string, std::string> configuration_map;
if (config_file.is_open()) {
while ( getline(config_file, line) ) {
vector<string> parsed_config;
split( parsed_config, line, boost::is_any_of(" ="), boost::token_compress_on );
configuration_map[ parsed_config[0] ] = parsed_config[1];
}
if (configuration_map.count("threshold_pps") != 0) {
ban_threshold = convert_string_to_integer( configuration_map[ "threshold_pps" ] );
}
#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) {
sort_parameter = 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("interfaces") != 0) {
work_on_interfaces = configuration_map[ "interfaces" ];
}
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" ];
}
} else {
logger<< log4cpp::Priority::INFO<<"Can't open config file";
}
}
/* 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::INFO<<"Can't get current rlimit for RLIMIT_CORE";
return;
} else {
rlim.rlim_cur = rlim.rlim_max;
setrlimit(RLIMIT_CORE, &rlim);
}
}
bool load_our_networks_list() {
if (file_exists("/etc/networks_whitelist")) {
vector<string> network_list_from_config = read_file_to_vector("/etc/networks_whitelist");
for( vector<string>::iterator ii=network_list_from_config.begin(); ii!=network_list_from_config.end(); ++ii) {
make_and_lookup(whitelist_tree, const_cast<char*>(ii->c_str()));
}
logger<<log4cpp::Priority::INFO<<"We loaded "<<network_list_from_config.size()<< " networks from whitelist file";
}
vector<string> networks_list_as_string;
// если мы на openvz ноде, то "свои" IP мы можем получить из спец-файла в /proc
if (file_exists("/proc/vz/version")) {
logger<< log4cpp::Priority::INFO<<"We found OpenVZ";
// тут искусствено добавляем суффикс 32
vector<string> openvz_ips = read_file_to_vector("/proc/vz/veip");
for( vector<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;
}
vector<string> subnet_as_string;
split( subnet_as_string, *ii, boost::is_any_of(" "), boost::token_compress_on );
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")) {
vector<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";
}
// если это ложь, то в моих функциях косяк
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( vector<string>::iterator ii=networks_list_as_string.begin(); ii!=networks_list_as_string.end(); ++ii) {
int cidr_mask = get_cidr_mask_from_network_as_string(*ii);
total_number_of_hosts_in_our_networks += pow(2, 32-cidr_mask);
make_and_lookup(lookup_tree, const_cast<char*>(ii->c_str()));
}
logger<<log4cpp::Priority::INFO<<"We loaded "<<networks_list_as_string.size()<<" subnets to our in-memory list of networks";
logger<<log4cpp::Priority::INFO<<"Total number of monitored hosts (total size of all networks): "
<<total_number_of_hosts_in_our_networks;
return true;
}
// extract 24 from 192.168.1.1/24
int get_cidr_mask_from_network_as_string(string network_cidr_format) {
vector<string> subnet_as_string;
split( subnet_as_string, network_cidr_format, boost::is_any_of("/"), boost::token_compress_on );
return convert_string_to_integer(subnet_as_string[1]);
}
void copy_networks_from_string_form_to_binary(vector<string> networks_list_as_string, vector<subnet>& our_networks ) {
for( vector<string>::iterator ii=networks_list_as_string.begin(); ii!=networks_list_as_string.end(); ++ii) {
vector<string> subnet_as_string;
split( subnet_as_string, *ii, boost::is_any_of("/"), boost::token_compress_on );
int cidr = convert_string_to_integer(subnet_as_string[1]);
uint32_t subnet_as_int = convert_ip_as_string_to_uint(subnet_as_string[0]);
uint32_t netmask_as_int = convert_cidr_to_binary_netmask(cidr);
subnet current_subnet = std::make_pair(subnet_as_int, netmask_as_int);
our_networks.push_back(current_subnet);
}
}
uint32_t convert_cidr_to_binary_netmask(int cidr) {
uint32_t binary_netmask = 0xFFFFFFFF;
binary_netmask = binary_netmask << ( 32 - cidr );
// htonl from host byte order to network
// ntohl from network byte order to host
// поидее, на выходе тут нужен network byte order
return htonl(binary_netmask);
}
string print_simple_packet(struct simple_packet packet) {
std::stringstream buffer;
string proto_name;
switch (packet.protocol) {
case IPPROTO_TCP:
proto_name = "tcp";
break;
case IPPROTO_UDP:
proto_name = "udp";
break;
case IPPROTO_ICMP:
proto_name = "icmp";
break;
default:
proto_name = "unknown";
break;
}
buffer<<convert_tiemval_to_date(packet.ts)<<" ";
buffer
<<convert_ip_as_uint_to_string(packet.src_ip)<<":"<<packet.source_port
<<" > "
<<convert_ip_as_uint_to_string(packet.dst_ip)<<":"<<packet.destination_port
<<" protocol: "<<proto_name
<<" size: "<<packet.length<<" bytes"<<"\n";
// используется \n вместо endl, ибо иначе начинается хрень всякая при передаче данной строки команде на stdin
return buffer.str();
}
// Обработчик для pf_ring, так как у него иной формат входных параметров
void parse_packet_pf_ring(const struct pfring_pkthdr *h, const u_char *p, const u_char *user_bytes) {
// Описание всех полей: http://www.ntop.org/pfring_api/structpkt__parsing__info.html
simple_packet packet;
/* We handle only IPv4 */
if (h->extended_hdr.parsed_pkt.ip_version == 4) {
/* PF_RING хранит данные в host byte order, а мы использум только network byte order */
packet.src_ip = htonl( h->extended_hdr.parsed_pkt.ip_src.v4 );
packet.dst_ip = htonl( h->extended_hdr.parsed_pkt.ip_dst.v4 );
packet.source_port = h->extended_hdr.parsed_pkt.l4_src_port;
packet.destination_port = h->extended_hdr.parsed_pkt.l4_dst_port;
packet.length = h->len;
packet.protocol = h->extended_hdr.parsed_pkt.l3_proto;
packet.ts = h->ts;
process_packet(packet);
//std::cout<<print_simple_packet(packet)<<std::endl;
//printf("hash%d\n",h->extended_hdr.pkt_hash);
}
}
// в случае прямого вызова скрипта колбэка - нужно конст, напрямую в хендлере - конст не нужно
void parse_packet(u_char *user, struct pcap_pkthdr *packethdr, const u_char *packetptr) {
struct ip* iphdr;
struct tcphdr* tcphdr;
struct udphdr* udphdr;
struct ether_header *eptr; /* net/ethernet.h */
eptr = (struct ether_header* )packetptr;
// проверяем тип эзернет фрейма и его принадлежность к типу "фрейм с VLAN"
if ( ntohs(eptr->ether_type) == VLAN_ETHERTYPE ) {
// это тегированный трафик, поэтому нужно отступить еще 4 байта, чтобы добраться до данных
packetptr += DATA_SHIFT_VALUE + VLAN_HDRLEN;
} else if (ntohs(eptr->ether_type) == IP_ETHERTYPE) {
// Skip the datalink layer header and get the IP header fields.
packetptr += DATA_SHIFT_VALUE;
} else if (ntohs(eptr->ether_type) == IP6_ETHERTYPE or ntohs(eptr->ether_type) == ARP_ETHERTYPE) {
// we know about it but does't not care now
} else {
// printf("Packet with non standard ethertype found: 0x%x\n", ntohs(eptr->ether_type));
}
iphdr = (struct ip*)packetptr;
// исходящий/входящий айпи это in_addr, http://man7.org/linux/man-pages/man7/ip.7.html
uint32_t src_ip = iphdr->ip_src.s_addr;
uint32_t dst_ip = iphdr->ip_dst.s_addr;
// The ntohs() function converts the unsigned short integer netshort from network byte order to host byte order
int packet_length = ntohs(iphdr->ip_len);
simple_packet current_packet;
// Advance to the transport layer header then parse and display
// the fields based on the type of hearder: tcp, udp or icmp
packetptr += 4*iphdr->ip_hl;
switch (iphdr->ip_p) {
case IPPROTO_TCP:
tcphdr = (struct tcphdr*)packetptr;
current_packet.source_port = ntohs(tcphdr->source);
current_packet.destination_port = ntohs(tcphdr->dest);
break;
case IPPROTO_UDP:
udphdr = (struct udphdr*)packetptr;
current_packet.source_port = ntohs(udphdr->source);
current_packet.destination_port = ntohs(udphdr->dest);
break;
case IPPROTO_ICMP:
// there are no port for ICMP
current_packet.source_port = 0;
current_packet.destination_port = 0;
break;
}
current_packet.protocol = iphdr->ip_p;
current_packet.src_ip = src_ip;
current_packet.dst_ip = dst_ip;
current_packet.length = packet_length;
/* Передаем пакет в обработку */
process_packet(current_packet);
}
uint32_t get_packet_hash(simple_packet& packet) {
/*
packet.protocol
packet.src_ip
packet.dst_ip
packet.lenght
packet.source_port
packet.destination_port
*/
return 0;
}
/* Производим обработку уже переданного нам пакета в простом формате */
void process_packet(simple_packet& current_packet) {
// Packets dump is very useful for bug hunting
if (DEBUG_DUMP_ALL_PACKETS) {
logger<< log4cpp::Priority::INFO<<"Dump: "<<print_simple_packet(current_packet);
}
direction packet_direction = get_packet_direction(current_packet.src_ip, current_packet.dst_ip);
total_counters_mutex.lock();
total_counters[packet_direction].packets++;
total_counters[packet_direction].bytes += current_packet.length;
total_counters_mutex.unlock();
if (packet_direction == INTERNAL) {
} else if (packet_direction == OUTGOING) {
// собираем данные для деталей при бане клиента
if (ban_list_details.count(current_packet.src_ip) > 0 &&
ban_list_details[current_packet.src_ip].size() < ban_details_records_count) {
ban_list_details[current_packet.src_ip].push_back(current_packet);
}
data_counters_mutex.lock();
DataCounter[ current_packet.src_ip ].out_packets++;
DataCounter[ current_packet.src_ip ].out_bytes += current_packet.length;
data_counters_mutex.unlock();
} else if (packet_direction == INCOMING) {
// собираемы данные для деталей при бане клиента
if (ban_list_details.count(current_packet.dst_ip) > 0 &&
ban_list_details[current_packet.dst_ip].size() < ban_details_records_count) {
ban_list_details[current_packet.dst_ip].push_back(current_packet);
}
data_counters_mutex.lock();
DataCounter[ current_packet.dst_ip ].in_packets ++;
DataCounter[ current_packet.dst_ip ].in_bytes += current_packet.length;
data_counters_mutex.unlock();
} else {
// Other traffic
}
}
#ifdef GEOIP
int get_asn_for_ip(uint32_t ip) {
char* asn_raw = GeoIP_org_by_name(geo_ip, convert_ip_as_uint_to_string(remote_ip).c_str());
uint32_t asn_number = 0;
if (asn_raw == NULL) {
asn_number = 0;
} else {
// split string: AS1299 TeliaSonera International Carrier
vector<string> asn_as_string;
split( asn_as_string, asn_raw, boost::is_any_of(" "), boost::token_compress_on );
// free up original string
free(asn_raw);
// extract raw number
asn_number = convert_string_to_integer(asn_as_string[0].substr(2));
}
return asn_number;
}
#endif
// void* void* data
void calculation_thread() {
// we need wait one second for calculating speed by recalculate_speed
while (1) {
// Availible only from boost 1.54: boost::this_thread::sleep_for( boost::chrono::seconds(check_period) );
boost::this_thread::sleep(boost::posix_time::seconds(check_period));
calculation_programm();
}
}
void recalculate_speed_thread_handler() {
while (1) {
// recalculate data every one second
// Availible only from boost 1.54: boost::this_thread::sleep_for( boost::chrono::seconds(1) );
boost::this_thread::sleep(boost::posix_time::seconds(1));
recalculate_speed();
}
}
/* Пересчитать мгновенную скорость для всех известных соединений */
void recalculate_speed() {
// TODO: WE SHOULD ZEROFY ALL ELEMETS IN TABLE SpeedCounter
double speed_calc_period = 1;
time_t current_time;
time(¤t_time);
// В случае, если наш поток обсчета скорости завис на чем-то эдак на 1+ секунд, то мы должны либо пропустить шаг либо попробовать поделить его на новую разницу
double time_difference = difftime(current_time, last_call_of_traffic_recalculation);
if (time_difference < 1) {
// It could occur on programm start
logger<< log4cpp::Priority::INFO<<"We skip one iteration of speed_calc because it runs so early!";
return;
} else if (int(time_difference) == 1) {
// все отлично! Запуск произошел ровно через +- секунду после прошлого
} else {
logger<< log4cpp::Priority::INFO<<"Time from last run of speed_recalc is soooo big, we got ugly lags: "<<time_difference;
speed_calc_period = time_difference;
}
//logger<< log4cpp::Priority::INFO<<"Difference: "<<time_difference;
// calculate speed for all our IPs
for( map_for_counters::iterator ii = DataCounter.begin(); ii != DataCounter.end(); ++ii) {
uint32_t client_ip = (*ii).first;
int in_pps = int((double)(*ii).second.in_packets / (double)speed_calc_period);
int out_pps = int((double)(*ii).second.out_packets / (double)speed_calc_period);
int in_bps = int((double)(*ii).second.in_bytes / (double)speed_calc_period);
int out_bps = int((double)(*ii).second.out_bytes / (double)speed_calc_period);
// we detect overspeed
if (in_pps > ban_threshold or out_pps > ban_threshold) {
execute_ip_ban(client_ip, in_pps, out_pps, in_bps, out_bps);