forked from Merit-Research/AMON
-
Notifications
You must be signed in to change notification settings - Fork 2
/
amonsenss.cc
2110 lines (1864 loc) · 55.4 KB
/
amonsenss.cc
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
/*
#
# Copyright (C) 2018 University of Southern California.
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License,
# version 2, as published by the Free Software Foundation.
#
# 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 <signal.h>
#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <fstream>
#include <sched.h>
#include <sys/types.h>
#include <sys/select.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
#include <sys/mman.h>
#include <errno.h>
#include <sys/poll.h>
#include <netinet/in_systm.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <netinet/tcp.h>
#include <netinet/udp.h>
#include <netinet/ip6.h>
#include <net/ethernet.h>
#include <sys/time.h>
#include <time.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <monetary.h>
#include <locale.h>
#include <regex.h>
#include <iostream>
#include <sstream>
#include <string>
#include <map>
#include <cmath>
#include <pcap.h>
#include <dirent.h>
// Limits
#include<bits/stdc++.h>
#include "utils.h"
using namespace std;
// Global variables
bool resetrunning = false;
char saveline[MAXLINE];
int numattack = 0;
// We store delimiters in this array
int* delimiters;
bool sim_filter = false;
unsigned int max_shufflelen = 0;
unsigned int max_shuffleoci = 0;
map<unsigned int, struct shuffle_cell> memshuffle;
extern vector<int> samplingrates;
int shuffle_index = 0;
// Something like strtok but it doesn't create new
// strings. Instead it replaces delimiters with 0
// in the original string
int parse(char* input, char delimiter, int** array)
{
int pos = 0;
memset(*array, 255, AR_LEN);
int len = strlen(input);
int found = 0;
for(int i = 0; i<len; i++)
{
if (input[i] == delimiter)
{
(*array)[pos] = i+1;
input[i] = 0;
pos++;
found++;
}
}
return found;
}
// Variables/structs needed for detection
struct cell
{
long int *databrick_p; // databrick volume
double *databrick_s; // databrick symmetry
long int *databrick_sent; // databrick pkts sent
long int *databrick_rec; // databrick pkts recvd
unsigned int *wfilter_p; // volume w filter
int *wfilter_s; // symmetry w filter
};
// Should we require destination prefix
bool noorphan = false;
// How many service ports are there
int numservices = 0;
// Save all flows for a given time slot
map<long, time_flow*> timeflows;
// We have multiple layers of stats - NUMB of
// them - this reduces false positives
// These are the bins where we store stats
cell cells[NUMB][QSIZE];
int cfront = 0;
int crear = 0;
bool cempty = true;
// Samples of flows for signatures
sample samples[NUMB];
// Signatures per bin
stat_r *signatures[NUMB];
// Is the bin abnormal or not
int *is_abnormal[NUMB];
// Did we detect an attack in a given bin
int *is_attack[NUMB];
// When we detected the attack
unsigned long* detection_time[NUMB];
// Did we complete training
bool training_done = false;
bool shuffle_done = false;
int BRICK_FINAL = 0;
int shuffled = 0;
int trained = 0;
const int MAX_SHUFFLES = 100;
// Current time
double curtime = 0;
double lasttime = 0;
double lastlogtime = 0;
double lastbintime = 0;
// Verbose bit
int verbose = 0;
double firsttime = 0; // Beginning of trace
long freshtime = 0; // Where we last ended when processing data
double firsttimeinfile = 0; // First time in the current file
long int allflows = 0; // How many flows were processed total
long int processedflows = 0;// How many flows were processed this second
long updatetime = 0; // Time of last stats update
long statstime = 0; // Time when we move the stats to history
char filename[MAXLINE]; // A string to hold filenames
struct timespec last_entry;
// Is this pcap file or flow file? Default is flow
bool is_pcap = false;
bool is_live = false;
bool is_nfdump = false;
bool is_flowride = false;
// Serialize access to statistics
pthread_mutex_t cells_lock = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t samples_lock = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t cnt_lock = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t rst_lock = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t final_lock = PTHREAD_MUTEX_INITIALIZER;
// Types of statistics. If this changes, update the entire section
enum period{cur, hist};
enum type{n, avg, ss};
enum dim{vol, sym};
// historical and current stats for attack detection
double* stats[NUMB][2][3][2];
double* cusum[NUMB][2];
// Parameters from as.config
map<string,double> parms;
// Keeping track of procesed flows
long int processedbytes = 0;
int nl = 0;
int l = 0;
int mal = 0;
int inserts = 0;
int cinserts = 0;
// Trim strings
char *trim(char *str)
{
size_t len = 0;
char *frontp = str;
char *endp = NULL;
if( str == NULL ) { return NULL; }
if( str[0] == '\0' ) { return str; }
len = strlen(str);
endp = str + len;
while( isspace((unsigned char) *frontp) ) { ++frontp; }
if( endp != frontp )
{
while( isspace((unsigned char) *(--endp)) && endp != frontp ) {}
}
if( str + len - 1 != endp )
*(endp + 1) = '\0';
else if( frontp != str && endp == frontp )
*str = '\0';
endp = str;
if( frontp != str )
{
while( *frontp ) { *endp++ = *frontp++; }
*endp = '\0';
}
return str;
}
// Parse configuration file and load into parms
void
parse_config(map <string,double>& parms)
{
char *s, buff[256];
FILE *fp = fopen ("amonsenss.config", "r");
if (fp == NULL)
{
cout <<"Config file amonsenss.config does not exist. Please include it and re-run.. \n";
exit (0);
}
cout << "Reading config file amonsenss.config ...";
while ((s = fgets(buff, sizeof buff, fp)) != NULL)
{
// Skip blank lines and comment lines
if (buff[0] == '\n' || buff[0] == '#')
continue;
// Look for = sign and abort if that does not
// exist
char name[MAXLINE], value[MAXLINE];
int found = -1;
int i = 0;
for(i=0; i<strlen(buff); i++)
{
if (buff[i] == '=')
{
strncpy(name,buff, i);
name[i] = 0;
found = i;
}
else if((buff[i] == ' ' || buff[i] == '\n') && found >= 0)
{
strncpy(value,buff+found+1,i-found-1);
value[i-found-1] = 0;
break;
}
}
if (i > 0 && found > -1)
{
strncpy(value,buff+found+1,i-found-1);
value[i-found-1] = 0;
}
if (found == -1)
continue;
trim(name);
trim(value);
cout<<"Parm "<<name<<" val "<<value<<endl;
parms.insert(pair<string,double>(name,strtod(value,0)));
}
fclose (fp);
}
// Check if the signature is subset or matches
// exactly the slot where anomaly was found.
// For example, if a source port's traffic was
// anomalous we have to have that source port in the
// signature
bool compliantsig(int i, flow_t sig)
{
int loc = int(i/BRICK_FINAL);
switch (loc)
{
case 0:
case 1:
return (sig.dst != 0 && (sig.dport != -1 || sig.sport != -1 || sig.proto == ICMP));
case 2:
case 4:
case 5:
return (sig.dst != 0 && (sig.sport != -1|| sig.proto == ICMP));
case 3:
case 6:
case 7:
return (sig.dst != 0 && (sig.dport != -1 || sig.proto == ICMP));
case 8:
case 9:
case 10:
case 11:
case 12:
case 13:
case 14:
case 15:
return (sig.dst != 0 && sig.flags != 0);
default:
return false;
}
}
void clearSamples(int index, int id)
{
flow_t key;
pthread_mutex_lock(&samples_lock);
for (int s=1; s<NF; s++)
{
samples[id].bins[index].flows[s].flow = key;
samples[id].bins[index].flows[s].len = 0;
samples[id].bins[index].flows[s].oci = 0;
}
pthread_mutex_unlock(&samples_lock);
}
// Add a flow to the samples bin
void addSample(int index, flow_p* f, int way, int id)
{
// Create some partial signatures for this flow, like src-dst combination,
// src-sport, etc. Don't allow just protocol
// Don't add samples for flags separately since they are already going
// to separate bins
for (int s=1; s<NF-8; s++)
{
pthread_mutex_lock(&samples_lock);
flow_t k;
k.proto = f->flow.proto;
if ((s & 8) > 0)
k.src = f->flow.src;
if ((s & 4) > 0 && isservice(f->flow.sport))
k.sport = f->flow.sport;
if ((s & 2) > 0)
k.dst = f->flow.dst;
if ((s & 1) > 0 && isservice(f->flow.dport))
k.dport = f->flow.dport;
if (way == LHOST || way == LPREF || way == LHFPORT || way == LHLPORT || way == LPFPORT || way == LPLPORT
|| way == LHSYN || way == LPSYN || way == LHSYNACK || way == LPSYNACK || way == LHRST || way == LPRST)
{
k.dst = f->flow.dst;
if (way == LPREF || way == LPFPORT || way == LPLPORT || way == LPSYN || way == LPSYNACK || way == LPRST)
k.dst &= 0xffffff00;
}
if (way == FPORT || way == LHFPORT || way == LPFPORT)
k.sport = f->flow.sport;
if (way == LPORT || way == LHLPORT || way == LPLPORT)
k.dport = f->flow.dport;
if (way >= LHSYN)
k.flags = f->flow.flags;
// Overload len so we can track frequency of contributions
// Insert sample if it does not exist
if (samples[id].bins[index].flows[s].flow == k)
{
// Else increase contributions of this signature wrt symmetry
samples[id].bins[index].flows[s].len += abs(f->oci);
samples[id].bins[index].flows[s].oci += f->oci;
}
else
{
// Boyer Moore to find signatures that cover the most flows
if (empty(samples[id].bins[index].flows[s].flow))
{
samples[id].bins[index].flows[s].flow = k;
samples[id].bins[index].flows[s].len = abs(f->oci);
samples[id].bins[index].flows[s].oci = f->oci;
}
else
{
int olen = samples[id].bins[index].flows[s].len;
samples[id].bins[index].flows[s].len -= abs(f->oci);
int nlen = samples[id].bins[index].flows[s].len;
// Replace this signature if there's another one,
// which covers more
if (samples[id].bins[index].flows[s].len < 0)
{
samples[id].bins[index].flows[s].flow = k;
samples[id].bins[index].flows[s].len = abs(f->oci);
samples[id].bins[index].flows[s].oci = f->oci;
}
}
}
pthread_mutex_unlock(&samples_lock);
}
}
// Does this flow match the given signature
int match(flow_t flow, flow_t sig)
{
if (flow.proto != sig.proto && sig.proto != 0)
{
return 0;
}
if (empty(sig))
{
return 0;
}
if ((flow.src == sig.src || sig.src == 0) &&
(flow.sport == sig.sport || sig.sport == -1) &&
(flow.dst == sig.dst || sig.dst == 0) &&
(flow.dport == sig.dport || sig.dport == -1) &&
((flow.flags & sig.flags) > 0 || sig.flags == 0))
{
return 1;
}
else
{
return 0;
}
}
// Is this timestamp within the range, which we expect in a given input file
// this check is only for flow files, since they can have some very outdated flows
int malformed(double timestamp)
{
// Give some space here in case we're off and have straggler flows
if (timestamp < firsttimeinfile - 2*parms["file_interval"] || (parms["file_interval"] > 0 && timestamp > firsttimeinfile +
2*parms["file_interval"]))
return 1;
return 0;
}
// Function to detect values higher than mean + parms[num_std] * stdev
double abnormal(int type, int index, cell* c, int id)
{
// Look up std and mean
double mean = stats[id][hist][avg][type][index];
double std = sqrt(stats[id][hist][ss][type][index]/
(stats[id][hist][n][type][index]-1));
// Look up current value
double data;
double ao = stats[id][cur][avg][type][index];
if (type == vol)
data = c->databrick_p[index];
else
data = c->databrick_s[index];
// Project how avg would look if we add current value to it
double ddata = stats[id][cur][avg][type][index] +
(double)(data - stats[id][cur][avg][type][index])/(stats[id][cur][n][type][index]+1);
data = ddata;
// If we don't have enough samples return 0
if (stats[id][hist][n][type][index] <
parms["min_train"]*MIN_SAMPLES)
return 0;
// calculate cusum
double tmp = cusum[id][type][index] + data - mean - 3*std;
if (tmp < 0)
tmp = 0;
double rto = tmp/(std+1);
if (rto > 0)
return rto;
else
return 0;
}
// Print alert into the alerts file
void print_alert(int i, cell* c, int na, int id)
{
int BRICKF= BRICK_UNIT + id*13;
int pos = int(i/BRICKF);
// 1 - local ip, 2 - local pref /24, 3 - foreign port, 4 - local port,
// 5 - localip+forport, 6 - localip+localport, 7 - localpref+forport, 8 - localpref+localport
// 9 - localip+syn, 10 - localpref+syn, 11 - localip+synack, 12 - localpref+synack, 13 - localip+rst, 14 - localpref+rst
double diff = curtime - lasttime;
if (diff < 1)
diff = 1;
double avgv = stats[id][hist][avg][vol][i];
double stdv = sqrt(stats[id][hist][ss][vol][i]/(stats[id][hist][n][vol][i]-1));
double avgs = stats[id][hist][avg][sym][i];
double stds = sqrt(stats[id][hist][ss][sym][i]/(stats[id][hist][n][sym][i]-1));
long int rate = c->databrick_p[i] - avgv - parms["num_std"]*stdv;
long int roci = c->databrick_s[i] - avgs - parms["num_std"]*stds;
// Write the start of the attack into alerts
ofstream out;
if (abs(roci) < parms["min_oci"])
return;
if (empty(signatures[id][i].sig))
return;
u_int32_t ip;
unsigned short port;
int matched = 1;
for (int y = 0; y < NUMB; y++)
{
if (y == id)
continue;
for (int j = 0; j < NUMF*(BRICK_UNIT + y*13); j++)
{
if(is_attack[y][j] && !empty(signatures[y][j].sig))
{
// Say we have a match if we match the dst of the signature in a layer
if (signatures[y][j].sig.dst == signatures[id][i].sig.dst)
{
matched++;
break;
}
}
}
}
pthread_mutex_lock(&cnt_lock);
char alertfile[MAXLINE];
sprintf(alertfile, "alerts.txt");
// Only print alerts that have matched all layers
if (matched == NUMB)
{
out.open(alertfile, std::ios_base::app);
out<<na<<" "<<i/BRICKF<<" "<<(long)curtime<<" ";
out<<"START "<<i<<" "<<abs(rate);
out<<" "<<abs(roci)<<" ";
out<<printsignature(signatures[id][i].sig)<<endl;
out.close();
}
pthread_mutex_unlock(&cnt_lock);
// Check if we should rotate file, if it exceeds 10MB
ifstream in(alertfile, std::ifstream::ate | std::ifstream::binary);
if (in.tellg() > 10000000)
system("./rotate");
}
void alert_ready(cell* c, int bucket, int id)
{
double volf = c->wfilter_p[bucket];
double volb = c->databrick_p[bucket];
if (volb == 0)
volb = 1;
double avgs = stats[id][hist][avg][sym][bucket];
double stds = sqrt(stats[id][hist][ss][sym][bucket]/(stats[id][hist][n][sym][bucket]-1));
double symf = abs(c->wfilter_s[bucket]);
double symb = abs(c->databrick_s[bucket]) - (abs(avgs) + parms["num_std"]*abs(stds));
if (symb < 0)
symb = symf;
double data = abs(c->databrick_s[bucket]);
if (symb == 0)
symb = 1;
if (symf/symb >= parms["filter_thresh"])
{
pthread_mutex_lock(&cnt_lock);
int na = numattack++;
pthread_mutex_unlock(&cnt_lock);
print_alert(bucket, c, na, id);
}
is_attack[id][bucket] = false;
detection_time[id][bucket] = 0;
clearSamples(bucket, id);
}
void checkReady(int bucket, cell* c, int id)
{
if (signatures[id][bucket].nm < MM)
{
strcpy(signatures[id][bucket].matches[signatures[id][bucket].nm++], saveline);
if (signatures[id][bucket].nm == MM)
{
alert_ready(c, bucket, id);
}
}
}
// Should we filter this flow?
bool shouldFilter(int bucket, flow_t flow, cell* c, int id)
{
if (!empty(signatures[id][bucket].sig) && match(flow,signatures[id][bucket].sig))
return true;
else
return false;
}
long votedtime = 0;
int votes = 0;
const int MINVOTES = 1; // setting this to higher number may help if flows are very perturbed
void findBestSignature(double curtime, int i, cell* c, int id)
{
flow_t bestsig;
int oci = 0;
int maxoci = 0;
double avgs = stats[id][hist][avg][sym][i];
double stds = sqrt(stats[id][hist][ss][sym][i]/(stats[id][hist][n][sym][i]-1));
int totoci = c->databrick_rec[i];
// Go through candidate signatures
for (int s=1; s<NF; s++)
{
if (empty(samples[id].bins[i].flows[s].flow))
continue;
double candrate = abs((double)samples[id].bins[i].flows[s].oci);
if (!compliantsig(i, samples[id].bins[i].flows[s].flow))
{
if (verbose)
cout<<"non compliant SIG: "<<i<<" for slot "<<s<<" candidate "<<printsignature(samples[id].bins[i].flows[s].flow)<<" v="<<samples[id].bins[i].flows[s].len<<" o="<<samples[id].bins[i].flows[s].oci<<" toto="<<totoci<<" candrate "<<candrate<<" divided "<<candrate/totoci<<endl;
continue;
}
// Print out each signature for debugging
if (verbose)
cout<<"SIG: "<<i<<" for slot "<<s<<" candidate "<<printsignature(samples[id].bins[i].flows[s].flow)<<" v="<<samples[id].bins[i].flows[s].len<<" o="<<samples[id].bins[i].flows[s].oci<<" toto="<<totoci<<" candrate "<<candrate<<" divided "<<candrate/totoci<<endl;
// Potential candidate
if (candrate/totoci > parms["filter_thresh"] && samples[id].bins[i].flows[s].oci > parms["min_oci"])
{
// Is it a more specific signature?
if (bettersig(samples[id].bins[i].flows[s].flow, bestsig))
{
if (verbose)
cout<<"SIG: changing to "<< printsignature(samples[id].bins[i].flows[s].flow)<<endl;
bestsig = samples[id].bins[i].flows[s].flow;
oci = candrate;
}
}
}
if (verbose)
cout<<"SIG: "<<i<<" best sig "<<printsignature(bestsig)<<" Empty? "<<empty(bestsig)<<" oci "<<maxoci<<" out of "<<totoci<<endl;
// Remember the signature if it is not empty and can filter
// at least filter_thresh flows in the sample
if (!empty(bestsig))
{
if (verbose)
cout<<curtime<<" ISIG: "<<i<<" volume "<<c->databrick_p[i]<<" oci "<<c->databrick_s[i]<<" installed sig "<<printsignature(bestsig)<<endl;
// insert signature and reset all the stats
if (sim_filter)
{
signatures[id][i].sig = bestsig;
signatures[id][i].vol = 0;
signatures[id][i].oci = 0;
signatures[id][i].nm = 0;
}
// Clear samples
clearSamples(i, id);
}
// Did not find a good signature
// drop the attack signal and try again later
else
{
if (verbose)
cout << "AT: Did not find good signature for attack "<<
" on bin "<<i<<" best sig "<<empty(bestsig)<<
" coverage "<<(float)oci/totoci<<" thresh "<<
parms["filter_thresh"]<<endl;
is_attack[id][i] = false;
}
}
void instant_detect(cell* c, double ltime, int i, int id)
{
c->databrick_s[i] = (double)c->databrick_rec[i]/(c->databrick_sent[i] + 1);
double avgv = stats[id][hist][avg][vol][i];
double stdv = sqrt(stats[id][hist][ss][vol][i]/(stats[id][hist][n][vol][i]-1));
double avgs = stats[id][hist][avg][sym][i];
double stds = sqrt(stats[id][hist][ss][sym][i]/(stats[id][hist][n][sym][i]-1));
int volume = c->databrick_p[i];
int asym = c->databrick_s[i];
if (!is_attack[id][i])
{
// If both volume and asymmetry are abnormal and training has completed
double a = abnormal(vol, i, c, id);
double b = abnormal(sym, i, c, id);
int volume = c->databrick_p[i];
int asym = c->databrick_s[i];
if (training_done && a && b)
{
double aavgs = abs(avgs);
if (aavgs == 0)
aavgs = 1;
double d = abs(abs(asym) - abs(avgs) - parms["num_std"]*abs(stds))/aavgs;
is_abnormal[id][i] = a+b;
if (is_abnormal[id][i] > int(parms["attack_high"]))
is_abnormal[id][i] = int(parms["attack_high"]);
if (verbose && is_abnormal[id][i])
cout<<std::fixed<<ltime<<" id="<<id<<" abnormal for "<<i<<" points "<<is_abnormal[id][i]<<" oci "<<c->databrick_s[i]<<" ranges " <<avgs<<"+-"<<stds<<", vol "<<c->databrick_p[i]<<" ranges " <<avgv<<"+-"<<stdv<<" over mean "<<d<<" a "<<a<<" b "<<b<<" cusum thresh " << parms["cusum_thresh"]<<endl;
// If abnormal score is above attack_low
// and oci is above MIN_OCI
if (is_abnormal[id][i] >= int(parms["attack_low"])
&& !is_attack[id][i])
{
// Signal attack detection
is_attack[id][i] = true;
detection_time[id][i] = ltime;
if (verbose)
cout<<"id="<<id<<" AT: Attack detected on "<<i<<" but not reported yet vol "<<c->databrick_p[i]<<" oci "<<c->databrick_s[i]<<" min oci "<<int(parms["min_oci"])<<endl;
// Find the best signature
findBestSignature(ltime, i, c, id);
}
}
}
}
// After finding big hitters we allocate all memory
void malloc_all(int index, int BRICKF)
{
for(int i=0; i<QSIZE; i++)
{
cells[index][i].databrick_p = (long int*) malloc(BRICKF*sizeof(long int));
cells[index][i].databrick_sent = (long int*) malloc(BRICKF*sizeof(long int));
cells[index][i].databrick_rec = (long int*) malloc(BRICKF*sizeof(long int));
cells[index][i].databrick_s = (double*) malloc(BRICKF*sizeof(long int));
cells[index][i].wfilter_p = (unsigned int*) malloc(BRICKF*sizeof(unsigned int));
cells[index][i].wfilter_s = (int*) malloc(BRICKF*sizeof(int));
}
signatures[index] = (stat_r*) malloc(BRICKF*sizeof(stat_r));
is_abnormal[index] = (int*) malloc(BRICKF*sizeof(int));
memset(is_abnormal[index], 0, BRICKF*sizeof(int));
is_attack[index] = (int*) malloc(BRICKF*sizeof(int));
memset(is_attack[index], 0, BRICKF*sizeof(int));
detection_time[index] = (unsigned long*) malloc(BRICKF*sizeof(unsigned long));
memset(detection_time[index], 0, BRICKF*sizeof(unsigned long));
for(int i=0; i<2;i++)
for(int j=0; j<3; j++)
for(int k=0; k<2; k++)
{
stats[index][i][j][k] = (double*) malloc(BRICKF*sizeof(double));
memset(stats[index][i][j][k], 0, BRICKF*sizeof(double));
}
for(int i=0; i<2;i++)
cusum[index][i] = (double*) malloc(BRICKF*sizeof(double));
samples[index].bins = (sample_p*) malloc(BRICKF*sizeof(sample_p));
}
int FRACTION = 10000;
// This function finds big hitters (e.g., IPs, ports) and these
// are stored in a cell by themselves
void shuffle(unsigned int addr, int len, int oci, unsigned int curtime)
{
if (memshuffle.find(addr) == memshuffle.end())
{
shuffle_cell c;
c.len = len;
c.oci = oci;
memshuffle[addr] = c;
}
else
{
memshuffle[addr].len += len;
memshuffle[addr].oci += oci;
}
if (memshuffle[addr].len > max_shufflelen)
max_shufflelen = memshuffle[addr].len;
if (memshuffle[addr].oci > max_shuffleoci)
max_shuffleoci = memshuffle[addr].oci;
// If there are too many, delete all that are
// lower than small fraction of the max
if (memshuffle.size() > BRICK_UNIT)
{
for (auto mit=memshuffle.begin(); mit != memshuffle.end(); )
{
auto it = mit;
if (mit->second.len < max_shufflelen/FRACTION && mit->second.oci < max_shuffleoci/FRACTION)
{
mit++;
memshuffle.erase(it);
}
else
{
mit++;
}
}
shuffled++;
if (shuffled > MAX_SHUFFLES && !shuffle_done)
{
pthread_mutex_lock(&final_lock);
shuffle_index = memshuffle.size();
int index = 0;
for (auto mit=memshuffle.begin(); mit != memshuffle.end(); mit++)
mit->second.index = index++;
BRICK_FINAL = shuffle_index*NUMF+BRICK_DIMENSION;
// Malloc everything
for (int index = 0; index < NUMB; index++)
malloc_all(index, BRICK_FINAL + index*13*NUMF);
shuffle_done = true;
pthread_mutex_unlock(&final_lock);
}
}
if (curtime - firsttime >= parms["min_train"] && !shuffle_done)
{
pthread_mutex_lock(&final_lock);
shuffle_index = memshuffle.size();
int index = 0;
for (auto mit=memshuffle.begin(); mit != memshuffle.end(); mit++)
mit->second.index = index++;
BRICK_FINAL = shuffle_index*NUMF+BRICK_DIMENSION;
// Malloc everything
for (int index = 0; index < NUMB; index++)
malloc_all(index, BRICK_FINAL + index*13*NUMF);
shuffle_done = true;
pthread_mutex_unlock(&final_lock);
}
}
// Main function, which processes each flow
void
amonProcessing(flow_t flow, int len, double start, double end, int oci)
{
// Detect if the flow is malformed and reject it
if (malformed(end))
{
mal++;
return;
}
// Detect if it is UDP for port 443 or 4500 or 4501 or 80
// and don't use it. It's most likely legitimate.
if (flow.proto == UDP && ((isspecial(flow.sport) && !isservice(flow.dport)) ||
(isspecial(flow.dport) && !isservice(flow.sport))))
return;
if (flow.proto == ICMP)
{
flow.sport = -2;
flow.dport = -2;
}
if (curtime == 0)
curtime = end;
if ((unsigned long)end > (unsigned long)curtime)
{
if (votes == 0)
votedtime = (int)end;
if ((int)end == votedtime)
votes++;
else
votes--;
if (votes >= MINVOTES)
{
curtime = end;
votedtime = 0;
votes = 0;
}
}
if (lasttime == 0)
lasttime = curtime;
flow_p fp(start, end, len, oci, flow);
for (int index = 0; index < NUMB; index++)
{
pthread_mutex_lock(&final_lock);
// This makes sure that bins in each layer are a little different
// to reduce collisions
int BRICKF = BRICK_FINAL + index*13*NUMF;
pthread_mutex_unlock(&final_lock);
int BRICKU = BRICK_UNIT+index*13;
// indices for the databrick
int d_bucket = -1, s_bucket = -1;
cell *c = &cells[index][crear];
int is_filtered = false;
if (!shuffle_done)
{
if (flow.dlocal)
shuffle(flow.dst, len, oci, curtime);
else
shuffle(flow.src, len, oci, curtime);
return;
}
if (sim_filter)
{
for (int way = LHOST; way <= LPRST; way++) // SERV is included in CLI
{
// Find buckets on which to work
if (way == LHOST || way == LPREF || way >= LHSYN)
{
if (flow.dlocal)
{
d_bucket = myhash(flow.dst, 0, way, BRICKU);
if (shouldFilter(d_bucket, flow, c, index))
{
is_filtered = true;
c->wfilter_p[d_bucket] += len;
c->wfilter_s[d_bucket] += oci;
checkReady(d_bucket, c, index);
}
}
}
else if (way == FPORT)
{
if (flow.dlocal)
{
// traffic from FPORT
s_bucket = myhash(0, flow.sport, way, BRICKU);
if (shouldFilter(s_bucket, flow, c, index))
{
is_filtered = true;
c->wfilter_p[s_bucket] += len;
c->wfilter_s[s_bucket] += oci;
checkReady(s_bucket, c, index);
}
}
}
else if (way == LPORT)
{
if (flow.dlocal)
{
// traffic to LPORT
d_bucket = myhash(0, flow.dport, way, BRICKU);
if (shouldFilter(d_bucket, flow, c, index))
{
is_filtered = true;
c->wfilter_p[d_bucket] += len;
c->wfilter_s[d_bucket] += oci;
checkReady(d_bucket, c, index);
}
}
}
else if (way == LHFPORT || way == LPFPORT || way == LHLPORT || way == LHFPORT)