-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathnDPId.c
6018 lines (5475 loc) · 228 KB
/
nDPId.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#if defined(__FreeBSD__) || defined(__APPLE__)
#include <sys/types.h>
#endif
#include <arpa/inet.h>
#include <errno.h>
#include <fcntl.h>
#include <ifaddrs.h>
#include <net/ethernet.h>
#include <net/if.h>
#include <netinet/in.h>
#include <ndpi_api.h>
#include <ndpi_classify.h>
#include <ndpi_main.h>
#include <ndpi_typedefs.h>
#include <pcap/dlt.h>
#include <pcap/pcap.h>
#include <pthread.h>
#include <signal.h>
#include <stdarg.h>
#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L
#include <stddef.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#if !defined(__FreeBSD__) && !defined(__APPLE__)
#include <sys/signalfd.h>
#endif
#include <sys/un.h>
#include <unistd.h>
#ifdef ENABLE_ZLIB
#include <zlib.h>
#endif
#include "config.h"
#include "nDPIsrvd.h"
#include "nio.h"
#ifdef ENABLE_PFRING
#include "npfring.h"
#endif
#include "utils.h"
#ifndef ETHERTYPE_DCE
#define ETHERTYPE_DCE 0x8903
#endif
#ifndef ETHERTYPE_PAE
#define ETHERTYPE_PAE 0x888e
#endif
#ifndef DLT_DSA_TAG_DSA
#define DLT_DSA_TAG_DSA 284
#endif
#ifndef DLT_DSA_TAG_EDSA
#define DLT_DSA_TAG_EDSA 285
#endif
#define NDPI_VERSION_CHECK ((NDPI_MAJOR == 4 && NDPI_MINOR < 9) || NDPI_MAJOR < 4)
#if NDPI_VERSION_CHECK
#error "nDPI >= 4.9.0 required"
#endif
#if nDPId_MAX_READER_THREADS <= 0
#error "Invalid value for nDPId_MAX_READER_THREADS"
#endif
#if nDPId_FLOW_SCAN_INTERVAL > nDPId_GENERIC_IDLE_TIME || nDPId_FLOW_SCAN_INTERVAL > nDPId_ICMP_IDLE_TIME || \
nDPId_FLOW_SCAN_INTERVAL > nDPId_TCP_IDLE_TIME || nDPId_FLOW_SCAN_INTERVAL > nDPId_UDP_IDLE_TIME
#error "Invalid value for nDPId_FLOW_SCAN_INTERVAL"
#endif
#if (nDPId_PACKETS_PLEN_MAX * 3) /* base64 encoded! */ > NETWORK_BUFFER_MAX_SIZE
#error "Invalid value for nDPId_PACKETS_PLEN_MAX"
#endif
/* MIPS* does not support Compare and Swap. Use traditional locking as fallback. */
#if !defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_4) || !defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_8)
#define MT_VALUE(name, type) \
struct name \
{ \
volatile uint64_t var; \
pthread_mutex_t var_mutex; \
} name
#define MT_INIT(value) \
{ \
value, PTHREAD_MUTEX_INITIALIZER \
}
#define MT_INIT2(name, value) \
do \
{ \
name.var = value; \
pthread_mutex_init(&name.var_mutex, NULL); \
} while (0)
static inline uint64_t mt_pt_get_and_add(volatile uint64_t * value, uint64_t add, pthread_mutex_t * mutex)
{
uint64_t result;
pthread_mutex_lock(mutex);
result = *value;
*value += add;
pthread_mutex_unlock(mutex);
return result;
}
#define MT_GET_AND_ADD(name, value) mt_pt_get_and_add(&name.var, value, &name.var_mutex)
static inline uint64_t mt_pt_get_and_sub(volatile uint64_t * value, uint64_t sub, pthread_mutex_t * mutex)
{
uint64_t result;
pthread_mutex_lock(mutex);
result = *value;
*value -= sub;
pthread_mutex_unlock(mutex);
return result;
}
#define MT_GET_AND_SUB(name, value) mt_pt_get_and_sub(&name.var, value, &name.var_mutex)
#else
#define MT_VALUE(name, type) volatile type name
#define MT_INIT(value) value
#define MT_INIT2(name, value) \
do \
{ \
name = value; \
} while (0)
#define MT_GET_AND_ADD(name, value) __sync_fetch_and_add(&name, value)
#define MT_GET_AND_SUB(name, value) __sync_fetch_and_sub(&name, value)
#endif
enum nDPId_l3_type
{
L3_IP,
L3_IP6
};
union nDPId_ip
{
struct
{
uint32_t ip;
} v4;
struct
{
union
{
uint64_t ip[2];
uint32_t ip_u32[4];
};
} v6;
};
enum nDPId_flow_state
{
FS_UNKNOWN = 0, // should never happen, bug otherwise
FS_SKIPPED, // flow should not be processed, see command line args -I and -E
FS_FINISHED, // detection done and detection data free'd
FS_INFO, // detection in progress, detection data allocated
FS_COUNT
};
enum nDPId_flow_direction
{
FD_SRC2DST = 0,
FD_DST2SRC,
FD_COUNT
};
struct nDPId_flow_analysis
{
struct ndpi_analyze_struct iat;
struct ndpi_analyze_struct pktlen;
uint8_t * directions;
struct ndpi_bin payload_len_bin[FD_COUNT];
float * entropies;
};
/*
* Minimal per-flow information required for flow mgmt and timeout handling.
*/
struct nDPId_flow_basic
{
enum nDPId_flow_state state;
enum nDPId_l3_type l3_type;
uint64_t hashval;
union nDPId_ip src;
union nDPId_ip dst;
uint8_t l4_protocol;
uint8_t tcp_fin_rst_seen : 1;
uint8_t tcp_is_midstream_flow : 1;
uint8_t reserved_00 : 6;
uint16_t vlan_id; // ETHERTYPE_VLAN: 802.1Q VLAN
uint16_t src_port;
uint16_t dst_port;
uint64_t last_pkt_time[FD_COUNT];
};
/*
* Information required for a full detection cycle.
*/
struct nDPId_flow_extended
{
struct nDPId_flow_basic flow_basic; // Do not move this element!
unsigned long long int flow_id;
uint16_t min_l4_payload_len[FD_COUNT];
uint16_t max_l4_payload_len[FD_COUNT];
unsigned long long int packets_processed[FD_COUNT];
uint64_t first_seen;
uint64_t last_flow_update;
struct nDPId_flow_analysis * flow_analysis;
unsigned long long int total_l4_payload_len[FD_COUNT];
struct ndpi_proto detected_l7_protocol;
};
#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L
_Static_assert(offsetof(struct nDPId_flow_extended, flow_basic) == 0,
"Offset of flow_basic is not zero any more. nDPId won't work anymore w/o changing it's core!");
#endif
/*
* Skipped flows need at least some information.
*/
struct nDPId_flow_skipped
{
struct nDPId_flow_basic flow_basic; // Do not move this element!
};
#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L
_Static_assert(offsetof(struct nDPId_flow_skipped, flow_basic) == 0,
"Offset of flow_basic is not zero any more. nDPId won't work anymore w/o changing it's core!");
#endif
/*
* Structure which is important for the detection process.
* The structure is also a compression target, if activated.
*/
struct nDPId_detection_data
{
uint32_t last_ndpi_flow_struct_hash;
struct ndpi_proto guessed_l7_protocol;
struct ndpi_flow_struct flow;
};
struct nDPId_flow
{
struct nDPId_flow_extended flow_extended; // Do not move this element!
union
{
struct
{
uint8_t detection_completed : 1; // Flow was detected. Detection updates may still occur.
uint8_t reserved_00 : 7;
uint8_t reserved_01[1];
#ifdef ENABLE_ZLIB
uint16_t detection_data_compressed_size;
#endif
struct nDPId_detection_data * detection_data;
} info;
struct
{
ndpi_risk risk;
ndpi_confidence_t confidence;
char * hostname;
} finished;
};
};
#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L
_Static_assert(offsetof(struct nDPId_flow, flow_extended) == 0,
"Offset of flow_extended is not zero any more. nDPId won't work anymore w/o changing it's core!");
#endif
struct nDPId_workflow
{
#ifdef ENABLE_PFRING
struct npfring npf;
#endif
pcap_t * pcap_handle;
MT_VALUE(error_or_eof, uint8_t);
uint8_t is_pcap_file;
uint16_t error_count;
unsigned long long int packets_captured;
unsigned long long int packets_processed;
unsigned long long int total_skipped_flows;
unsigned long long int total_l4_payload_len;
unsigned long long int libnDPI_errors;
unsigned long long int total_not_detected_flows;
unsigned long long int total_guessed_flows;
unsigned long long int total_detected_flows;
unsigned long long int total_flow_detection_updates;
unsigned long long int total_flow_updates;
#ifdef ENABLE_MEMORY_PROFILING
uint64_t last_memory_usage_log_time;
#endif
#ifdef ENABLE_ZLIB
uint64_t last_compression_scan_time;
uint64_t total_compressions;
uint64_t total_compression_diff;
uint64_t current_compression_diff;
#endif
uint64_t last_scan_time;
uint64_t last_status_time;
uint64_t last_global_time;
uint64_t last_thread_time;
uint64_t last_error_time;
void ** ndpi_flows_active;
unsigned long long int max_active_flows;
unsigned long long int cur_active_flows;
unsigned long long int total_active_flows;
void ** ndpi_flows_idle;
unsigned long long int max_idle_flows;
unsigned long long int cur_idle_flows;
unsigned long long int total_idle_flows;
unsigned long long int total_events_serialized;
ndpi_serializer ndpi_serializer;
struct ndpi_detection_module_struct * ndpi_struct;
};
struct nDPId_reader_thread
{
struct nDPId_workflow * workflow;
pthread_t thread;
int collector_sockfd;
int collector_sock_last_errno;
size_t array_index;
};
enum packet_event
{
PACKET_EVENT_INVALID = 0,
PACKET_EVENT_PAYLOAD, // A single packet that does not belong to a flow for whatever reasons.
// E.g. it could be malformed and thus no flow handling is done.
// There may be additional use-cases in the future.
PACKET_EVENT_PAYLOAD_FLOW, // Special case; A packet event that belongs to a flow but does not include all
// information a flow event requires.
PACKET_EVENT_COUNT
};
enum flow_event
{
FLOW_EVENT_INVALID = 0,
FLOW_EVENT_NEW,
FLOW_EVENT_END, // TCP only: FIN/RST packet seen.
FLOW_EVENT_IDLE, // Flow timed out.
FLOW_EVENT_UPDATE, // Inform distributor applications about flows with a long lifetime.
FLOW_EVENT_ANALYSE, // Print information regarding a flow analysis, see `struct nDPId_flow_analysis'.
FLOW_EVENT_GUESSED,
FLOW_EVENT_DETECTED,
FLOW_EVENT_DETECTION_UPDATE, // Some information in `struct ndpi_flow_struct' changed.
FLOW_EVENT_NOT_DETECTED,
FLOW_EVENT_COUNT
};
enum error_event
{
ERROR_EVENT_INVALID = 0,
UNKNOWN_DATALINK_LAYER,
UNKNOWN_L3_PROTOCOL,
UNSUPPORTED_DATALINK_LAYER,
PACKET_TOO_SHORT,
PACKET_TYPE_UNKNOWN,
PACKET_HEADER_INVALID,
IP4_PACKET_TOO_SHORT,
IP4_SIZE_SMALLER_THAN_HEADER,
IP4_L4_PAYLOAD_DETECTION_FAILED,
IP6_PACKET_TOO_SHORT, // 10
IP6_SIZE_SMALLER_THAN_HEADER,
IP6_L4_PAYLOAD_DETECTION_FAILED,
TCP_PACKET_TOO_SHORT,
UDP_PACKET_TOO_SHORT,
CAPTURE_SIZE_SMALLER_THAN_PACKET_SIZE,
MAX_FLOW_TO_TRACK,
FLOW_MEMORY_ALLOCATION_FAILED,
ERROR_EVENT_COUNT // 17
};
enum daemon_event
{
DAEMON_EVENT_INVALID = 0,
DAEMON_EVENT_INIT,
DAEMON_EVENT_RECONNECT,
DAEMON_EVENT_SHUTDOWN,
DAEMON_EVENT_STATUS,
DAEMON_EVENT_COUNT
};
static char const * const flow_state_name_table[FS_COUNT] = {
[FS_UNKNOWN] = "unknown", [FS_SKIPPED] = "skipped", [FS_FINISHED] = "finished", [FS_INFO] = "info"};
static char const * const packet_event_name_table[PACKET_EVENT_COUNT] = {
[PACKET_EVENT_INVALID] = "invalid", [PACKET_EVENT_PAYLOAD] = "packet", [PACKET_EVENT_PAYLOAD_FLOW] = "packet-flow"};
static char const * const flow_event_name_table[FLOW_EVENT_COUNT] = {[FLOW_EVENT_INVALID] = "invalid",
[FLOW_EVENT_NEW] = "new",
[FLOW_EVENT_END] = "end",
[FLOW_EVENT_IDLE] = "idle",
[FLOW_EVENT_UPDATE] = "update",
[FLOW_EVENT_ANALYSE] = "analyse",
[FLOW_EVENT_GUESSED] = "guessed",
[FLOW_EVENT_DETECTED] = "detected",
[FLOW_EVENT_DETECTION_UPDATE] = "detection-update",
[FLOW_EVENT_NOT_DETECTED] = "not-detected"};
static char const * const error_event_name_table[ERROR_EVENT_COUNT] = {
[ERROR_EVENT_INVALID] = "invalid",
[UNKNOWN_DATALINK_LAYER] = "Unknown datalink layer packet",
[UNKNOWN_L3_PROTOCOL] = "Unknown L3 protocol",
[UNSUPPORTED_DATALINK_LAYER] = "Unsupported datalink layer",
[PACKET_TOO_SHORT] = "Packet too short",
[PACKET_TYPE_UNKNOWN] = "Unknown packet type",
[PACKET_HEADER_INVALID] = "Packet header invalid",
[IP4_PACKET_TOO_SHORT] = "IP4 packet too short",
[IP4_SIZE_SMALLER_THAN_HEADER] = "Packet smaller than IP4 header",
[IP4_L4_PAYLOAD_DETECTION_FAILED] = "nDPI IPv4/L4 payload detection failed",
[IP6_PACKET_TOO_SHORT] = "IP6 packet too short",
[IP6_SIZE_SMALLER_THAN_HEADER] = "Packet smaller than IP6 header",
[IP6_L4_PAYLOAD_DETECTION_FAILED] = "nDPI IPv6/L4 payload detection failed",
[TCP_PACKET_TOO_SHORT] = "TCP packet smaller than expected",
[UDP_PACKET_TOO_SHORT] = "UDP packet smaller than expected",
[CAPTURE_SIZE_SMALLER_THAN_PACKET_SIZE] = "Captured packet size is smaller than expected packet size",
[MAX_FLOW_TO_TRACK] = "Max flows to track reached",
[FLOW_MEMORY_ALLOCATION_FAILED] = "Flow memory allocation failed",
};
static char const * const daemon_event_name_table[DAEMON_EVENT_COUNT] = {
[DAEMON_EVENT_INVALID] = "invalid",
[DAEMON_EVENT_INIT] = "init",
[DAEMON_EVENT_RECONNECT] = "reconnect",
[DAEMON_EVENT_SHUTDOWN] = "shutdown",
[DAEMON_EVENT_STATUS] = "status",
};
static struct ndpi_global_context * global_context = NULL;
static struct nDPId_reader_thread reader_threads[nDPId_MAX_READER_THREADS] = {};
static MT_VALUE(nDPId_main_thread_shutdown, int) = MT_INIT(0);
static MT_VALUE(global_flow_id, uint64_t) = MT_INIT(1);
static MT_VALUE(ndpi_memory_alloc_count, uint64_t) = MT_INIT(0);
static MT_VALUE(ndpi_memory_alloc_bytes, uint64_t) = MT_INIT(0);
static MT_VALUE(ndpi_memory_free_count, uint64_t) = MT_INIT(0);
static MT_VALUE(ndpi_memory_free_bytes, uint64_t) = MT_INIT(0);
#ifdef ENABLE_ZLIB
static MT_VALUE(zlib_compressions, uint64_t) = MT_INIT(0);
static MT_VALUE(zlib_decompressions, uint64_t) = MT_INIT(0);
static MT_VALUE(zlib_compression_diff, uint64_t) = MT_INIT(0);
static MT_VALUE(zlib_compression_bytes, uint64_t) = MT_INIT(0);
#endif
static struct
{
/* options which are resolved automatically */
struct nDPIsrvd_address parsed_collector_address;
union nDPId_ip pcap_dev_ip4, pcap_dev_ip6;
union nDPId_ip pcap_dev_netmask4, pcap_dev_netmask6;
union nDPId_ip pcap_dev_subnet4, pcap_dev_subnet6;
/* opts */
struct cmdarg config_file;
struct cmdarg pcap_file_or_interface;
struct cmdarg bpf_str;
struct cmdarg pidfile;
struct cmdarg user;
struct cmdarg group;
struct cmdarg custom_risk_domain_file;
struct cmdarg custom_protocols_file;
struct cmdarg custom_categories_file;
struct cmdarg custom_ja4_file;
struct cmdarg custom_sha1_file;
struct cmdarg collector_address;
struct cmdarg instance_alias;
struct cmdarg instance_uuid;
struct cmdarg process_internal_initial_direction;
struct cmdarg process_external_initial_direction;
#ifdef ENABLE_ZLIB
struct cmdarg enable_zlib_compression;
#endif
struct cmdarg enable_data_analysis;
#ifdef ENABLE_EPOLL
struct cmdarg use_poll;
#endif
#ifdef ENABLE_PFRING
struct cmdarg use_pfring;
#endif
/* subopts */
struct cmdarg max_flows_per_thread;
struct cmdarg max_idle_flows_per_thread;
struct cmdarg reader_thread_count;
struct cmdarg daemon_status_interval;
#ifdef ENABLE_MEMORY_PROFILING
struct cmdarg memory_profiling_log_interval;
#endif
#ifdef ENABLE_ZLIB
struct cmdarg compression_scan_interval;
struct cmdarg compression_flow_inactivity;
#endif
struct cmdarg flow_scan_interval;
struct cmdarg generic_max_idle_time;
struct cmdarg icmp_max_idle_time;
struct cmdarg udp_max_idle_time;
struct cmdarg tcp_max_idle_time;
struct cmdarg tcp_max_post_end_flow_time;
struct cmdarg max_packets_per_flow_to_send;
struct cmdarg max_packets_per_flow_to_process;
struct cmdarg max_packets_per_flow_to_analyse;
struct cmdarg error_event_threshold_n;
struct cmdarg error_event_threshold_time;
} nDPId_options = {.config_file = CMDARG_STR(NULL),
.pcap_file_or_interface = CMDARG_STR(NULL),
.bpf_str = CMDARG_STR(NULL),
.pidfile = CMDARG_STR(nDPId_PIDFILE),
.user = CMDARG_STR(DEFAULT_CHUSER),
.group = CMDARG_STR(NULL),
.custom_risk_domain_file = CMDARG_STR(NULL),
.custom_protocols_file = CMDARG_STR(NULL),
.custom_categories_file = CMDARG_STR(NULL),
.custom_ja4_file = CMDARG_STR(NULL),
.custom_sha1_file = CMDARG_STR(NULL),
.collector_address = CMDARG_STR(COLLECTOR_UNIX_SOCKET),
.instance_alias = CMDARG_STR(NULL),
.instance_uuid = CMDARG_STR(NULL),
.process_internal_initial_direction = CMDARG_BOOL(0),
.process_external_initial_direction = CMDARG_BOOL(0),
#ifdef ENABLE_ZLIB
.enable_zlib_compression = CMDARG_BOOL(0),
#endif
.enable_data_analysis = CMDARG_BOOL(0),
#ifdef ENABLE_EPOLL
.use_poll = CMDARG_BOOL(0),
#endif
#ifdef ENABLE_PFRING
.use_pfring = CMDARG_BOOL(0),
#endif
.max_flows_per_thread = CMDARG_ULL(nDPId_MAX_FLOWS_PER_THREAD / 2),
.max_idle_flows_per_thread = CMDARG_ULL(nDPId_MAX_IDLE_FLOWS_PER_THREAD / 2),
#ifdef CROSS_COMPILATION
/*
* We are assuming that in the cross compilation case
* our target system is an embedded one with not much memory available.
* To further reduce memory consumption caused by allocating nDPId / nDPI workflows per thread,
* we set the default reader thread count to two.
*/
.reader_thread_count = CMDARG_ULL(2),
#else
.reader_thread_count = CMDARG_ULL(nDPId_MAX_READER_THREADS / 3),
#endif
.daemon_status_interval = CMDARG_ULL(nDPId_DAEMON_STATUS_INTERVAL),
#ifdef ENABLE_MEMORY_PROFILING
.memory_profiling_log_interval = CMDARG_ULL(nDPId_MEMORY_PROFILING_LOG_INTERVAL),
#endif
#ifdef ENABLE_ZLIB
.compression_scan_interval = CMDARG_ULL(nDPId_COMPRESSION_SCAN_INTERVAL),
.compression_flow_inactivity = CMDARG_ULL(nDPId_COMPRESSION_FLOW_INACTIVITY),
#endif
.flow_scan_interval = CMDARG_ULL(nDPId_FLOW_SCAN_INTERVAL),
.generic_max_idle_time = CMDARG_ULL(nDPId_GENERIC_IDLE_TIME),
.icmp_max_idle_time = CMDARG_ULL(nDPId_ICMP_IDLE_TIME),
.udp_max_idle_time = CMDARG_ULL(nDPId_UDP_IDLE_TIME),
.tcp_max_idle_time = CMDARG_ULL(nDPId_TCP_IDLE_TIME),
.tcp_max_post_end_flow_time = CMDARG_ULL(nDPId_TCP_POST_END_FLOW_TIME),
.max_packets_per_flow_to_send = CMDARG_ULL(nDPId_PACKETS_PER_FLOW_TO_SEND),
.max_packets_per_flow_to_process = CMDARG_ULL(nDPId_PACKETS_PER_FLOW_TO_PROCESS),
.max_packets_per_flow_to_analyse = CMDARG_ULL(nDPId_PACKETS_PER_FLOW_TO_ANALYZE),
.error_event_threshold_n = CMDARG_ULL(nDPId_ERROR_EVENT_THRESHOLD_N),
.error_event_threshold_time = CMDARG_ULL(nDPId_ERROR_EVENT_THRESHOLD_TIME)};
struct confopt general_config_map[] = {CONFOPT("netif", &nDPId_options.pcap_file_or_interface),
CONFOPT("bpf", &nDPId_options.bpf_str),
CONFOPT("pidfile", &nDPId_options.pidfile),
CONFOPT("user", &nDPId_options.user),
CONFOPT("group", &nDPId_options.group),
CONFOPT("riskdomains", &nDPId_options.custom_risk_domain_file),
CONFOPT("protocols", &nDPId_options.custom_protocols_file),
CONFOPT("categories", &nDPId_options.custom_categories_file),
CONFOPT("ja4", &nDPId_options.custom_ja4_file),
CONFOPT("sha1", &nDPId_options.custom_sha1_file),
CONFOPT("collector", &nDPId_options.collector_address),
CONFOPT("alias", &nDPId_options.instance_alias),
CONFOPT("uuid", &nDPId_options.instance_uuid),
CONFOPT("internal", &nDPId_options.process_internal_initial_direction),
CONFOPT("external", &nDPId_options.process_external_initial_direction),
#ifdef ENABLE_ZLIB
CONFOPT("compression", &nDPId_options.enable_zlib_compression),
#endif
CONFOPT("analysis", &nDPId_options.enable_data_analysis),
#ifdef ENABLE_EPOLL
CONFOPT("poll", &nDPId_options.use_poll),
#endif
#ifdef ENABLE_PFRING
CONFOPT("pfring", &nDPId_options.use_pfring)
#endif
};
struct confopt tuning_config_map[] = {
CONFOPT("max-flows-per-thread", &nDPId_options.max_flows_per_thread),
CONFOPT("max-idle-flows-per-thread", &nDPId_options.max_idle_flows_per_thread),
CONFOPT("max-reader-threads", &nDPId_options.reader_thread_count),
CONFOPT("daemon-status-interval", &nDPId_options.daemon_status_interval),
#ifdef ENABLE_MEMORY_PROFILING
CONFOPT("memory-profiling-log-interval", &nDPId_options.memory_profiling_log_interval),
#endif
#ifdef ENABLE_ZLIB
CONFOPT("compression-scan-interval", &nDPId_options.compression_scan_interval),
CONFOPT("compression-flow-inactivity", &nDPId_options.compression_flow_inactivity),
#endif
CONFOPT("flow-scan-interval", &nDPId_options.flow_scan_interval),
CONFOPT("generic-max-idle-time", &nDPId_options.generic_max_idle_time),
CONFOPT("icmp-max-idle-time", &nDPId_options.icmp_max_idle_time),
CONFOPT("udp-max-idle-time", &nDPId_options.udp_max_idle_time),
CONFOPT("tcp-max-idle-time", &nDPId_options.tcp_max_idle_time),
CONFOPT("tcp-max-post-end-flow-time", &nDPId_options.tcp_max_post_end_flow_time),
CONFOPT("max-packets-per-flow-to-send", &nDPId_options.max_packets_per_flow_to_send),
CONFOPT("max-packets-per-flow-to-process", &nDPId_options.max_packets_per_flow_to_process),
CONFOPT("max-packets-per-flow-to-analyse", &nDPId_options.max_packets_per_flow_to_analyse),
CONFOPT("error-event-threshold-n", &nDPId_options.error_event_threshold_n),
CONFOPT("error-event-threshold-time", &nDPId_options.error_event_threshold_time),
};
static void sighandler(int signum);
static WARN_UNUSED int processing_threads_error_or_eof(void);
static void free_workflow(struct nDPId_workflow ** const workflow);
static void serialize_and_send(struct nDPId_reader_thread * const reader_thread);
static void jsonize_flow_event(struct nDPId_reader_thread * const reader_thread,
struct nDPId_flow_extended * const flow_ext,
enum flow_event event);
static void jsonize_flow_detection_event(struct nDPId_reader_thread * const reader_thread,
struct nDPId_flow * const flow,
enum flow_event event);
static int set_collector_nonblock(struct nDPId_reader_thread * const reader_thread)
{
int current_flags;
while ((current_flags = fcntl(reader_thread->collector_sockfd, F_GETFL, 0)) == -1 && errno == EINTR) {}
if (current_flags == -1) {}
while ((current_flags = fcntl(reader_thread->collector_sockfd, F_SETFL, current_flags | O_NONBLOCK)) == -1 &&
errno == EINTR)
{
// Retry if interrupted by a signal.
}
if (current_flags == -1)
{
reader_thread->collector_sock_last_errno = errno;
logger(1,
"[%8llu] Could not set collector fd %d to non-blocking mode: %s",
reader_thread->workflow->packets_processed,
reader_thread->collector_sockfd,
strerror(errno));
return 1;
}
return 0;
}
static int set_collector_block(struct nDPId_reader_thread * const reader_thread)
{
int current_flags = fcntl(reader_thread->collector_sockfd, F_GETFL, 0);
if (current_flags == -1 || fcntl(reader_thread->collector_sockfd, F_SETFL, current_flags & ~O_NONBLOCK) == -1)
{
reader_thread->collector_sock_last_errno = errno;
logger(1,
"[%8llu] Could not set collector fd %d to blocking mode: %s",
reader_thread->workflow->packets_processed,
reader_thread->collector_sockfd,
strerror(errno));
return 1;
}
return 0;
}
u_int8_t plen2slot(u_int16_t plen)
{
if (plen > nDPId_ANALYZE_PLEN_MAX)
{
return nDPId_ANALYZE_PLEN_NUM_BINS - 1;
}
else
{
return plen / nDPId_ANALYZE_PLEN_BIN_LEN;
}
}
static uint64_t get_last_pkt_time(struct nDPId_flow_basic const * const flow_basic)
{
return ndpi_max(flow_basic->last_pkt_time[FD_SRC2DST], flow_basic->last_pkt_time[FD_DST2SRC]);
}
static uint64_t timer_sub(uint64_t a, uint64_t b)
{
if (b > a)
{
return 0;
}
return a - b;
}
#ifdef ENABLE_ZLIB
#define ZLIB_ERROR_COMPRESSED_SIZE (-7)
#define ZLIB_ERROR_SIZE (-8)
#define ZLIB_ERROR_ALLOCATION (-9)
static uLong zlib_deflate(void * const src, int srcLen, void * const dst, int dstLen)
{
z_stream strm = {0};
strm.total_in = strm.avail_in = srcLen;
strm.total_out = strm.avail_out = dstLen;
strm.next_in = (Bytef *)src;
strm.next_out = (Bytef *)dst;
strm.zalloc = Z_NULL;
strm.zfree = Z_NULL;
strm.opaque = Z_NULL;
int err = -1;
uLong ret = 0;
err = deflateInit2(&strm, Z_BEST_COMPRESSION, Z_BINARY, 15, 9, Z_HUFFMAN_ONLY);
if (err != Z_OK)
{
err = deflateInit(&strm, Z_BEST_COMPRESSION);
}
if (err == Z_OK)
{
err = deflate(&strm, Z_FINISH);
if (err == Z_STREAM_END)
{
ret = strm.total_out;
MT_GET_AND_ADD(zlib_compressions, 1);
MT_GET_AND_ADD(zlib_compression_diff, srcLen - ret);
MT_GET_AND_ADD(zlib_compression_bytes, ret);
}
else
{
deflateEnd(&strm);
return err;
}
}
else
{
deflateEnd(&strm);
return err;
}
deflateEnd(&strm);
return ret;
}
static uLong zlib_inflate(void * const src, int srcLen, void * const dst, int dstLen)
{
z_stream strm = {0};
strm.total_in = strm.avail_in = srcLen;
strm.total_out = strm.avail_out = dstLen;
strm.next_in = (Bytef *)src;
strm.next_out = (Bytef *)dst;
strm.zalloc = Z_NULL;
strm.zfree = Z_NULL;
strm.opaque = Z_NULL;
int err = -1;
uLong ret = 0;
err = inflateInit2(&strm, (15 + 32)); // 15 window bits, and the +32 tells zlib to to detect if using gzip or zlib
if (err == Z_OK)
{
err = inflate(&strm, Z_FINISH);
if (err == Z_STREAM_END)
{
ret = strm.total_out;
MT_GET_AND_ADD(zlib_decompressions, 1);
MT_GET_AND_SUB(zlib_compression_diff, ret - srcLen);
}
else
{
inflateEnd(&strm);
return err;
}
}
else
{
inflateEnd(&strm);
return err;
}
inflateEnd(&strm);
return ret;
}
static int detection_data_deflate(struct nDPId_flow * const flow)
{
uint8_t tmpOut[sizeof(*flow->info.detection_data)];
uLong size;
if (flow->info.detection_data_compressed_size > 0)
{
return ZLIB_ERROR_COMPRESSED_SIZE;
}
size = zlib_deflate(flow->info.detection_data, sizeof(*flow->info.detection_data), tmpOut, sizeof(tmpOut));
if (size == 0 || size > sizeof(*flow->info.detection_data))
{
return ZLIB_ERROR_SIZE;
}
struct nDPId_detection_data * const new_det_data = ndpi_malloc(size);
if (new_det_data == NULL)
{
return ZLIB_ERROR_ALLOCATION;
}
ndpi_free(flow->info.detection_data);
flow->info.detection_data = new_det_data;
memcpy(flow->info.detection_data, tmpOut, size);
flow->info.detection_data_compressed_size = (uint16_t)size;
return (int)size;
}
static int detection_data_inflate(struct nDPId_flow * const flow)
{
uint8_t tmpOut[sizeof(*flow->info.detection_data)];
uLong size;
if (flow->info.detection_data_compressed_size == 0)
{
return ZLIB_ERROR_COMPRESSED_SIZE;
}
size = zlib_inflate(flow->info.detection_data, flow->info.detection_data_compressed_size, tmpOut, sizeof(tmpOut));
if (size == 0 || size > sizeof(*flow->info.detection_data))
{
return ZLIB_ERROR_SIZE;
}
struct nDPId_detection_data * const new_det_data = ndpi_malloc(size);
if (new_det_data == NULL)
{
return ZLIB_ERROR_ALLOCATION;
}
ndpi_free(flow->info.detection_data);
flow->info.detection_data = new_det_data;
memcpy(flow->info.detection_data, tmpOut, size);
flow->info.detection_data_compressed_size = 0;
return (int)size;
}
static void ndpi_comp_scan_walker(void const * const A, ndpi_VISIT which, int depth, void * const user_data)
{
struct nDPId_workflow * const workflow = (struct nDPId_workflow *)user_data;
struct nDPId_flow_basic * const flow_basic = *(struct nDPId_flow_basic **)A;
(void)depth;
if (workflow == NULL || flow_basic == NULL)
{
return;
}
if (which == ndpi_preorder || which == ndpi_leaf)
{
switch (flow_basic->state)
{
case FS_UNKNOWN:
case FS_COUNT:
case FS_SKIPPED:
case FS_FINISHED:
break;
case FS_INFO:
{
if (get_last_pkt_time(flow_basic) + GET_CMDARG_ULL(nDPId_options.compression_flow_inactivity) <
workflow->last_thread_time)
{
struct nDPId_flow * const flow = (struct nDPId_flow *)flow_basic;
if (flow->info.detection_data_compressed_size > 0)
{
break;
}
int ret = detection_data_deflate(flow);
if (ret < 0)
{
logger(1,
"zLib compression failed for flow %llu with error code: %d",
flow->flow_extended.flow_id,
ret);
}
else
{
workflow->total_compressions++;
workflow->total_compression_diff += ret;
workflow->current_compression_diff += ret;
}
}
break;
}
}
}
}
static void check_for_compressable_flows(struct nDPId_reader_thread * const reader_thread)
{
struct nDPId_workflow * const workflow = reader_thread->workflow;
if (workflow->last_compression_scan_time + GET_CMDARG_ULL(nDPId_options.compression_scan_interval) <
workflow->last_thread_time)
{
for (size_t comp_scan_index = 0; comp_scan_index < workflow->max_active_flows; ++comp_scan_index)
{
ndpi_twalk(workflow->ndpi_flows_active[comp_scan_index], ndpi_comp_scan_walker, workflow);
}
workflow->last_compression_scan_time = workflow->last_thread_time;
}
}
#endif
static void ip_netmask_to_subnet(union nDPId_ip const * const ip,
union nDPId_ip const * const netmask,
union nDPId_ip * const subnet,
enum nDPId_l3_type type)
{
switch (type)
{
case L3_IP:
subnet->v4.ip = ip->v4.ip & netmask->v4.ip;
break;
case L3_IP6:
subnet->v6.ip[0] = ip->v6.ip[0] & netmask->v6.ip[0];
subnet->v6.ip[1] = ip->v6.ip[1] & netmask->v6.ip[1];
break;
}
}
static int is_ip_in_subnet(union nDPId_ip const * const cmp_ip,
union nDPId_ip const * const netmask,
union nDPId_ip const * const cmp_subnet,
enum nDPId_l3_type const type)
{
switch (type)
{
case L3_IP:
return (cmp_ip->v4.ip & netmask->v4.ip) == cmp_subnet->v4.ip;
case L3_IP6:
return (cmp_ip->v6.ip[0] & netmask->v6.ip[0]) == cmp_subnet->v6.ip[0] &&
(cmp_ip->v6.ip[1] & netmask->v6.ip[1]) == cmp_subnet->v6.ip[1];
}
return 0;
}
static void get_ip4_from_sockaddr(struct sockaddr_in const * const saddr, union nDPId_ip * dest)
{
if (saddr->sin_family == AF_INET)
{
dest->v4.ip = saddr->sin_addr.s_addr;
}
}
static void get_ip6_from_sockaddr(struct sockaddr_in6 const * const saddr, union nDPId_ip * dest)
{
if (saddr->sin6_family == AF_INET6)
{
#if defined(__FreeBSD__) || defined(__APPLE__)
dest->v6.ip_u32[0] = saddr->sin6_addr.__u6_addr.__u6_addr32[0];
dest->v6.ip_u32[1] = saddr->sin6_addr.__u6_addr.__u6_addr32[1];
dest->v6.ip_u32[2] = saddr->sin6_addr.__u6_addr.__u6_addr32[2];
dest->v6.ip_u32[3] = saddr->sin6_addr.__u6_addr.__u6_addr32[3];
#else
dest->v6.ip_u32[0] = saddr->sin6_addr.s6_addr32[0];
dest->v6.ip_u32[1] = saddr->sin6_addr.s6_addr32[1];
dest->v6.ip_u32[2] = saddr->sin6_addr.s6_addr32[2];
dest->v6.ip_u32[3] = saddr->sin6_addr.s6_addr32[3];
#endif
}