scieee AI-readable full text Open interactive document viewer

Detection of malware traffic with NetFlow

Codina Poquet, Joël

Abstract

Traffic classification has always been a fundamental aspect regarding the identification of applications on the network that has allowed to apply different actions or services depending on their type, such as best-effort delivery or discarding the traffic in case of a malicious application. The cons

Full text

Author: Joël Codina Poquet Director: Pere Barlet-Ros Date: 26/10/2017 Detection of malware traffic with Netflow Bachelor Degree in Informatics Engineering, Information Technology Abstract Traffic classification has always been a fundamental aspect regarding the identification of applications on the network that has allowed to apply different actions or services depending on their type, such as best-effort delivery or discarding the traffic in case of a malicious application. The constant growth of the internet and the relentless pace of change on the applications have made traditional methods no longer feasible. Nonetheless, the application of machine learning methods has gathered strength over time. In this thesis, we analyze different algorithms with the aim to obtain a good classifier and design a solution capable of achieving an acceptable performance when identifying malware traffic in a real-time environment using the information provided by Netflow protocol. Keywords: Traffic analysis, Malware, Netflow, Machine Learning, C5.0, Random Forest, Naïve Bayes. Acknowledgement I would like to thank my thesis’ director Dr. Pere Barlet-Ros for giving me the opportunity to do this investigation project and guiding me through the process. This work wouldn’t have been possible without his support. Also thanks to all my family that has given me strengths during these 4 years path. Special gratitude to all my friends for the amazing times and all the unbelievable companionship granted during the degree. Content 1. Context .................................................................................................................................. 1 1.1 Introduction............................................................................................................... 1 1.2 Traffic classification ................................................................................................... 2 1.3 Stakeholders .............................................................................................................. 4 2. Formulation of the problem .................................................................................................. 5 2.1 Problem ........................................................................................................................... 5 2.2 Objectives ........................................................................................................................ 5 3. Project Management ............................................................................................................. 7 3.1 Project Scope ................................................................................................................... 7 3.2 Methodology and Rigor ................................................................................................... 7 3.3 Time schedule ................................................................................................................. 9 3.3 Resources ...................................................................................................................... 11 3.5 Alternatives and action plan ......................................................................................... 13 3.6 Cost estimation ............................................................................................................. 13 3.7 Control management .................................................................................................... 16 4 Sustainability ........................................................................................................................ 17 4.1 Economic ....................................................................................................................... 17 4.2 Social ............................................................................................................................. 17 4.3 Environmental ............................................................................................................... 17 5. Data acquisition ................................................................................................................... 19 5.1 Obtaining normal traffic captures ................................................................................. 19 5.2 Obtaining malware traffic captures .............................................................................. 19 6. Data preparation ................................................................................................................. 21 6.1 Capture processing ........................................................................................................ 21 6.2 Data Cleaning ................................................................................................................ 22 6.3 IP Selection .................................................................................................................... 23 6.4 The Dataset ................................................................................................................... 23 7. Algorithms Used .................................................................................................................. 25 7.1 Naïve Bayes ................................................................................................................... 25 7.2 Decision Trees ............................................................................................................... 26 8. Model Evaluation ................................................................................................................ 30 8.1 Metric ............................................................................................................................ 30 8.2 K-fold Cross Validation .................................................................................................. 30 8.3 Binary Response ............................................................................................................ 31 8.4 Multiclass Response ...................................................................................................... 37 9. Optimization ........................................................................................................................ 41 9.1 Blacklist Concept ........................................................................................................... 41 9.2 Using IP blacklists for optimization ............................................................................... 41 9.4 Implementation ............................................................................................................. 43 9.5 Optimization Results ..................................................................................................... 44 10. Conclusions. ...................................................................................................................... 47 10.1 Summary ..................................................................................................................... 47 10.2 Future Work ................................................................................................................ 47 Appendices .............................................................................................................................. 48 Gantt Diagram ......................................................................................................................... 49 11. References ......................................................................................................................... 50 Tables Index Table 3.1: Time estimation per task ............................................................................................ 11 Table 3.2: Direct costs of each task according to Gantt chart .................................................... 13 Table 3.3: Cost per hour of each role .......................................................................................... 14 Table 3.4: Hardware costs estimation......................................................................................... 14 Table 3.5: Indirect Costs .............................................................................................................. 15 Table 3.6: Final budget estimation .............................................................................................. 16 Table 4.1: Sustainability Matrix ................................................................................................... 18 Table 5.1: List of Malware Captured Used for the Dataset ......................................................... 20 Table 6.1: Binary Dataset after under-sampling ........................................................................ 24 Table 6.2: Multiclass Dataset after under-sampling ................................................................... 24 Table 7.1: Versatile machine learning algorithms and factors. ................................................... 25 Tables of Figure Figure 1.1: Barplot of the malware traffic evolution since 1984 .................................................. 1 Figure 1.2: Machine learning Traffic classification ........................................................................ 3 Figure 3.1: Phases of Iterative Waterfall methodology .............................................................. 14 Figure 6.1: Nfdump command used to convert nfcapd files. ...................................................... 21 Figure 6.2: Steps to transform .pcap to a CSV Netflow dataset. ................................................. 22 Figure 6.3: Summary of data before cleaning. ............................................................................ 22 Figure 6.4: Program that selects the Public IP from two columns .............................................. 23 Figure 7.1: Example of a decision tree where leaves are the class. ............................................ 27 Figure 7.2: Example of how random forests make a decision. ................................................... 28 Figure 7.3: Random Forest in Pseudo-code. ............................................................................... 28 Figure 8.1: K-fold Cross Validation Pseudo-code. ....................................................................... 31 Figure 8.2: 10-fold Cross Validation of Naïve Bayes. .................................................................. 32 Figure 8.3: Accuracy of Random Forest for different number of decision trees.. ...................... 33 Figure 8.4: Linear relation between time and number of decision trees.. ................................. 33 Figure 8.5: 10-fold Cross Validation of Random Forest with Number of Trees = 300.. .............. 34 Figure 8.6: Variable Importance for Random Forest.. ................................................................ 35 Figure 8.7: Accuracy of Boosted C5.0 Decision Tree.. ................................................................. 36 Figure 8.8: 10-fold Cross Validation of Boosted C5.0 with Number of Trials = 20... ................... 36 Figure 8.9: Comparison for different models’ performance for binary class.............................. 37 Figure 8.10: Confusion matrix of Multiclass Naïve Bayes.... ....................................................... 38 Figure 8.11: Confusion matrix of Multiclass Random Forest n = 10.... ....................................... 38 Figure 8.12: Confusion matrix of Multiclass Random Forest n = 300.... ..................................... 38 Figure 8.13: Confusion matrix of Multiclass C5.0 without boosting.... ....................................... 39 Figure 8.14: Confusion matrix of Multiclass Boosted C5.0 with 20 trials...... ............................. 39 Figure 8.15: Comparison for different models’ performance for multiclass..... ......................... 39 Figure 9.1: Blacklist optimization workflow..... ........................................................................... 42 Figure 9.2: Accuracy over % Checked Flows...... ......................................................................... 45 Figure 9.3: Time spent over % of Checked Traffic...... ................................................................. 46 1. CONTEXT 1 1. Context 1.1 Introduction Malware, short for malicious software, is a type of software that wants to gather sensitive information, gain access of the computer, display unwanted advertising or destroy all what is inside the computer. This term includes all the intrusive and dangerous software like computer viruses, worms, trojan horses, ransomware, spyware, adware, scareware… In a world where malware traffic has increased every year [1] (Figure 1.1), there is a need for organizations to prevent any type of malicious software inside their systems and laptops in order to protect their critical information. This final degree project of the Facultat de Informàtica de Barcelona (Universitat Politècnica de Catalunya) aims to find a proper model that uses Netflow features and is able to detect and classify malware traffic with them. Figure 1.1: Barplot of the malware traffic evolution since 1984 Routers and switches, that support Cisco standard Netflow version 5, can collect network traffic statistics in any interface with Netflow enabled and give us the information summarized in IP Flows. An IP Flow is a unidirectional sequence of packets that share a set of 5 up to 7 IP packet values (Ingress interface, Source IP address, Destination address, IP protocol, Source port, Destination port and IP Type of Service). 1. CONTEXT 2 1.2 Traffic classification Network traffic classification is used to identify applications, protocols and content that exist in a network [2]. Some actions that could be done after having classified network traffic could be monitor, analyze, optimize, control or discovery with the finality of improving the network performance. After classifying the traffic, the router could adopt different policies depending on the class they have. For example, to guarantee a good quality service in case of streaming media, to discard flows tagged as malware or to provide a best-effort delivery. 1.2.1 State of art Traffic classification is an automated process that categorizes the network traffic making use of some parameters like port numbers or protocol. We are going to make a brief explanation of three traditional means that have been used to perform the classification: Port based, Deep Packet Inspection and statistical analysis. The first approach is port based classification that has been used in several papers [3] which are based on the correlation between the transport layer’s port number and the application or group of applications. They make use of well-known ports which have a range between 1 and 1023 since 1992 (Before it was from 1 to 255). Port descriptive information is managed by the Internet Assigned Numbers authority (IANA). They also used information of non-well-known ports used by many applications, whose information is registered in RFCs like the RFC1700 (now obsolete). The approach is supported by many devices and it doesn’t require information about the application-layer payload, which doesn’t compromise users’ privacy. As it only requires from port information, this method is fast and low resources consuming. However, there are a lot of applications that use dynamic ports so it is only useful for applications and services that have a fixed port assigned, which are easy to cheat by changing the port number on the system. After knowing that port based inspection is not suitable in a lot of scenarios, we introduce the second approach that would be Deep Packet Inspection (DPI). This method consists on inspecting the whole packet payload but also the headers like the ports, flags, protocol, etc providing a higher accuracy than the previous one. This method searches for signatures inside the packets that could identify the flow as a certain application. Even if this method seems to be quite good, it faces some important problems. Analyzing every packet’s payload is slow and high resource-consuming. Also, nowadays there is more encrypted traffic than before; this makes the signatures almost impossible to be identified. Moreover, the signature database should be updated frequently as applications change very quickly. This method has also an ethical impact as it is used in some countries as China or Iran to censor pages and has been criticized recently because people think that analyzing the content of a packet attempts against their privacy. 3. PROJECT MANAGEMENT 9 3.2.3 Validation meetings In favor of ensuring the quality of the project, there will be meetings scheduled with the final project director. He will check that all is going as planned and there are not deviations in the process. 3.3 Time schedule The time expected for the realization of this project is 4 months in the period compressed between February 2017 and June 2017. This document presents what project management tasks should be done and when. 3.3.1 Task description All tasks will take all human and hardware resources stated below for their accomplishment. 3.3.1.1 Project Management It corresponds to the different subtasks and deliverables of the subject GEP. To accomplish this task, 7 deliverables that have different dedication times. The different subtasks are the following: 1) Context and scope of the project (24.5 hours) 2) Project planning (8.25 hours) 3) Budget and sustainability (9.25 hours) 4) First oral presentation (6.25 hours) 5) Specialization competence (8.5 hours) 6) Oral presentation and final document (18.25 hours) Additional resources needed: Microsoft Office, Gantter, FIB’s racó and UPC’s Atenea. 3.3.1.2 Documentation and learning process The student should get familiar with the software tools, the working environment and gain the enough technical knowledge to make a good quality project. To do that, some learning time is required. This task can be parallelized with the Project Management one. 3.3.1.3 Data acquisition It consists in the acquisition of data by capturing network traffic. This task has two subtasks: 3. PROJECT MANAGEMENT 10  Benign traffic capture: Acquisition of benign traffic by capturing it from the network.  Malign traffic generation and capture: As malign traffic is not the usual one, it is needed to generate it with malware software. After that, capturing it with the same process as the benign traffic. It will take more time to capture packets than benign ones. Resources: softflowd and internet connection. 3.3.1.4 Data preparation Also known as “data wrangling”, this task involves all the preprocessing of the dataset: Export of the data, cleaning of missing, featuring, reshaping the data to make it readable for the data mining software and the user. Resources: RStudio will be used for the preprocessing. 3.3.1.5 Modeling The best statistical model is chosen in this task. There are some subtasks that will be done to achieve this goal.  Hypothesis & Modeling: In this step, machine learning techniques will be applied. The separation into training, validation and test sets.  Evaluation & Interpretation: The model created is evaluated and compared with other models previously created. These subtasks can be repeated as many times as needed until having the best performing model. 3.3.1.6 Optimization This task is optional depending on the results reported on the previous task. It consists of studying and implementing optimizations to the model in the interest of making it better and more robust. 3. PROJECT MANAGEMENT 11 3.3.2 Time estimation Table 3.1 showsthe time in hours of each project task. Table 3.1: Time estimation per task 3.3 Resources 3.3.1 Human Resources The most important resource to a project is its people. In this project, only one worker will be required. This person is doing all tasks to complete the project. To be able to finish it in time, the worker should have some previous knowledge in data mining and networking for the sake of interpreting the results. The time spent for the worker in the project in a week will be between 20 – 30 hours depending on the amount of work needed to be done or if there are long waiting times for some tasks that require high hardware resources that the worker cannot do anything until they are finished. However, if there is a huge workload at some point, spending more hours is also contemplated. 3.3.2 Hardware Resources 1) Acer Aspire V5 laptop with a 15.6" screen: Hardware tool necessary to develop the project. It is going to be used for all tasks that require a computer to be done. a. OS: Windows 10 and Ubuntu 16 3. PROJECT MANAGEMENT 12 b. Processor: Intel Core i5-3317U 1.70GHz x64 c. Memory: 8GB d. Capacity: 256GB SSD 2) LG 32” screen (optional): Hardware tool that helps reducing the time spent when working with extended screen. 3) Router: That provides internet connection to be able to capture packets in the dataset construction task. 3.3.3 Software Resources 1) Softflowd: It is a flow-based network traffic analyzer that allows exporting data in Cisco Netflow. 2) Nfcapd: is the Netflow capture daemon of the nfdump tools. It reads Netflow data from the network and stores it into files. The output file is automatically rotated and renamed every n minutes - typically 5 min - according the timestamp YYYYMMddhhmm of the interval e.g. nfcapd.201107110845 contains the data from July 11th 2011 08:45 onward. 3) Weka: It is a collection of machine learning algorithms for data mining tasks that can be applied to a dataset. It also allows preprocessing and cleaning. It’s useful to test algorithms in a faster way. 4) RStudio: It is an IDE for R programming language that allows executing R scripts and generating markdowns. 5) Microsoft Azure Machine Learning Studio: Online machine learning tool that allows executing data mining algorithms in the cloud. Useful when R or Weka don’t have enough hardware resources or the algorithm takes a lot of time. 6) Gantter: It is a webpage that allows creating Gantt diagrams, needed for the time schedule representation of the project. 7) Gmail: Email tool used to maintain a communication between the director and the student during the project. 8) Microsoft Office: Tools that will be used to write the project memory, do the tables, calculate the costs and hours and do the presentations. 3. PROJECT MANAGEMENT 13 3.5 Alternatives and action plan During the development of the project, some deviations might occur because of the number of hours for one task is insufficient and requires more time than the expected. It is possible that the student requires more time for the “welcome aboard” and get familiar with the software tools could affect the project negatively. However, this would be only in the initial part of the project. Also, the problems stated on the previous report could cause delays in the tasks. These delays have already been calculated and the deadlines have been adjusted with the goal of having an extra time margin. On the one hand, the fact that the project is being done by only one person, it allows to make a more flexible time planning. If there is a task that has been finished before the expected time, the student could go on with the next one without having to wait anyone. On the other hand, if he requires more time to finish one task, he could take hours of another task in order to guarantee the finalization of the project in time. 3.6 Cost estimation In this section, there is an estimation of the project economical costs. As the project is not developing anything material, production costs have been excluded. The estimation is going to be done based on the human resources, hardware, software and other costs. The cost estimation has been linked to task description according to Gantt chart. 3.6.1 Human Resources As the project is going to be developed by only one person, who is doing all the tasks, he is going to adopt different roles along the project. These roles have different costs per hour depending on their responsibility and difficulty. We assume that the people who are contracted have some experience, so the learning task will not be contemplated in the costs. Task Role Cost estimation Project Manager Network Engineer Data Scientist Project management 75h 0h 0h 3.000 € Data acquisition 0h 60h 0h 2.280 € Data preparation 0h 5h 10h 540 € Modeling 0h 0h 170h 5.950 € Model optimization 0h 10h 20h 1.080 € Documentation 50h 7h 10h 2.616 € Total 125h 82h 210h 15.466 € Table 3.2: Direct costs of each task according to Gantt chart 3. PROJECT MANAGEMENT 14 Role Project Manager Network Engineer Data Scientist Cost per hour 40€/h 38€/h 35€/h Table 3.3: Cost per hour of each role 3.6.2 Hardware Apart from the human resources costs, there are also costs associated to hardware and material. For this project, only a computer for computational calculus and a router that provides internet connection are essentially needed. However, in the interest of reducing human resources costs, a second monitor (the laptop has one integrated) has been added to reduce tasks time when working dual screen [14]. Product Units Price Useful life Amortization/hour Hours Total amortization Total Cost Acer Aspire V5 1 750 € 5 0,08 € 417 31,27 € 750 € LG 32" Monitor 1 300 € 6 0,03 € 417 10,42 € 300 € Router 1 40 € 6 0,00 € 60 0,18 € 40 € Total 1.090 € Table 3.4: Hardware costs estimation. For the amortization per hour, it has been considered that a year has 250 working days and for each day there are 8 hours which the people work. For modeling simulations, sometimes leaving the computed turned on all the day is necessary but this has not been contemplated as it wouldn’t be the usual thing. 3.6.3 Software licenses Almost all programs in this project are Open Source and can be used without any additional costs. The only private software is Microsoft Windows 10, which is already included in the computer price listed above, and the suite Microsoft Office 2016 that costs 149€. For the traffic capture, Ubuntu OS and softflowd will be used and both are free. The other software resources used for project management and modeling (RStudio, Weka, Microsoft Azure Machine Learning Studio, Gantter) are also free. 3. PROJECT MANAGEMENT 15 The total costs associated to software licenses are 149€. 3.6.4 Other costs In the project, there are other costs that don’t enter in hardware, software nor human resources costs categories. These other costs could be classified as following: 1) Indirect costs: In this category, all costs related with the location where the project takes place are included. They are intangible products but necessary for any worker that needs to work in an office. The office is rented for the duration of the project. For the costs, the duration of the project has been considered (4 months) and has been used to calculate the estimated costs of the following table. Product Price /month Estimate Cost Light 40 € 160 € Internet 31 € 124 € Office 400 € 1.200 € Water 20 € 80 € Total 491 € 1.564 € Table 3.5: Indirect Costs 2) Contingency: In the risk section it can be seen that a project has problems and incidences that could cause the project costs increase respect the estimated ones. In order to have some margin and prevent it, it is important to reserve an amount of money for these cases. The amount of money saved will be the 15% of the sum of all the previous costs, direct and indirect ones. In this case we would have a contingency of: 1.564€+149€+15.466€+1.090€ = 18.269€ 15% of 18.269€ = 2.740€ 3) Other incidents: In this section, other incidents that may appear during the project are taken into account. One of the main problems could be that the computer breaks and stops working. This incidence is critical, as the computer is the main tool of the project. Depending on the level of breaking, in would be needed between 2 – 5 hours of an IT Administrator, who works for 20€/hour (Maximum 100€), to fix it or the purchasing of a new computer, which may cost an additional 750€. As the project needs to be finished in 4 months, having to send the computer to the manufacturer for fixing it is not an option, as it could take too much time. There could be also a problem with the duration of the project. It could be that the data scientist need more time in exchange for finishing its task. It may need 20 more hours that cost 35h/hour * 20 hours = 700€. Total: 800€ 3. PROJECT MANAGEMENT 16 3.6.5 Final budget To sum up, it is necessary to reflect all the calculated costs together and see what the final estimated costs for the project are. This project is Open Source because is part of the final year project of a student and doesn’t aim to take profit of it, that is why profit margin has not been taken into consideration. Concept Cost Human Resources 15.466 € Hardware 1.090 € Software Licenses 149 € Indirect Costs 1.564 € Contingency 2.740 € Other Incidents 800 € Total 21.809 € Table 3.6: Final budget estimation 3.7 Control management The control management will be done at human resources level, as the other costs are very fixed and costs are not as big as the human ones. There will be scheduled sessions with the project director with the intention of having a weekly control of what is being done and by whom. At the end of every week, each worker (in this case only one) should present an imputation of hours sheet where it is indicated what he has done every day and in which task has been working. This is important in order to avoid time deviations and see the current status of the project. If the project requires more hours, money from other incidences and on the last instance from contingency could be taken to pay these extra hours. There is enough money to cover a large deviation in the worst case. 4 SUSTAINABILITY 17 4 Sustainability 4.1 Economic The costs have been assessed on the previous chapter. This project is viable as it doesn’t have production costs because it doesn’t produce any tangent product. It can be seen that almost a 75% of the costs are taken by the human resources, so the project is pretty competitive. As it is a research project, it could be replicated for similar researches in this field and escalated conveniently according to their resources. 4.2 Social This project is important for two reasons from the social point of view:  People, who don’t have enough knowledge to be saved from hackers, may be infected with malware and see how all their personal information is stolen and in the worst case, leaked. The implementation of the results of this project in an ISP level could drastically decrease the malware traffic on the internet and protecting end-user from them.  Nowadays, with the recent scandals, internet privacy has gained a more importance as people have realized that their personal information is not safe. Actual monitoring packet tools make use of packet payload inspection (packet content), which means that if it is not encrypted, the information is accessed. However, the method investigated in this project avoids this packet inspection, and that is positive from a user privacy point of view. 4.3 Environmental Even if this project doesn’t have a production goal, the application of the results could reduce the amount of hardware and computational costs that are spent only for deep inspection packet. There is not public information about neither how much energy is spent on malware detection nor how many computers are abandoned after being infected by malware, but it could be said that globally the environmental impact would be positive. The malware detection would take less hardware resources; this fact has a direct correlation with the energy spent on the process. While having less abandoned PCs in early stages would help to reduce ecological footprint. 4 SUSTAINABILITY 18 Project Development Exploitation Risks Environmental Consumption Design Ecological footprint Environmental Risks 7 14 0 Economic Project Bill Viability plan Economic risks 4 10 -3 Social Personal impact Social impact Social risks 8 15 0 Sustainability range 19 39 -3 55 Table 4.1: Sustainability Matrix 7. ALGORITHMS USED 25 7. Algorithms Used In this section we are going to introduce the supervised algorithms that have been chosen to be applied on the dataset with the purpose of creating the models. The selection of the algorithms has been done by having into account factors like if they supported Multi class (Necessary for our classification), their interpretability and if they accepted a mixed predictor. The following table shows the algorithms that have been proven to be versatile applied in many data science projects and they have been used on past literature regarding traffic classification. Table 7.1: Versatile machine learning algorithms and factors. We wanted an algorithm that had multiclass support but easier to interpret, so k-Nearest Neighbor and SVM (Support Vector Machines) were discarded. The following supervised algorithms have been implemented:  Naïve Bayes  Random Forest  C5.0 Decision Tree 7.1 Naïve Bayes Naïve-Bayes is a method based on the Bayesian theorem. It analyses the relationship between each feature of each observation with the class of that instance to compute a conditional probability between the feature values and the class. Let’s assume X is a vector of characteristics (𝑥1,𝑥2,…,𝑥𝑛), for learning we estimate the likelihood of our data or probability that observation (𝑥1,𝑥2,…,𝑥𝑛) belongs to class 𝑐𝑖 [𝑥𝑖 𝑖𝑠 𝑓𝑒𝑎𝑡𝑢𝑟𝑒 𝑖 𝑜𝑓 𝑜𝑏𝑠𝑒𝑟𝑣𝑎𝑡𝑖𝑜𝑛 𝑥]: 𝑝(𝑥1,𝑥2,…,𝑥𝑛|𝑐𝑖) It also calculates the simply proportion of elements in class j, 𝑃(𝑐𝑗). 7. ALGORITHMS USED 26 One of the key points used on Naïve-Bayes method that makes it viable for huge datasets is the assumption that the attributes are independent, so the probability results on the product of the probabilities of each attribute. This assumption makes it easier to compute, getting the following equality: 𝑃(𝑥1,𝑥2,…,𝑥𝑛|𝑐𝑗)= ∏𝑃(𝑥𝑖|𝑐𝑗) 𝑖 For classifying, given an observation (𝑥1,𝑥2,…,𝑥𝑛) we should look for the class that has the maximum probability of belonging to that class, so the class assigned to a new observation is: 𝐶𝑛𝑒𝑤𝑜𝑏𝑠 =argmax 𝑐𝑗∈𝐶 𝑃(𝑥1,𝑥2,…,𝑥𝑛|𝑐𝑗)×𝑃(𝑐𝑗) 𝑃(𝑥1,𝑥2,…,𝑥𝑛)=argmax 𝑐𝑗∈𝐶 𝑃(𝑐𝑗)×∏𝑃(𝑥𝑖|𝑐𝑗) 𝑖 The formula stated above can only be applied if the attributes 𝑋𝑖 are qualitative or nominal. Probabilities are estimated by counting the frequency of a value in a feature. Numerical variables could have a huge number of different cases so a frequency distribution cannot be estimated. In these cases there are two ways to cope with this problem. The first one consists on discretizing or making these numerical variables qualitative dividing them into intervals hence reducing the number of different cases. The second way named kernel density estimation, is modelling the attributes with a continuous probability distribution using multiple Gaussian distributions, which is more effective than just using one. 7.2 Decision Trees The main idea of a decision tree is to understand the relationships in large collections of data, i.e., multiple observations of variables, whose structure is difficult to determine. The main way a decision tree is applied is by using the properties of an observation as questions and going over the tree until we reach a leaf identifying the observation in a certain class. The structure of a decision tree is built by a machine learning algorithm on the training phase. 7. ALGORITHMS USED 27 Figure 7.1: Example of a decision tree where leaves are the class. The algorithms that we are using are based on these decision trees. 7.2.1 Random Forest By their definition [23], random forests are a combination of decision tree predictors such that each tree depends on the values of a random vector sampled independently and with the same distribution for all trees in the forest. Using a random selection of features to split each node gets lower errors compared to Adaboost [24]. For prediction, each decision tree predictor votes for a decision that is pooled with the other decision trees’ responses, getting as definitive the decision with the higher rate. 7. ALGORITHMS USED 28 Figure 7.2: Example of how random forests make a decision. This algorithm is usually more robust against noise when more decision trees are built and, in the same way, the higher the number of decision trees, the higher the accuracy we get. Making more trees has a greater time consuming cost, so we should maximize the trade-off between time/accuracy. Figure 7.3: Random Forest in Pseudo-code. 7. ALGORITHMS USED 29 7.2.2 C5.0 Decision Tree The last method we are going to apply is C5.0 Decision Tree, a successor of the C4.5 Decision tree presented by Quinlain in [25] that has been already used on several papers [http://personals.ac.upc.edu/pbarlet/papers/autonomic-retraining.jnsm2013.pdf] proving its better performance than its antecessor at classifying traffic. Several papers have analyzed it highlighting that this algorithm is faster than the C4.5 algorithm, having shorter training times. It also manages the memory usage more efficiently. Its rule sets have lower error rates on unseen cases and also builds smaller decision trees in comparison with C4.5. Moreover, C5.0 allows us to weight different cases and misclassification types and it includes an option that automatically winnows the attributes to remove those that might be unhelpful. 8. MODEL EVALUATION 30 8. Model Evaluation 8.1 Metric In order to measure the quality of the different models, we need a metric that allows us to compare the different model performances. There are a lot of metrics that could be used for evaluating a machine learning algorithm (RMSE, LogLoss, Accuracy, ROC Curve…). The metric chosen for this project has been the accuracy, which could be expressed in the following way: 𝐴𝑐𝑐𝑢𝑟𝑎𝑐𝑦= 𝑇𝑃+𝑇𝑁 𝑇𝑃+𝑇𝑁+𝐹𝑃+𝐹𝑁 = 𝑇𝑃+𝑇𝑁 𝑇𝑜𝑡𝑎𝑙 𝐹𝑙𝑜𝑤𝑠 where: Assuming the positive class is the Normal traffic and the negative class the malware traffic.  TP (True Positives): The number of correctly identified normal traffic flows.  TN (True Negatives): The number of correctly identified malware traffic flows.  FP (False Positives): The number of incorrectly identified normal traffic flows.  FN (True Negatives): The number of incorrectly identified malware traffic flows. 8.2 K-fold Cross Validation After knowing the metric that we are going to use, we need an estimator to get it. Instead of using the conventional method that would mean splitting the dataset into 70% training and 30% validation, which could cause a significant lost in testing capability, we are using a technique named cross-validation. There are two types of cross-validation: exhaustive and non-exhaustive. The main difference between each other is that exhaustive learn and test all possible ways to divide the original sample into a training and validation set while the non-exhaustive doesn’t compute all the ways of splitting the original sample. We are using a type of non-exhaustive cross validation that is k-fold cross-validation. This method for estimating the accuracy of the models consists on splitting the dataset into k subsets. One single subsample is saved for using it as validation data, while the other k-1 subsets are used for training data. This process is repeated k times while saving a different subset for validation each time. The k results, in this case the accuracy obtained by this process, are averaged to produce a better estimation with a lower variance than a single hold-out set estimator. The advantage of this method over the conventional one is that all data is used for training and testing while each observation is only used once for validation. 8. MODEL EVALUATION 31 Figure 8.1: K-fold Cross Validation Pseudo-code 8.3 Binary Response First of all, we are going to compare the different models and their predictive performance when facing a binary class (Normal or Malware). For the three algorithms, it doesn’t make sense to use the feature of the Public IP as leased IPs usually change with time and including it would cause a biased training dataset that would classify normal flows that have an IP that was used by malware when the model was trained, incorrectly. For validating the models we are going to apply a 10-fold cross validation that is the most used one. 8.3.1 Naïve Bayes After applying the 10-fold Cross Validation to Naïve Bayes, we see that it is the fastest algorithm of the three types used as it only calculates probabilities and doesn’t need to create any costly data structure. We can see in the Figure 8.2, the results obtained for each one of the folds and the average accuracy of the model. 8. MODEL EVALUATION 32 Figure 8.2: 10-fold Cross Validation of Naïve Bayes As we can see, even if the time cost of training the model is really low, the accuracy is far away from the other two algorithms while having a 75.698% of global accuracy. Training phase on Naïve Bayes took 12.32 seconds being the lowest of the three algorithms. 8.3.2 Random Forest For the second algorithm used, we are facing an issue that random forest implemented in R has and it is that they don’t accept qualitative features with more than 32 levels [26], so we are excluding the two features regarding the port origin and port destination from the model. The R implementation allows us to specify the number of decision trees built for the majority vote. Figure 8.3 shows how the accuracy increases when we increase the number of decision trees. 8. MODEL EVALUATION 33 Figure 8.3: Accuracy of Random Forest for different number of decision trees. As we can see, the accuracy increases until we get into a certain number of trees (Approximately 300 decision trees). However, it doesn’t increase anymore but it decreases a little bit instead. By the nature of this algorithm, which takes random seeds to grow the trees, we have executed each model 5 times and have done the mean of the medium values. Figure 8.4 represents how time increases linearly with the number of trees. Figure 8.4: Linear relation between time and number of decision trees. With a linear relation, it doesn’t make any sense to increase the number of decision trees after 300 as it has maximized the trade-off between accuracy and time. The final accuracy is 10% greater than in Naïve Bayes. 84,5 85 85,5 86 86,5 87 87,5 88 0 100 200 300 400 500 600 Accuracy N of Decision Trees Random Forest Accuracy 0 50 100 150 200 250 300 350 400 0 100 200 300 400 500 600 Time in seconds N of Decision Trees Time and # Dicision Trees 8. MODEL EVALUATION 34 Figure 8.5: 10-fold Cross Validation of Random Forest with Number of Trees = 300. Finally, we estimate the most significant variables of the model by computing the mean decrease of accuracy over all out-of-bag errors (Prediction errors) averaged, when a given variable is permuted after training. Figure 8.6 shows how BPP and Duration are the most significant ones while the Protocol is the least important. 9. OPTIMIZATION 41 9. Optimization One of the main problems of statistical malware traffic classification is that models have been trained with the most recent malware samples which were attacking at that moment, but malware programs are constantly changing, every day there are new malware programs with different attack patterns. There also exist metamorphic viruses that can transform their behavior based on the ability that they can translate, edit and rewrite their own code. This type of malware is especially dangerous for computers because antivirus scanners cannot detect a type of virus that changes its internal structure on every computer it infects being unable to obtain a clear signature. That is why our models have a lower performance when a new malware is presented. To cope with an environment that change constantly, we need to apply model retraining with the latest malware flows to keep it updated. On this last section, we are going to study how we could use the feature Public IP, that we obtained on Section 6.3 and was not useful for statistical classification. 9.1 Blacklist Concept Traffic Blacklists are a basic control access that could contain IP addresses, hashes, domain names, URLs, etc. These blacklists contain potentially dangerous addresses, which traffic should be denied. These blacklists can be implemented locally in various points of a network architecture depending of what we want to block, for example in a DNS server to block domain names or in a firewall to block IPs. There are private blacklist maintained by companies for their own products like antivirus, firewalls or even for search engines to avoid displaying malicious webpages. But there are other organizations that maintain public blacklists that can be downloaded or consulted on their webpage or via API REST performing a GET to the service. 9.2 Using IP blacklists for optimization Usually when a Trojan infects a computer, it is expected that the intention of the attackers is stealing information of that machine. One of the main things that they will do is to program the malware to send it to some Domain Name System (DNS) address or a pool of IPs where they have machines waiting for the data. However, it is not rare for a malware to be spread into the network with the goal of infecting as many computers or servers as possible. But this is a double edge sword, as the more spread the malware is, the easier that the attackers get blacklisted into an IP Blacklist or a DNS based blacklists (DNSBL). 9. OPTIMIZATION 42 9.3 Solution The approach proposed to obtain retrained models that are able to face new malware versions is the following: 1) Check the Public IP of the flows that go through our network. 2) Build a dataset with the flows with blacklisted IPs. 3) Test that dataset of blacklisted flows with the actual model. 4) Flows that were predicted as normal traffic are included into the training dataset for a retraining of the model labeled as malware. Figure 9.1: Blacklist optimization workflow. We should point out that the solution is limited for optimizing a binary response. Blacklists don’t differentiate between IPs consulted by different types of malware so we cannot retrain the model tagging the flows on the three classes specified on Section 8.4. 9. OPTIMIZATION 43 9.4 Implementation After capturing the network traffic from a medium size network of about 30 computers and 5 servers during a whole hour, 92.342 flows were generated. This means that for this size 25 should be processed every second approximately. That is why it is important for traffic analysis tools to be as fast as possible; a slow method could cause a bottle neck on the packet queues that would make them to be discarded. For this solution, we have tried do an implementation the nearest to what we could find on the real world and besides having some hardware limitations, as fast as possible in order to process the maximum number of flows in one hour. The implementation consists on a cache and a database with blacklists. First of all, the cache in our case is implemented via software but that it could be also a small memory module implemented via hardware to any machine who wanted to use this method. Caches are used to serve information faster than if we had to search the information on a data base, disk or memory. We will take advantage of the temporal locality of the Public IP as we can see on Figure 6.3 that there are a lot of flows that make requests or connect to the same Public IP, this will allow us to save a lot of time by avoiding searching already checked IPs. We also have the database with a stored blacklist that is not stored on the machine but stored in an outside server. We are going to consult the IPs via a GET request to an API [29]. When a flow passes through the network, the first step is looking if it is located on the cache that has an access time of X less than the access time to the database, which takes X to give an answer. The cache stores the IPs that were checked on the blacklist database and the number of blacklists where the IP appears, allowing us to make a filter considering for example malicious traffic if it appears in more than X blacklists. In case of having 0 occurrences, it means that the IP has not been found on the database hence it would potentially be normal traffic. If the IP is not found on the cache, we do a GET with the IP to the API to check if it appears on the database. The result of this operation is saved on the cache for the next time the same IP appears. Even if searching with the API is more time consuming task in comparison of checking a database that is stored locally, we would have to update it every few time if we want it to be actualized with the last malicious IPs (IPs can change with the time) but also increase the cost of buying new storage for it. 9. OPTIMIZATION 44 9.5 Optimization Results In this section we are going to expose the studies that have been done while analyzing if the solution could be viable in a real world scenario. We have done a study of how the trade-off between accuracy and time spent within the solution is affected by changing the proportion of traffic that is checked by the blacklist. For the sake of getting unbiased and realistic results, we flush the cache for every one of the different tests; this is done because we would get faster times for each new test as the IPs used would be on the cache avoiding then the call to the API. For the model selection, we are going to use Boosted C5.0 with 20 trials as it is the model that had the better performance for binary classification and training time is not a big issue as models can be serialized so we can be retraining one model while using the old one until the retraining phase is finished. Applying the blacklist we obtain more accuracy than applying the model to predict the flows but model predictor is much faster than the blacklist (6559 times faster), that is why we should evaluate the accuracy and the time spent of the whole solution so we can study and maximize the trade-off. Total time that could be expressed as following: 𝑇𝑜𝑡𝑎𝑙 𝑇𝑖𝑚𝑒 = 𝑇𝑖𝑚𝑒 𝑜𝑓 𝑡ℎ𝑒 𝑐𝑎𝑐ℎ𝑒+ 𝑇𝑖𝑚𝑒 𝑜𝑓 𝑡ℎ𝑒 𝑏𝑙𝑎𝑐𝑘𝑙𝑖𝑠𝑡 + 𝑇𝑖𝑚𝑒 𝑜𝑓 𝑡ℎ𝑒 𝑚𝑜𝑑𝑒𝑙 𝑝𝑟𝑒𝑑𝑖𝑐𝑡𝑖𝑜𝑛 + 𝑅𝑒𝑡𝑟𝑎𝑖𝑛𝑖𝑛𝑔 𝑇𝑖𝑚𝑒 For the experiment, we merged traffic generated by a new unseen malware Sathurbot [30] with also new normal traffic that wasn’t used for training the model, resulting into a balanced 1000 flow dataset that couldn’t be bigger for limitations of time (API takes 1,1 seconds per flow to collate with the blacklist). This allows us to test the performance of our model when is tested with traffic that has a different behavior than the one that was used for training. In Figure 9.1 it can be seen the increase of the accuracy when the solution is applied for different % of Flows checked from the traffic. 9. OPTIMIZATION 45 Figure 9.2: Accuracy over % Checked Flows. As shown, testing the model without applying any optimization and checking the 0% of the new traffic through the blacklist gets a lot less accuracy that what we obtained in Section 8.3 with an 82.55% of accuracy. However, when flows start to be checked by the blacklist and the model is retrained with those flows that it incorrectly predicted, the accuracy starts increasing until getting a maximum of 95.48% accuracy when checking the 55% of the traffic through the blacklist without needing more retraining samples, much better compared with the one obtained without applying any retraining to it. Now we should compare the time spent for the whole solution Figure 9.2 shows us the total time spent in seconds. Time has lineal cost with the number of flows checked on the blacklist which means that the process is bottle necked with the time expend calling the API and getting the response. 80 82 84 86 88 90 92 94 96 98 100 020 40 60 80 100 % Overall Accuracy % of Checked Flows on the Blacklist Accuracy over of % Checked Flows 9. OPTIMIZATION 46 Figure 9.3: Time spent over % of Checked Traffic. We could deduce that it doesn’t make sense to check a higher percentage than 55%, as the accuracy is not increased while the cost in time goes on increasing with the percentage of checked Flows. The solution could be adjusted into a real time traffic assuming the worst case scenario that would be that all IPs are new. In that case, the maximum percentage of flows that should be checked is: % 𝑜𝑓 𝑐ℎ𝑒𝑐𝑘𝑒𝑑 𝑓𝑙𝑜𝑤𝑠 =max (55,𝑀𝑒𝑎𝑛 𝐴𝑐𝑐𝑒𝑠𝑠 𝐴𝑃𝐼 𝑡𝑖𝑚𝑒 𝑝𝑒𝑟 𝑓𝑙𝑜𝑤 3600 𝑠𝑒𝑐𝑜𝑛𝑑𝑠 𝑀𝑒𝑎𝑛 𝑜𝑓 𝑓𝑙𝑜𝑤𝑠 𝑝𝑒𝑟 ℎ𝑜𝑢𝑟 × 100) We can observe that it is a very simple operation that can be made pretty fast. This allows us to calculate the % of checked flows dynamically and change it as a parameter of the solution. That is why we could adapt the traffic classifier to the quantity of traffic that is passing through the network at any moment without compromising or slowing the whole network. 0 200 400 600 800 1000 1200 010 20 30 40 50 60 70 80 90 100 Total Time (Seconds) % of Checked Flows on the Blacklist Time spent over % of Checked Flows 10. CONCLUSIONS 47 10. Conclusions 10.1 Summary The aim of this thesis was to study the different machine learning algorithms to classify malware traffic using only the information provided by the Netflow protocol. At first, we evaluated the predictive capacity of the models for the binary class trying to see if they could classify with more or less accuracy the traffic between normal and malware ones. After that, we tested the models for a multiclass prediction differentiating between normal, Trojan and Botnet traffic. In both cases we achieved the highest accuracy with a boosted version of the C5.0 decision tree. Later on, optimizations were applied using additional resources to obtain a solution that could be updated and adapted to the changing environment of the network and get a great performance. After doing so, we can conclude that we achieved the goal. We obtained a high accuracy for both, binary but also multiclass classifications. In addition, the proposed solution obtained very good results improving the accuracy with respect to when we applied only the model and could also be applied to traffic classification in real time. 10.2 Future Work For future work, the implementation was done without using any type of parallelization that could speed the process up. We were limited to one instance that was processing all the flows being unable to handle the 100% of them. The read and processing of different flows could be parallelized on different instances in order to be able to process more flows and adapt the solution to bigger environments. The study of different ways to decrease the time of accessing the blacklist database could give a significant speed-up on the process. For example, partially downloading a blacklist (with the X most recent IPs) and storing it into memory as second cache. The effects of having a smaller blacklist stored in local could be also analyzed. Moreover, splitting the normal traffic into more classes defining each one for a benign application could be performed to see if the accuracy decreases after including more classes or if the model can still differentiate them along with Trojans and botnets. 48 Appendices 49 Gantt Diagram 11. REFERENCES 50 11. References [1] GmbH, A.-T. (2017) AV-TEST – the independent iT-security institute. [2] Atique, Z. and Harkut, D. (2017). An Overview of Network Traffic Classification Methods. International Journal on Recent and Innovation Trends in Computing and Communication, 3(2), p.482. [3] Schneider, P. (2017). TCP/IP Traffic Classification Based on Port Numbers. [4] Anderson, B., Paul, S. and McGrew, D. (2016) Deciphering Malware’s use of TLS (without Decryption). [5] Williams, N., Zander, S. and Armitage, G. (2006) ‘A Preliminary Performance Comparison of Five Machine Learning Algorithms for Practical IP Traffic Flow Classification’ [6] Free online virus, Malware and URL scanner (no date) Available at: https://www.virustotal.com [7] Mai, J., Ye, T., Zang, H. and Sridharan, A. (2006) Is Sampled Data Sufficient for Anomaly Detection? Available at: http://conferences.sigcomm.org/imc/2006/papers/p17-mai.pdf. [8] Bilge, L., Balzarotti, D., Robertson, W., Kirda, E. and Kruegel, C. (2012) DISCLOSURE: Detecting Botnet Command and Control Servers Through Large-Scale Netflow Analysis. Available at: https://seclab.nu/static/publications/acsac2012disclosure.pdf [9] A. Wagner and B. Plattner (2005) Entropy based worm and anomaly detection in fast IP networks - IEEE Xplore document. [10] Alam, S., Traore, I. and Sogukpinar, I. (2014) Current Trends and the Future of Metamorphic Malware Detection. [11] Softflowd - fast software Netflow probe Available at: http://www.mindrot.org/projects/softflowd/ [12] Manpages.ubuntu.com. (2017). Ubuntu Manpage: nfcapd - Netflow capture daemon. [online] Available at: http://manpages.ubuntu.com/manpages/xenial/man1/nfcapd.1.html [13] Manpages.ubuntu.com. (2017). Ubuntu Manpage: nfdump - Netflow display and analyze program. [online] Available at: http://manpages.ubuntu.com/manpages/xenial/man1/nfdump.1.html [14] Kang, Y. and Stasko, J. (2017). Lightweight Task/Application Performance using Single versus Multiple Monitors: A Comparative Study.