├── .gitignore ├── .gitmodules ├── README.md ├── doc └── HACKING ├── install.txt ├── requirements.txt └── src ├── __init__.py ├── analysis ├── __init__.py ├── analyse_trainer.py ├── exp_config │ └── linear_simple.xml ├── experimentor.py ├── l2b_experiment.py ├── mRMR.py ├── mrmr ├── mrmr_osx_maci_leopard └── test_module.py ├── data └── filters │ └── regex_filters.xml ├── features ├── .gitignore ├── LICENSE ├── README.md └── src │ ├── __init__.py │ ├── feature_HTTP_response_code_rate.py │ ├── feature_average_request_interval.py │ ├── feature_cycling_user_agent.py │ ├── feature_html_to_image_ratio.py │ ├── feature_payload_size_average.py │ ├── feature_percentage_consecutive_requests.py │ ├── feature_request_depth.py │ ├── feature_request_depth_std.py │ ├── feature_session_length.py │ ├── feature_variance_request_interval.py │ └── learn2ban_feature.py ├── initialise_db.py ├── ip_sieve.py ├── ip_sieve_shlex.py ├── profiler └── profile_trainer.py ├── test ├── __init__.py ├── speed_test │ ├── l2b_profiler.py │ ├── l2b_profiler.py.orig │ └── numpy_vs_python_double_array.py ├── svm_test.t ├── test_analyser.py ├── test_ats_record_digest.py ├── test_features.py └── test_trainer.py ├── tools ├── __init__.py ├── apache_log_muncher.py ├── learn2bantools.py └── training_set.py └── train2ban.py /.gitignore: -------------------------------------------------------------------------------- 1 | *.py[co] 2 | 3 | # Packages 4 | *.egg 5 | *.egg-info 6 | dist 7 | build 8 | eggs 9 | parts 10 | bin 11 | var 12 | sdist 13 | develop-eggs 14 | .installed.cfg 15 | 16 | # Installer logs 17 | pip-log.txt 18 | 19 | # Unit test / coverage reports 20 | .coverage 21 | .tox 22 | 23 | #Translations 24 | *.mo 25 | 26 | #Mr Developer 27 | .mr.developer.cfg 28 | 29 | #config 30 | src/config/train2ban.cfg 31 | 32 | # backup 33 | *~ 34 | \#*\# 35 | .\#*\# 36 | .\#* 37 | 38 | src/*~ 39 | src/\#*\# 40 | src/.\#*\# 41 | src/.\#* 42 | src/*.orig 43 | src/*.prof 44 | 45 | src/features/*~ 46 | src/features/\#*\# 47 | src/features/.\#*\# 48 | src/features/.\#* 49 | src/features/*.orig 50 | 51 | src/test/*~ 52 | src/test/\#*\# 53 | src/test/.\#*\# 54 | src/test/.\#* 55 | src/test/*.orig 56 | src/test/l2b_pickle* 57 | 58 | src/tools/*~ 59 | src/tools/\#*\# 60 | src/tools/.\#*\# 61 | src/tools/.\#* 62 | src/tools/*.orig 63 | 64 | src/analysis/*~ 65 | src/analysis/\#*\# 66 | src/analysis/.\#*\# 67 | src/analysis/.\#*j 68 | src/analysis/*.orig 69 | src/analysis/results_dir/* 70 | src/output_dump/* 71 | 72 | #logs 73 | src/test/*log* 74 | src/data/training/* 75 | 76 | #profiling history 77 | src/test/*.prof 78 | src/test/speed_test/*.prof 79 | 80 | # OS generated files 81 | .DS_Store 82 | .DS_Store? 83 | ._* 84 | .Spotlight-V100 85 | .Trashes 86 | Icon? 87 | ehthumbs.db 88 | Thumbs.db 89 | 90 | #don't contain fail2ban 91 | fail2ban 92 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "src/fail2ban"] 2 | path = src/fail2ban 3 | url = github.com:/equalitie/fail2ban 4 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Learn2ban 2 | ========= 3 | Open source machine learning DDOS detection tool 4 | 5 | Copyright 2013 eQualit.ie 6 | 7 | Learn2ban is free software: you can redistribute it and/or modify 8 | it under the terms of the GNU Affero General Public License as 9 | published by the Free Software Foundation, either version 3 of the 10 | License, or (at your option) any later version. 11 | 12 | This program is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU Affero General Public License for more details. 16 | 17 | You should have received a copy of the GNU Affero General Public License 18 | along with this program. If not, see ``. 19 | 20 | Installation 21 | ============ 22 | 23 | The following libraries should be installed 24 | 25 | [sudo] apt-get install libmysqlclient-dev 26 | [sudo] apt-get install build-essential python-dev python-numpy python-setuptools python-scipy libatlas-dev 27 | [sudo] apt-get install python-matplotlib 28 | easy_install pip 29 | 30 | Install required packages 31 | 32 | pip install -r requirements.txt 33 | 34 | Initialize Learn2ban training database 35 | 36 | python src/initialise_db.py 37 | 38 | Testing: 39 | -------- 40 | Run python unit tests in the Learn2ban/src/test/ directory to ensure functionality. 41 | 42 | Configuration 43 | ============= 44 | 45 | Access to mysql server 46 | ---------------------- 47 | User needs to enter the access detail for a mysql server in config/train2ban.cfg. For example: 48 | 49 | db_user = root 50 | db_password = thisisapassword 51 | db_host = mydb.myserver.com 52 | db_name = learn2ban 53 | config_profile = myconfig 54 | 55 | Then user need to run initialise_db.py 56 | 57 | python initialise_db.py 58 | 59 | To create the database. User then is required to make a record in config table with profile name equal to config_profile (myconfig in this example) and enter the relevant directories in the table. 60 | 61 | Regex filters 62 | ------------- 63 | 64 | In order to annotate input logs, Learn2ban uses the fail2ban regex filtering system to mark IP addresses as malicious or legitimate. The regex rules to apply can be added to regex_filter table in learn2ban database 65 | 66 | Training data 67 | ------------- 68 | The data from which the Learn2ban SVM model will be constructed should be placed in the directory defined in the profile or entered in absolute path in experiment table if the profile asks for absolute path. 69 | 70 | Running Learn2ban Experiments 71 | ============================= 72 | 73 | Learn2ban is currently designed to run in an experimental mode to allow users to create multiple variations of models, based on their training data, and to easily analyze the efficacy and accuracy of these models. 74 | 75 | User needs to enter the log file names in logs table, assign the regexes which identifies the bots in the log in regex_assignment table. User then design an experiment in experiments table, and assign the log to it in experiment_logs. 76 | 77 | To run a configured learn2ban experiment, enable the experiment in experiments table and execute 78 | 79 | python src/analysis/experimentor.py 80 | 81 | Learn2ban model feature set 82 | =========================== 83 | In order to classify requesting IP addresses as legitimate or malicious the Learn2ban SVM model takes into account the following set of features derived from HTTP log data. 84 | 85 | These features are implemented at Learn2ban/src/features. 86 | 87 | * average_request_interval - this feature considers the behaviour of the requester in terms of the average number of request made within a given interval. This is essentially the frequency with which a requester attempts to access a given host. It takes into account the requests as whole not merely in terms of a single page. 88 | * cycling_user_agent - a common attack for DDOS Botnets is to change user agent repeatedly during an attack. This strategy can be quite effective against even the most generalised regex rules. If the IP never repeats its user agent then rules put in place to block requesters using obscure user agents will still be subverted. In the context of a real human user, or even a spider bot, user agent rotation is highly aberrant. 89 | * html_to_image_ratio - This feature considers the type of content that is being requested. It considers if a requester is only retrieving HTML content but no ancillary data such as images, css or javascript files. 90 | * variance_request_interval - While many DDOS attacks use a very simplistic brute force approach, some have incorporated a slightly more sophisticated approach by making burst requests in order to avoid being blocked by simple rules which allow only a certain number of requests within a time frame. 91 | * payload_size_average - this feature looks at the size of the content that a requester is retrieving. 92 | * HTTP_response_code_rate - Considers http response rate, primarily looking for error codes that may signal a cache busting attack. 93 | * request_depth - Normal site users with commonly browse beyond the home page of a given site. Human users interaction with a website will resemble browsing more than that of a botnet. 94 | * request_depth_std - As an adjunct to request depth, this feature considers the standard deviation of a bot's request. 95 | * session_length - This feature also elucidates general behaviour considering the requester's interaction with a given sight in terms of session time. 96 | * percentage_consecutive_requests - To further elucidate the requester's interaction with a given site we additionally consider how many of the requests made were consecutive as another window onto frequency. 97 | 98 | Adding new features 99 | =================== 100 | 101 | It is possible to easily extend Learn2ban's feature set by inheriting from the prototype feature at Lear2ban/src/features/learn2ban_feature.py. 102 | 103 | The new feature needs to register the log data index of the feature under consideration and implement the compute() method which will return the feature value. 104 | 105 | This project forms part of the [Deflect](https://deflect.ca) project. 106 | -------------------------------------------------------------------------------- /doc/HACKING: -------------------------------------------------------------------------------- 1 | Feature classes should be stored in src/features folder. Inherit them from Learn2banFeature class. 2 | 3 | For now, features ip related, IPSieve class should be use to extract all records related to separate ips. The input to te Learn2BanFeature is the result of IPSieve for individual ips. Sieve -------------------------------------------------------------------------------- /install.txt: -------------------------------------------------------------------------------- 1 | sudo apt-get install mysql 2 | sudo apt-get install libmysqlclient-dev 3 | sudo apt-get install build-essential python-dev python-numpy python-setuptools python-scipy libatlas-dev 4 | sudo apt-get install python-matplotlib 5 | easy_install pip 6 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | mysql-python==1.2.4 2 | scikit-learn 3 | fail2ban 4 | numpy 5 | 6 | -------------------------------------------------------------------------------- /src/__init__.py: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /src/analysis/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/equalitie/learn2ban/d45420c9d2eea2c81972c778a96a2ca42b318b6f/src/analysis/__init__.py -------------------------------------------------------------------------------- /src/analysis/analyse_trainer.py: -------------------------------------------------------------------------------- 1 | """ 2 | Analyse efficacy of learn2ban SVM system 3 | 4 | AUTHORS: 5 | 6 | - Bill (bill@equalit.ie) 2013/02/09 7 | """ 8 | from multiprocessing import Process 9 | from os.path import dirname, abspath 10 | from os import getcwd, chdir 11 | import sys 12 | 13 | try: 14 | src_dir = dirname(dirname(abspath(__file__))) 15 | except NameError: 16 | #the best we can do to hope that we are in the test dir 17 | src_dir = dirname(getcwd()) 18 | 19 | sys.path.append(src_dir) 20 | 21 | #our test svm to be trained 22 | from sklearn import svm 23 | import numpy as np 24 | 25 | #train to ban 26 | from train2ban import Train2Ban 27 | 28 | from tools.learn2bantools import Learn2BanTools 29 | 30 | import logging 31 | import datetime 32 | 33 | import cProfile 34 | 35 | from l2b_experiment import L2BExperiment 36 | 37 | 38 | class Analyser(): 39 | # This approach is obsulite as now the L2BExperiments themselves 40 | # run the experiments and that can be marked in db 41 | 42 | # #user will send one of these values to make tweak the analyser behavoir 43 | # #train begin will take the begining portion of the data for training 44 | # #train random will choose random rows of the sample set 45 | # TRAIN_BEGIN = 0 46 | # TRAIN_RANDOM = 1 47 | # def __init__(self, where_to_train = TRAIN_BEGIN, training_portion = 1): 48 | # """ 49 | # Intitiate the behavoir of the analyzer. These parametrs should be 50 | # also tweakable from database 51 | 52 | # INPUT: 53 | 54 | # - where_to_train: which part of the sample should be used for 55 | # training 56 | # - training_protion: Between 0 - 1, tells the analyser how much 57 | # of the sample is for training and how much 58 | # for testing. 59 | # """ 60 | # self._where_to_train = where_to_train 61 | # self._training_portion = training_portion 62 | 63 | def profile(self, exp, filename): 64 | cProfile.runctx('self.run_experiments(exp)', {'exp': exp}, locals(), filename) 65 | 66 | def run_experiments(self, exp): 67 | l2btools = Learn2BanTools() 68 | l2btools.load_train2ban_config() 69 | utc_datetime = datetime.datetime.utcnow() 70 | utc_datetime.strftime("%Y-%m-%d-%H%MZ") 71 | analyse_log_file = l2btools.analyser_results_dir + 'analyse_' + str(utc_datetime) 72 | 73 | logging.basicConfig(filename=analyse_log_file, level=logging.INFO) 74 | logging.info('Begin learn 2 ban analysis for Experiment Id: ' + str(exp['id'])) 75 | 76 | l2btools.set_training_log(exp['training_log']) 77 | self.analyse_trainer = Train2Ban(l2btools.construct_classifier(exp['kernel_type'])) 78 | self.analyse_trainer.add_malicious_history_log_files(l2btools.load_training_logs()) 79 | training_set = l2btools.gather_all_features() 80 | self.analyse_trainer.add_to_sample(training_set) 81 | self.analyse_trainer.normalise(exp['norm_mode']) 82 | #This step will also update teh regex filter file to point to the experiment file 83 | self.analyse_trainer.add_bad_regexes(l2btools.load_bad_filters_from_db(exp['regex_filter_id'])) 84 | #Train for training data 85 | self.analyse_trainer.mark_and_train() 86 | #Predict for training data using constructed model 87 | self.analyse_trainer.predict(training_set) 88 | logging.info('Training errors: ' + str(self.analyse_trainer.model_errors())) 89 | 90 | ip_index, data, target = self.analyse_trainer.get_training_model() 91 | bad_ips = [ip_index[cur_target] for cur_target in range(0, len(target)) if target[cur_target]] 92 | #logging.info('Training Bad IPs identified: '+ bad_ips) 93 | #Load testing data 94 | l2btools.set_testing_log(exp['testing_log']) 95 | #Clear IP_Sieve 96 | l2btools.clear_data() 97 | #Predict for testing data using model constructed from training data 98 | self.analyse_trainer.predict(l2btools.gather_all_features()) 99 | 100 | logging.info('Testing errors: ' + str(self.analyse_trainer.model_errors())) 101 | experiment_result = {} 102 | experiment_result['experiment_id'] = exp['id'] 103 | experiment_result['result_file'] = analyse_log_file 104 | l2btools.save_experiment(experiment_result) 105 | 106 | #here we would like to interfere and have some randomization. 107 | #Maybe as a pramater, we tell analyser what portion of the 108 | #sample should be used for training and what portion for 109 | #verification. Also, another parameter would be if that portion 110 | #should be taken from the begining of the sample or randomly. 111 | 112 | def run_l2b_experiments(self, exp, train_portion): 113 | l2btools = Learn2BanTools() 114 | l2btools.load_train2ban_config() 115 | utc_datetime = datetime.datetime.utcnow() 116 | utc_datetime.strftime("%Y-%m-%d-%H%MZ") 117 | analyse_log_file = l2btools.analyser_results_dir + 'analyse_' + str(utc_datetime) 118 | 119 | logging.basicConfig(filename=analyse_log_file, level=logging.INFO) 120 | logging.info('Begin learn 2 ban analysis for Experiment Id: ' + str(exp['id'])) 121 | 122 | l2btools.set_training_log(exp['training_log']) 123 | 124 | experiment_classifier = l2btools.construct_classifier(exp['kernel_type']) 125 | self.analyse_trainer = Train2Ban(experiment_classifier) 126 | self.analyse_trainer.add_malicious_history_log_files(l2btools.load_training_logs()) 127 | training_set = l2btools.gather_all_features() 128 | self.analyse_trainer.add_to_sample(training_set) 129 | self.analyse_trainer.normalise(exp['norm_mode']) 130 | #This step will also update teh regex filter file to point to the experiment file 131 | self.analyse_trainer.add_bad_regexes(l2btools.load_bad_filters_from_db(exp['regex_filter_id'])) 132 | #marking training data 133 | self.analyse_trainer.mark_bad_target() 134 | 135 | marked_training_set = self.analyse_trainer.get_training_set() 136 | train_selector, test_selector = l2btools.random_slicer(len(marked_training_set), train_portion) 137 | train_set = marked_training_set.get_training_subset(case_selector=train_selector) 138 | test_set = marked_training_set.get_training_subset(case_selector=test_selector) 139 | 140 | #initializes L2BEXperiment 141 | cur_experiment = L2BExperiment(train_set, test_set, experiment_classifier) 142 | #cur_experiment.train() 143 | 144 | #Predict for training data using constructed model 145 | #logging.info('Crossvalidation score: ' + str(cur_experiment.cross_validate_test())) 146 | 147 | #graph the result 148 | dim_reducers = ['PCA', 'Isomap'] 149 | kernels = ['linear', 'rbf', 'poly'] 150 | all_possible_choices = np.transpose(np.array([np.tile(dim_reducers, len(kernels)), np.repeat(kernels, len(dim_reducers))])) 151 | 152 | for cur_choice in all_possible_choices: 153 | cur_experiment.plot(dim_reduction_strategy=cur_choice[0], kernel=cur_choice[1]) 154 | 155 | if __name__ == "__main__": 156 | l2btools = Learn2BanTools() 157 | l2btools.load_train2ban_config() 158 | experiment_set = l2btools.retrieve_experiments() 159 | for exp in experiment_set: 160 | p = Process(target=Analyser().run_experiments(exp)) 161 | p.start() 162 | 163 | 164 | #TODO: add support for multiple experiment files 165 | #TODO: output results in formatted log 166 | #TODO: plot graphs of results 167 | -------------------------------------------------------------------------------- /src/analysis/exp_config/linear_simple.xml: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/equalitie/learn2ban/d45420c9d2eea2c81972c778a96a2ca42b318b6f/src/analysis/exp_config/linear_simple.xml -------------------------------------------------------------------------------- /src/analysis/experimentor.py: -------------------------------------------------------------------------------- 1 | """ 2 | Analyse efficacy of learn2ban SVM system 3 | 4 | AUTHORS: 5 | 6 | - Bill (bill@equalit.ie) 2013/02/09 7 | - Vmon: July 2013: Change log status. Trying to return back to OOP model 8 | after learn2bantool reconstruction disaster 9 | - Vmon: Nov 2013: store the experiment model along with the experminet 10 | results 11 | """ 12 | from multiprocessing import Process 13 | from os.path import dirname, abspath 14 | import os 15 | import sys 16 | 17 | try: 18 | src_dir = dirname(dirname(abspath(__file__))) 19 | except NameError: 20 | #the best we can do to hope that we are in the test dir 21 | src_dir = dirname(getcwd()) 22 | 23 | sys.path.append(src_dir) 24 | 25 | from sklearn import svm 26 | import numpy as np 27 | import logging 28 | import datetime 29 | 30 | #learn2ban classes: 31 | from ip_sieve import IPSieve 32 | 33 | #feature classes 34 | from features.src.learn2ban_feature import Learn2BanFeature 35 | 36 | #train to ban and other tools 37 | from train2ban import Train2Ban 38 | from tools.training_set import TrainingSet 39 | 40 | from tools.learn2bantools import Learn2BanTools 41 | 42 | from l2b_experiment import L2BExperiment 43 | 44 | nb_training = 10 45 | training_portions = [x / float(nb_training) for x in range(1, nb_training)] 46 | 47 | class Experimentor(): 48 | """ 49 | There is need for two type of Experiment objests one that correspond 50 | to each experiment record in experiment table and one that correspond 51 | to each result record in experiment_result. 52 | 53 | That is becaues from one experiment you can run many other experiments 54 | with little change in paramters and we don't want to store all these 55 | in DB as the design (train/test protion for example). 56 | 57 | Hence InseminatorExperiment read the experiment from the db (Expriment type 1) 58 | and Generator the L2BExperiment (Experiment type 2) 59 | """ 60 | # #user will send one of these values to make tweak the analyser behavoir 61 | # #train begin will take the begining portion of the data for training 62 | # #train random will choose random rows of the sample set 63 | # TRAIN_BEGIN = 0 64 | # TRAIN_RANDOM = 1 65 | # def __init__(self, where_to_train = TRAIN_BEGIN, training_portion = 1): 66 | # """ 67 | # Intitiate the behavoir of the analyzer. These parametrs should be 68 | # also tweakable from database 69 | 70 | # INPUT: 71 | 72 | # - where_to_train: which part of the sample should be used for 73 | # training 74 | # - training_protion: Between 0 - 1, tells the analyser how much 75 | # of the sample is for training and how much 76 | # for testing. 77 | # """ 78 | # self._where_to_train = where_to_train 79 | # self._training_portion = training_portion 80 | def __init__(self, exp, l2btools): 81 | """ 82 | store the exp config in self's attribute. 83 | """ 84 | self.expr_dict = exp 85 | self.id = self.expr_dict['id'] 86 | self.l2btools = l2btools 87 | 88 | self.ip_sieve = IPSieve() 89 | self.ip_feature_db = {} 90 | 91 | #Create classifier, currently only SVM supported 92 | #but trainer is agnostic of classifier used provided it supports fit and predict 93 | self.experiment_classifier = self.l2btools.construct_svm_classifier(self.expr_dict['kernel_type']) 94 | #Create classifier 95 | self.trainer = Train2Ban(self.experiment_classifier) 96 | #Setup base data set 97 | #the base filename we are going to associate to the result of this experiment 98 | utc_datetime = datetime.datetime.utcnow() 99 | utc_datetime.strftime("%Y-%m-%d-%H%MZ") 100 | self.base_analyse_log_file = self.l2btools.analyser_results_dir + 'base_analyse_' + str(utc_datetime) 101 | #this make more sense to happens in the constructor however, 102 | self._process_logs() 103 | self._mark_bots() 104 | 105 | def param_stochastifier(self): 106 | """ 107 | Here we return a randomised set of parameters for the experiments. 108 | At present we choose between for normalisation(sparse,individual), dimension reduction(PCA,ISOMap, MD5) and training portion(scale from 0-1) 109 | """ 110 | param_set = [] 111 | return param_set 112 | 113 | def _process_logs(self): 114 | """ 115 | get the log name from db and gathers all features 116 | 117 | INPUT: 118 | log_files: the logs that we went through it. 119 | """ 120 | #this is not a oop way of retrieving the logs but I think we are 121 | #avoiding db access in other classes beside l2btools 122 | cur_experiment_logs = self.l2btools.retrieve_experiment_logs(self.id) 123 | 124 | #if there is no log associated to this experiment then there is nothing 125 | #to do 126 | if len(cur_experiment_logs) == 0: 127 | logging.info("Giving up on experiment %i with no training log"%self.expr_dict['id']) 128 | return 129 | 130 | #log id is needed to be send to the trainer so the the trainer 131 | #knows which regex is detecting the bots for which log 132 | self.trainer.add_malicious_history_log_files([(cur_log_info['log_id'], cur_log_info['file_name']) for cur_log_info in cur_experiment_logs]) 133 | 134 | #extracitng the filenames 135 | #Get IP Features 136 | log_filenames = tuple(cur_log['file_name'] for cur_log in cur_experiment_logs) 137 | #At this stage it is only a peliminary list we might lose features 138 | #due to 0 variance 139 | self._active_feature_list = [] 140 | #do a dry run on all features just to gather the indeces of all available 141 | #features 142 | for CurrentFeatureType in Learn2BanFeature.__subclasses__(): 143 | cur_feature_tester = CurrentFeatureType(self.ip_sieve, self.ip_feature_db) 144 | self._active_feature_list.append(cur_feature_tester._FEATURE_INDEX) 145 | 146 | for cur_log_file in log_filenames: #in theory it might be more memory efficient 147 | #to crunch the logs one by one but python is quite disappointing in memory 148 | #management 149 | try: 150 | self.ip_sieve.add_log_file(cur_log_file) 151 | self.ip_sieve.parse_log() 152 | except IOError: 153 | print "Unable to read ", cur_log_file, "skipping..." 154 | 155 | for CurrentFeatureType in Learn2BanFeature.__subclasses__(): 156 | cur_feature_tester = CurrentFeatureType(self.ip_sieve, self.ip_feature_db) 157 | logging.info("Computing feature %i..."%cur_feature_tester._FEATURE_INDEX) 158 | cur_feature_tester.compute() 159 | 160 | # we have memory problem here :( 161 | # import objgraph 162 | # objgraph.show_refs([self.ip_sieve._ordered_records], filename='ips-graph.png') 163 | 164 | del self.ip_sieve._ordered_records 165 | del self.ip_sieve 166 | 167 | #fuck python with not letting the memory released 168 | # import gc 169 | # gc.collect() 170 | # print gc.garbage() 171 | 172 | self.trainer.add_to_sample(self.ip_feature_db) 173 | 174 | #we store the non-normailized vectors in a json file 175 | jsonized_ip_feature_db = {} 176 | for k,v in self.ip_feature_db.items(): 177 | jsonized_ip_feature_db[str(k)] = v 178 | import json 179 | with open(self.base_analyse_log_file+".prenormal_ip_feature_db.json", "w") as ip_feature_file: 180 | json.dump(jsonized_ip_feature_db, ip_feature_file) 181 | 182 | del self.ip_feature_db 183 | del jsonized_ip_feature_db 184 | 185 | #Normalise training set, normalisation should happen after all 186 | #sample is gathered 187 | self.trainer.normalise(self.expr_dict['norm_mode']) 188 | 189 | def _mark_bots(self): 190 | """ 191 | Read the regexes correspond to this experience log and apply them to 192 | the trainer. this should be called after the logs has been processed. 193 | """ 194 | #Add Faill2Ban filters 195 | filters_for_experiment = self.l2btools.load_bad_filters_from_db(self.id) 196 | for cur_filter in filters_for_experiment: 197 | self.trainer.add_bad_regexes(cur_filter['log_id'], (cur_filter['regex'],)) 198 | #Use Fail2ban filters to identify and mark DDOS IPs in data set 199 | malicious_ips = self.trainer.mark_bad_target() 200 | 201 | with open(self.base_analyse_log_file+".malicious_ip_list", "w") as malicious_ip_file: 202 | malicious_ip_file.write(str(malicious_ips).strip('[]')) 203 | 204 | def _pca_importance_ananlysis(self, pca_model): 205 | """ 206 | Retrieve the pca transformation and use the following formula to 207 | determine the importance of each feature: 208 | 209 | length(variance*|c_1j|/sqrt(sum(c1i_2^2))) 210 | 211 | INPUT: 212 | pca_model: (the transfarmation matrix in np array, importance of each 213 | component) the output of L2BExperiment.PCA_transform_detail 214 | OUTPUT: an array containing the importance ratio of features based 215 | on above forumla 216 | """ 217 | pca_transform_matrix = pca_model[0] 218 | pca_var_ratio = pca_model[1] 219 | 220 | #row_sums = pca_transform_matrix.sum(axis=1) 221 | #apparently pca transfomation is normalised along both access 222 | #anyway for some reason reshape(-1) doesn't work as transpose 223 | scaled_coeffs = pca_var_ratio.reshape(len(pca_var_ratio),1) * pca_transform_matrix 224 | 225 | return np.apply_along_axis(np.linalg.norm, 0 , scaled_coeffs) 226 | 227 | def run_l2b_experiment(self, train_portion, stochastic_params): 228 | """ 229 | Run individual instance of given experiment 230 | """ 231 | utc_datetime = datetime.datetime.utcnow() 232 | utc_datetime.strftime("%Y-%m-%d-%H%MZ") 233 | analyse_log_file = self.l2btools.analyser_results_dir + 'analyse_' + str(utc_datetime) 234 | logging.basicConfig(filename=analyse_log_file, level=logging.INFO) 235 | logging.info('Begin learn 2 ban analysis for Experiment Id: ' + str(self.expr_dict['id'])) 236 | 237 | #Divide up data set into training and testing portions based on initial given value 238 | marked_training_set = self.trainer.get_training_set() 239 | 240 | #if no body is a bot then this is not a fruitful experiment 241 | if marked_training_set.no_culprit(): 242 | logging.info("No bot detected, Giving up on experiment " + str(self.expr_dict['id'])) 243 | return 244 | 245 | #here we need to check if we lost features or not due to normalisation 246 | #sparse normaliastion doesn't cut off feature 247 | if self.expr_dict['norm_mode']=='individual': 248 | dimension_reducer = [cur_feature_std != 0 for cur_feature_std in marked_training_set._normalisation_data[marked_training_set.SAMPLE_STD]] 249 | self._active_feature_list = [self._active_feature_list[red_plc[0]] for red_plc in enumerate(dimension_reducer) if red_plc[1]] 250 | 251 | active_features = str(self._active_feature_list).strip('[]') 252 | #TODO: Iterate with different slicing to get reliable result 253 | train_selector, test_selector = self.l2btools.random_slicer(len(marked_training_set), train_portion) 254 | train_set = marked_training_set.get_training_subset(case_selector=train_selector) 255 | test_set = marked_training_set.get_training_subset(case_selector=test_selector) 256 | #initializes L2BEXperiment 257 | cur_experiment = L2BExperiment(train_set, test_set, self.trainer) 258 | 259 | #TODO:mRMR and PCA are independent of slicing and should 260 | # computed over the whole dataset 261 | # Get the mRMR 262 | mrmr = cur_experiment.get_mrmr() 263 | logging.info('mRMR score: ' + str(mrmr)) 264 | 265 | # Get the PCA ratios as a string 266 | pca_ratios = str(self._pca_importance_ananlysis(cur_experiment.pca_transform_detail())).strip('[]') 267 | logging.info('PCA ratios: ' + pca_ratios) 268 | 269 | #Train model against training set 270 | cur_experiment.train() 271 | 272 | #Predict for training data using constructed model 273 | score = cur_experiment.cross_validate_test() 274 | logging.info('Crossvalidation score: ' + str(score)) 275 | 276 | self.store_results(analyse_log_file, train_portion, score, active_features, pca_ratios, mrmr) 277 | 278 | def store_results(self, analyse_log_file, train_portion, score, active_features, pca_ratios, mrmr): 279 | # Add the result to the database 280 | experiment_result = {} 281 | experiment_result['experiment_id'] = self.expr_dict['id'] 282 | experiment_result['result_file'] = analyse_log_file 283 | experiment_result['proportion'] = train_portion 284 | experiment_result['score'] = score 285 | experiment_result['active_features'] = active_features 286 | experiment_result['pca_ratios'] = pca_ratios 287 | experiment_result['mrmr_score'] = str(mrmr).strip('[]') 288 | 289 | #while the pickle model is always created the result file only 290 | #get stored in the case there are an error 291 | self.l2btools.save_experiment_result(experiment_result) 292 | 293 | self.trainer.save_model(analyse_log_file+".l2b_pickle_model") 294 | #also try to store in recontsructable libsvm format if the function 295 | #if the save_svm_model function is implmented 296 | try: 297 | self.trainer.save_model(analyse_log_file+".normal_svm_model", "normal_svm") 298 | except NotImplementedError: 299 | print "save_svm_model is not implmeneted in your scikit-learn, skipping storing the model in libsvm format" 300 | 301 | print "Experiment", self.expr_dict['id'], ": train portion = ", train_portion, ", score = ", score, ", mRMR = ", mrmr, ", PCA ratios = ", pca_ratios 302 | print experiment_result 303 | 304 | # Graph the result 305 | # print cur_experiment.dim_reduction_PCA() 306 | # dim_reducers = ['PCA', 'Isomap'] 307 | # kernels = ['linear', 'rbf', 'poly'] 308 | # all_possible_choices = np.transpose(np.array([np.tile(dim_reducers, len(kernels)), np.repeat(kernels, len(dim_reducers))])) 309 | # for cur_choice in all_possible_choices: 310 | # cur_experiment.plot(dim_reduction_strategy=cur_choice[0], kernel=cur_choice[1]) 311 | 312 | if __name__ == "__main__": 313 | l2btools = Learn2BanTools() 314 | l2btools.load_train2ban_config() 315 | 316 | desired_portions = [portion/100.0 for portion in range(10,100,10)] 317 | # Delete all previous experiments (will have to be commented out when performing series of experiments) 318 | #l2btools.delete_all_experiments_results() 319 | # Retrieve all the experiments stored in the db 320 | experiment_set = l2btools.retrieve_experiments() 321 | 322 | for exp in experiment_set: 323 | cur_expr = Experimentor(exp, l2btools) 324 | 325 | for cur_portion in desired_portions: 326 | stochastic_params = cur_expr.param_stochastifier() 327 | 328 | #single process 329 | #cur_expr.run_l2b_experiment(0.8, stochastic_params) 330 | 331 | #multi-processing: disabled temp cause hard to debug 332 | p = Process(target=cur_expr.run_l2b_experiment, args=(cur_portion, stochastic_params)) 333 | p.start() 334 | print "process started with training prottion: ", cur_portion 335 | p.join() 336 | 337 | #objgraph.show_refs([cur_expr], filename='sample-graph.png') #I guess this is a fall back if process can not start? 338 | #if pid == 0: 339 | # print 'begin' 340 | # Experimentor().run_l2b_experiment(exp, 0.8, l2btools, stochastic_params) 341 | 342 | # Display all the results 343 | print "all processes started" 344 | # experiment_results = l2btools.retrieve_experiments_results() 345 | # for res in experiment_results: 346 | # print res 347 | 348 | #os._exit(0) 349 | 350 | #TODO: add support for multiple experiment files 351 | #TODO: output results in formatted log 352 | #TODO: plot graphs of results 353 | -------------------------------------------------------------------------------- /src/analysis/l2b_experiment.py: -------------------------------------------------------------------------------- 1 | """ 2 | To represent an experiment run by the Analyser, tester, etc. 3 | 4 | AUTHORS: 5 | - Vmon (vmon@equalit.ie) Feb 2013: Initial version 6 | - Ben (benj.renard@gmail.com) June 2013: pca, mRMR 7 | - Vmon July 2013: Modified PCA analysis to actually rate importance of 8 | features. 9 | """ 10 | from sklearn import svm, decomposition, manifold 11 | import pylab as pl 12 | import numpy as np 13 | import sys 14 | import os 15 | 16 | from analysis.mRMR import mrmr 17 | 18 | 19 | class L2BExperiment(): 20 | """ 21 | Each L2BExperiment consists of a 22 | - Training Set and Testing Set, 23 | - It might have a known Test target or not in that case it (should 24 | be able to TODO) cross valdiate it self return an score. It can graph 25 | It 26 | - It can graph itself. 27 | - It (TODO) can load and store itself into the database. 28 | """ 29 | def __init__(self, training_set=None, testing_set=None, experiment_trainer=None): 30 | """ 31 | Simple initialization by setting the training set and the test 32 | set. Either can be null, the experiment can be only training or 33 | only testing. The classifier can be indicated during training or 34 | testing. 35 | """ 36 | self._training_set = training_set 37 | self._testing_set = testing_set 38 | self._experiment_trainer = experiment_trainer 39 | 40 | #set mRMR executable 41 | cur_dir = os.path.dirname(__file__) 42 | if sys.platform == 'darwin': 43 | aux = 'mrmr_osx_maci_leopard' 44 | else: 45 | aux = 'mrmr' 46 | self.mrmr_ex = cur_dir + '/' + aux 47 | 48 | def train(self, experiment_trainer=None): 49 | """ 50 | It make a train2ban object in the spot, set the training set and 51 | train. 52 | 53 | INPUT: 54 | experiment_classifier: Can be None if it set before otherwise 55 | raise an exception 56 | 57 | """ 58 | if (experiment_trainer): 59 | self._experiment_trainer = experiment_trainer 60 | 61 | self._experiment_trainer.set_training_set(self._training_set) 62 | 63 | self._experiment_trainer.train() 64 | 65 | def predict(self, experiment_trainer=None): 66 | """ 67 | Run the predict and update the _predicted_target 68 | 69 | INPUT: 70 | experiment_classifier: Can be None if it set before otherwise 71 | raise an exception 72 | """ 73 | if (experiment_trainer): 74 | self._experiment_trainer = experiment_trainer 75 | 76 | self._predicted_target = self._experiment_trainer.predict(testing_set._ip_feature_array) 77 | 78 | def cross_validate_test(self, experiment_trainer=None): 79 | """ 80 | Use the classifier score function to cross-validate 81 | the result on the test set. user has to train the 82 | classifier in advance 83 | 84 | INPUT: 85 | experiment_classifier: Can be None if it set before otherwise 86 | raise an exception 87 | """ 88 | if (experiment_trainer): 89 | self._experiment_trainer = experiment_trainer 90 | 91 | if ((self._testing_set == None) or (self._testing_set._target == None)): 92 | raise ValueError, "A valid Testing set with known target is required" 93 | 94 | return self._experiment_trainer._ban_classifier.score(self._testing_set._ip_feature_array, self._testing_set._target) 95 | 96 | def cross_validate_score_train(self, experiment_trainer=None, no_of_repetition=1): 97 | """ 98 | Uses the native sklearn cross_validation class method to split only 99 | the traiing set and compute the prediction score 100 | 101 | INPUT: 102 | experiment_classifier: Can be None if it set before otherwise 103 | raise an exception 104 | 105 | no_of_repetition: no of type to repeat the validaion 106 | """ 107 | if (experiment_trainer): 108 | self._experiment_trainer = experiment_trainer 109 | 110 | from sklearn import cross_validation 111 | 112 | scores = cross_validation.cross_val_score(self._experiment_trainer._ban_classifier, self._training_set._ip_feature_array, self._training_set._target, cv=no_of_repetition) 113 | return (scores.mean(), scores.std()) 114 | 115 | def pca_transform_detail(self, nb_components=0): 116 | """ 117 | Compute the PCA transformation for the self._ip_feature_array with 118 | nb_components PCA components. 119 | 120 | This is used in determining the important features 121 | 122 | Suppose 123 | PCA1 = c_11*feature_1 + c12*feature_2 + ... + c1n*feature_n 124 | 125 | For now we only look at normalised coefficients 126 | 127 | |c_11|/sqrt(sum(c1i_2^2)) 128 | 129 | and we look at how much of the variance is explained in PCA1 130 | If PCA1 one is small one can go to PCA2 etc. 131 | to retrieve c_1i we compute pca_trans(e_i)[0] 132 | 133 | INPUT: 134 | nb_components: the number of PCA to be used to explain the model 135 | 0 means as many as number features. 136 | 137 | OUTPUT: 138 | (the transfarmation matrix in np array, importance of each component) 139 | """ 140 | no_of_features = self._training_set._ip_feature_array.shape[1] 141 | if (nb_components==0): 142 | nb_components = no_of_features 143 | 144 | whole_space = np.append(self._training_set._ip_feature_array, self._testing_set._ip_feature_array, axis=0) 145 | whole_target = np.append(self._training_set._target, self._testing_set._target, axis=0) 146 | 147 | dim_reducer = decomposition.PCA(n_components=nb_components) 148 | dim_reducer.fit(whole_space) 149 | 150 | #retrieving the coefficients by transforming identity matrix 151 | #each column of pca_coeffs is describing each pca components 152 | #in term of features, so it is (PCA_Transform)^(Trasposed) 153 | pca_coeffs = dim_reducer.transform(np.identity(no_of_features)) 154 | 155 | # Tests by Ben 156 | return (pca_coeffs, dim_reducer.explained_variance_ratio_) 157 | 158 | def plot(self, dim_reduction_strategy='PCA', kernel='linear'): 159 | """ 160 | Plot the result of the fiting 161 | """ 162 | whole_space = np.append(self._training_set._ip_feature_array, self._testing_set._ip_feature_array, axis=0) 163 | 164 | whole_target = np.append(self._training_set._target, self._testing_set._target, axis=0) 165 | if dim_reduction_strategy == 'PCA': 166 | # change randomizedPCA to PCA 167 | # dim_reducer = decomposition.RandomizedPCA(n_components=2) 168 | dim_reducer = decomposition.PCA(n_components=2) 169 | elif dim_reduction_strategy == 'Isomap': 170 | n_neighbors = 30 171 | dim_reducer = manifold.Isomap(n_neighbors, n_components=2) 172 | elif dim_reduction_strategy == 'MDS': 173 | dim_reducer = manifold.MDS(n_components=2, n_init=1, max_iter=100) 174 | 175 | dim_reducer.fit(whole_space) 176 | reduced_train_spc = dim_reducer.transform(self._training_set._ip_feature_array) 177 | reduced_test_spc = dim_reducer.transform(self._testing_set._ip_feature_array) 178 | 179 | reduced_whole_space = np.append(reduced_train_spc, reduced_test_spc, axis=0) 180 | 181 | clf = svm.SVC(kernel=str(kernel), gamma=10) 182 | clf.fit(reduced_train_spc, self._training_set._target) 183 | 184 | pl.figure(0) 185 | pl.clf() 186 | pl.scatter(reduced_whole_space[:, 0], reduced_whole_space[:, 1], c=whole_target, zorder=10, cmap=pl.cm.Paired) 187 | 188 | # Circle out the test data 189 | pl.scatter(reduced_test_spc[:, 0], reduced_test_spc[:, 1], 190 | s=80, facecolors='none', zorder=10) 191 | 192 | pl.axis('tight') 193 | x_min = reduced_whole_space[:, 0].min() 194 | x_max = reduced_whole_space[:, 0].max() 195 | y_min = reduced_whole_space[:, 1].min() 196 | y_max = reduced_whole_space[:, 1].max() 197 | 198 | XX, YY = np.mgrid[x_min:x_max:200j, y_min:y_max:200j] 199 | Z = clf.decision_function(np.c_[XX.ravel(), YY.ravel()]) 200 | 201 | # Put the result into a color plot 202 | Z = Z.reshape(XX.shape) 203 | pl.pcolormesh(XX, YY, Z > 0, cmap=pl.cm.Paired) 204 | pl.contour(XX, YY, Z, colors=['k', 'k', 'k'], 205 | linestyles=['--', '-', '--'], 206 | levels=[-.5, 0, .5]) 207 | 208 | norm_mode = (self._training_set._normalisation_data and "individual" or "sparse") 209 | pl.title("Norm: " + norm_mode + ", Kernel:" + kernel + ", Dimension reduced by " + dim_reduction_strategy) 210 | 211 | pl.show() 212 | 213 | def get_mrmr(self): 214 | """ 215 | Gets the mRMR associated with this experiment 216 | """ 217 | whole_space = np.append(self._training_set._ip_feature_array, self._testing_set._ip_feature_array, axis=0) 218 | fn = ['F%d' % n for n in range(len(whole_space[0]))] 219 | 220 | whole_target = np.append(self._training_set._target, self._testing_set._target, axis=0) 221 | 222 | #we need to map Good to 1 and Bad to -1 Good is 0 and Bad 1 223 | #x = Good y = 1 224 | #x = Bad y = -1 225 | #y =(Good - Bad)/ (1 -(-1)) *(x - Good) + 1 226 | new_slope = (1-(-1))/(self._training_set.GOOD_TARGET-self._training_set.BAD_TARGET) 227 | mRMR_target = [new_slope*(cur_class - self._training_set.GOOD_TARGET)+1 for cur_class in whole_target] 228 | 229 | mrmrout = mrmr(whole_space, fn, mRMR_target, mrmrexe=self.mrmr_ex) 230 | R = mrmrout['mRMR'] 231 | 232 | # print 'Order \t Fea \t Name \t Score' 233 | # for i in range(len(R['Fea'])): 234 | # print '%d \t %d \t %s \t %f\n' % (i, R['Fea'][i], fn[R['Fea'][i]], R['Score'][i]) 235 | 236 | return R['Score'] 237 | -------------------------------------------------------------------------------- /src/analysis/mRMR.py: -------------------------------------------------------------------------------- 1 | ''' 2 | This is a python wrapper around Peng's mRMR algorithm. 3 | 4 | mRMR is the min redundancy max relevance feature selection algorithm by 5 | Hanchuan Peng. See http://penglab.janelia.org/proj/mRMR for more details about 6 | the code and its author, as well as the sources and the license. 7 | 8 | Author: Brice Rebsamen 9 | Version: 0.1 10 | Released on: June 1st, 2011 11 | 12 | 13 | Copyright 2011 Brice Rebsamen 14 | 15 | This program is free software: you can redistribute it and/or modify 16 | it under the terms of the GNU General Public License as published by 17 | the Free Software Foundation, either version 3 of the License, or 18 | (at your option) any later version. 19 | 20 | This program is distributed in the hope that it will be useful, 21 | but WITHOUT ANY WARRANTY; without even the implied warranty of 22 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 23 | GNU General Public License for more details. 24 | 25 | You should have received a copy of the GNU General Public License 26 | along with this program. If not, see . 27 | ''' 28 | 29 | 30 | import numpy as np 31 | import os 32 | from subprocess import Popen, PIPE 33 | import tempfile 34 | 35 | 36 | def _savemrmrdatafile(data, featNames, classNames): 37 | ''' 38 | Save the data to a CSV file in the format required by mRMR. 39 | - first row is the name of the features. 40 | - first col is the class names. 41 | - data is organized, with a sample per row. 42 | Returns the filename (a temporary file with the .csv extension). 43 | ''' 44 | 45 | f = tempfile.NamedTemporaryFile(suffix='.csv', prefix='tmp_mrmr_', delete=False, mode='w') 46 | f.write(','.join(['class']+featNames)+os.linesep) 47 | data = np.asarray(data) 48 | for i in range(data.shape[0]): 49 | f.write(','.join([str(classNames[i])]+[str(d) for d in data[i, :]])+os.linesep) 50 | f.close() 51 | return f.name 52 | 53 | 54 | def mrmr(data, featNames, classNames, threshold=None, nFeats=None, selectionMethod='MID', mrmrexe='./mrmr'): 55 | ''' 56 | A wrapper around the mrmr executable. 57 | 58 | Arguments: 59 | data: a 2D array (size NxF) 60 | featNames: list of feature names (F elements) 61 | classNames: list of class names (N elements) 62 | 63 | Optional Arguments: 64 | threshold: data must be discrete or discretized. The default value (None) 65 | assumes that the data has already been discretized. Otherwise 66 | it has to be discretized as below u-t*s, above u+t*s or between: 67 | -1, +1 or 0, where u is the mean, s the standard deviation and 68 | t the threshold. This is done feature by feature. 69 | nFeats: the number of feature to select. If not given it defaults to all 70 | features. This will only sort the features. 71 | selectionMethod: either 'MID' or 'MIQ'. Default is 'MID' 72 | mrmrexe: the path to the mrmr executable. Defaults to './mrmr' 73 | 74 | Returns: 75 | A dictionnary with 2 elements: MaxRel and mRMR, which are the 2 results 76 | returned by mrmr (the 2 different feature selection criterions). 77 | Each is a dictionnary, with fields Fea and Score, holding the feature 78 | numbers and the scores respectively. 79 | 80 | Example: 81 | Generate some data: 200 samples, 2 classes, 7 features, the 2 first 82 | features are correlated with the class label, the 5 others are 83 | irrelevant. Feature names (fn) with a capital F are the relevant 84 | features. 85 | >>> N = 100 86 | >>> data = np.r_[ np.random.randn(N,2)+2, np.random.randn(N,2)-2 ] 87 | >>> data = np.c_[ data, np.random.randn(N*2,5) ] 88 | >>> c = [1]*N+[-1]*N 89 | >>> fn = ['F%d' % n for n in range(2)] + ['f%d' % n for n in range(5)] 90 | 91 | Pass to the mRMR program 92 | >>> mrmrout = mrmr(data, fn, c, threshold=0.5) 93 | 94 | Get the result: 95 | >>> R = mrmrout['mRMR'] 96 | >>> print 'Order \t Fea \t Name \t Score' 97 | >>> for i in range(len(R['Fea'])): 98 | ... print '%d \t %d \t %s \t %f\n' % \ 99 | ... (i, R['Fea'][i], fn[R['Fea'][i]], R['Score'][i]) 100 | ... 101 | 102 | Order Fea Name Score 103 | 0 1 F1 0.131000 104 | 1 0 F0 0.128000 105 | 2 4 f4 -0.008000 106 | 3 0 f0 -0.009000 107 | 4 3 f3 -0.010000 108 | 5 1 f1 -0.013000 109 | 6 2 f2 -0.015000 110 | ''' 111 | 112 | data = np.asarray(data) 113 | N, M = data.shape 114 | 115 | if nFeats is None: 116 | nFeats = M 117 | else: 118 | assert nFeats <= M 119 | 120 | mrmrexe = os.path.abspath(mrmrexe) 121 | 122 | assert os.path.exists(mrmrexe) and os.access(mrmrexe, os.X_OK) 123 | 124 | # Save data to a temporary file that can be understood by the mrmr binary 125 | fn = _savemrmrdatafile(data, featNames, classNames) 126 | 127 | # Generate the command line. See the help of mrmr for info on options 128 | cmdstr = mrmrexe 129 | cmdstr += ' -i %s -n %d -s %d -v %d -m %s' % (fn, nFeats, N, M, selectionMethod) 130 | if threshold is not None: 131 | assert threshold > 0 132 | cmdstr += ' -t ' + str(threshold) 133 | 134 | # Call mrmr. The result is printed to stdout. 135 | mrmrout = Popen(cmdstr, stdout=PIPE, shell=True).stdout.read().split('\n') 136 | 137 | # delete the temporary file 138 | os.remove(fn) 139 | 140 | # A function to parse the result 141 | def extractRes(key): 142 | Fea = [] 143 | Score = [] 144 | state = 0 145 | for l in mrmrout: 146 | if state == 0: 147 | if l.find(key) != -1: 148 | state = 1 149 | elif state == 1: 150 | state = 2 151 | elif state == 2: 152 | if l == '': 153 | break 154 | else: 155 | n, f, fn, s = l.split(' \t ') 156 | Fea.append(int(f)-1) 157 | Score.append(float(s)) 158 | return {'Fea': np.asarray(Fea), 'Score': np.asarray(Score)} 159 | 160 | # Return a dictionnary holding the features and their score for both the 161 | # MaxRel and mRMR criterions 162 | return {'MaxRel': extractRes('MaxRel features'), 163 | 'mRMR': extractRes('mRMR features')} 164 | 165 | 166 | if __name__ == '__main__': 167 | # Make some data 168 | N = 100 169 | data = np.c_[np.r_[np.random.randn(N, 5)+2, np.random.randn(N, 5)-2], np.random.randn(N*2, 30)] 170 | c = [1]*N+[-1]*N 171 | fn = ['F%d' % n for n in range(5)] + ['f%d' % n for n in range(30)] 172 | assert data.shape == (len(c), len(fn)) 173 | 174 | mrmrout = mrmr(data, fn, c, threshold=0.5) 175 | 176 | R = mrmrout['mRMR'] 177 | print 'Order \t Fea \t Name \t Score' 178 | for i in range(len(R['Fea'])): 179 | print '%d \t %d \t %s \t %f' % \ 180 | (i, R['Fea'][i], fn[R['Fea'][i]], R['Score'][i]) 181 | -------------------------------------------------------------------------------- /src/analysis/mrmr: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/equalitie/learn2ban/d45420c9d2eea2c81972c778a96a2ca42b318b6f/src/analysis/mrmr -------------------------------------------------------------------------------- /src/analysis/mrmr_osx_maci_leopard: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/equalitie/learn2ban/d45420c9d2eea2c81972c778a96a2ca42b318b6f/src/analysis/mrmr_osx_maci_leopard -------------------------------------------------------------------------------- /src/analysis/test_module.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/equalitie/learn2ban/d45420c9d2eea2c81972c778a96a2ca42b318b6f/src/analysis/test_module.py -------------------------------------------------------------------------------- /src/data/filters/regex_filters.xml: -------------------------------------------------------------------------------- 1 | 2 | ^<HOST> .*Firefox/1\.0\.1 3 | ^<HOST> .*MSIE 5 4 | ^<HOST> .*msnbot 5 | 6 | -------------------------------------------------------------------------------- /src/features/.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | 5 | # C extensions 6 | *.so 7 | 8 | # Distribution / packaging 9 | .Python 10 | env/ 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | *.egg-info/ 23 | .installed.cfg 24 | *.egg 25 | 26 | # PyInstaller 27 | # Usually these files are written by a python script from a template 28 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 29 | *.manifest 30 | *.spec 31 | 32 | # Installer logs 33 | pip-log.txt 34 | pip-delete-this-directory.txt 35 | 36 | # Unit test / coverage reports 37 | htmlcov/ 38 | .tox/ 39 | .coverage 40 | .coverage.* 41 | .cache 42 | nosetests.xml 43 | coverage.xml 44 | *,cover 45 | 46 | # Translations 47 | *.mo 48 | *.pot 49 | 50 | # Django stuff: 51 | *.log 52 | 53 | # Sphinx documentation 54 | docs/_build/ 55 | 56 | # PyBuilder 57 | target/ 58 | -------------------------------------------------------------------------------- /src/features/LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | 663 | -------------------------------------------------------------------------------- /src/features/README.md: -------------------------------------------------------------------------------- 1 | # eqfeaturemine 2 | Feature computed from IP behavoir and network traffic to analyze and classify attack/attackers 3 | -------------------------------------------------------------------------------- /src/features/src/__init__.py: -------------------------------------------------------------------------------- 1 | #All features 2 | __all__ = ["feature_average_request_interval", "feature_variance_request_interval", "feature_cycling_user_agent", "feature_html_to_image_ratio", "feature_request_depth", "feature_HTTP_response_code_rate", "feature_payload_size_average", "feature_request_depth_std", "feature_session_length", "feature_percentage_consecutive_requests"] 3 | -------------------------------------------------------------------------------- /src/features/src/feature_HTTP_response_code_rate.py: -------------------------------------------------------------------------------- 1 | """ 2 | For each IP compute the HTTP error rate for a given set of requests 3 | 4 | AUTHORS:: 5 | 6 | - Bill (bill@equalit.ie) 2012: Initial version 7 | 8 | """ 9 | from learn2ban_feature import Learn2BanFeature 10 | import operator 11 | class FeatureHTTPResponseCodeRate(Learn2BanFeature): 12 | def __init__(self, ip_sieve, ip_feature_db): 13 | """ 14 | Simply calls the parent constructor 15 | """ 16 | Learn2BanFeature.__init__(self, ip_sieve, ip_feature_db) 17 | 18 | #Each feature need to have unique index as the field number 19 | #in ip_feature_db 20 | self._FEATURE_INDEX = 6 21 | 22 | 23 | def compute(self): 24 | """ 25 | retrieve the ip dictionary and compute the average for each 26 | ip. This feature returns the rate of HTTP error codes for a given IP address. 27 | """ 28 | ip_recs = self._ip_sieve.ordered_records() 29 | 30 | for cur_ip_rec in ip_recs: 31 | total_error_statuses = 0 32 | total_requests = 0 33 | for payload in ip_recs[cur_ip_rec]: 34 | status_code = int(payload.get_http_status_code() or 0) 35 | if status_code >= 400 and status_code < 500: 36 | total_error_statuses += 1 37 | total_requests += 1 38 | #Percentage of http status errors over the course of the requests 39 | feature_value = 0 if total_error_statuses <= 0 else float(total_error_statuses)/float(total_requests) 40 | 41 | self.append_feature(cur_ip_rec, feature_value) 42 | 43 | 44 | -------------------------------------------------------------------------------- /src/features/src/feature_average_request_interval.py: -------------------------------------------------------------------------------- 1 | """ 2 | For each IP compute the average time between two request 3 | 4 | AUTHORS:: 5 | 6 | - Vmon (vmon@equalit.ie) 2012: Initial version 7 | 8 | """ 9 | from learn2ban_feature import Learn2BanFeature 10 | 11 | class FeatureAverageRequestInterval(Learn2BanFeature): 12 | def __init__(self, ip_sieve, ip_feature_db): 13 | """ 14 | Simply calls the parent constructor 15 | """ 16 | Learn2BanFeature.__init__(self, ip_sieve, ip_feature_db) 17 | 18 | #Each feature need to have unique index as the field number 19 | #in ip_feature_db 20 | self._FEATURE_INDEX = 1 21 | 22 | def compute(self): 23 | """ 24 | retrieve the ip dictionary and compute the average for each 25 | ip. This is basically the time of the last request - first / no of requests. 26 | """ 27 | ip_recs = self._ip_sieve.ordered_records() 28 | for cur_ip_rec in ip_recs: 29 | # print len(ip_recs[cur_ip_rec]) 30 | # print ip_recs[cur_ip_rec][-1].time_to_second(), ip_recs[cur_ip_rec][0].time_to_second() 31 | # print (ip_recs[cur_ip_rec][-1].time_to_second() - ip_recs[cur_ip_rec][0].time_to_second())/(len(ip_recs[cur_ip_rec])-1.0) 32 | feature_value = (len(ip_recs[cur_ip_rec]) > 1) and (ip_recs[cur_ip_rec][-1].time_to_second() - ip_recs[cur_ip_rec][0].time_to_second())/(len(ip_recs[cur_ip_rec])-1.0) or self.MAX_IDEAL_SESSION_LENGTH #If there's only one request then what average time mean? It should be infinity instead fo zero 33 | # print feature_value 34 | self.append_feature(cur_ip_rec, feature_value) 35 | -------------------------------------------------------------------------------- /src/features/src/feature_cycling_user_agent.py: -------------------------------------------------------------------------------- 1 | """ 2 | For each IP compute the average time between two request 3 | 4 | AUTHORS:: 5 | 6 | - Bill (bill@equalit.ie) 2012: Initial version 7 | 8 | """ 9 | 10 | from learn2ban_feature import Learn2BanFeature 11 | import operator 12 | class FeatureCyclingUserAgent(Learn2BanFeature): 13 | def __init__(self, ip_sieve, ip_feature_db): 14 | """ 15 | Simply calls the parent constructor 16 | """ 17 | Learn2BanFeature.__init__(self, ip_sieve, ip_feature_db) 18 | 19 | #Each feature need to have unique index as the field number 20 | #in ip_feature_db 21 | self._FEATURE_INDEX = 2 22 | 23 | 24 | def compute(self): 25 | """ 26 | retrieve the ip dictionary and compute the average for each 27 | ip to determine the change rate of UA per IP. 28 | """ 29 | ip_recs = self._ip_sieve.ordered_records() 30 | 31 | for cur_ip_rec in ip_recs: 32 | ua_request_map = {} 33 | total_requests = 0 34 | highest_percentage_UA = 0; 35 | for payload in ip_recs[cur_ip_rec]: 36 | cur_UA = payload.get_UA() 37 | if cur_UA not in ua_request_map: 38 | ua_request_map[cur_UA] = 1 39 | else: 40 | ua_request_map[cur_UA] += 1 41 | 42 | #Sort UAs by number of requests 43 | sorted_ua_request_map = sorted(ua_request_map.iteritems(), key=operator.itemgetter(1), reverse=True) 44 | #Percentage of times UA has changed over the course of the requests 45 | feature_value = float(sorted_ua_request_map[0][1])/float(len(ip_recs[cur_ip_rec])) 46 | 47 | self.append_feature(cur_ip_rec, feature_value) 48 | -------------------------------------------------------------------------------- /src/features/src/feature_html_to_image_ratio.py: -------------------------------------------------------------------------------- 1 | """ 2 | For each IP compute the ratio of HTML requests to Image requests 3 | 4 | AUTHORS:: 5 | 6 | - Bill (bill@equalit.ie) 2012: Initial version 7 | 8 | """ 9 | 10 | from learn2ban_feature import Learn2BanFeature 11 | import operator 12 | class FeatureHtmlToImageRatio(Learn2BanFeature): 13 | def __init__(self, ip_sieve, ip_feature_db): 14 | """ 15 | Simply calls the parent constructor 16 | """ 17 | Learn2BanFeature.__init__(self, ip_sieve, ip_feature_db) 18 | 19 | #Each feature need to have unique index as the field number 20 | #in ip_feature_db 21 | self._FEATURE_INDEX = 3 22 | 23 | 24 | def compute(self): 25 | """ 26 | retrieve the ip dictionary and compute the average for each 27 | ip. This feature computes the ratio of HTML to Image requests for a given session. 28 | """ 29 | ip_recs = self._ip_sieve.ordered_records() 30 | # print ip_recs 31 | for cur_ip_rec in ip_recs: 32 | doc_type_request_map = {} 33 | for payload in ip_recs[cur_ip_rec]: 34 | cur_type = payload.get_doc_type() 35 | if len(cur_type): 36 | if cur_type not in doc_type_request_map: 37 | doc_type_request_map[cur_type] = 1 38 | else: 39 | doc_type_request_map[cur_type] += 1 40 | 41 | """ 42 | Current version looks at ratio of Images to HTML requested by given IP 43 | An extension or evoltion would be to look at ratio of resources such as 44 | JS and CSS as well 45 | """ 46 | feature_value = 0 if ( 'image' not in doc_type_request_map or 'html' not in doc_type_request_map ) else ( float( doc_type_request_map['image'] ) / float( doc_type_request_map['html'] ) ) 47 | #feature_value = 0 if ( 'image' not in doc_type_request_map or 'html' not in doc_type_request_map) else ( float( doc_type_request_map['image'] ) / float( doc_type_request_map['html'] ) ) 48 | self.append_feature(cur_ip_rec, feature_value) 49 | 50 | -------------------------------------------------------------------------------- /src/features/src/feature_payload_size_average.py: -------------------------------------------------------------------------------- 1 | """ 2 | For each IP compute the average time between two request 3 | 4 | AUTHORS:: 5 | 6 | - Bill (bill@equalit.ie) 2012: Initial version 7 | 8 | """ 9 | 10 | from learn2ban_feature import Learn2BanFeature 11 | import operator 12 | class FeaturePayloadSizeAverage(Learn2BanFeature): 13 | def __init__(self, ip_sieve, ip_feature_db): 14 | """ 15 | Simply calls the parent constructor 16 | """ 17 | Learn2BanFeature.__init__(self, ip_sieve, ip_feature_db) 18 | 19 | #Each feature need to have unique index as the field number 20 | #in ip_feature_db 21 | self._FEATURE_INDEX = 5 22 | 23 | 24 | def compute(self): 25 | """ 26 | retrieve the ip dictionary and compute the average for each 27 | ip to determine the change rate of UA per IP. 28 | """ 29 | ip_recs = self._ip_sieve.ordered_records() 30 | 31 | #Vmon: obviously the total size comparative to all other sizes is important 32 | #so we are better off not to divide because the normalizer will 33 | #compute that value and apply it during prediction 34 | 35 | #Vmon: totally bullshit. Normalization divides by all request of all 36 | #requesters while here we are only average for this specific ip 37 | for cur_ip_rec in ip_recs: 38 | total_size = 0 39 | for payload in ip_recs[cur_ip_rec]: 40 | total_size += int(payload.get_payload_size()) 41 | 42 | #Calculate average pyalod size for given IP 43 | self.append_feature(cur_ip_rec, (total_size > 0) and total_size / len(ip_recs[cur_ip_rec]) or 0) 44 | -------------------------------------------------------------------------------- /src/features/src/feature_percentage_consecutive_requests.py: -------------------------------------------------------------------------------- 1 | """ 2 | For each IP compute the percentage of consecutive requests 3 | 4 | AUTHORS:: 5 | 6 | - Bill (bill@equalit.ie) 2012: Initial version 7 | - Vmon (vmon@equalit.ie) 2012: Took the average 8 | - Tomato (cerasiforme@gmail.com) 2013: Find percentage consecutive requests 9 | 10 | """ 11 | from learn2ban_feature import Learn2BanFeature 12 | import operator 13 | class FeaturePercentageConsecutiveRequests(Learn2BanFeature): 14 | def __init__(self, ip_sieve, ip_feature_db): 15 | """ 16 | Simply calls the parent constructor 17 | """ 18 | Learn2BanFeature.__init__(self, ip_sieve, ip_feature_db) 19 | 20 | #Each feature need to have unique index as the field number 21 | #in ip_feature_db 22 | self._FEATURE_INDEX = 10 23 | 24 | 25 | def compute(self): 26 | """ 27 | retrieve the ip dictionary and compute the average for each 28 | ip. This feature returns the average depth of uri requests by IP. 29 | This is intended to distinguish between bots and real live persons. 30 | """ 31 | #Vmon: Again why average has any meaning here, while normalizing will 32 | #take care care of it 33 | #Beside: I feel that wasn't the original intent, the original 34 | #intent is that in a website how many time you need to click to 35 | #reach that page which is not obtainable form the logs 36 | ip_recs = self._ip_sieve.ordered_records() 37 | 38 | 39 | 40 | for cur_ip_rec in ip_recs: 41 | last_req_folder = "" 42 | num_consec_reqs = 0 43 | no_html_requests = 0 44 | for payload in ip_recs[cur_ip_rec]: 45 | if payload.get_doc_type() == 'html': 46 | cur_req_folder = payload.get_requested_element().rfind('/') 47 | if cur_req_folder == last_req_folder: 48 | num_consec_reqs +=1 49 | 50 | no_html_requests += 1 51 | last_req_folder = cur_req_folder 52 | 53 | 54 | self.append_feature(cur_ip_rec, no_html_requests and num_consec_reqs/float(no_html_requests) or 0) 55 | 56 | 57 | 58 | -------------------------------------------------------------------------------- /src/features/src/feature_request_depth.py: -------------------------------------------------------------------------------- 1 | """ 2 | For each IP compute the average depth of page requests 3 | 4 | AUTHORS:: 5 | 6 | - Bill (bill@equalit.ie) 2012: Initial version 7 | - Vmon (vmon@equalit.ie) 2012: Took the average 8 | 9 | """ 10 | from learn2ban_feature import Learn2BanFeature 11 | import operator 12 | class FeatureRequestDepth(Learn2BanFeature): 13 | def __init__(self, ip_sieve, ip_feature_db): 14 | """ 15 | Simply calls the parent constructor 16 | """ 17 | Learn2BanFeature.__init__(self, ip_sieve, ip_feature_db) 18 | 19 | #Each feature need to have unique index as the field number 20 | #in ip_feature_db 21 | self._FEATURE_INDEX = 7 22 | 23 | 24 | def compute(self): 25 | """ 26 | retrieve the ip dictionary and compute the average for each 27 | ip. This feature returns the average depth of uri requests by IP. 28 | This is intended to distinguish between bots and real live persons. 29 | """ 30 | #Vmon: Again why average has any meaning here, while normalizing will 31 | #take care care of it 32 | #Beside: I feel that wasn't the original intent, the original 33 | #intent is that in a website how many time you need to click to 34 | #reach that page which is not obtainable form the logs 35 | ip_recs = self._ip_sieve.ordered_records() 36 | 37 | for cur_ip_rec in ip_recs: 38 | total_page_depth = 0 39 | total_html_requests = 0 40 | for payload in ip_recs[cur_ip_rec]: 41 | if payload.get_doc_type() == 'html': 42 | page_depth = payload.get_requested_element().count('/') 43 | total_page_depth += page_depth 44 | total_html_requests += 1 45 | 46 | self.append_feature(cur_ip_rec, total_html_requests and total_page_depth/total_html_requests or 0) 47 | -------------------------------------------------------------------------------- /src/features/src/feature_request_depth_std.py: -------------------------------------------------------------------------------- 1 | """ 2 | For each IP compute the standard diviation of depth of page requests 3 | 4 | AUTHORS:: 5 | 6 | - Sofia 2012: Initial version. 7 | 8 | """ 9 | from learn2ban_feature import Learn2BanFeature 10 | import operator 11 | import numpy as np 12 | class FeatureRequestDepthStd(Learn2BanFeature): 13 | def __init__(self, ip_sieve, ip_feature_db): 14 | """ 15 | Simply calls the parent constructor 16 | """ 17 | Learn2BanFeature.__init__(self, ip_sieve, ip_feature_db) 18 | 19 | #Each feature need to have unique index as the field number 20 | #in ip_feature_db 21 | self._FEATURE_INDEX = 8 22 | 23 | 24 | def compute(self): 25 | """ 26 | retrieve the ip dictionary and compute the average for each 27 | ip. This feature returns the average depth of uri requests by IP. 28 | This is intended to distinguish between bots and real live persons. 29 | """ 30 | #Vmon: Again why average has any meaning here, while normalizing will 31 | #take care care of it 32 | #Beside: I feel that wasn't the original intent, the original 33 | #intent is that in a website how many time you need to click to 34 | #reach that page which is not obtainable form the logs 35 | ip_recs = self._ip_sieve.ordered_records() 36 | 37 | for cur_ip_rec in ip_recs: 38 | total_html_requests = 0 39 | depth_list = [] 40 | for payload in ip_recs[cur_ip_rec]: 41 | if payload.get_doc_type() == 'html': 42 | page_depth = payload.get_requested_element().count('/') 43 | depth_list.append(page_depth) 44 | 45 | self.append_feature(cur_ip_rec, len(depth_list)==0 and -1 or np.std(depth_list)) 46 | -------------------------------------------------------------------------------- /src/features/src/feature_session_length.py: -------------------------------------------------------------------------------- 1 | """ 2 | For each IP compute the length of time between first and last request (i.e., length of the session) 3 | 4 | AUTHORS:: 5 | 6 | - Vmon (vmon@equalit.ie) 2012: Initial version (average time of request) 7 | - Tomato (cerasiforme@gmail.com) 2013: Make into length of session instead 8 | 9 | """ 10 | from learn2ban_feature import Learn2BanFeature 11 | 12 | class FeatureSessionLength(Learn2BanFeature): 13 | def __init__(self, ip_sieve, ip_feature_db): 14 | """ 15 | Simply calls the parent constructor 16 | """ 17 | Learn2BanFeature.__init__(self, ip_sieve, ip_feature_db) 18 | 19 | #Each feature need to have unique index as the field number 20 | #in ip_feature_db 21 | self._FEATURE_INDEX = 9 22 | 23 | 24 | def compute(self): 25 | """ 26 | retrieve the ip dictionary and compute the average for each 27 | ip. This is basically the time of the last request - first. 28 | """ 29 | ip_recs = self._ip_sieve.ordered_records() 30 | 31 | for cur_ip_rec in ip_recs: 32 | feature_value = (len(ip_recs[cur_ip_rec]) > 1) and (ip_recs[cur_ip_rec][-1].time_to_second() - ip_recs[cur_ip_rec][0].time_to_second()) or 0 33 | #DEBUG 34 | #print len(ip_recs[cur_ip_rec]), ip_recs[cur_ip_rec][-1].time_to_second(),ip_recs[cur_ip_rec][0].time_to_second() 35 | #print feature_value 36 | self.append_feature(cur_ip_rec, feature_value) 37 | -------------------------------------------------------------------------------- /src/features/src/feature_variance_request_interval.py: -------------------------------------------------------------------------------- 1 | """ 2 | For each IP compute the variance of the time intervals between two 3 | requests. That is: 4 | 5 | var(X) = sum (x_i - \bar{X})^2/(n-1) 6 | 7 | This is divided by n-1 because we are actually estimating the stddiv of the 8 | bot using a finite sample of the society. 9 | 10 | AUTHORS:: 11 | 12 | - Vmon (vmon@equalit.ie) 2012: Initial version 13 | - Vmon Nov 2013: Using numpy instead of manual std 14 | 15 | """ 16 | from learn2ban_feature import Learn2BanFeature 17 | import numpy as np 18 | 19 | class FeatureVarianceRequestInterval(Learn2BanFeature): 20 | def __init__(self, ip_sieve, ip_feature_db): 21 | """ 22 | Simply calls the parent constructor 23 | """ 24 | Learn2BanFeature.__init__(self, ip_sieve, ip_feature_db) 25 | 26 | #Each feature need to have unique index as the field number 27 | #in ip_feature_db 28 | self._FEATURE_INDEX = 4 29 | 30 | 31 | def compute(self): 32 | """ 33 | retrieve the ip dictionary and compute the average for each 34 | ip. Then walk between each two consecutive requests and compute the 35 | difference of their time lag and mean. Basically the pencil and 36 | paper way. 37 | 38 | (a_i - a_{i -1} - mu)^2 +...+ (a_{i+1}- a_i - mu)^2 39 | 40 | TODO:: This can improved. In the way that we compute the moving 41 | varianceinstead. However, this need the feature object to remember 42 | the old calculation which is very reasonable requirement. We should 43 | move to that model soon. 44 | """ 45 | ip_recs = self._ip_sieve.ordered_records() 46 | 47 | for cur_ip_rec in ip_recs: 48 | sample_size = len(ip_recs[cur_ip_rec]) - 1 49 | 50 | if sample_size < 2: 51 | #the variance of single value is 0 obviously 52 | feature_value = 0 53 | 54 | else: 55 | interval_list = [] 56 | #just storing each interval in a list 57 | for i in xrange(0, sample_size): 58 | cur_interval = ip_recs[cur_ip_rec][i+1].time_to_second() - ip_recs[cur_ip_rec][i].time_to_second() 59 | interval_list.append(cur_interval) 60 | 61 | feature_value = np.std(interval_list) 62 | 63 | self.append_feature(cur_ip_rec, feature_value) 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | -------------------------------------------------------------------------------- /src/features/src/learn2ban_feature.py: -------------------------------------------------------------------------------- 1 | """ 2 | The parent class for all features used to distinguished an attack from a legitimate request 3 | 4 | AUTHORS:: 5 | 6 | - Vmon (vmon@equalit.ie) 2012: Initial version 7 | 8 | """ 9 | class Learn2BanFeature(object): 10 | """ 11 | We need to get the data for IPSieve class and analyze it. IPSieve 12 | provide the Feature with a dictionary and the feature needs to return 13 | a dictionary of IPs and numerical value 14 | 15 | (This is new-style particularly to loop through its children using 16 | __subclass__) 17 | """ 18 | MAX_IDEAL_SESSION_LENGTH = 1800 #seconds 19 | def __init__(self, ip_sieve, ip_feature_db): 20 | """ 21 | Set the corresponding ip_sieve 22 | 23 | INPUT:: 24 | ip_sieve: the IPSieve object to crunch the ATS log file 25 | ip_feature_db: the global db that store all features of 26 | all ips 27 | """ 28 | self._ip_sieve = ip_sieve 29 | self._ip_feature_db = ip_feature_db 30 | 31 | self._FEATURE_INDEX = -1 #This is an abstract class so no real feature 32 | 33 | def compute(self): 34 | """ 35 | The feature should overload this function to implement the feautere 36 | computation. At the end the results should be stored 37 | in a dictionary with the format of IP:value where the value is a double 38 | or an integer value 39 | """ 40 | pass 41 | 42 | def append_feature(self, inspected_ip, feature_value): 43 | """ 44 | Just checks if the ip is in the database adds the feature to it 45 | otherwise make a new record for the ip in the ip dictioanry 46 | 47 | INPUT:: 48 | ispected_ip: the ip whose record we want to manipulate 49 | feature_value: the value that we want to add as 50 | {_FEATURE_INDEX: feature_value} to the record 51 | """ 52 | if inspected_ip in self._ip_feature_db: 53 | self._ip_feature_db[inspected_ip][self._FEATURE_INDEX] = feature_value 54 | else: 55 | self._ip_feature_db[inspected_ip] = {self._FEATURE_INDEX:feature_value} 56 | -------------------------------------------------------------------------------- /src/initialise_db.py: -------------------------------------------------------------------------------- 1 | """ 2 | Construct the db 3 | 4 | AUTHORS: Bill: Initial version, 5 | Ben: June 2013: Storing the results, PCA, mRMR. 6 | Vmon: July 2013: Making tables for the regex and corresponding logs 7 | August 2013: Add config profiles to config table 8 | 9 | - July 2013: Experiments should only store the log_ids for 10 | training and testing. the regex_assignments will tell which regexes are detecting the 11 | bots in that log. This is mainly because one might need more regex to detect all bots in 12 | a file. This problem was previously address by putting more than one regex in a filter. 13 | However, applying regexes that finds bots in some attacks not necessarily will single out bots in another log 14 | 15 | I see no reason for not storing the regex itself in the database. 16 | """ 17 | from tools.learn2bantools import Learn2BanTools 18 | 19 | l2btools = Learn2BanTools() 20 | 21 | l2btools.connect_to_db() 22 | 23 | l2btools.cur.execute("create table IF NOT EXISTS config (id INT NOT NULL AUTO_INCREMENT,profile_name VARCHAR(255), absolute_paths BOOLEAN , training_directory VARCHAR (255), testing_directory VARCHAR(255), analyser_results_directory VARCHAR(255), regex_filter_directory VARCHAR(255),default_filter_file VARCHAR(255), PRIMARY KEY(id) ) ENGINE=INNODB;") 24 | 25 | l2btools.cur.execute("create table IF NOT EXISTS regex_filters ( id INT NOT NULL AUTO_INCREMENT, name VARCHAR(255), regex VARCHAR(4096), PRIMARY KEY(id)) ENGINE = INNODB;") 26 | 27 | l2btools.cur.execute("create table IF NOT EXISTS experiments (id INT NOT NULL AUTO_INCREMENT, regex_filter_id INT, kernel_type VARCHAR(255), training_log VARCHAR(255), testing_log VARCHAR(255), enabled BOOLEAN, comment LONGTEXT, FOREIGN KEY(regex_filter_id) REFERENCES regex_filters(id), norm_mode VARCHAR(100), PRIMARY KEY(id) ) ENGINE = INNODB") 28 | 29 | # created by Ben for storing additional results. In the end experiment_result should be dropped 30 | # l2btools.cur.execute("drop table experiment_results") 31 | l2btools.cur.execute("create table IF NOT EXISTS experiment_results( id INT NOT NULL AUTO_INCREMENT, experiment_id INT, FOREIGN KEY(experiment_id) references experiments(id), result_file VARCHAR(255), proportion FLOAT, score FLOAT, active_features VARCHAR(255), pca_ratios VARCHAR(255), mrmr_score VARCHAR(255), PRIMARY KEY(id) )") 32 | 33 | #Keeping track of the name of training logs in the db 34 | l2btools.cur.execute("create table IF NOT EXISTS logs( id INT NOT NULL AUTO_INCREMENT, file_name VARCHAR(255), note LONGTEXT, PRIMARY KEY(id) )") 35 | 36 | l2btools.cur.execute("create table IF NOT EXISTS regex_assignment( id INT NOT NULL AUTO_INCREMENT, regex_filter_id INT, log_id INT, FOREIGN KEY (log_id) REFERENCES logs(id), FOREIGN KEY(regex_filter_id) REFERENCES regex_filters(id), PRIMARY KEY(id) )") 37 | 38 | l2btools.cur.execute("create table IF NOT EXISTS experiment_logs( id INT NOT NULL AUTO_INCREMENT, experiment_id INT, log_id INT, FOREIGN KEY (experiment_id) REFERENCES experiments(id), FOREIGN KEY (log_id) REFERENCES logs(id), PRIMARY KEY(id) )") 39 | 40 | l2btools.cur.execute("Insert into config( training_directory, testing_directory, analyser_results_directory,regex_filter_directory,default_filter_file) values ('/data/training/','/data/testing/','/analysis/results_dir/', '/data/filters/', 'regex_filters.xml')") 41 | 42 | #l2btools.cur.execute("Insert into regex_filters( name, filter_file) values ('User Agent', 'regex_filters.xml')") 43 | #l2btools.db.commit() 44 | 45 | l2btools.cur.execute("Insert into experiments(regex_filter_id,kernel_type, training_log, testing_log, norm_mode) values (1,'linear', 'training.log', 'testing.log','sparse')") 46 | l2btools.cur.execute("Insert into experiments(regex_filter_id,kernel_type, training_log, testing_log, norm_mode) values (1,'linear', 'training.log', 'testing.log','individual')") 47 | l2btools.cur.execute("Insert into experiments(regex_filter_id,kernel_type, training_log, testing_log, norm_mode) values (1,'linear', 'training.log', 'testing.log','sparse')") 48 | l2btools.cur.execute("Insert into experiments(regex_filter_id,kernel_type, training_log, testing_log, norm_mode) values (1,'linear', 'training.log', 'testing.log','individual')") 49 | 50 | l2btools.cur.execute("Insert into experiments(regex_filter_id,kernel_type, training_log, testing_log, norm_mode) values (1,'linear', 'training.log', 'testing.log','sparse')") 51 | l2btools.cur.execute("Insert into experiments(regex_filter_id,kernel_type, training_log, testing_log, norm_mode) values (1,'linear', 'training.log', 'testing.log','individual')") 52 | 53 | l2btools.db.commit() 54 | 55 | l2btools.disconnect_from_db() 56 | -------------------------------------------------------------------------------- /src/ip_sieve.py: -------------------------------------------------------------------------------- 1 | """ 2 | Parses a log file on the server and return the records corresponding to each client separately 3 | 4 | AUTHORS: 5 | 6 | - Vmon (vmon@equalit.ie) 2012: Initial version. 7 | - Bill (bill.doran@gmail.com) 2012: lexify and other ATSRecord method depending on it. 8 | - Vmon Oct 2013: Session tracking added. 9 | 10 | """ 11 | 12 | from time import strptime, mktime 13 | from tools.apache_log_muncher import parse_line as parse_apache_line 14 | 15 | class ATSRecord: 16 | """ 17 | This is to keep the info from one ATS record. For now we only extract 18 | the time but this can be change. 19 | 20 | INPUT: 21 | cur_rec_dict: a dictionary resulted from 22 | TODO:: 23 | We probably shouldn't read the whole table. There should be a way to 24 | temporally restrict the inspected data 25 | """ 26 | #ATS_TIME_FORMAT = '%d/%b/%Y:%H:%M:%S' 27 | ATS_TIME_FORMAT = '%Y-%m-%dT%H:%M:%S' 28 | ATS_NO_FIELDS = 8 #maximum field index + 1 of the tokenized payload being 29 | #used in the feauter computation 30 | #to decide that the session is dead and we need to start a new session 31 | 32 | def __init__(self, cur_rec_dict): 33 | self.ip = cur_rec_dict["host"] 34 | self.time = cur_rec_dict["time"]; 35 | self.payload = cur_rec_dict; 36 | 37 | #do not run lexify it is slow 38 | #self.lexify() 39 | 40 | def lexify(self): 41 | """ 42 | Stores tockenize version of the payload in a array 43 | """ 44 | try: 45 | self.tokenised_payload = shlex.split(self.payload, posix=False) 46 | #The posix=False will help with ignoring single single quotes 47 | #Other soltions: 48 | #1. getting rid of ' 49 | #parsed_string.replace('\'','') 50 | 51 | #2. Use the shlex.shlex instead and tell it to ignore ' 52 | # lex = shlex.shlex(str(self.payload)) 53 | # lex.quotes = '"' 54 | # lex.whitespace_split = '.' 55 | # tokenised_payload = list(lex) 56 | #return '' if len(tokenised_payload) <= 0 else tokenised_payload[payloadIndex] 57 | if len(self.tokenised_payload) <= 0: 58 | self.tokenized_payload = [''] * ATS_NO_FIELDS 59 | except ValueError, err: 60 | print(str(err)) 61 | #for debug purpose 62 | print self.payload 63 | return '' #Return empty in case of error maintainig normal 64 | #behavoir so the program doesn't crash 65 | def get_UA(self): 66 | """ 67 | Return the User Agent for this payload 68 | """ 69 | return self.payload["agent"] 70 | 71 | def time_to_second(self): 72 | """ 73 | convert the time value to total no of seconds passed 74 | since ???? to facilitate computation. 75 | """ 76 | #find to ignore time-zone 77 | try: 78 | digested_time = strptime(self.time[:self.time.find('Z')], self.ATS_TIME_FORMAT) 79 | except (ValueError): 80 | print "time is ", self.time 81 | 82 | return mktime(digested_time) 83 | 84 | def get_doc_type(self): 85 | """ 86 | Retrieves the document type, if present, for the current payload 87 | """ 88 | return self.payload["type"] 89 | 90 | def get_payload_size(self): 91 | """ 92 | Retrieves the payload size, if present, for the current payload 93 | """ 94 | return self.payload["size"] 95 | 96 | def get_http_status_code(self): 97 | """ 98 | Retrieves the HTTP status code, if present, for the current payload 99 | """ 100 | return self.payload["status"] 101 | 102 | def get_requested_element(self): 103 | """ 104 | Retrieves the requested uri, if present, for the current payload 105 | """ 106 | return self.payload["request"] 107 | 108 | class IPSieve(): 109 | DEAD_SESSION_PAUSE = 1800 #minimum number of seconds between two session 110 | 111 | def __init__(self, log_filename=None): 112 | self._ordered_records = {} 113 | self._log_file_list = [] 114 | 115 | #This tells the sieve that needs to re-read data from the file. 116 | if (log_filename): 117 | add_log_file(self, log_filename) 118 | else: 119 | #If no file is specied then no record means all records 120 | self.dict_invalid = False 121 | self._log_lines = None #can be a file handle or array of lines 122 | 123 | def add_log_file(self, log_filename): 124 | """ 125 | It takes the name of the log file and store it in a list 126 | """ 127 | self._log_file_list.append(log_filename) 128 | self.dict_invalid = True 129 | 130 | def add_log_files(self, log_filename_list): 131 | """ 132 | It takes a list of name of the log files and extend the filelist to it 133 | """ 134 | self._log_file_list.extend(log_filename_list) 135 | self.dict_invalid = True 136 | 137 | def set_log_lines(self, log_lines): 138 | """ 139 | It takes an array of log lines 140 | """ 141 | self.dict_invalid = True 142 | self._log_lines = log_lines 143 | 144 | def set_pre_seived_order_records(self, pre_seived_records): 145 | """ 146 | It sets the order records directy to the dictionary 147 | supplied by the user 148 | """ 149 | self.dict_invalid = False 150 | self._ordered_records = pre_seived_records 151 | 152 | def parse_log(self): 153 | """ 154 | Read each line of the log file and batch the records corresponding 155 | to each client (ip) make a dictionary of lists each consisting of all 156 | records 157 | """ 158 | #to check the performance and the sensitivity of the log mancher 159 | total_failure_munches = 0 160 | for log_filename in self._log_file_list: 161 | try: 162 | self._log_lines = open(log_filename) 163 | except IOError: 164 | raise IOError 165 | 166 | self._log_lines.seek(0, 2) #go to end to check the size 167 | total_file_size = self._log_lines.tell() 168 | self._log_lines.seek(0, 0) #and go back to the begining 169 | previous_progress = 0 170 | 171 | print "Parsing ", log_filename.split('/')[-1] 172 | 173 | #we are going to keep track of each ip and last session number corresponding 174 | #to that ip 175 | ip_session_tracker = {} 176 | for cur_rec in self._log_lines: 177 | new_session = False 178 | cur_rec_dict = parse_apache_line(cur_rec) 179 | 180 | if cur_rec_dict: 181 | cur_ip = cur_rec_dict["host"]; 182 | cur_ats_rec = ATSRecord(cur_rec_dict); 183 | 184 | if not cur_ip in ip_session_tracker: 185 | ip_session_tracker[cur_ip] = 0 186 | new_session = True 187 | 188 | #now we are checking if we hit a new session 189 | #if we already decided that we are in a new session then there is nothing 190 | #to investigate 191 | if not new_session: 192 | #so we have a session already recorded, compare 193 | #the time of that last record of that session with 194 | #this session 195 | if cur_ats_rec.time_to_second() - self._ordered_records[(cur_ip, ip_session_tracker[cur_ip])][-1].time_to_second() > self.DEAD_SESSION_PAUSE: 196 | #the session is dead we have to start a new session 197 | ip_session_tracker[cur_ip] += 1 198 | new_session = True 199 | 200 | if new_session: 201 | self._ordered_records[(cur_ip, ip_session_tracker[cur_ip])] = [cur_ats_rec] 202 | else: 203 | self._ordered_records[(cur_ip, ip_session_tracker[cur_ip])].append(cur_ats_rec) 204 | 205 | else: 206 | #unable to munch and grasp the data due to unrecognizable format 207 | total_failure_munches += 1 208 | 209 | #reporting progress 210 | current_progress = (self._log_lines.tell()*100)/total_file_size 211 | if (current_progress != previous_progress): 212 | print "%", current_progress 213 | previous_progress = current_progress 214 | 215 | 216 | self._log_lines.close() 217 | 218 | self._log_file_list = [] 219 | 220 | #for debug, it should be moved to be dumped in the logger 221 | print "Parsed ", len(self._ordered_records) 222 | if total_failure_munches > 0: 223 | print "Failed to parse ", total_failure_munches, " records" 224 | self.dict_invalid = False 225 | 226 | def parse_log_old(self): 227 | """ 228 | Read each line of the log file and batch the 229 | records corresponding to each (client (ip), session) 230 | make a dictionary of lists each consisting of all records of that session 231 | """ 232 | for cur_rec in self._log_lines: 233 | #Here (at least for now) we only care about the ip and the time record. 234 | time_pos = cur_rec.find('-') 235 | if time_pos == -1: #Not a valid record 236 | continue 237 | 238 | http_req_pos = cur_rec.find('"') 239 | cur_ip = cur_rec[:time_pos-1] 240 | rec_time = cur_rec[time_pos + 3:http_req_pos - 2] 241 | rec_payload = cur_rec[http_req_pos:] 242 | #check if we have already encountered this ip 243 | 244 | 245 | cur_ats_rec = ATSRecord(cur_ip, rec_time, rec_payload) 246 | if not cur_ip in self._ordered_records: 247 | self._ordered_records[cur_ip] = [cur_ats_rec] 248 | else: 249 | self._ordered_records[cur_ip].append(cur_ats_rec) 250 | 251 | self.dict_invalid = False 252 | 253 | def ordered_records(self): 254 | """ 255 | Wrapper for the record dictionary 256 | """ 257 | if (self.dict_invalid): 258 | self.parse_log() 259 | 260 | return self._ordered_records 261 | -------------------------------------------------------------------------------- /src/ip_sieve_shlex.py: -------------------------------------------------------------------------------- 1 | """ 2 | Parses a log file on the server and return the records corresponding to each client separately 3 | 4 | AUTHORS: 5 | 6 | - Vmon (vmon@equalit.ie) 2012: Initial version. 7 | - Bill (bill.doran@gmail.com) 2012: lexify and other ATSRecord method depending on it. 8 | 9 | """ 10 | 11 | from time import strptime, mktime 12 | import shlex 13 | 14 | class ATSRecord: 15 | """ 16 | This is to keep the info from one ATS record. For now we only extract 17 | the time but this can be change. 18 | 19 | TODO:: 20 | We probably shouldn't read the whole table. There should be a way to 21 | temporally restrict the ispected data 22 | """ 23 | ATS_TIME_FORMAT = '%d/%b/%Y:%H:%M:%S' 24 | ATS_NO_FIELDS = 8 #maximum field index + 1 of the tokenized payload being 25 | #used in the feauter computation 26 | def __init__(self, ip, time, payload): 27 | self.ip = ip 28 | self.time = time 29 | self.payload = payload 30 | 31 | #run lexify once and for all to validate tokenised_payload 32 | self.lexify() 33 | 34 | def lexify(self): 35 | """ 36 | Stores tockenize version of the payload in a array 37 | """ 38 | try: 39 | self.tokenised_payload = shlex.split(self.payload, posix=False) 40 | #The posix=False will help with ignoring single single quotes 41 | #Other soltions: 42 | #1. getting rid of ' 43 | #parsed_string.replace('\'','') 44 | 45 | #2. Use the shlex.shlex instead and tell it to ignore ' 46 | # lex = shlex.shlex(str(self.payload)) 47 | # lex.quotes = '"' 48 | # lex.whitespace_split = '.' 49 | # tokenised_payload = list(lex) 50 | #return '' if len(tokenised_payload) <= 0 else tokenised_payload[payloadIndex] 51 | if len(self.tokenised_payload) <= 0: 52 | self.tokenized_payload = [''] * ATS_NO_FIELDS 53 | except ValueError, err: 54 | print(str(err)) 55 | #for debug purpose 56 | print self.payload 57 | return '' #Return empty in case of error maintainig normal 58 | #behavoir so the program doesn't crash 59 | def get_UA(self): 60 | """ 61 | Return the User Agent for this payload 62 | """ 63 | return self.tokenised_payload[5] 64 | 65 | def time_to_second(self): 66 | """ 67 | convert the time value to total no of seconds passed 68 | since ???? to facilitate computation. 69 | """ 70 | #find to ignore time-zone 71 | digested_time = strptime(self.time[:self.time.find(' ')], self.ATS_TIME_FORMAT) 72 | return mktime(digested_time) 73 | def get_doc_type(self): 74 | """ 75 | Retrieves the document type, if present, for the current payload 76 | """ 77 | return self.tokenised_payload[7] 78 | def get_payload_size(self): 79 | """ 80 | Retrieves the payload size, if present, for the current payload 81 | """ 82 | 83 | return self.tokenised_payload[4] 84 | def get_http_status_code(self): 85 | """ 86 | Retrieves the HTTP status code, if present, for the current payload 87 | """ 88 | 89 | return self.tokenised_payload[3] 90 | def get_requested_element(self): 91 | """ 92 | Retrieves the requested uri, if present, for the current payload 93 | """ 94 | 95 | return self.tokenised_payload[0] 96 | 97 | class IPSieve(): 98 | def __init__(self, log_filename=None): 99 | self._ordered_records = {} 100 | 101 | #This tells the sieve that needs to re-read data from the file. 102 | if (log_filename): 103 | set_log_file(self, log_filename) 104 | else: 105 | #If no file is specied then no record means all records 106 | self.dict_invalid = False 107 | self._log_filename = None 108 | self._log_lines = None #can be a file handle or array of lines 109 | 110 | def set_log_file(self, log_filename): 111 | """ 112 | It takes the name of the log file and open the file 113 | throw and exception if not successful. 114 | """ 115 | self.dict_invalid = True 116 | self._log_filename = log_filename 117 | self._log_lines = open(self._log_filename) 118 | 119 | 120 | def set_log_lines(self, log_lines): 121 | """ 122 | It takes an array of log lines 123 | """ 124 | self.dict_invalid = True 125 | self._log_lines = log_lines 126 | 127 | def parse_log(self): 128 | """ 129 | Read each line of the log file and batch the 130 | records corresponding to each client (ip) 131 | make a dictionary of lists each consisting of all records 132 | """ 133 | for cur_rec in self._log_lines: 134 | #Here (at least for now) we only care about the ip and the time record. 135 | time_pos = cur_rec.find('-') 136 | if time_pos == -1: #Not a valid record 137 | continue 138 | 139 | http_req_pos = cur_rec.find('"') 140 | cur_ip = cur_rec[:time_pos-1] 141 | rec_time = cur_rec[time_pos + 3:http_req_pos - 2] 142 | rec_payload = cur_rec[http_req_pos:] 143 | #check if we have already encountered this ip 144 | cur_ats_rec = ATSRecord(cur_ip, rec_time, rec_payload) 145 | if not cur_ip in self._ordered_records: 146 | self._ordered_records[cur_ip] = [cur_ats_rec] 147 | else: 148 | self._ordered_records[cur_ip].append(cur_ats_rec) 149 | 150 | self.dict_invalid = False 151 | 152 | def ordered_records(self): 153 | """ 154 | Wrapper for the record dictionary 155 | """ 156 | if (self.dict_invalid): 157 | self.parse_log() 158 | 159 | return self._ordered_records 160 | 161 | -------------------------------------------------------------------------------- /src/profiler/profile_trainer.py: -------------------------------------------------------------------------------- 1 | """ 2 | Profiler for Train2Ban 3 | 4 | AUTHORS: 5 | 6 | - Bill (bill@equalit.ie) 2013: initial version 7 | """ 8 | 9 | import cProfile 10 | import pstats 11 | 12 | import unittest 13 | from os.path import dirname, abspath 14 | from os import getcwd, chdir 15 | import sys 16 | import datetime 17 | 18 | try: 19 | src_dir = dirname(dirname(abspath(__file__))) 20 | except NameError: 21 | #the best we can do to hope that we are in the test dir 22 | src_dir = dirname(getcwd()) 23 | 24 | sys.path.append(src_dir) 25 | 26 | #train to ban 27 | from analysis.analyse_trainer import Analyser 28 | from tools.learn2bantools import Learn2BanTools 29 | import pstats 30 | 31 | class Profiler(): 32 | l2btools = Learn2BanTools() 33 | def profile_learn2ban(self): 34 | self.l2btools.load_train2ban_config() 35 | experiment_set = self.l2btools.retrieve_experiments() 36 | for exp in experiment_set: 37 | utc_datetime = datetime.datetime.utcnow() 38 | utc_datetime.strftime("%Y-%m-%d-%H%MZ") 39 | filename = src_dir+'/profiler/logs/profile_'+str(utc_datetime) 40 | Analyser().profile(exp,0.8, filename) 41 | break 42 | p = pstats.Stats(filename) 43 | p.strip_dirs().sort_stats(-1).print_stats() 44 | p.dump_stats(src_dir+'profiler/logs/stats_'+str(utc_datetime)) 45 | # cProfile.run(a.run_experiments(exp))#, 'profile'+str(utc_datetime)) 46 | if __name__ == "__main__": 47 | Profiler().profile_learn2ban() 48 | -------------------------------------------------------------------------------- /src/test/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/equalitie/learn2ban/d45420c9d2eea2c81972c778a96a2ca42b318b6f/src/test/__init__.py -------------------------------------------------------------------------------- /src/test/speed_test/l2b_profiler.py: -------------------------------------------------------------------------------- 1 | """ 2 | profiles and generates time sheet for different modules of Learn2Ban 3 | 4 | AUTHORS: 5 | Vmon March 2013 Initial version 6 | """ 7 | from os.path import dirname, abspath 8 | from os import getcwd, chdir 9 | import sys 10 | import cProfile 11 | import datetime 12 | import subprocess 13 | import pdb 14 | pdb.set_trace() 15 | 16 | try: 17 | src_dir = dirname(dirname(dirname(abspath(__file__)))) 18 | if not src_dir: src_dir = "/lu101/sahosse/doc/code/deflect/learn2ban/src" 19 | except NameError: 20 | #the best we can do to hope that we are in the test dir 21 | src_dir = dirname(getcwd()) 22 | 23 | #adding the src dir to the path for importing 24 | sys.path.append(src_dir) 25 | sys.path.append(src_dir) 26 | 27 | 28 | #I need a way to run cProfile on modules instead of functions because 29 | #all I need is to profile. 30 | def profile_features(): 31 | import test.test_features 32 | 33 | utc_datetime = datetime.datetime.utcnow() 34 | utc_datetime.strftime("%Y-%m-%d-%H%MZ") 35 | profile_log = 'profile_features_' + str(utc_datetime) +".prof" 36 | 37 | cProfile.run('test.test_features.run_tests()', profile_log) 38 | #subprocess.call(['/usr/lib/python2.7/cProfile.py', '-o', profile_log, '../test_features.py']); 39 | 40 | if __name__ == "__main__": 41 | #profile all modules 42 | #import pdb 43 | #pdb.set_trace() 44 | profile_features() 45 | -------------------------------------------------------------------------------- /src/test/speed_test/l2b_profiler.py.orig: -------------------------------------------------------------------------------- 1 | """ 2 | profiles and generates time sheet for different modules of Learn2Ban 3 | 4 | <<<<<<< HEAD 5 | AUTHORS: 6 | Vmon March 2013 Initial version 7 | """ 8 | from os.path import dirname, abspath 9 | ======= 10 | AUTHORS: 11 | Vmon March 2013 Initial version 12 | """ 13 | from os.path import dirname 14 | >>>>>>> bf45af850b4850f592927ca918a77381b0e8b6a9 15 | from os import getcwd, chdir 16 | import sys 17 | import cProfile 18 | import datetime 19 | import subprocess 20 | <<<<<<< HEAD 21 | import pdb 22 | pdb.set_trace() 23 | 24 | try: 25 | src_dir = dirname(dirname(dirname(abspath(__file__)))) 26 | if not src_dir: src_dir = "/lu101/sahosse/doc/code/deflect/learn2ban/src" 27 | ======= 28 | 29 | try: 30 | src_dir = dirname(dirname(__file__)) 31 | if not src_dir: src_dir = "/home/vmon/doc/code/deflect/learn2ban/src" 32 | >>>>>>> bf45af850b4850f592927ca918a77381b0e8b6a9 33 | except NameError: 34 | #the best we can do to hope that we are in the test dir 35 | src_dir = dirname(getcwd()) 36 | 37 | #adding the src dir to the path for importing 38 | sys.path.append(src_dir) 39 | <<<<<<< HEAD 40 | sys.path.append(src_dir) 41 | ======= 42 | >>>>>>> bf45af850b4850f592927ca918a77381b0e8b6a9 43 | 44 | 45 | #I need a way to run cProfile on modules instead of functions because 46 | #all I need is to profile. 47 | def profile_features(): 48 | <<<<<<< HEAD 49 | import test.test_features 50 | 51 | ======= 52 | import tests.test_features 53 | 54 | >>>>>>> bf45af850b4850f592927ca918a77381b0e8b6a9 55 | utc_datetime = datetime.datetime.utcnow() 56 | utc_datetime.strftime("%Y-%m-%d-%H%MZ") 57 | profile_log = 'profile_features_' + str(utc_datetime) +".prof" 58 | 59 | <<<<<<< HEAD 60 | cProfile.run('test.test_features.run_tests()', profile_log) 61 | ======= 62 | cProfile.run('tests.test_features.run_tests()', profile_log) 63 | >>>>>>> bf45af850b4850f592927ca918a77381b0e8b6a9 64 | #subprocess.call(['/usr/lib/python2.7/cProfile.py', '-o', profile_log, '../test_features.py']); 65 | 66 | if __name__ == "__main__": 67 | #profile all modules 68 | #import pdb 69 | #pdb.set_trace() 70 | profile_features() 71 | -------------------------------------------------------------------------------- /src/test/speed_test/numpy_vs_python_double_array.py: -------------------------------------------------------------------------------- 1 | """ 2 | This is to compare how fast numpy or python filling up their double array 3 | 4 | AUTHORS: 5 | - Vmon (vmon@equalit.ie) 2012: initial version. 6 | 7 | """ 8 | 9 | import numpy as np 10 | from time import clock 11 | 12 | test_size = 3*10**3 13 | print "Testing an array of size %ix%i"%(test_size,test_size) 14 | #initialization 15 | t0 = clock() 16 | py_double = [[x for x in xrange(0,test_size)] for y in xrange(0,test_size)] 17 | t1 = clock() 18 | print "py init:",(t1-t0) 19 | 20 | t0 = clock() 21 | numpy_double = np.zeros((test_size, test_size)) 22 | t1 = clock() 23 | print "numpy init:",(t1-t0) 24 | 25 | t0 = clock() 26 | for i in xrange(0,test_size): 27 | for j in xrange(0,test_size): 28 | py_double[i][j] = i * test_size + j 29 | t1 = clock() 30 | print "py fillup:",(t1-t0) 31 | 32 | t0 = clock() 33 | for i in xrange(0,test_size): 34 | for j in xrange(0,test_size): 35 | numpy_double[i][j] = i * test_size + j 36 | t1 = clock() 37 | print "numpy fillup:",(t1-t0) 38 | -------------------------------------------------------------------------------- /src/test/svm_test.t: -------------------------------------------------------------------------------- 1 | 1 0:-1.09010482 1:-1.39443338 2:-0.24494897 3:-0.19554826 4:1.48202486 5:-0.39840538 6:1.80276255 -------------------------------------------------------------------------------- /src/test/test_analyser.py: -------------------------------------------------------------------------------- 1 | """ 2 | Unit tests for Analyser 3 | 4 | AUTHORS: 5 | 6 | - Bill (bill@equalit.ie) 2013: initial version 7 | """ 8 | from multiprocessing import Process 9 | 10 | import unittest 11 | from os.path import dirname, abspath 12 | from os import getcwd, chdir 13 | import sys 14 | 15 | try: 16 | src_dir = dirname(dirname(abspath(__file__))) 17 | except NameError: 18 | #the best we can do to hope that we are in the test dir 19 | src_dir = dirname(getcwd()) 20 | 21 | sys.path.append(src_dir) 22 | 23 | from analysis.experimentor import Experimentor 24 | from tools.learn2bantools import Learn2BanTools 25 | 26 | class BasicTest(unittest.TestCase): 27 | l2btools = Learn2BanTools() 28 | experiment_set = ({'regex_filter_id': 1L, 'testing_log': 'testing.log', 'kernel_type': 'linear', 'training_log': 'training.log', 'norm_mode': 'individual', 'id': 2L},) 29 | 30 | def nontest_analyser(self): 31 | self.l2btools.load_train2ban_config() 32 | experiment_set = self.l2btools.retrieve_experiments() 33 | for exp in experiment_set: 34 | p = Process(target=Analyser().run_experiments(exp)) 35 | p.start() 36 | 37 | def test_l2b_experiment(self): 38 | self.l2btools.load_train2ban_config() 39 | for exp in self.experiment_set: 40 | cur_experimentor = Experimentor(exp, self.l2btools) 41 | cur_experimentor.run_l2b_experiment(0.70, []) 42 | 43 | if __name__ == "__main__": 44 | unittest.main() 45 | -------------------------------------------------------------------------------- /src/test/test_ats_record_digest.py: -------------------------------------------------------------------------------- 1 | """ 2 | Unit tests for digesting the ATS records 3 | 4 | AUTHORS: 5 | 6 | - Vmon (vmon@equalit.ie) 2012: initial version 7 | """ 8 | import unittest 9 | from os.path import dirname 10 | from os import getcwd, chdir 11 | import sys 12 | 13 | try: 14 | src_dir = dirname(dirname(abspath(__file__))) 15 | except NameError: 16 | #the best we can do to hope that we are in the test dir 17 | src_dir = dirname(getcwd()) 18 | 19 | sys.path.append(src_dir) 20 | 21 | #adding the src dir to the path for importing 22 | 23 | from ip_sieve import IPSieve, ATSRecord 24 | from tools.apache_log_muncher import parse_line as parse_apache_line 25 | 26 | class KnownValues(unittest.TestCase): 27 | known_values = (('0.0.0.0 - [28/Sep/2012:16:14:01 -0800] "GET /assets/ico/hr-63567a98ba59eebda09903edeec1ff93.gif HTTP/1.1" http www.kavkaz-uzel.ru 304 0 "Mozilla/5.0 (X11; Linux x86_64; rv:12.0) Gecko/20100101 Firefox/12.0" TCP_IMS_MISS - www.kavkaz-uzel.ru 319 http://www.kavkaz-uzel.ru/assets/ico/hr-63567a98ba59eebda09903edeec1ff93.gif', 1348863241),) 28 | 29 | def test_correct_seconds(self): 30 | for cur_value in self.known_values: 31 | cur_rec_dict = parse_apache_line(cur_value[0]) 32 | test_record = ATSRecord(cur_rec_dict) 33 | assert(cur_value[1] == test_record.time_to_second()) 34 | 35 | # class BasicTests(unittest.TestCase): 36 | # log_files = ("deflect_test.log",) 37 | # test_ip_sieve = IPSieve() 38 | # test_ip_feature_db = {} 39 | 40 | # def test_ip_sieve_parse(self): 41 | # set_trace() 42 | # for cur_log_file in self.log_files: 43 | # self.test_ip_sieve.set_log_file(cur_log_file) 44 | # self.test_ip_sieve.parse_log() 45 | 46 | if __name__ == "__main__": 47 | unittest.main() 48 | -------------------------------------------------------------------------------- /src/test/test_features.py: -------------------------------------------------------------------------------- 1 | """ 2 | Unit tests for features 3 | 4 | AUTHORS: 5 | 6 | - Vmon (vmon@equalit.ie) 2012: initial version, unit tests for average, variance 7 | """ 8 | 9 | import unittest 10 | from os.path import dirname 11 | from os import getcwd, chdir 12 | import sys 13 | import cProfile 14 | import datetime 15 | 16 | 17 | try: 18 | src_dir = dirname(dirname(__file__)) 19 | if not src_dir: src_dir = "/home/vmon/doc/code/deflect/learn2ban/src" 20 | except NameError: 21 | #the best we can do to hope that we are in the test dir 22 | src_dir = dirname(getcwd()) 23 | 24 | #adding the src dir to the path for importing 25 | sys.path.append(src_dir) 26 | 27 | from ip_sieve import IPSieve 28 | from features.src.learn2ban_feature import Learn2BanFeature 29 | from features.src.feature_average_request_interval import FeatureAverageRequestInterval 30 | from features.src.feature_variance_request_interval import FeatureVarianceRequestInterval 31 | from features.src.feature_cycling_user_agent import FeatureCyclingUserAgent 32 | from features.src.feature_html_to_image_ratio import FeatureHtmlToImageRatio 33 | from features.src.feature_request_depth import FeatureRequestDepth 34 | from features.src.feature_HTTP_response_code_rate import FeatureHTTPResponseCodeRate 35 | from features.src.feature_payload_size_average import FeaturePayloadSizeAverage 36 | from features.src.feature_request_depth_std import FeatureRequestDepthStd 37 | 38 | class KnownValues(unittest.TestCase): 39 | pass 40 | 41 | class BasicTests(unittest.TestCase): 42 | log_files = (src_dir+"/test/deflect_test.log", src_dir+"/test/deflect.log_cool1.20120810_five_percent.log")#src_dir+"/test/deflect.log_cool1.20120810.23h59m50s-20120812.00h00m00s.old" ) 43 | #log_files = (src_dir+"/tests/deflect_test.log", src_dir+"/tests/deflect_test.log") 44 | test_ip_sieve = IPSieve() 45 | test_ip_feature_db = {} 46 | def __init__(self): 47 | pass 48 | def test_ip_sieve_parse(self): 49 | for cur_log_file in self.log_files: 50 | self.test_ip_sieve.add_log_file(cur_log_file) 51 | self.test_ip_sieve.parse_log() 52 | 53 | def test_all_features(self): 54 | for cur_log_file in self.log_files: 55 | self.test_ip_sieve.add_log_file(cur_log_file) 56 | self.test_ip_sieve.parse_log() 57 | 58 | for CurrentFeatureType in Learn2BanFeature.__subclasses__(): 59 | cur_feature_tester = CurrentFeatureType(self.test_ip_sieve, self.test_ip_feature_db) 60 | cur_feature_tester.compute() 61 | 62 | print self.test_ip_feature_db 63 | 64 | def run_tests(self): 65 | """ 66 | needs a function to feed to the profiler 67 | """ 68 | self.test_ip_sieve_parse(); 69 | self.test_all_features(); 70 | 71 | def run_foo(): 72 | my_tester = BasicTests(); 73 | my_tester.run_tests() 74 | 75 | def profile_features(): 76 | 77 | utc_datetime = datetime.datetime.utcnow() 78 | utc_datetime.strftime("%Y-%m-%d-%H%MZ") 79 | profile_log = 'profile_features_' + str(utc_datetime) +".prof" 80 | 81 | cProfile.run('run_foo()', profile_log) 82 | #subprocess.call(['/usr/lib/python2.7/cProfile.py', '-o', profile_log, '../test_features.py']); 83 | 84 | if __name__ == "__main__": 85 | profile_features() 86 | #unittest.main() 87 | -------------------------------------------------------------------------------- /src/test/test_trainer.py: -------------------------------------------------------------------------------- 1 | """ 2 | Unit tests for Train2Ban 3 | 4 | AUTHORS: 5 | 6 | - Vmon (vmon@equalit.ie) 2012: initial version 7 | """ 8 | 9 | import unittest 10 | import numpy as np 11 | 12 | from os.path import dirname, abspath 13 | from os import getcwd, chdir 14 | import sys 15 | 16 | try: 17 | src_dir = dirname(dirname(abspath(__file__))) 18 | except NameError: 19 | #the best we can do to hope that we are in the test dir 20 | src_dir = dirname(getcwd()) 21 | 22 | sys.path.append(src_dir) 23 | 24 | #train to ban 25 | from tools.learn2bantools import Learn2BanTools 26 | from tools.training_set import TrainingSet 27 | from train2ban import Train2Ban 28 | 29 | class KnownValues(unittest.TestCase): 30 | pass 31 | 32 | class BasicTests(unittest.TestCase): 33 | TEST_LOG_FILENAME = src_dir + "/test/training_1000hit.log" 34 | TEST_LOG_ID = 0 35 | TEST_REGEX = "^ .*Firefox/1\.0\.1" 36 | 37 | def setUp(self): 38 | """Call before every test case.""" 39 | self.l2btools = Learn2BanTools() 40 | self.l2btools.load_train2ban_config() 41 | 42 | self.l2btools.retrieve_experiments() 43 | self.log_files = [[self.TEST_LOG_ID, self.TEST_LOG_FILENAME]] 44 | 45 | #we are testing trainin 46 | self.test_trainer = Train2Ban(self.l2btools.construct_svm_classifier()) 47 | self.test_trainer._training_set = TrainingSet() #clean the training set 48 | self.test_trainer.add_to_sample(self.l2btools.gather_all_features([self.TEST_LOG_FILENAME])) 49 | 50 | def test_normalization(self): 51 | self.test_trainer.normalise('sparse') 52 | self.test_trainer.normalise('individual') 53 | 54 | def test_training(self): 55 | self.test_trainer.normalise('individual') 56 | #indicate bad ips 57 | self.test_trainer.add_malicious_history_log_files([[self.TEST_LOG_ID, self.TEST_LOG_FILENAME]]) 58 | 59 | self.test_trainer.add_bad_regexes(self.TEST_LOG_ID, [self.TEST_REGEX]) 60 | self.test_trainer.mark_and_train() 61 | 62 | ip_index, data, target = self.test_trainer.get_training_model() 63 | 64 | bad_ips = [ip_index[cur_target][0] for cur_target in range(0,len(target)) if target[cur_target]] 65 | 66 | print "Bad IPs:",bad_ips 67 | #test pickling of model 68 | import datetime 69 | utc_datetime = datetime.datetime.utcnow() 70 | utc_datetime.strftime("%Y-%m-%d-%H%MZ") 71 | filename = 'l2b_pickle_'+str(utc_datetime) 72 | result = self.test_trainer.save_model(filename) 73 | self.test_trainer.save_model(filename+".normal_svm_model", "normal_svm") 74 | result = self.test_trainer.load_model(filename) 75 | 76 | #sizzeling for the sake of david's little kind heart 77 | # import numpy as np 78 | # import pylab as pl 79 | 80 | # X = [cur_row[0] for cur_row in data] 81 | # Y = [cur_row[4] for cur_row in data] 82 | 83 | # Z = self.tester_svm.fit(zip(X,Y), target) 84 | # pl.figure(0) 85 | # pl.clf() 86 | # pl.scatter(X, Y, c=target, zorder=10, cmap=pl.cm.Paired) 87 | # pl.axis('tight') 88 | 89 | # x_min = min(X) 90 | # x_max = max(X) 91 | # y_min = min(Y) 92 | # y_max = max(Y) 93 | 94 | # XX, YY = np.mgrid[x_min:x_max:200j, y_min:y_max:200j] 95 | # Z = self.tester_svm.decision_function(np.c_[XX.ravel(), YY.ravel()]) 96 | 97 | # # Put the result into a color plot 98 | # Z = Z.reshape(XX.shape) 99 | # pl.pcolormesh(XX, YY, Z > 0, cmap=pl.cm.Paired) 100 | # pl.contour(XX, YY, Z, colors=['k', 'k', 'k'], 101 | # linestyles=['--', '-', '--'], 102 | # levels=[-.5, 0, .5]) 103 | 104 | # pl.title("Training result") 105 | # pl.show() 106 | 107 | def test_subset_training(self): 108 | #we are testing the training 109 | scoring_svm = self.test_trainer._ban_classifier 110 | 111 | #indicate bad ips 112 | self.test_trainer.add_malicious_history_log_files(self.log_files) 113 | self.test_trainer.add_bad_regexes(self.TEST_LOG_ID, (self.TEST_REGEX,)) 114 | #retrieve the training set 115 | self.test_trainer.mark_bad_target() 116 | 117 | marked_training_set = self.test_trainer.get_training_set() 118 | 119 | #now we break the set into two sets 120 | print len(marked_training_set) 121 | first_halver = np.array([i <= len(marked_training_set)/2 for i in range(0, len(marked_training_set))]) 122 | 123 | first_half = marked_training_set.get_training_subset(case_selector = first_halver) 124 | 125 | second_halver = np.logical_not(first_halver) 126 | second_half = marked_training_set.get_training_subset(case_selector = second_halver) 127 | print len(second_half) ,len(first_half) 128 | 129 | assert(abs(len(second_half) - len(first_half)) <= 1) 130 | 131 | #predicting the second half 132 | self.test_trainer.set_training_set(first_half) 133 | self.test_trainer.train() 134 | 135 | print "Predicting second half using first half. Score: ", scoring_svm.score(second_half._ip_feature_array, second_half._target) 136 | 137 | #predicting the first half 138 | self.test_trainer.set_training_set(second_half) 139 | self.test_trainer.train() 140 | 141 | print "Predicting first half using second half half. Score: ", scoring_svm.score(first_half._ip_feature_array, first_half._target) 142 | 143 | #now choose a random subset of size %10 and train 144 | random_selector, test_selector = self.l2btools.random_slicer(len(marked_training_set), train_portion = 0.1) 145 | self.test_trainer.set_training_set(marked_training_set.get_training_subset(random_selector)) 146 | 147 | test_part = marked_training_set.get_training_subset(case_selector = test_selector) 148 | print "Predicting %90 of data using %10 random cases. Score: ", scoring_svm.score(test_part._ip_feature_array, test_part._target) 149 | 150 | #TODO test feature subselection 151 | 152 | if __name__ == "__main__": 153 | unittest.main() 154 | -------------------------------------------------------------------------------- /src/tools/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/equalitie/learn2ban/d45420c9d2eea2c81972c778a96a2ca42b318b6f/src/tools/__init__.py -------------------------------------------------------------------------------- /src/tools/apache_log_muncher.py: -------------------------------------------------------------------------------- 1 | import re 2 | import glob 3 | from os.path import dirname 4 | from os import getcwd 5 | months = { 6 | 'Jan':'01', 7 | 'Feb':'02', 8 | 'Mar':'03', 9 | 'Apr':'04', 10 | 'May':'05', 11 | 'Jun':'06', 12 | 'Jul':'07', 13 | 'Aug':'08', 14 | 'Sep':'09', 15 | 'Oct':'10', 16 | 'Nov':'11', 17 | 'Dec':'12'} 18 | 19 | parts = [ 20 | r'(?P\S+)', # host %h 21 | r'(?P\S+)', # user %u 22 | r'\[(?P\S{2})\/(?P\S{3})\/(?P\S{4}):(?P