-
-
Notifications
You must be signed in to change notification settings - Fork 568
/
Copy pathfast_library.cpp
2513 lines (1900 loc) · 81.4 KB
/
fast_library.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
#include "fast_library.hpp"
#include <fstream>
#include <iostream>
// Windows does not use ioctl
#ifndef _WIN32
#include <sys/ioctl.h>
#endif
#ifndef _WIN32
// For uname function
#include <sys/utsname.h>
#endif
#include "all_logcpp_libraries.hpp"
#include <boost/asio.hpp>
#include <boost/asio/ssl/error.hpp>
#include <boost/asio/ssl/stream.hpp>
#include <boost/asio/connect.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/beast/core.hpp>
#include <boost/beast/http.hpp>
#include <boost/beast/version.hpp>
#ifdef ENABLE_CAPNP
#include "simple_packet_capnp/simple_packet.capnp.h"
#include <capnp/message.h>
#include <capnp/serialize-packed.h>
#endif
#include <boost/algorithm/string.hpp>
#include <boost/regex.hpp>
#include "iana_ip_protocols.hpp"
boost::regex regular_expression_cidr_pattern("^\\d+\\.\\d+\\.\\d+\\.\\d+\\/\\d+$");
boost::regex regular_expression_host_pattern("^\\d+\\.\\d+\\.\\d+\\.\\d+$");
// convert string to integer
int convert_string_to_integer(std::string line) {
return atoi(line.c_str());
}
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);
}
std::string convert_ipv4_subnet_to_string(const subnet_cidr_mask_t& subnet) {
std::stringstream buffer;
buffer << convert_ip_as_uint_to_string(subnet.subnet_address) << "/" << subnet.cidr_prefix_length;
return buffer.str();
}
// convert integer to string
std::string convert_int_to_string(int value) {
std::stringstream out;
out << value;
return out.str();
}
// Converts IP address in cidr form 11.22.33.44/24 to our representation
bool convert_subnet_from_string_to_binary_with_cidr_format_safe(const std::string& subnet_cidr, subnet_cidr_mask_t& subnet_cidr_mask) {
if (subnet_cidr.empty()) {
return false;
}
// It's not a cidr mask
if (!is_cidr_subnet(subnet_cidr)) {
return false;
}
std::vector<std::string> subnet_as_string;
split(subnet_as_string, subnet_cidr, boost::is_any_of("/"), boost::token_compress_on);
if (subnet_as_string.size() != 2) {
return false;
}
uint32_t subnet_as_int = 0;
bool ip_to_integer_convresion_result = convert_ip_as_string_to_uint_safe(subnet_as_string[0], subnet_as_int);
if (!ip_to_integer_convresion_result) {
return false;
}
int cidr = 0;
bool ip_conversion_result = convert_string_to_any_integer_safe(subnet_as_string[1], cidr);
if (!ip_conversion_result) {
return false;
}
subnet_cidr_mask = subnet_cidr_mask_t(subnet_as_int, cidr);
return true;
}
std::string convert_subnet_to_string(subnet_cidr_mask_t my_subnet) {
std::stringstream buffer;
buffer << convert_ip_as_uint_to_string(my_subnet.subnet_address) << "/" << my_subnet.cidr_prefix_length;
return buffer.str();
}
// extract 24 from 192.168.1.1/24
unsigned int get_cidr_mask_from_network_as_string(std::string network_cidr_format) {
std::vector<std::string> subnet_as_string;
split(subnet_as_string, network_cidr_format, boost::is_any_of("/"), boost::token_compress_on);
if (subnet_as_string.size() != 2) {
return 0;
}
return convert_string_to_integer(subnet_as_string[1]);
}
std::string print_time_t_in_fastnetmon_format(time_t current_time) {
struct tm* timeinfo;
char buffer[80];
timeinfo = localtime(¤t_time);
strftime(buffer, sizeof(buffer), "%d_%m_%y_%H:%M:%S", timeinfo);
return std::string(buffer);
}
// extract 192.168.1.1 from 192.168.1.1/24
std::string get_net_address_from_network_as_string(std::string network_cidr_format) {
std::vector<std::string> subnet_as_string;
split(subnet_as_string, network_cidr_format, boost::is_any_of("/"), boost::token_compress_on);
if (subnet_as_string.size() != 2) {
return std::string();
}
return subnet_as_string[0];
}
std::string get_printable_protocol_name(unsigned int protocol) {
std::string proto_name;
switch (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;
}
return proto_name;
}
uint32_t convert_cidr_to_binary_netmask(unsigned int cidr) {
// We can do bit shift only for 0 .. 31 bits but we cannot do it in case of 32 bits
// Shift for same number of bits as type has is undefined behaviour in C standard:
// https://stackoverflow.com/questions/7401888/why-doesnt-left-bit-shift-for-32-bit-integers-work-as-expected-when-used
// We will handle this case manually
if (cidr == 0) {
return 0;
}
uint32_t binary_netmask = 0xFFFFFFFF;
binary_netmask = binary_netmask << (32 - cidr);
// We need network byte order at output
return htonl(binary_netmask);
}
bool is_cidr_subnet(std::string subnet) {
boost::cmatch what;
return regex_match(subnet.c_str(), what, regular_expression_cidr_pattern);
}
bool is_v4_host(std::string host) {
boost::cmatch what;
return regex_match(host.c_str(), what, regular_expression_host_pattern);
}
// 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;
}
}
bool folder_exists(std::string path) {
if (access(path.c_str(), 0) == 0) {
struct stat status;
stat(path.c_str(), &status);
if (status.st_mode & S_IFDIR) {
return true;
}
}
return false;
}
// http://www.gnu.org/software/libc/manual/html_node/Elapsed-Time.html
int timeval_subtract(struct timeval* result, struct timeval* x, struct timeval* y) {
/* Perform the carry for the later subtraction by updating y. */
if (x->tv_usec < y->tv_usec) {
int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1;
y->tv_usec -= 1000000 * nsec;
y->tv_sec += nsec;
}
if (x->tv_usec - y->tv_usec > 1000000) {
int nsec = (x->tv_usec - y->tv_usec) / 1000000;
y->tv_usec += 1000000 * nsec;
y->tv_sec -= nsec;
}
/* Compute the time remaining to wait. tv_usec is certainly positive. */
result->tv_sec = x->tv_sec - y->tv_sec;
result->tv_usec = x->tv_usec - y->tv_usec;
/* Return 1 if result is negative. */
return x->tv_sec < y->tv_sec;
}
std::string print_tcp_flags(uint8_t flag_value) {
if (flag_value == 0) {
return "-";
}
/*
// Required for decoding tcp flags
#define TH_FIN_MULTIPLIER 0x01
#define TH_SYN_MULTIPLIER 0x02
#define TH_RST_MULTIPLIER 0x04
#define TH_PUSH_MULTIPLIER 0x08
#define TH_ACK_MULTIPLIER 0x10
#define TH_URG_MULTIPLIER 0x20
*/
std::vector<std::string> all_flags;
if (extract_bit_value(flag_value, TCP_FIN_FLAG_SHIFT)) {
all_flags.push_back("fin");
}
if (extract_bit_value(flag_value, TCP_SYN_FLAG_SHIFT)) {
all_flags.push_back("syn");
}
if (extract_bit_value(flag_value, TCP_RST_FLAG_SHIFT)) {
all_flags.push_back("rst");
}
if (extract_bit_value(flag_value, TCP_PSH_FLAG_SHIFT)) {
all_flags.push_back("psh");
}
if (extract_bit_value(flag_value, TCP_ACK_FLAG_SHIFT)) {
all_flags.push_back("ack");
}
if (extract_bit_value(flag_value, TCP_URG_FLAG_SHIFT)) {
all_flags.push_back("urg");
}
std::ostringstream flags_as_string;
if (all_flags.empty()) {
return "-";
}
// concatenate all vector elements with comma
std::copy(all_flags.begin(), all_flags.end() - 1, std::ostream_iterator<std::string>(flags_as_string, ","));
// add last element
flags_as_string << all_flags.back();
return flags_as_string.str();
}
std::vector<std::string> split_strings_to_vector_by_comma(std::string raw_string) {
std::vector<std::string> splitted_strings;
boost::split(splitted_strings, raw_string, boost::is_any_of(","), boost::token_compress_on);
return splitted_strings;
}
// http://stackoverflow.com/questions/14528233/bit-masking-in-c-how-to-get-first-bit-of-a-byte
int extract_bit_value(uint8_t num, int bit) {
if (bit > 0 && bit <= 8) {
return ((num >> (bit - 1)) & 1);
} else {
return 0;
}
}
// Overloaded version with 16 bit integer support
int extract_bit_value(uint16_t num, int bit) {
if (bit > 0 && bit <= 16) {
return ((num >> (bit - 1)) & 1);
} else {
return 0;
}
}
int set_bit_value(uint8_t& num, int bit) {
if (bit > 0 && bit <= 8) {
num = num | 1 << (bit - 1);
return 1;
} else {
return 0;
}
}
int set_bit_value(uint16_t& num, int bit) {
if (bit > 0 && bit <= 16) {
num = num | 1 << (bit - 1);
return 1;
} else {
return 0;
}
}
int clear_bit_value(uint8_t& num, int bit) {
if (bit > 0 && bit <= 8) {
num = num & ~(1 << (bit - 1));
return 1;
} else {
return 0;
}
}
// http://stackoverflow.com/questions/47981/how-do-you-set-clear-and-toggle-a-single-bit-in-c-c
int clear_bit_value(uint16_t& num, int bit) {
if (bit > 0 && bit <= 16) {
num = num & ~(1 << (bit - 1));
return 1;
} else {
return 0;
}
}
// Encodes simple packet with all fields as separate fields in json format
bool serialize_simple_packet_to_json(const simple_packet_t& packet, nlohmann::json& json_packet) {
extern log4cpp::Category& logger;
std::string protocol_version;
std::string source_ip_as_string;
std::string destination_ip_as_string;
if (packet.ip_protocol_version == 4) {
protocol_version = "ipv4";
source_ip_as_string = convert_ip_as_uint_to_string(packet.src_ip);
destination_ip_as_string = convert_ip_as_uint_to_string(packet.dst_ip);
} else if (packet.ip_protocol_version == 6) {
protocol_version = "ipv6";
source_ip_as_string = print_ipv6_address(packet.src_ipv6);
destination_ip_as_string = print_ipv6_address(packet.dst_ipv6);
} else {
protocol_version = "unknown";
}
try {
// We use arrival_time as traffic telemetry protocols do not provide this time in a reliable manner
json_packet["timestamp"] = packet.arrival_time;
json_packet["ip_version"] = protocol_version;
json_packet["source_ip"] = source_ip_as_string;
json_packet["destination_ip"] = destination_ip_as_string;
json_packet["source_asn"] = packet.src_asn;
json_packet["destination_asn"] = packet.dst_asn;
json_packet["source_country"] = country_static_string_to_dynamic_string(packet.src_country);
json_packet["destination_country"] = country_static_string_to_dynamic_string(packet.dst_country);
json_packet["input_interface"] = packet.input_interface;
json_packet["output_interface"] = packet.output_interface;
// Add ports for TCP and UDP
if (packet.protocol == IPPROTO_TCP or packet.protocol == IPPROTO_UDP) {
json_packet["source_port"] = packet.source_port;
json_packet["destination_port"] = packet.destination_port;
}
// Add agent information
std::string agent_ip_as_string = convert_ip_as_uint_to_string(packet.agent_ip_address);
json_packet["agent_address"] = agent_ip_as_string;
if (packet.protocol == IPPROTO_TCP) {
std::string tcp_flags = print_tcp_flags(packet.flags);
json_packet["tcp_flags"] = tcp_flags;
}
// Add forwarding status
std::string forwarding_status = forwarding_status_to_string(packet.forwarding_status);
json_packet["forwarding_status"] = forwarding_status;
json_packet["fragmentation"] = packet.ip_fragmented;
json_packet["packets"] = packet.number_of_packets;
json_packet["length"] = packet.length;
json_packet["ip_length"] = packet.ip_length;
json_packet["ttl"] = packet.ttl;
json_packet["sample_ratio"] = packet.sample_ratio;
std::string protocol = get_printable_protocol_name(packet.protocol);
json_packet["protocol"] = protocol;
} catch (...) {
logger << log4cpp::Priority::ERROR << "Exception was triggered in JSON logic in serialize_simple_packet_to_json";
return false;
}
return true;
}
std::string print_simple_packet(simple_packet_t packet) {
std::stringstream buffer;
if (packet.ts.tv_sec == 0) {
// Netmap does not generate timestamp for all packets because it's very CPU
// intensive operation
// But we want pretty attack report and fill it there
gettimeofday(&packet.ts, NULL);
}
buffer << convert_timeval_to_date(packet.ts) << " ";
std::string source_ip_as_string = "";
std::string destination_ip_as_string = "";
if (packet.ip_protocol_version == 4) {
source_ip_as_string = convert_ip_as_uint_to_string(packet.src_ip);
destination_ip_as_string = convert_ip_as_uint_to_string(packet.dst_ip);
} else if (packet.ip_protocol_version == 6) {
source_ip_as_string = print_ipv6_address(packet.src_ipv6);
destination_ip_as_string = print_ipv6_address(packet.dst_ipv6);
} else {
// WTF?
}
std::string protocol_name = get_ip_protocol_name_by_number_iana(packet.protocol);
// We use lowercase format
boost::algorithm::to_lower(protocol_name);
buffer << source_ip_as_string << ":" << packet.source_port << " > " << destination_ip_as_string << ":"
<< packet.destination_port << " protocol: " << protocol_name;
// Print flags only for TCP
if (packet.protocol == IPPROTO_TCP) {
buffer << " flags: " << print_tcp_flags(packet.flags);
}
buffer << " frag: " << packet.ip_fragmented << " ";
buffer << " ";
buffer << "packets: " << packet.number_of_packets << " ";
buffer << "size: " << packet.length << " bytes ";
// We should cast it to integer because otherwise it will be interpreted as char
buffer << "ttl: " << unsigned(packet.ttl) << " ";
buffer << "sample ratio: " << packet.sample_ratio << " ";
buffer << " \n";
return buffer.str();
}
std::string convert_timeval_to_date(const timeval& tv) {
time_t nowtime = tv.tv_sec;
tm* nowtm = localtime(&nowtime);
std::ostringstream ss;
ss << std::put_time(nowtm, "%F %H:%M:%S");
// Add microseconds
// If value is short we will add leading zeros
ss << "." << std::setfill('0') << std::setw(6) << tv.tv_usec;
return ss.str();
}
uint64_t convert_speed_to_mbps(uint64_t speed_in_bps) {
return uint64_t((double)speed_in_bps / 1000 / 1000 * 8);
}
std::string get_protocol_name_by_number(unsigned int proto_number) {
struct protoent* proto_ent = getprotobynumber(proto_number);
std::string proto_name = proto_ent->p_name;
return proto_name;
}
// Exec command in shell and capture output
bool exec(const std::string& cmd, std::vector<std::string>& output_list, std::string& error_text) {
FILE* pipe = popen(cmd.c_str(), "r");
if (!pipe) {
// We need more details in case of failure
error_text = "error code: " + std::to_string(errno) + " error text: " + strerror(errno);
return false;
}
char buffer[256];
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 true;
}
bool print_pid_to_file(pid_t pid, std::string pid_path) {
std::ofstream pid_file;
pid_file.open(pid_path.c_str(), std::ios::trunc);
if (pid_file.is_open()) {
pid_file << pid << "\n";
pid_file.close();
return true;
} else {
return false;
}
}
bool read_pid_from_file(pid_t& pid, std::string pid_path) {
std::fstream pid_file(pid_path.c_str(), std::ios_base::in);
if (pid_file.is_open()) {
pid_file >> pid;
pid_file.close();
return true;
} else {
return false;
}
}
bool store_data_to_graphite(unsigned short int graphite_port, std::string graphite_host, graphite_data_t graphite_data) {
// Do not bother Graphite if we do not have any metrics here
if (graphite_data.size() == 0) {
return true;
}
int client_sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (client_sockfd < 0) {
return false;
}
struct sockaddr_in serv_addr;
memset(&serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(graphite_port);
int pton_result = inet_pton(AF_INET, graphite_host.c_str(), &serv_addr.sin_addr);
if (pton_result <= 0) {
close(client_sockfd);
return false;
}
int connect_result = connect(client_sockfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr));
if (connect_result < 0) {
close(client_sockfd);
return false;
}
std::stringstream buffer;
time_t current_time = time(NULL);
for (graphite_data_t::iterator itr = graphite_data.begin(); itr != graphite_data.end(); ++itr) {
buffer << itr->first << " " << itr->second << " " << current_time << "\n";
}
std::string buffer_as_string = buffer.str();
int write_result = write(client_sockfd, buffer_as_string.c_str(), buffer_as_string.size());
close(client_sockfd);
if (write_result > 0) {
return true;
} else {
return false;
}
}
// Get list of all available interfaces on the server
interfaces_list_t get_interfaces_list() {
interfaces_list_t interfaces_list;
// Format: 1: eth0: < ....
boost::regex interface_name_pattern("^\\d+:\\s+(\\w+):.*?$");
std::string error_text;
std::vector<std::string> output_list;
bool exec_result = exec("ip -o link show", output_list, error_text);
if (!exec_result) {
return interfaces_list;
}
if (output_list.empty()) {
return interfaces_list;
}
for (std::vector<std::string>::iterator iter = output_list.begin(); iter != output_list.end(); ++iter) {
boost::match_results<std::string::const_iterator> regex_results;
if (boost::regex_match(*iter, regex_results, interface_name_pattern)) {
// std::cout<<"Interface: "<<regex_results[1]<<std::endl;
interfaces_list.push_back(regex_results[1]);
}
}
return interfaces_list;
}
// Get all IPs for interface: main IP and aliases
ip_addresses_list_t get_ip_list_for_interface(const std::string& interface_name) {
ip_addresses_list_t ip_list;
std::string error_text;
std::vector<std::string> output_list;
bool exec_result = exec("ip address show dev " + interface_name, output_list, error_text);
if (!exec_result) {
return ip_list;
}
if (output_list.empty()) {
return ip_list;
}
boost::regex interface_alias_pattern("^\\s+inet\\s+(\\d+\\.\\d+\\.\\d+\\.\\d+).*?$");
// inet 188.40.35.142
for (std::vector<std::string>::iterator iter = output_list.begin(); iter != output_list.end(); ++iter) {
boost::match_results<std::string::const_iterator> regex_results;
if (boost::regex_match(*iter, regex_results, interface_alias_pattern)) {
ip_list.push_back(regex_results[1]);
// std::cout<<"IP: "<<regex_results[1]<<std::endl;
}
}
return ip_list;
}
ip_addresses_list_t get_local_ip_v4_addresses_list() {
ip_addresses_list_t ip_list;
std::vector<std::string> list_of_ignored_interfaces;
list_of_ignored_interfaces.push_back("lo");
list_of_ignored_interfaces.push_back("venet0");
interfaces_list_t interfaces_list = get_interfaces_list();
if (interfaces_list.empty()) {
return ip_list;
}
for (interfaces_list_t::iterator iter = interfaces_list.begin(); iter != interfaces_list.end(); ++iter) {
std::vector<std::string>::iterator iter_exclude_list =
std::find(list_of_ignored_interfaces.begin(), list_of_ignored_interfaces.end(), *iter);
// Skip ignored interface
if (iter_exclude_list != list_of_ignored_interfaces.end()) {
continue;
}
// std::cout<<*iter<<std::endl;
ip_addresses_list_t ip_list_on_interface = get_ip_list_for_interface(*iter);
// Append list
ip_list.insert(ip_list.end(), ip_list_on_interface.begin(), ip_list_on_interface.end());
}
return ip_list;
}
std::string convert_prefix_to_string_representation(prefix_t* prefix) {
std::string address = convert_ip_as_uint_to_string(prefix->add.sin.s_addr);
return address + "/" + convert_int_to_string(prefix->bitlen);
}
// It could not be on start or end of the line
boost::regex ipv6_address_compression_algorithm("(0000:){2,}");
// Returns true when all octets of IP address are set to zero
bool is_zero_ipv6_address(const in6_addr& ipv6_address) {
const uint8_t* b = ipv6_address.s6_addr;
if (b[0] == 0 && b[1] == 0 && b[2] == 0 && b[3] == 0 && b[4] == 0 && b[5] == 0 && b[6] == 0 && b[7] == 0 &&
b[8] == 0 && b[9] == 0 && b[10] == 0 && b[11] == 0 && b[12] == 0 && b[13] == 0 && b[14] == 0 && b[15] == 0) {
return true;
}
return false;
}
std::string print_ipv6_address(const in6_addr& ipv6_address) {
char buffer[128];
// For short print
const uint8_t* b = ipv6_address.s6_addr;
sprintf(buffer, "%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x", b[0], b[1], b[2], b[3],
b[4], b[5], b[6], b[7], b[8], b[9], b[10], b[11], b[12], b[13], b[14], b[15]);
std::string buffer_string(buffer);
// Compress IPv6 address
std::string result = boost::regex_replace(buffer_string, ipv6_address_compression_algorithm, ":", boost::format_first_only);
return result;
}
direction_t get_packet_direction_ipv6(patricia_tree_t* lookup_tree,
struct in6_addr src_ipv6,
struct in6_addr dst_ipv6,
subnet_ipv6_cidr_mask_t& subnet) {
direction_t packet_direction;
bool our_ip_is_destination = false;
bool our_ip_is_source = false;
prefix_t prefix_for_check_address;
prefix_for_check_address.family = AF_INET6;
prefix_for_check_address.bitlen = 128;
patricia_node_t* found_patrica_node = NULL;
prefix_for_check_address.add.sin6 = dst_ipv6;
found_patrica_node = patricia_search_best2(lookup_tree, &prefix_for_check_address, 1);
subnet_ipv6_cidr_mask_t destination_subnet;
if (found_patrica_node) {
our_ip_is_destination = true;
destination_subnet.subnet_address = found_patrica_node->prefix->add.sin6;
destination_subnet.cidr_prefix_length = found_patrica_node->prefix->bitlen;
}
found_patrica_node = NULL;
prefix_for_check_address.add.sin6 = src_ipv6;
subnet_ipv6_cidr_mask_t source_subnet;
found_patrica_node = patricia_search_best2(lookup_tree, &prefix_for_check_address, 1);
if (found_patrica_node) {
our_ip_is_source = true;
source_subnet.subnet_address = found_patrica_node->prefix->add.sin6;
source_subnet.cidr_prefix_length = found_patrica_node->prefix->bitlen;
}
if (our_ip_is_source && our_ip_is_destination) {
packet_direction = INTERNAL;
} else if (our_ip_is_source) {
subnet = source_subnet;
packet_direction = OUTGOING;
} else if (our_ip_is_destination) {
subnet = destination_subnet;
packet_direction = INCOMING;
} else {
packet_direction = OTHER;
}
return packet_direction;
}
/* Get traffic type: check it belongs to our IPs */
direction_t get_packet_direction(patricia_tree_t* lookup_tree, uint32_t src_ip, uint32_t dst_ip, subnet_cidr_mask_t& subnet) {
direction_t packet_direction;
bool our_ip_is_destination = false;
bool our_ip_is_source = false;
prefix_t prefix_for_check_adreess;
prefix_for_check_adreess.family = AF_INET;
prefix_for_check_adreess.bitlen = 32;
patricia_node_t* found_patrica_node = NULL;
prefix_for_check_adreess.add.sin.s_addr = dst_ip;
subnet_cidr_mask_t destination_subnet;
found_patrica_node = patricia_search_best2(lookup_tree, &prefix_for_check_adreess, 1);
if (found_patrica_node) {
our_ip_is_destination = true;
destination_subnet.subnet_address = found_patrica_node->prefix->add.sin.s_addr;
destination_subnet.cidr_prefix_length = found_patrica_node->prefix->bitlen;
}
found_patrica_node = NULL;
prefix_for_check_adreess.add.sin.s_addr = src_ip;
subnet_cidr_mask_t source_subnet;
found_patrica_node = patricia_search_best2(lookup_tree, &prefix_for_check_adreess, 1);
if (found_patrica_node) {
our_ip_is_source = true;
source_subnet.subnet_address = found_patrica_node->prefix->add.sin.s_addr;
source_subnet.cidr_prefix_length = found_patrica_node->prefix->bitlen;
}
if (our_ip_is_source && our_ip_is_destination) {
packet_direction = INTERNAL;
} else if (our_ip_is_source) {
subnet = source_subnet;
packet_direction = OUTGOING;
} else if (our_ip_is_destination) {
subnet = destination_subnet;
packet_direction = INCOMING;
} else {
packet_direction = OTHER;
}
return packet_direction;
}
std::string get_direction_name(direction_t 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;
}
#ifdef __linux__
bool manage_interface_promisc_mode(std::string interface_name, bool switch_on) {
extern log4cpp::Category& logger;
// We need really any socket for ioctl
int fd = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
if (!fd) {
logger << log4cpp::Priority::ERROR << "Can't create socket for promisc mode manager";
return false;
}
struct ifreq ethreq;
memset(ðreq, 0, sizeof(ethreq));
strncpy(ethreq.ifr_name, interface_name.c_str(), IFNAMSIZ);
int ioctl_res = ioctl(fd, SIOCGIFFLAGS, ðreq);
if (ioctl_res == -1) {
logger << log4cpp::Priority::ERROR << "Can't get interface flags";
return false;
}
bool promisc_enabled_on_device = ethreq.ifr_flags & IFF_PROMISC;
if (switch_on) {
if (promisc_enabled_on_device) {
logger << log4cpp::Priority::INFO << "Interface " << interface_name << " in promisc mode already";
return true;
} else {
logger << log4cpp::Priority::INFO << "Interface in non promisc mode now, switch it on";
ethreq.ifr_flags |= IFF_PROMISC;
int ioctl_res_set = ioctl(fd, SIOCSIFFLAGS, ðreq);
if (ioctl_res_set == -1) {
logger << log4cpp::Priority::ERROR << "Can't set interface flags";
return false;
}
return true;
}
} else {
if (!promisc_enabled_on_device) {
logger << log4cpp::Priority::INFO << "Interface " << interface_name << " in normal mode already";
return true;
} else {
logger << log4cpp::Priority::INFO << "Interface in promisc mode now, switch it off";
ethreq.ifr_flags &= ~IFF_PROMISC;
int ioctl_res_set = ioctl(fd, SIOCSIFFLAGS, ðreq);
if (ioctl_res_set == -1) {
logger << log4cpp::Priority::ERROR << "Can't set interface flags";
return false;
}
return true;
}
}
}
#endif
std::string serialize_attack_description(const attack_details_t& current_attack) {
std::stringstream attack_description;
attack_type_t attack_type = detect_attack_type(current_attack);
std::string printable_attack_type = get_printable_attack_name(attack_type);
attack_description << "Attack type: " << printable_attack_type << "\n"
<< "Initial attack power: " << current_attack.attack_power << " packets per second\n"
<< "Peak attack power: " << current_attack.max_attack_power << " packets per second\n"
<< "Attack direction: " << get_direction_name(current_attack.attack_direction) << "\n"
<< "Attack protocol: " << get_printable_protocol_name(current_attack.attack_protocol) << "\n";
attack_description
<< "Total incoming traffic: " << convert_speed_to_mbps(current_attack.traffic_counters.total.in_bytes) << " mbps\n"
<< "Total outgoing traffic: " << convert_speed_to_mbps(current_attack.traffic_counters.total.out_bytes) << " mbps\n"
<< "Total incoming pps: " << current_attack.traffic_counters.total.in_packets << " packets per second\n"
<< "Total outgoing pps: " << current_attack.traffic_counters.total.out_packets << " packets per second\n"
<< "Total incoming flows: " << current_attack.traffic_counters.in_flows << " flows per second\n"
<< "Total outgoing flows: " << current_attack.traffic_counters.out_flows << " flows per second\n";
attack_description
<< "Incoming ip fragmented traffic: " << convert_speed_to_mbps(current_attack.traffic_counters.fragmented.in_bytes) << " mbps\n"
<< "Outgoing ip fragmented traffic: " << convert_speed_to_mbps(current_attack.traffic_counters.fragmented.out_bytes)
<< " mbps\n"
<< "Incoming ip fragmented pps: " << current_attack.traffic_counters.fragmented.in_packets << " packets per second\n"
<< "Outgoing ip fragmented pps: " << current_attack.traffic_counters.fragmented.out_packets << " packets per second\n"
<< "Incoming dropped traffic: " << convert_speed_to_mbps(current_attack.traffic_counters.dropped.in_bytes) << " mbps\n"
<< "Outgoing dropped traffic: " << convert_speed_to_mbps(current_attack.traffic_counters.dropped.out_bytes) << " mbps\n"
<< "Incoming dropped pps: " << current_attack.traffic_counters.dropped.in_packets << " packets per second\n"