forked from vjanelle/nprobe
-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.c
3661 lines (2928 loc) · 110 KB
/
util.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
/*
* nProbe - a Netflow v5/v9/IPFIX probe for IPv4/v6
*
* Copyright (C) 2002-14 Luca Deri <deri@ntop.org>
*
* http://www.ntop.org/
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "nprobe.h"
#ifdef FREEBSD
#include <pthread_np.h>
typedef cpuset_t cpu_set_t;
#endif
#ifdef __NetBSD__
#include <pthread.h>
#include <sched.h>
#endif
#ifdef sun
extern char *strtok_r(char *, const char *, char **);
#endif
#ifdef WIN32
//#define strtok_r(a, b, c) strtok(a, b)
#endif
#ifdef HAVE_SQLITE
extern void sqlite_exec_sql(char* sql);
#endif
#ifdef HAVE_GEOIP
#define GEOIP_DIR_LOCAL_TEMPLATE "%s"
#define GEOIP_DIR_SYSTEM_TEMPLATE PREFIX "/nprobe/%s"
#define GEOIP_DIR_NTOPNG "/usr/share/ntopng/httpdocs/geoip/%s"
#endif
static u_int8_t getIfIdx(struct in_addr *addr, u_int16_t *interface_id);
/* ********************** */
static char *port_mapping[0xFFFF] = { NULL };
static char *proto_mapping[0xFF] = { NULL };
/* ************************************ */
void traceEvent(const int eventTraceLevel, const char* file,
const int line, const char * format, ...) {
va_list va_ap;
if(eventTraceLevel <= readOnlyGlobals.traceLevel) {
char buf[2048], out_buf[640];
char theDate[32], *extra_msg = "";
time_t theTime = time(NULL);
va_start (va_ap, format);
/* We have two paths - one if we're logging, one if we aren't
* Note that the no-log case is those systems which don't support it (WIN32),
* those without the headers !defined(USE_SYSLOG)
* those where it's parametrically off...
*/
memset(buf, 0, sizeof(buf));
strftime(theDate, 32, "%d/%b/%Y %H:%M:%S", localtime(&theTime));
vsnprintf(buf, sizeof(buf)-1, format, va_ap);
if(eventTraceLevel == 0 /* TRACE_ERROR */)
extra_msg = "ERROR: ";
else if(eventTraceLevel == 1 /* TRACE_WARNING */)
extra_msg = "WARNING: ";
while(buf[strlen(buf)-1] == '\n') buf[strlen(buf)-1] = '\0';
snprintf(out_buf, sizeof(out_buf)-1, "%s [%s:%d] %s%s", theDate,
#ifdef WIN32
strrchr(file, '\\')+1,
#else
file,
#endif
line, extra_msg, buf);
#ifndef WIN32
if(readOnlyGlobals.useSyslog) {
if(!readWriteGlobals->syslog_opened) {
openlog(readOnlyGlobals.nprobeId, LOG_PID, LOG_DAEMON);
readWriteGlobals->syslog_opened = 1;
}
syslog(LOG_INFO, "%s", out_buf);
} else
printf("%s\n", out_buf);
#else
printf("%s\n", out_buf);
#endif
}
fflush(stdout);
va_end(va_ap);
}
/* ************************************ */
#ifdef WIN32
unsigned long waitForNextEvent(unsigned long ulDelay /* ms */) {
unsigned long ulSlice = 1000L; /* 1 Second */
while(ulDelay > 0L) {
if(ulDelay < ulSlice)
ulSlice = ulDelay;
Sleep(ulSlice);
ulDelay -= ulSlice;
}
return ulDelay;
}
/* ******************************* */
void initWinsock32() {
WORD wVersionRequested;
WSADATA wsaData;
int err;
wVersionRequested = MAKEWORD(2, 0);
err = WSAStartup( wVersionRequested, &wsaData );
if( err != 0 ) {
/* Tell the user that we could not find a usable */
/* WinSock DLL. */
traceEvent(TRACE_ERROR, "FATAL ERROR: unable to initialise Winsock 2.x.");
exit(-1);
}
}
/* ******************************** */
short isWinNT() { return(1); }
/* ****************************************************** */
/*
int snprintf(char *string, size_t maxlen, const char *format, ...) {
int ret=0;
va_list args;
va_start(args, format);
vsprintf(string,format,args);
va_end(args);
return ret;
}
*/
#endif /* Win32 */
/* ******************************************************************* */
u_int8_t ip2mask(IpAddress *addr, HostInfo *ip) {
if(ip->mask != 0) return(ip->mask);
else if((readOnlyGlobals.numInterfaceNetworks == 0) || (addr->ipVersion != 4))
return(0);
else {
int i;
u_int32_t address = htonl(addr->ipType.ipv4);
for(i=0; i<readOnlyGlobals.numInterfaceNetworks; i++) {
if((address & readOnlyGlobals.interfaceNetworks[i].netmask) == readOnlyGlobals.interfaceNetworks[i].network) {
// traceEvent(TRACE_INFO, "--> %d", readOnlyGlobals.interfaceNetworks[i].netmask_v6);
ip->mask = readOnlyGlobals.interfaceNetworks[i].netmask_v6;
return(ip->mask);
}
}
}
return(0); /* Unknown */
}
/* ******************************************************************* */
static ip_to_AS _ip_to_AS;
static fillASinfo _fillASinfo;
void initAS() {
_ip_to_AS = NULL;
_fillASinfo = NULL;
}
void setIp2AS(ip_to_AS ptr) {
_ip_to_AS = ptr;
}
void setFillASInfo(fillASinfo ptr) {
_fillASinfo = ptr;
}
void fillASInfo(FlowHashBucket *bkt) {
if(/* (!readWriteGlobals->shutdownInProgress) && */ _fillASinfo)
_fillASinfo(bkt);
}
/* ******************************************************************* */
static u_int32_t _ip2AS(IpAddress *ip) {
char *rsp = NULL;
u_int32_t as;
if((!readWriteGlobals->shutdownInProgress) && (_ip_to_AS != NULL))
return(_ip_to_AS(*ip));
#ifdef HAVE_GEOIP
if(readOnlyGlobals.geo_ip_asn_db == NULL) return(0);
#ifdef WIN32
if(ip.ipVersion == 6) return(0);
#endif
pthread_rwlock_wrlock(&readWriteGlobals->geoipRwLock);
if(ip->ipVersion == 4)
rsp = GeoIP_name_by_ipnum(readOnlyGlobals.geo_ip_asn_db, ip->ipType.ipv4);
else {
#ifdef HAVE_GEOIP_IPv6
#ifndef WIN32
/* Invalid database type GeoIP ASNum Edition, expected GeoIP Organization Edition */
if(readOnlyGlobals.geo_ip_asn_db_v6)
rsp = GeoIP_name_by_ipnum_v6(readOnlyGlobals.geo_ip_asn_db_v6, ip->ipType.ipv6);
#endif
#endif
}
pthread_rwlock_unlock(&readWriteGlobals->geoipRwLock);
as = rsp ? atoi(&rsp[2]) : 0;
free(rsp);
/* traceEvent(TRACE_WARNING, "--> %s (%d)", rsp, as); */
return(as);
#else
return(0);
#endif
}
/* ************************************* */
u_int32_t _getAS(IpAddress *addr, HostInfo *bkt) {
if(bkt->aspath && (bkt->aspath_len > 0)) {
/* The last element is the host AS, the first one is our AS */
bkt->asn = bkt->aspath[bkt->aspath_len-1];
} else
bkt->asn = _ip2AS(addr);
/* traceEvent(TRACE_WARNING, "--> %u", ret); */
return(bkt->asn);
}
/* ************************************ */
u_int32_t getAS(IpAddress *addr, HostInfo *bkt) {
return((bkt->asn != 0) ? bkt->asn : _getAS(addr, bkt));
}
/* ************************************ */
void readASs(char *path) {
#ifdef HAVE_GEOIP
if(path == NULL)
return;
else {
struct stat stats;
char the_path[256];
if(stat(path, &stats) == 0)
snprintf(the_path, sizeof(the_path), GEOIP_DIR_LOCAL_TEMPLATE, path);
else {
snprintf(the_path, sizeof(the_path), GEOIP_DIR_NTOPNG, path);
if(stat(path, &stats) != 0)
snprintf(the_path, sizeof(the_path), GEOIP_DIR_SYSTEM_TEMPLATE, path);
}
if((readOnlyGlobals.geo_ip_asn_db = GeoIP_open(the_path, GEOIP_CHECK_CACHE)) != NULL) {
traceEvent(TRACE_NORMAL, "GeoIP: loaded AS config file %s", the_path);
} else
traceEvent(TRACE_WARNING, "Unable to load AS file %s. AS support disabled", the_path);
/* ********************************************* */
strcpy(&the_path[strlen(the_path)-4], "v6.dat");
if((readOnlyGlobals.geo_ip_asn_db_v6 = GeoIP_open(the_path, GEOIP_CHECK_CACHE)) != NULL) {
traceEvent(TRACE_NORMAL, "GeoIP: loaded AS IPv6 config file %s", the_path);
} else
traceEvent(TRACE_WARNING, "Unable to load AS IPv6 file %s. AS IPv6 support disabled", the_path);
}
#endif
}
/* ************************************ */
void readCities(char *path) {
#ifdef HAVE_GEOIP
if(path == NULL)
return;
else {
struct stat stats;
char the_path[256];
if(stat(path, &stats) == 0)
snprintf(the_path, sizeof(the_path), GEOIP_DIR_LOCAL_TEMPLATE, path);
else {
snprintf(the_path, sizeof(the_path), GEOIP_DIR_NTOPNG, path);
if(stat(path, &stats) != 0)
snprintf(the_path, sizeof(the_path), GEOIP_DIR_SYSTEM_TEMPLATE, path);
}
if((readOnlyGlobals.geo_ip_city_db = GeoIP_open(the_path, GEOIP_CHECK_CACHE)) != NULL) {
traceEvent(TRACE_NORMAL, "GeoIP: loaded cities config file %s", the_path);
} else
traceEvent(TRACE_WARNING, "Unable to load cities file %s. IP geolocation disabled", the_path);
/* ********************************************* */
strcpy(&the_path[strlen(the_path)-4], "v6.dat");
if((readOnlyGlobals.geo_ip_city_db_v6 = GeoIP_open(the_path, GEOIP_CHECK_CACHE)) != NULL) {
traceEvent(TRACE_NORMAL, "GeoIP: loaded IPv6 cities config file %s", the_path);
} else
traceEvent(TRACE_WARNING, "Unable to load IPv6 cities file %s. IPv6 cities geolocation disabled", the_path);
}
#endif
}
/* ******************************************** */
void copyInt8(u_int8_t t8, char *outBuffer,
uint *outBufferBegin, uint *outBufferMax) {
if((*outBufferBegin)+sizeof(t8) < (*outBufferMax)) {
memcpy(&outBuffer[(*outBufferBegin)], &t8, sizeof(t8));
(*outBufferBegin) += sizeof(t8);
}
}
/* ******************************************** */
void copyInt16(u_int16_t _t16, char *outBuffer,
uint *outBufferBegin, uint *outBufferMax) {
u_int16_t t16 = htons(_t16);
if((*outBufferBegin)+sizeof(t16) < (*outBufferMax)) {
memcpy(&outBuffer[(*outBufferBegin)], &t16, sizeof(t16));
(*outBufferBegin) += sizeof(t16);
}
}
/* ******************************************** */
void copyInt32(u_int32_t _t32, char *outBuffer,
uint *outBufferBegin, uint *outBufferMax) {
u_int32_t t32 = htonl(_t32);
if((*outBufferBegin)+sizeof(t32) < (*outBufferMax)) {
#ifdef DEBUG
char buf1[32];
printf("(8) %s\n", _intoaV4(_t32, buf1, sizeof(buf1)));
#endif
memcpy(&outBuffer[(*outBufferBegin)], &t32, sizeof(t32));
(*outBufferBegin) += sizeof(t32);
}
}
/* ******************************************** */
/* 64-bit version of ntohl and htonl */
u_int64_t _htonll(u_int64_t v) {
union { u_int32_t lv[2]; u_int64_t llv; } u;
u.lv[0] = htonl(v >> 32);
u.lv[1] = htonl(v & 0xFFFFFFFFULL);
return u.llv;
}
u_int64_t _ntohll(u_int64_t v) {
union { u_int32_t lv[2]; u_int64_t llv; } u;
u.llv = v;
return ((u_int64_t)ntohl(u.lv[0]) << 32) | (u_int64_t)ntohl(u.lv[1]);
}
/* ******************************************** */
void copyInt64(u_int64_t _t64, char *outBuffer,
uint *outBufferBegin, uint *outBufferMax) {
u_int64_t t64 = _htonll(_t64);
if((*outBufferBegin)+sizeof(t64) < (*outBufferMax)) {
memcpy(&outBuffer[(*outBufferBegin)], &t64, sizeof(t64));
(*outBufferBegin) += sizeof(t64);
}
}
/* ******************************************** */
void copyLen(u_char *str, int strLen, char *outBuffer,
uint *outBufferBegin, uint *outBufferMax) {
if((*outBufferBegin)+strLen < (*outBufferMax)) {
memcpy(&outBuffer[(*outBufferBegin)], str, strLen);
(*outBufferBegin) += strLen;
}
}
/* ******************************************** */
static u_int8_t isEven(u_int num) { return(((num % 2) == 0) ? 1 : 0); }
/* ******************************************** */
u_int16_t ifIdx(FlowHashBucket *myBucket,
int inputIfIdx /* 1=if_input, 0=if_output */) {
u_char *mac;
u_int16_t idx;
struct in_addr addr;
if(readOnlyGlobals.use_vlanId_as_ifId != vlan_disabled) {
switch(readOnlyGlobals.use_vlanId_as_ifId) {
case single_vlan:
if(isEven(myBucket->core.tuple.key.vlanId)) {
/* Even VLAN Tag */
if(inputIfIdx) return(0);
else return(myBucket->core.tuple.key.vlanId);
} else {
/* Odd VLAN Tag */
if(inputIfIdx) return(myBucket->core.tuple.key.vlanId-1);
else return(0);
}
break;
case double_vlan:
if(isEven(myBucket->core.tuple.key.vlanId)) {
/* Even VLAN Tag */
if(inputIfIdx) return(myBucket->core.tuple.key.vlanId+1);
else return(myBucket->core.tuple.key.vlanId);
} else {
/* Odd VLAN Tag */
if(inputIfIdx) return(myBucket->core.tuple.key.vlanId-1);
else return(myBucket->core.tuple.key.vlanId);
}
break;
default:
return(myBucket->core.tuple.key.vlanId);
}
}
addr.s_addr = inputIfIdx ? htonl(myBucket->core.tuple.key.k.ipKey.src.ipType.ipv4) : htonl(myBucket->core.tuple.key.k.ipKey.dst.ipType.ipv4);
if(getIfIdx(&addr, &idx))
return(idx);
if(readWriteGlobals->num_src_mac_export > 0) {
int i;
for(i = 0; i<readWriteGlobals->num_src_mac_export; i++)
if(inputIfIdx && (memcmp(myBucket->ext->srcInfo.macAddress, readOnlyGlobals.mac_if_match[i].mac_address, 6) == 0))
return(readOnlyGlobals.mac_if_match[i].interface_id);
else if((!inputIfIdx) && (memcmp(myBucket->ext->dstInfo.macAddress,readOnlyGlobals.mac_if_match[i].mac_address, 6) == 0))
return(readOnlyGlobals.mac_if_match[i].interface_id);
}
if(inputIfIdx) {
if(readOnlyGlobals.inputInterfaceIndex != NO_INTERFACE_INDEX)
return(readOnlyGlobals.inputInterfaceIndex);
} else {
if(readOnlyGlobals.outputInterfaceIndex != NO_INTERFACE_INDEX)
return(readOnlyGlobals.outputInterfaceIndex);
}
/* ...else dynamic */
/* Calculate the input/output interface using
the last two MAC address bytes */
if(inputIfIdx)
mac = &(myBucket->ext->srcInfo.macAddress[4]);
else
mac = &(myBucket->ext->dstInfo.macAddress[4]);
idx = (mac[0] * 256) + mac[1];
return(idx);
}
/* ******************************************** */
char* port2name(u_int16_t port, u_int8_t proto) {
#if 0
struct servent *svt;
if((svt = getservbyport(htons(port), proto2name(proto))) != NULL)
return(svt->s_name);
else {
static char the_port[8];
snprintf(the_port, sizeof(the_port), "%d", port);
return(the_port);
}
#else
if(port_mapping[port] != NULL)
return(port_mapping[port]);
else if(proto == 6) return("tcp_other");
else if(proto == 17) return("udp_other");
else return("<unknown>"); /* Not reached */
#endif
}
/* ******************************************** */
u_int16_t getServerPort(FlowHashBucket *theFlow) {
switch(theFlow->core.tuple.key.k.ipKey.proto) {
case IPPROTO_TCP:
case IPPROTO_UDP:
return((theFlow->core.tuple.key.k.ipKey.dport < theFlow->core.tuple.key.k.ipKey.sport) ? theFlow->core.tuple.key.k.ipKey.dport : theFlow->core.tuple.key.k.ipKey.sport);
default:
return(0);
}
}
/* **************************************************************** */
void reset_bitmask(bitmask_selector *selector) {
memset((char*)selector->bits_memory, 0, selector->num_bits/8);
}
/* **************************************************************** */
int alloc_bitmask(u_int32_t tot_bits, bitmask_selector *selector) {
uint tot_mem = 1 + (tot_bits >> 3); /* /= 8 */
if((selector->bits_memory = malloc(tot_mem)) != NULL) {
} else {
selector->num_bits = 0;
return(-1);
}
selector->num_bits = tot_bits;
reset_bitmask(selector);
return(0);
}
/* ********************************** */
void free_bitmask(bitmask_selector *selector) {
if(selector->bits_memory > 0) {
free(selector->bits_memory);
selector->bits_memory = 0;
}
}
/* ******************************************** */
void bitmask_set(u_int32_t n, bitmask_selector* p) { (((char*)p->bits_memory)[n >> 3] |= (1 << (n & 7))); }
void bitmask_clr(u_int32_t n, bitmask_selector* p) { (((char*)p->bits_memory)[n >> 3] &= ~(1 << (n & 7))); }
u_int8_t bitmask_isset(u_int32_t n, bitmask_selector* p) { return(((char*)p->bits_memory)[n >> 3] & (1 << (n & 7))); }
/* ******************************************** */
void loadApplProtocols(void) {
struct servent *s;
alloc_bitmask(65536, &readOnlyGlobals.udpProto);
alloc_bitmask(65536, &readOnlyGlobals.tcpProto);
#ifndef WIN32
setservent(1);
#endif
while((s = getservent()) != NULL) {
s->s_port = ntohs(s->s_port);
if(s->s_proto[0] == 'u')
bitmask_set(s->s_port, &readOnlyGlobals.udpProto);
else
bitmask_set(s->s_port, &readOnlyGlobals.tcpProto);
}
endservent();
/* Add extra protocols (if missing) */
bitmask_set(4343 /* das */, &readOnlyGlobals.tcpProto);
bitmask_set(80 /* http */, &readOnlyGlobals.tcpProto);
bitmask_set(43 /* whois */, &readOnlyGlobals.tcpProto);
bitmask_set(443 /* https */, &readOnlyGlobals.tcpProto);
bitmask_set(25 /* smtp */, &readOnlyGlobals.tcpProto);
bitmask_set(53 /* dns */, &readOnlyGlobals.udpProto);
}
/* ******************************************** */
u_int16_t port2ApplProtocol(u_int8_t proto, u_int16_t port) {
u_int16_t value;
if(proto == IPPROTO_TCP)
value = bitmask_isset(port, &readOnlyGlobals.tcpProto);
else if(proto == IPPROTO_UDP)
value = bitmask_isset(port, &readOnlyGlobals.udpProto);
else
value = 0;
return(value ? port : 0);
}
/* ******************************************** */
u_int16_t getFlowApplProtocol(FlowHashBucket *theFlow) {
u_int16_t value;
u_int16_t proto_sport = port2ApplProtocol(theFlow->core.tuple.key.k.ipKey.proto, theFlow->core.tuple.key.k.ipKey.sport);
u_int16_t proto_dport = port2ApplProtocol(theFlow->core.tuple.key.k.ipKey.proto, theFlow->core.tuple.key.k.ipKey.dport);
if((theFlow->core.tuple.key.k.ipKey.proto == IPPROTO_TCP) || (theFlow->core.tuple.key.k.ipKey.proto == IPPROTO_UDP)) {
if(proto_sport == 0) value = proto_dport;
else if(proto_dport == 0) value = proto_sport;
else {
if(theFlow->core.tuple.key.k.ipKey.sport < theFlow->core.tuple.key.k.ipKey.dport) value = proto_sport;
else value = proto_dport;
}
} else
value = 0;
// traceEvent(TRACE_ERROR, "[%u/%u] -> %u", theFlow->core.tuple.key.k.ipKey.sport, theFlow->core.tuple.key.k.ipKey.dport, value);
return(value);
}
/* ******************************************** */
void load_mappings() {
struct servent *sv;
#if !defined(WIN32)
struct protoent *pe;
#endif
while((sv = getservent()) != NULL) {
u_short port = ntohs(sv->s_port);
if(port_mapping[port] == NULL)
port_mapping[port] = strdup(sv->s_name);
}
#if !defined(WIN32)
endservent();
#endif
/* ******************** */
#if !defined(WIN32)
while((pe = getprotoent()) != NULL) {
if(proto_mapping[pe->p_proto] == NULL) {
proto_mapping[pe->p_proto] = strdup(pe->p_name);
// traceEvent(TRACE_INFO, "[%d][%s]", pe->p_proto, pe->p_name);
}
}
endprotoent();
#else
proto_mapping[0] = strdup("ip");
proto_mapping[1] = strdup("icmp");
proto_mapping[2] = strdup("igmp");
proto_mapping[6] = strdup("tcp");
proto_mapping[17] = strdup("udp");
#endif
}
/* ******************************************** */
void unload_mappings() {
int i;
for(i=0; i<0xFFFF; i++) if(port_mapping[i]) free(port_mapping[i]);
for(i=0; i<0xFF; i++) if(proto_mapping[i]) free(proto_mapping[i]);
}
/* ******************************************** */
/* FIX: improve performance */
char* proto2name(u_int8_t proto) {
#if 0
struct protoent *svt;
if(proto == 6) return("tcp");
else if(proto == 17) return("udp");
else if(proto == 1) return("icmp");
else if(proto == 2) return("igmp");
else if((svt = getprotobynumber(proto)) != NULL)
return(svt->p_name);
else {
static char the_proto[8];
snprintf(the_proto, sizeof(the_proto), "%d", proto);
return(the_proto);
}
#else
if(proto_mapping[proto] != NULL) {
// traceEvent(TRACE_INFO, "[%d][%s]", proto, proto_mapping[proto]);
return(proto_mapping[proto]);
} else
return("unknown");
#endif
}
/* ******************************************** */
/*
0 1 2
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Label | Exp |S|
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Label: Label Value, 20 bits
Exp: Experimental Use, 3 bits
S: Bottom of Stack, 1 bit
*/
static int mplsLabel2int(struct mpls_labels *mplsInfo, int labelId) {
int32_t val;
if(mplsInfo == NULL)
return(0);
val = (mplsInfo->mplsLabels[labelId][0] << 12)
+ (mplsInfo->mplsLabels[labelId][1] << 4)
+ ((mplsInfo->mplsLabels[labelId][2] >> 4) & 0xff);
return(val);
}
/* ******************************************** */
static u_int printRecordWithTemplate(V9V10TemplateElementId *theTemplateElement,
PluginEntryPoint *pluginEntryPoint,
char *line_buffer, u_int line_buffer_len,
FlowHashBucket *theFlow, FlowDirection direction,
u_int8_t json_mode) {
char buf[128], *dst, *country, *city;
#ifdef HAVE_GEOIP
GeoIPRecord *geo = NULL;
#endif
int avail_len;
u_int ret = 0, i, t;
struct timeval *tv;
u_int8_t add_quote = 0;
u_int teid = theTemplateElement->templateElementId;
if(unlikely(readOnlyGlobals.enable_debug))
traceEvent(TRACE_INFO, "%s [%s/%u][%d]", __FUNCTION__,
theTemplateElement->netflowElementName,
theTemplateElement->templateElementId,
theTemplateElement->templateElementLen);
dst = line_buffer, avail_len = line_buffer_len-1;
if(avail_len == 0) return(ret);
if(json_mode) {
if(theFlow->core.tuple.key.k.ipKey.src.ipVersion == 6) {
if(teid == IPV4_SRC_ADDR) teid = IPV6_SRC_ADDR;
else if(teid == IPV4_DST_ADDR) teid = IPV6_DST_ADDR;
else if(teid == IPV4_NEXT_HOP) return(ret);
} else {
if(teid == IPV6_SRC_ADDR) teid = IPV4_SRC_ADDR;
else if(teid == IPV6_DST_ADDR) teid = IPV4_DST_ADDR;
else if(teid == IPV6_NEXT_HOP) return(ret);
}
#ifdef HAVE_ZMQ
if(readOnlyGlobals.zmq.publisher /* ZMQ */
&& (!readOnlyGlobals.json_symbolic_labels))
i = snprintf(dst, avail_len, "\"%d\":%s", teid, add_quote ? "\"" : "");
else
#endif
i = snprintf(dst, avail_len, "\"%s\":%s", theTemplateElement->netflowElementName, add_quote ? "\"" : "");
ret += i;
dst = &line_buffer[ret], avail_len -= i;
}
if(avail_len == 0) return(ret);
switch(teid) {
case IN_BYTES:
i = snprintf(dst, avail_len, "%u",
direction == dst2src_direction ? theFlow->core.tuple.flowCounters.bytesRcvd : theFlow->core.tuple.flowCounters.bytesSent);
break;
case IN_PKTS:
i = snprintf(dst, avail_len, "%u",
direction == dst2src_direction ? theFlow->core.tuple.flowCounters.pktRcvd : theFlow->core.tuple.flowCounters.pktSent);
break;
case PROTOCOL:
i = snprintf(dst, avail_len, "%d", theFlow->core.tuple.key.k.ipKey.proto);
break;
case PROTOCOL_MAP:
i = snprintf(dst, avail_len, json_mode ? "\"%s\"" : "%s", proto2name(theFlow->core.tuple.key.k.ipKey.proto));
break;
case SRC_TOS:
i = snprintf(dst, avail_len, "%d",
(theFlow->ext == NULL) ? 0 : ((direction == src2dst_direction) ? theFlow->ext->src2dstTos : theFlow->ext->dst2srcTos));
break;
case TCP_FLAGS:
i = snprintf(dst, avail_len, "%d",
(theFlow->ext == NULL) ? 0 : ((direction == src2dst_direction) ? theFlow->ext->protoCounters.tcp.src2dstTcpFlags
: theFlow->ext->protoCounters.tcp.dst2srcTcpFlags));
break;
case L4_SRC_PORT:
i = snprintf(dst, avail_len, "%d",
direction == src2dst_direction ? theFlow->core.tuple.key.k.ipKey.sport : theFlow->core.tuple.key.k.ipKey.dport);
break;
case L4_SRC_PORT_MAP:
i = snprintf(dst, avail_len, json_mode ? "\"%s\"" : "%s",
port2name(direction == src2dst_direction ? theFlow->core.tuple.key.k.ipKey.sport : theFlow->core.tuple.key.k.ipKey.dport,
theFlow->core.tuple.key.k.ipKey.proto));
break;
case IPV4_SRC_ADDR:
case IPV6_SRC_ADDR:
{
u_int8_t ip_v = (teid == IPV4_SRC_ADDR) ? 4 : 6;
if(theFlow->core.tuple.key.is_ip_flow && theFlow->core.tuple.key.k.ipKey.src.ipVersion == ip_v) {
i = snprintf(dst, avail_len, json_mode ? "\"%s\"" : "%s",
_intoa(direction == src2dst_direction ? theFlow->core.tuple.key.k.ipKey.src: theFlow->core.tuple.key.k.ipKey.dst, buf, sizeof(buf)));
} else {
IpAddress addr;
memset(&addr, 0, sizeof(addr));
addr.ipVersion = ip_v;
i = snprintf(dst, avail_len, json_mode ? "\"%s\"" : "%s", _intoa(addr, buf, sizeof(buf)));
}
}
break;
case IPV4_SRC_MASK:
i = snprintf(dst, avail_len, "%d",
((theFlow->ext == NULL) || (!theFlow->core.tuple.key.is_ip_flow)) ? 0 :
((direction == src2dst_direction) ? ip2mask(&theFlow->core.tuple.key.k.ipKey.src, &theFlow->ext->srcInfo)
: ip2mask(&theFlow->core.tuple.key.k.ipKey.dst, &theFlow->ext->dstInfo)));
break;
case INPUT_SNMP:
i = snprintf(dst, avail_len, "%d", (theFlow->ext == NULL) ? 0 :
((direction == src2dst_direction) ? theFlow->ext->if_input : theFlow->ext->if_output));
break;
case L4_DST_PORT:
i = snprintf(dst, avail_len, "%d",
direction == src2dst_direction ? theFlow->core.tuple.key.k.ipKey.dport : theFlow->core.tuple.key.k.ipKey.sport);
break;
case L4_DST_PORT_MAP:
i = snprintf(dst, avail_len, json_mode ? "\"%s\"" : "%s",
port2name(direction == src2dst_direction ? theFlow->core.tuple.key.k.ipKey.dport : theFlow->core.tuple.key.k.ipKey.sport,
theFlow->core.tuple.key.k.ipKey.proto));
break;
case L4_SRV_PORT:
i = snprintf(dst, avail_len, "%u", getServerPort(theFlow));
break;
case L4_SRV_PORT_MAP:
i = snprintf(dst, avail_len, json_mode ? "\"%s\"" : "%s", port2name(getServerPort(theFlow), theFlow->core.tuple.key.k.ipKey.proto));
break;
case IPV4_DST_ADDR:
case IPV6_DST_ADDR:
{
u_int8_t ip_v = (teid == IPV4_DST_ADDR) ? 4 : 6;
if(theFlow->core.tuple.key.is_ip_flow && theFlow->core.tuple.key.k.ipKey.dst.ipVersion == ip_v) {
i = snprintf(dst, avail_len, json_mode ? "\"%s\"" : "%s",
_intoa(direction == src2dst_direction ? theFlow->core.tuple.key.k.ipKey.dst: theFlow->core.tuple.key.k.ipKey.src, buf, sizeof(buf)));
} else {
IpAddress addr;
memset(&addr, 0, sizeof(addr));
addr.ipVersion = ip_v;
i = snprintf(dst, avail_len, json_mode ? "\"%s\"" : "%s", _intoa(addr, buf, sizeof(buf)));
}
}
break;
case IPV4_DST_MASK:
i = snprintf(dst, avail_len, "%d",
((theFlow->ext == NULL) || (!theFlow->core.tuple.key.is_ip_flow)) ? 0 :
((direction == dst2src_direction) ? ip2mask(&theFlow->core.tuple.key.k.ipKey.src, &theFlow->ext->srcInfo) :
ip2mask(&theFlow->core.tuple.key.k.ipKey.dst, &theFlow->ext->dstInfo)));
break;
case OUTPUT_SNMP:
i = snprintf(dst, avail_len, "%d",
(theFlow->ext == NULL) ? 0 : ((direction != src2dst_direction) ? theFlow->ext->if_input : theFlow->ext->if_output));
break;
case IPV4_NEXT_HOP:
if(theFlow->ext && (theFlow->ext->nextHop.ipVersion == 4))
i = snprintf(dst, avail_len, json_mode ? "\"%s\"" : "%s", _intoa(theFlow->ext->nextHop, buf, sizeof(buf)));
else
i = snprintf(dst, avail_len, json_mode ? "\"%s\"" : "%s", "0.0.0.0");
break;
case SRC_AS:
i = snprintf(dst, avail_len, "%d", (theFlow->ext == NULL) ? 0 :
((direction == src2dst_direction) ? getAS(&theFlow->core.tuple.key.k.ipKey.src, &theFlow->ext->srcInfo)
: getAS(&theFlow->core.tuple.key.k.ipKey.dst, &theFlow->ext->dstInfo)));
break;
case DST_AS:
i = snprintf(dst, avail_len, "%d", (theFlow->ext == NULL) ? 0 :
((direction == src2dst_direction) ? getAS(&theFlow->core.tuple.key.k.ipKey.dst, &theFlow->ext->dstInfo)
: getAS(&theFlow->core.tuple.key.k.ipKey.src, &theFlow->ext->srcInfo)));
break;
case LAST_SWITCHED:
case FLOW_END_SEC:
tv = getFlowEndTime(theFlow, direction);
if(json_mode)
i = snprintf(dst, avail_len, "%u", (unsigned int)tv->tv_sec);
else
i = formatTimestamp(tv, dst, avail_len);
break;
case FIRST_SWITCHED:
case FLOW_START_SEC:
tv = getFlowBeginTime(theFlow, direction);
if(json_mode)
i = snprintf(dst, avail_len, "%u", (unsigned int)tv->tv_sec);
else
i = formatTimestamp(tv, dst, avail_len);
break;
case OUT_BYTES:
i = snprintf(dst, avail_len, "%u",
direction == dst2src_direction ? theFlow->core.tuple.flowCounters.bytesSent : theFlow->core.tuple.flowCounters.bytesRcvd);
break;
case OUT_PKTS:
i = snprintf(dst, avail_len, "%u",
direction == src2dst_direction ? theFlow->core.tuple.flowCounters.pktRcvd : theFlow->core.tuple.flowCounters.pktSent);
break;
case IPV6_SRC_MASK:
case IPV6_DST_MASK:
i = snprintf(dst, avail_len, "%d", 0);
break;
case ICMP_TYPE:
i = snprintf(dst, avail_len, "%d",
(theFlow->ext == NULL) ? 0 :
(direction == src2dst_direction ? theFlow->ext->protoCounters.icmp.src2dstIcmpType : theFlow->ext->protoCounters.icmp.dst2srcIcmpType));
break;
case SAMPLING_INTERVAL:
i = snprintf(dst, avail_len, "%d", readOnlyGlobals.pktSampleRate /* 1:1 = no sampling */);
break;
case SAMPLING_ALGORITHM:
i = snprintf(dst, avail_len, "%d",
0x01 /* 1=Deterministic Sampling, 0x02=Random Sampling */);
break;
case FLOW_ACTIVE_TIMEOUT:
i = snprintf(dst, avail_len, "%d",
readOnlyGlobals.lifetimeTimeout);
break;
case FLOW_INACTIVE_TIMEOUT:
i = snprintf(dst, avail_len, "%d",
readOnlyGlobals.idleTimeout);
break;
case ENGINE_TYPE:
i = snprintf(dst, avail_len, "%d",
theFlow->core.engine_type);
break;
case ENGINE_ID:
i = snprintf(dst, avail_len, "%d",
theFlow->core.engine_id);
break;
case TOTAL_BYTES_EXP:
i = snprintf(dst, avail_len, "%d",
readWriteGlobals->flowExportStats.totExportedBytes);
break;
case TOTAL_PKTS_EXP:
i = snprintf(dst, avail_len, "%d",
readWriteGlobals->flowExportStats.totExportedPkts);
break;
case TOTAL_FLOWS_EXP:
i = snprintf(dst, avail_len, "%d",
readWriteGlobals->flowExportStats.totExportedFlows);
break;
case MIN_TTL:
i = snprintf(dst, avail_len, "%d",
(theFlow->ext == NULL) ? 0 :
(direction == src2dst_direction ? theFlow->ext->src2dstMinTTL : theFlow->ext->dst2srcMinTTL));
break;
case MAX_TTL:
i = snprintf(dst, avail_len, "%d",
(theFlow->ext == NULL) ? 0 :
(direction == src2dst_direction ? theFlow->ext->src2dstMaxTTL : theFlow->ext->dst2srcMaxTTL));