-
Notifications
You must be signed in to change notification settings - Fork 47
Expand file tree
/
Copy pathlorg
More file actions
executable file
·4852 lines (4074 loc) · 256 KB
/
lorg
File metadata and controls
executable file
·4852 lines (4074 loc) · 256 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env php
<?php
/*------------------------------------------------------------------\
| LORG v0.41 | Sat Jun 15 20:20:22 CEST 2013 |
| Logfile Outlier Recognition and Gathering |
| |
| Author: Jens Mueller {jens.a.mueller@rub.de}, Ruhr-Uni Bochum |
| License: GPL v2 (http://www.gnu.org/licenses/gpl-2.0.html) |
| |
| **************************** INSTALL **************************** |
| STEP 1: (optional) get PHPIDS from http://phpids.org, gunzip |
| and untar, then move IDS/ into the following directory |
| */ static $phpids_path = './phpids/'; /* |
| STEP 2: (optional) for geotargeting, download php-x.xx.tar.gz |
| and GeoLiteCity.dat.gz from http://geolite.maxmind.com/ |
| and gunzip/untar all files into the following directory |
| */ static $geoip_path = './geoip/'; /* |
| STEP 3: (optional) for some nice graphics in HTML reports, get |
| the php5-gd library and pChart from http://pchart.net/ |
| and gunzip/untar all files into the following directory |
| */ static $pchart_path = './pchart/'; /* |
| STEP 4: run ./lorg.php access.log |
| |
| *************************** CONFIGURE *************************** |
| you can define your own Apache-style logline formats, e.g. |
| 'custom' => '%h %l %u %t \"%r\" %>s %b %{X-Forwarded-For}' |
| (see http://httpd.apache.org/docs/mod/mod_log_config.html) |
\------------------------------------------------------------------*/
# define allowed input formats (apache style, feel free to complement)
static $allowed_input_types = array(
'common' => '%h %l %u %t \"%r\" %>s %b',
'combined' => '%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"',
'vhost' => '%v %h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"',
'logio' => '%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\ %I %O"',
'cookie' => '%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" \"%{Cookie}i\"'
);
# define output types, client identifiers and attack vectors (don't change!)
static $allowed_output_types = array('html', 'json', 'xml', 'csv');
static $allowed_client_ident = array('host', 'session', 'user', 'logname', 'all');
static $additional_attack_vectors = array('path', 'argnames', 'cookie', 'agent', 'all');
# define dnsbl types and corresponding servers (feel free to modify)
static $allowed_dnsbl_types = array(
'tor' => array('tor.dnsbl.sectoor.de'),
'proxy' => array('dnsbl.proxybl.org', 'http.dnsbl.sorbs.net', 'socks.dnsbl.sorbs.net'),
'zombie' => array('xbl.spamhaus.org', 'zombie.dnsbl.sorbs.net'),
'spam' => array('b.barracudacentral.org', 'spam.dnsbl.sorbs.net', 'sbl.spamhaus.org'), # 'sbl.nszones.com': slow!
'dialup' => array('dyn.nszones.com'), # slow!
'all' => ''
);
# define implemented modes of anomaly detection (don't change!)
static $allowed_detect_modes = array('chars', 'phpids', 'mcshmm', 'dnsbl', 'geoip', 'all'); # 'length'
# define implemented modes of attack quantification (don't change!)
static $allowed_quantify_types = array('status', 'bytes', 'replay', 'all');
# define known HTTP/1.1 methods (RFC 2616)
static $allowed_http_methods = array('HEAD', 'GET', 'POST', 'PUT', 'TRACE', 'OPTIONS', 'CONNECT');
# define session id strings to look for (case-insensitive)
# note: you can also use a regex like: '(\w)*SESS(ION)?ID(\w)*'
static $session_identifiers = array('SID', 'SESSID', 'PHPSESSID', 'JSESSIONID', 'ASP.NET_SessionId');
# define client inactivity time span until new session starts
static $max_session_duration = 3600;
# define maximum number of attack replays for a single client
static $max_replay_per_client = 1000;
# define maximum number of harmless requests to show between attacks
static $max_harmless_summarize = 100;
# define file extensions considered as web applications
static $web_app_extensions = array('cgi', 'php[3-5]?', 'phtml', 'pl', 'jsp', 'aspx?', 'cfm', 'exe');
# only detect attacks made to web applications (matched by file extension)
static $only_check_webapps = false;
# always normalize requests with PHPIDS (even for other detect modes)
static $use_phpids_converter = false;
# create pie chart of most noisy clients, if pChart and GD libraries installed
static $use_pchart_library = true;
// ------------------------- CHARS settings -------------------------//
# define minimum number of required observations
static $var_min_learn = 10;
# define maximum variance (above, algorithm will perform badly)
static $var_citical_val = 10;
// ------------------------- MCSHMM settings -------------------------//
# define minimum number of required observations
# (if not hit, we will not make a detection statement)
static $hmm_min_learn = 50;
# define maximum number of observations to learn
# (if hit, aggregation stops since we have enough training data)
static $hmm_max_learn = 150;
# define maximal number of iterations for training
# (if hit, training stops even HMM is not yet precise)
static $hmm_max_iter = 100;
# define tolerance for testing convergence function
static $hmm_tolerance = 1.0E-5;
# define probability of validity for unknown symbols
static $hmm_decrease = 1.0E-10;
# define the number of models (HMMs) per ensemble
static $hmm_num_models = 5;
// ------------------------- GEOIP settings ------------------------- //
# define minimum number of items to learn for LOF algorihm
static $lof_min_learn = 40;
# define maximum number of items to learn for LOF algorihm
static $lof_max_learn = 150;
# define lower and upper bounds of k-nearest neighbors
static $lof_minpts_lb = 10;
static $lof_minpts_ub = 20;
// ------------------------- LORG switches -------------------------- //
# by default, use a moderate detection threshold (see -t)
# note: this will also be the result for DNSBL detect mode
$default_threshold = 10;
# by default, don't be to chatty (see '-v')
$default_verbosity = 1;
# by default, don't do attack quantification (see '-q')
$quantify_type = array();
# by default, summarize detection results (see '-n')
$do_summarize = true;
# by default, don't try to determine hostnames (see '-h')
$dns_lookup = false;
# by default, don't do dnsbl lookups (see '-b')
$dnsbl_lookup = false;
# by default, don't do geoip lookups (see '-g')
$geoip_lookup = false;
# by default, don't try to urldecode requests (see '-u')
$url_decode = false;
# by default, don't use additional attack vectors (see '-a')
$add_vector = false;
# by default, don't do naive logfile tamper detection (see '-p')
$tamper_test = false;
// ------------------------------------------------------------------ //
# check if running from the command line
if (!defined("STDIN"))
die("[!] Please run this programm from the CLI\n\n");
# set threshold to default
$GLOBALS['verbosity'] = $default_verbosity;
// ------------------------------------------------------------------ //
# remove first element first of argv (scriptname)
array_shift($argv);
# parse command line options and flags
foreach(getopt("i:o:d:a:c:b:q:t:v:nuhgp") as $opt => $value)
{
### echo "\n======================= <DEBUG: \$argv $opt -> $value> =======================\n";
### print_r($argv);
### echo "======================= </DEBUG: \$argv ======================\n";
switch ($opt)
{
case 'i':
$input_type = $value;
// check for correct input file type
if (array_key_exists($input_type, $allowed_input_types) == false)
{
print_message(0, "[!] Input format '$input_type' not allowed\n");
usage_die();
}
// remove switch and option from argument vector
if (strlen($argv[0]) <= 2) array_shift($argv); array_shift($argv);
break;
case 'o':
$output_type = $value;
// check for correct output file type
if (in_array($output_type, $allowed_output_types) == false)
{
print_message(0, "[!] Output format '$output_type' not allowed\n");
usage_die();
}
// remove switch and option from argument vector
if (strlen($argv[0]) <= 2) array_shift($argv); array_shift($argv);
break;
case 'd':
$detect_mode = (is_array($value) ? $value : array($value));
foreach ($detect_mode as $mode)
{
// check for correct detection mode
if (in_array($mode, $allowed_detect_modes) == false)
{
print_message(0, "[!] Detect mode '$mode' not allowed\n");
usage_die();
}
// remove switch and option from argument vector
if (strlen($argv[0]) <= 2) array_shift($argv); array_shift($argv);
}
// if 'all' selected, create array of detection modes
if (in_array('all', $detect_mode))
{
$detect_mode = $allowed_detect_modes;
array_pop($detect_mode); // remove element 'all'
}
break;
case 'a':
$add_vector = array($value);
// check for correct attack vector
if (in_array($add_vector[0], $additional_attack_vectors) == false)
{
print_message(0, "[!] Additional attack vector '$add_vector[0]' not allowed\n");
usage_die();
}
// if all selected, create array of additional attack vectors
if ($add_vector[0] == 'all')
{
$add_vector = $additional_attack_vectors;
array_pop($add_vector); // remove element 'all'
}
// remove switch and option from argument vector
if (strlen($argv[0]) <= 2) array_shift($argv); array_shift($argv);
break;
case 'c':
$client_ident = $value;
// check for correct client identifier type
if (in_array($client_ident, $allowed_client_ident) == false)
{
print_message(0, "[!] Remote ID '$client_ident' not allowed\n");
usage_die();
}
// remove switch and option from argument vector
if (strlen($argv[0]) <= 2) array_shift($argv); array_shift($argv);
break;
case 'b':
$dnsbl_type = array($value);
// check for correct dnsbl type
if (array_key_exists($dnsbl_type[0], $allowed_dnsbl_types) == false)
{
print_message(0, "[!] DNSBL type '$dnsbl_type[0]' not allowed\n");
usage_die();
}
// if all selected, create array of dnsbl types
if ($dnsbl_type[0] == 'all')
{
$dnsbl_type = array_keys($allowed_dnsbl_types);
array_pop($dnsbl_type); // remove element 'all'
}
$dnsbl_lookup = true;
// remove switch and option from argument vector
if (strlen($argv[0]) <= 2) array_shift($argv); array_shift($argv);
break;
case 'q':
$quantify_type = array($value);
// check for correct attack vector
if (in_array($quantify_type[0], $allowed_quantify_types) == false)
{
print_message(0, "[!] Quantification type '$quantify_type[0]' not allowed\n");
usage_die();
}
// if all selected, create array of additional attack vectors
if ($quantify_type[0] == 'all')
{
$quantify_type = $allowed_quantify_types;
array_pop($quantify_type); // remove element 'all'
}
// remove switch and option from argument vector
if (strlen($argv[0]) <= 2) array_shift($argv); array_shift($argv);
break;
case 't':
$threshold = $value;
// check for correct $threshold (= minimum impact) type and value
if (filter_var($threshold, FILTER_VALIDATE_INT, array('options' => array('min_range' => 0))) === false)
{
print_message(0, "[!] Threshold must be a positive integer or zero\n");
usage_die();
}
// remove switch and option from argument vector
if (strlen($argv[0]) <= 2) array_shift($argv); array_shift($argv);
break;
case 'v':
$GLOBALS['verbosity'] = $value;
// check for correct verbosity level type and value
if (filter_var($value, FILTER_VALIDATE_INT, array('options' => array('min_range' => 0, 'max_range' => 3))) === false)
{
print_message(0, "[!] Verbosity must be an integer value from 0 to 3\n");
usage_die();
}
// remove switch and option from argument vector
if (strlen($argv[0]) <= 2) array_shift($argv); array_shift($argv);
break;
case 'n':
$do_summarize = false;
// we cannot handle two flags at a time
if (strlen($argv[0]) > 2)
usage_die();
// remove flag from argument vector
array_shift($argv);
break;
case 'u':
$url_decode = true;
// we cannot handle two flags at a time
if (strlen($argv[0]) > 2)
usage_die();
// remove flag from argument vector
array_shift($argv);
break;
case 'h':
$dns_lookup = true;
// we cannot handle two flags at a time
if (strlen($argv[0]) > 2)
usage_die();
// remove flag from argument vector
array_shift($argv);
break;
case 'g':
$geoip_lookup = true;
// we cannot handle two flags at a time
if (strlen($argv[0]) > 2)
usage_die();
// remove flag from argument vector
array_shift($argv);
break;
case 'p':
$tamper_test = true;
// we cannot handle two flags at a time
if (strlen($argv[0]) > 2)
usage_die();
// remove flag from argument vector
array_shift($argv);
break;
}
}
# parse command line arguments
if (isset($argv[0]))
$input_file = $argv[0];
if (isset($argv[1]))
$output_file = $argv[1];
// ------------------------------------------------------------------ //
# print newline to stdout
print_message(1, "\n");
# turn off PHP warnings in non-verbose mode
if ($GLOBALS['verbosity'] <= 1)
error_reporting(E_ERROR | E_PARSE);
// ------------------------------------------------------------------ //
# exit, if no input file given
if (!isset($input_file))
{
print_message(0, "[!] Specify at least an input logfile\n");
usage_die();
}
# set input file basename
$input_file_basename = basename($input_file);
// ------------------------------------------------------------------ //
# try to open input file for reading
if (($input_stream = fopen($input_file, 'r')) == false)
{
print_message(0, "[!] Cannot read from input file '$input_file'\n");
usage_die();
}
// ------------------------------------------------------------------ //
# try auto-detection of input format, if none given
if (!isset($input_type))
{
if ($input_type = detect_logformat($input_stream, $allowed_input_types))
print_message(1, "[#] No input file format given - guessing '$input_type'\n");
else
{
print_message(0, "[!] Cannot auto-detect input format of '$input_file_basename'\n");
usage_die();
}
}
// ------------------------------------------------------------------ //
# set regex for given input format
format_to_regex($allowed_input_types[$input_type], $regex_fields, $regex_string, $num_fields);
# set geoip objects to zero-value
$geoip_stream = null; $geoip_data = null;
// ------------------------------------------------------------------ //
# set default output format, if none given
if (!isset($output_type))
{
$output_type = $allowed_output_types[0];
print_message(1, "[#] No output file format given - using '$output_type'\n");
}
// ------------------------------------------------------------------ //
# set default output filename, if none given
if (!isset($output_file))
{
$output_file = 'report_' . date("d-M-Y-His") . '.' . $output_type;
print_message(1, "[#] No output file given - using '$output_file'\n");
}
// ------------------------------------------------------------------ //
# check if pChart-installation is present, if needed
if (($output_type == 'html') and $do_summarize and $use_pchart_library)
{
// try to include pChart framework
$pchart_requires = array('pData.class.php', 'pDraw.class.php', 'pPie.class.php', 'pImage.class.php');
$pchart_included = (extension_loaded('gd') and function_exists('gd_info'));
$pchart_included = $pchart_included ? include_multiple("$pchart_path/class/", $pchart_requires) : false;
// print errors in case pChart-installation not found
if ($pchart_included)
{
print_message(2, "[*] pChart/php5-gd library found in '$pchart_path'\n");
}
else
{
print_message(1, "[#] Cannot find pChart/GD library - charting disabled\n");
$use_pchart_library = false;
}
}
// ------------------------------------------------------------------ //
# set default detection mode, if none given
if (!isset($detect_mode))
{
$detect_mode = array($allowed_detect_modes[0]);
print_message(1, "[#] No detect mode given - using '$detect_mode[0]'\n");
}
// ------------------------------------------------------------------ //
# check if PHPIDS-installation is present, if needed
if (in_array('phpids', $detect_mode) or $use_phpids_converter)
{
# try to include PHPIDS framework
$phpids_requires = array('Init.php', 'Event.php', 'Filter.php', 'Report.php', 'Converter.php');
$phpids_included = include_multiple("$phpids_path/", $phpids_requires);
# print errors in case PHPIDS-installation not found
if ($phpids_included)
{
print_message(2, "[*] PHPIDS installation found in '$phpids_path'\n");
// overwrite some configs so we can always find the PHPIDS directory
$phpids_init = IDS_Init::init($phpids_path . '/Config/Config.ini.php');
$phpids_init->config['General']['base_path'] = $phpids_path . '/';
$phpids_init->config['General']['use_base_path'] = true;
}
else
{
// in case we're using PHPIDS detection
if (in_array('phpids', $detect_mode))
{
unset($detect_mode[array_search('phpids', $detect_mode)]);
// quit, if no other dectection modes are enabled
if (count($detect_mode) == 0)
die("[!] No PHPIDS installation found - exiting!\n\n");
else
print_message(0, "[#] No PHPIDS installation found - detection disabled\n");
}
// else, just disable PHPIDS request conversion
if ($use_phpids_converter)
{
print_message(1, "[#] No PHPIDS installation found - request conversion disabled\n");
$use_phpids_converter = false;
}
}
}
else // do not leave variable unset
$phpids_init = null;
// ------------------------------------------------------------------ //
# ask for target host, if active replay enabled
if (in_array('replay', $quantify_type))
{
print_message(0, "[#] Active replay enabled - this will re-probe all attacks!\n");
// eh, screw good practics (...and use GOTO)
REPLAY: $target = readline(" Please enter target host: ");
// HINT: You need to configure PHP --with-readline
// TODO: maybe migrate to stream_get_line()
// add http:// substring to target URI, if not given
if (!preg_match("/^https?:\/\//", $target))
$target = 'http://' . $target;
// try to connect to HTTP(S) server
$body = @file_get_contents( $target . '/', false);
if ($body === FALSE)
{
print_message(0, "[!] Cannot connect to '$target'\n");
goto REPLAY; // a little GOTO here and there
}
}
else
$target = null;
// ------------------------------------------------------------------ //
# set default threshold, if none given
if (!isset($threshold))
{
// process all requests with threshold greater ten
$threshold = $default_threshold;
print_message(1, "[#] No threshold given - using default value '$default_threshold'\n");
}
else
{
if ($threshold > 0)
print_message(1, "[#] Ignoring requests with a threshold less than '$threshold'\n");
else
print_message(1, "[#] Threshold set to zero - Logging everything!\n");
}
// ------------------------------------------------------------------ //
# set default client identifier, if none given
if (!isset($client_ident))
{
$client_ident = $allowed_client_ident[0];
print_message(1, "[#] No client identifier given - using '$client_ident'\n");
}
// ------------------------------------------------------------------ //
# check if geoip-information is present, if used
if ($geoip_lookup)
{
// workaround: program crashes if php5-geoip is installed!
if (function_exists('geoip_record_by_name'))
{
print_message(1, "[#] Incompatible php5-geoip installation found - geotargeting disabled\n");
$geoip_lookup = false;
}
else
{
/*------------------------------------------------------------------------\
| files needed for geotargeting: |
| *********************************************************************** |
| - http://geolite.maxmind.com/download/geoip/api/php/php-x.xx.tar.gz |
| - http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz |
| (don't forget to gunzip/untar all files into $geoip_path folder) |
\------------------------------------------------------------------------*/
# try to include 'maxmind geoip city' framework
$geoip_requires = array('geoipregionvars.php', 'geoip.inc', 'geoipcity.inc');
$geoip_included = include_multiple("$geoip_path/", $geoip_requires);
$geoip_database = $geoip_path.'/GeoLiteCity.dat';
# print errors in case geoip-installation not found
if ($geoip_included and file_exists($geoip_database))
{
print_message(2, "[*] GeoIP information found in '$geoip_path'\n");
# for speeding this up a bit, you might want to try GEOIP_SHARED_MEMORY or GEOIP_MEMORY_CACHE
$geoip_stream = geoip_open($geoip_database, GEOIP_STANDARD);
}
else
{
print_message(1, "[#] No GeoIP information available - geotargeting disabled\n");
$geoip_lookup = false;
}
}
}
// ------------------------------------------------------------------ //
# remove geoip from detection modes, if geoip lookup disabled
if (in_array('geoip', $detect_mode))
{
if ($geoip_lookup == false)
{
unset($detect_mode[array_search('geoip', $detect_mode)]);
print_message(0, "[!] To use GeoIP detection, you have to enable geotargeting (-g)\n");
// quit, if no other dectection modes are enabled
if (count($detect_mode) == 0)
die("\n");
}
}
// ------------------------------------------------------------------ //
# remove dnsbl from detection modes, if dnsbl lookup disabled
if (in_array('dnsbl', $detect_mode))
if ($dnsbl_lookup == false)
{
unset($detect_mode[array_search('dnsbl', $detect_mode)]);
print_message(0, "[!] To use DNSBL detection, you have to choose a DNSBL type (-b)\n");
// quit, if no other dectection modes are enabled
if (count($detect_mode) == 0)
die("\n");
}
// ------------------------------------------------------------------ //
# show speed warning, if dnsbl lookup enabled
if ($dnsbl_lookup)
print_message(1, "[#] DNSBL lookup enabled - this might be a significant slowdown\n");
// ------------------------------------------------------------------ //
# show speed warning, if hostname lookup enabled
if ($dns_lookup)
print_message(1, "[#] Hostname lookup enabled - this might be a significant slowdown\n");
// ------------------------------------------------------------------ //
# show speed warning, if additional attack vectors used
if ($add_vector)
print_message(1, "[#] Scanning additional attack vectors - this might be a significant slowdown\n");
// ------------------------------------------------------------------ //
# show information, if url-decoding enabled
if ($url_decode)
print_message(1, "[#] Non-binary urlencoded requests will be decoded\n");
// ------------------------------------------------------------------ //
# show message in case summarization is disabled
if ($do_summarize == false)
print_message(1, "[#] Summarization and robot detection disabled\n");
// ------------------------------------------------------------------ //
# set counters for statistics
$line_index = 0; $progress = -1; $request_count = 0; $attack_count = 0;
$tags_count = 0; $tag_stats = $replay_count = array(); $success = null;
$pathes = array(); $dates = array();
# set if tags are to shown in output
$add_tags = in_array('phpids', $detect_mode) ? true : false;
# poor man's dns/dnsbl/geoip/lof cache
$dns_cache = $dnsbl_cache = $geoip_cache = $lof_cache = null;
# main dataset and client collection
$dataset = $clients = array();
// --------------------------------------------------------------
# breakpoint: read logfile, count it's lines and aggregate dataset if needed
function pre_processing() {}
// decide if we have to create a dataset
$do_aggregate = (in_array('chars', $detect_mode)
or in_array('length', $detect_mode)
or in_array('mcshmm', $detect_mode)
or in_array('geoip', $detect_mode)
or in_array('bytes', $quantify_type));
// decide if we have to read all lines of logfile
$do_readlines = ($do_aggregate or $tamper_test);
// save logfile modification time
$last_modified = filemtime($input_file);
// number of lines
$line_count = 0;
// number of vectors
$vector_count = 0;
// needed for variance calculation
$avg_delay = $avg_request = $avg_subst = $var_delay = $var_request = $var_subst = 0.0; $index_delay = $index_request = $index_subst = 0;
// print feedback (important, when dealing with huge files)
print_message(1, '[>] ' . ($do_aggregate ? 'Creating dataset' : ($do_readlines ?
'Gathering statistics' : 'Counting number of lines')) . " of '$input_file_basename'" . ($do_readlines ? '' : "\n"));
// reset position indicator to zero
fseek($input_stream, 0);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
if ($do_readlines)
{
// loop over input file
while ($line = fgets($input_stream))
{
// increment number of lines
$line_count++;
// remove junk like MS-wordwraps
$line = trim($line);
// ignore empty lines
if (empty($line))
continue;
// convert logline to HTTP object
$data = logline_to_httpdata($line, $regex_string, $regex_fields, $num_fields);
// create dataset
if (isset($data))
{
// extract request (+additional attack vectors) and path from HTTP-data
$vector = httpdata_to_vector($data, $add_vector, $use_phpids_converter, $phpids_path, $phpids_init,
$detect_mode, $only_check_webapps, $web_app_extensions, $input_file, null);
// get request used for detection
$request = $vector[0];
// get path of the web application
$path = $vector[1];
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# calculate variance of inter request time delay, based on Welford1962 online algorithm
if ($tamper_test and (isset($data['Date'])))
{
// convert date to unix timestamp format
$current_date = strtotime(date("r", apachedate_to_timestamp($data['Date'])));
if (isset($last_date))
{
// get inter-request time delay
$value = $current_date - $last_date;
// set maximum delay, if new max
$max_delay = max($value, (isset($max_delay) ? $max_delay : 0));
// online variance and mean calculation of delay
online_variance($avg_delay, $var_delay, $index_delay, $value);
}
// set last date to current date
$last_date = $current_date;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# aggregate dataset needed for mcshmm/geoip detection and attack quantification
if ($do_aggregate)
{
// if request contains a remote-host entry
if (array_key_exists('Remote-Host', $data))
{
// this might be an ip address _or_ a hostname
$remote_host = $data['Remote-Host'];
// convert hostnames to ip addresses (needed for geoip lookups)
if (in_array('geoip', $detect_mode))
$ipaddr = hostname_to_ipaddr($data['Remote-Host'], $dns_cache);
}
else
// set remote-host to current line if client identified by ip address, else unknown
$remote_host = ($client_ident == 'host') ? "client_$line_count" : 'unknown_host';
// try to retrieve client's identity
$client = client_identification($data, $client_ident, $remote_host, $session_identifiers);
// if status code is valid (if present)
if (isset($data['Final-Status']) ? preg_match("/^(2|3)[0-9]+$/", $data['Final-Status']) : true)
{
if (in_array('chars', $detect_mode)) # add information needed for chars detection
aggregate_chars($dataset, $data, $path, $vector, $client, $request, $avg_subst, $var_subst, $index_subst);
if (in_array('length', $detect_mode)) # add information needed for length detection
aggregate_length($dataset, $data, $path, $vector, $client, $request, $avg_request, $var_request, $index_request);
if (in_array('mcshmm', $detect_mode)) # add information needed for mcshmm detection
aggregate_mcshmm($dataset, $path, $request, $vector_count, $add_vector, $client, $hmm_max_learn);
if (in_array('geoip', $detect_mode)) # add information needed for geoip detection
aggregate_geoip($dataset, $geoip_cache, $geoip_stream, $ipaddr, $lof_max_learn);
if (in_array('bytes', $quantify_type)) # add information needed for attack quantification;
aggregate_bytes($dataset, $data, $path, $vector, $client, $lof_max_learn);
}
}
}
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# chose random samples for geoip detection
if (in_array('geoip', $detect_mode))
{
// calculate number of geoip samples to choose
$sample_count = isset($dataset['geolocation']) ? count($dataset['geolocation']) : 0;
$sample_count = ($sample_count >= $lof_max_learn) ? $lof_max_learn : $sample_count;
// in case we have collected enough samples for geoip detection
if ($sample_count >= $lof_min_learn)
{
// randomize geoip samples
$dataset['geolocation'] = array_rand_multi($dataset['geolocation'], $sample_count);
carriage_return(1, "[#] [GeoIP detect] Choosing $sample_count random geolocations\n", $line_count, $input_file_basename);
}
else // remove geoip from detection modes,
{
unset($detect_mode[array_search('geoip', $detect_mode)]); $dataset['geolocation'] = null;
carriage_return(0, "[!] Not enough geolocations available - GeoIP detection disabled", $line_count, $input_file_basename);
// die, if geoip is only used detection mode
if (count($detect_mode) == 0)
die("\n");
}
}
# chose random samples for bytes quantification
if (in_array('bytes', $quantify_type) and isset($dataset['query']))
{
// for all webapps do
foreach ($dataset['query'] as $key => &$path)
{
// calculate number of bytes samples to choose
$sample_count = isset($path['bytes']) ? count($path['bytes']) : 0;
$sample_count = ($sample_count >= $lof_max_learn) ? $lof_max_learn : $sample_count;
// in case we have collected enough samples for bytes quantification
if ($sample_count >= $lof_min_learn)
{
// randomize bytes samples
$path['bytes'] = array_rand_multi($path['bytes'], $sample_count);
}
else // unset bytes-quantification of webapp
{
carriage_return(2, "[*] [Quantification] Not enough samples available to do attack quantification for '$key'", $line_count, $input_file_basename);
// skip attack quantification if 'bytes-sent' dataset ist not large enough
$path['bytes'] = null;
}
}
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# final calculation for variance/mean of delay
if ($tamper_test)
{
$avg_delay = round($avg_delay, 2);
$var_delay = round(($index_delay > 1) ? $var_delay / ($index_delay-1) : $var_delay, 2); // avoid division by zero if logfile contains a single line
carriage_return(2, "[*] [Tamper test] Mean of inter-request time delay is $avg_delay\n"
. "[*] [Tamper test] Variance of inter-request time delay is $var_delay\n", $line_count, $input_file_basename);
// tmp variable needs to be non-set later
unset($last_date);
}
# final calculation for variance/mean of request
if (in_array('chars', $detect_mode))
{
$avg_subst = round($avg_subst, 2);
$var_subst = round(($index_subst > 1) ? $var_subst / ($index_subst-1) : $var_subst, 2); // avoid division by zero if logfile contains a single line
carriage_return(2, "[*] [Chars detect] Mean of requests is $avg_subst\n"
. "[*] [Chars detect] Variance of requests is $var_subst\n", $line_count, $input_file_basename);
if ($var_subst > $var_citical_val)
carriage_return(1, "[#] High variance - You should use to another detect mode than 'chars'!\n", $line_count, $input_file_basename);
}
# final calculation for variance/mean of request
if (in_array('length', $detect_mode))
{
$avg_request = round($avg_request, 2);
$var_request = round(($index_request > 1) ? $var_request / ($index_request-1) : $var_request, 2); // avoid division by zero if logfile contains a single line
carriage_return(2, "[*] [Length detect] Mean of requests is $avg_request\n"
. "[*] [Length detect] Variance of requests is $var_request\n", $line_count, $input_file_basename);
}
}
else
# loop fast over input file and count lines
while (fgets($input_stream))
$line_count++;
### echo "\n======================= <DEBUG: \$dataset> =======================\n";
### print_r($dataset);
### echo "======================= </DEBUG: \$dataset> ======================\n";
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// reset position indicator to zero
fseek($input_stream, 0);
// emtpy file status cache
clearstatcache();
// check if logfile has been modified
if (filemtime($input_file) != $last_modified)
carriage_return(1, "[#] Logfile '$input_file_basename' changed while reading\n", $line_count, $input_file_basename);
// ------------------------------------------------------------------ //
# train mcshmm data for anomaly detection with hidden markov models
if (in_array('mcshmm', $detect_mode))
$list_of_ensembles = training_mcshmm($dataset, $add_vector, $hmm_min_learn, $hmm_max_iter, $hmm_tolerance, $vector_count, $detect_mode, $hmm_num_models);
// ------------------------------------------------------------------ //
# try to open output file for writing
if (($output_stream = fopen($output_file, 'w')) == false)
{
print_message(0, "[!] Cannot write to output file '$output_file'\n");
usage_die();
}
// -------------------- MAIN PROGRAM STARTS HERE -------------------- //
# insert header data into output file
if ($do_summarize == false)
{
log_header($output_type, $output_stream, $regex_fields, $client_ident, $dns_lookup,
$geoip_lookup, $dnsbl_lookup, $quantify_type, $add_tags, $do_summarize, $input_file);
log_sub_header($output_type, $output_stream, $regex_fields, null, $client_ident, $dns_lookup, $geoip_lookup,
$dnsbl_lookup, $detect_mode, null, null, $quantify_type, $add_tags, $do_summarize, '0');
}
# catch SIGINT (CTRL+C) to do a clean exit (e.g. log footer)
declare(ticks = 1); pcntl_signal(SIGINT, "clean_exit");
# in non-summarization mode, results are directly written to disk
if ($do_summarize == false)
carriage_return(1, "[#] Press Ctrl-C to view partial results\n", $line_count, $input_file_basename);
// ------------------------------------------------------------------ //
# breakpoint: main programm starts here
function main_processing() {}
# main loop over input logfile
while ($line = fgets($input_stream))
{
// increment line index
$line_index++;
// remove junk like MS-wordwraps
$line = trim($line);
// ignore empty lines
if (empty($line)) continue;
// convert logline to HTTP object
$data = logline_to_httpdata($line, $regex_string, $regex_fields, $num_fields);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# check if line is not crippled, else print error message
if ($data == null)
print_badline($line, $line_index, $line_count, $input_type, $input_file_basename);
else
{
# extract request (+additional attack vectors) and path from HTTP-data
$vector = httpdata_to_vector($data, $add_vector, $use_phpids_converter, $phpids_path, $phpids_init,
$detect_mode, $only_check_webapps, $web_app_extensions, $input_file, $line_index);
// get request used for detection
$request = $vector[0];
// get path of the web application
$path = $vector[1];
# convert date to unix timestamp format
if (array_key_exists('Date', $data))
$date = $data['Date'] = date("r", apachedate_to_timestamp($data['Date']));
// aggregate dates for 'traffic over time' statistics
# if ($do_summarize)
# {
# $day = date("Y/m/d", strtotime($date));
# $dates['traffic'][$day] ? $dates['traffic'][$day]++ : $dates['traffic'][$day] = 1;