Full text
Universidade do Minho Escola de Engenharia Jorge Fernando Alves Cruz Vulnerabilities Preservation Using Code Mutation November, 2022
Universidade do Minho Escola de Engenharia Jorge Fernando Alves Cruz Vulnerabilities Preservation Using Code Mutation Master’s Dissertation Integrated Master’s in Informatics Engineering Work supervised by Jorge Sousa Pinto Daniela da Cruz November, 2022
i COPYRIGHT AND TERMS OF USE OF THIS WORK BY A THIRD PARTY This is academic work that can be used by third parties as long as internationally accepted rules and good practices regarding copyright and related rights are respected. Accordingly, this work may be used under the license provided below. If the user needs permission to make use of the work under conditions not provided for in the indicated licensing, they should contact the author through the RepositóriUM of Universidade do Minho. License granted to the users of this work Creative Commons Atribuição-NãoComercial-CompartilhaIgual 4.0 Internacional CC BY-NC-SA 4.0 https://creativecommons.org/licenses/by-nc-sa/4.0/deed.pt
ii STATEMENT OF INTEGRITY I hereby declare having conducted this academic work with integrity. I confirm that I have not used plagiarism or any form of undue use of information or falsification of results along the process leading to its elaboration. I further declare that I have fully acknowledged the Code of Ethical Conduct of the Universidade do Minho. , (Location) (Date) (Jorge Fernando Alves Cruz)
Acknowledgements I would like to express my deepest gratitude to my supervisor Jorge Sousa Pinto and co-supervisor Daniela da Cruz for sticking with me during the course of this project. I could not have undertaken this journey without their invaluable patience and feedback. A big thank you to both. Likewise, I would also like to thank my family and friends for supporting me and for insisting on asking me when this dissertation would be finished. Special thanks to my brother João for all his help and review of the document. iii
Abstract The main goal of software security testing is to assess the security risks of an application so that programmers can eliminate all vulnerabilities, as early as possible, before they are exploited by attackers. There are several tools on the market that allow to perform these tests during the software development life cycle to ensure that there are no security flaws in the final product. However, like all tools, these can also have imperfections, one of them being unable to detect weaknesses in vulnerable software. The project of this dissertation aims to tackle this problem, so that it is possible to find and correct flaws in security tests in order to, consequently, increase the effectiveness of the tools that intend to certify the security of applications. For this, the solution studied in this document is to apply syntactic transformations in vulnerable code samples without interfering in the presence of the vulnerabilities that should later be detected. This process is based on: 𝑖) code refactoring techniques that allow improving the internal quality of the software; 𝑖𝑖) the mutation testing system used to evaluate the quality of software testing. To implement this idea, a tool called VSG was developed with the functionality of producing new code samples with security flaws. This document describes the whole development process, from the architecture to the implementation of the tool. In the end, there is an analysis with the results obtained when trying to detect the vulnerabilities present in the samples produced through the CxSAST application of the company Checkmarx, from which this dissertation emerged. Keywords: application security testing, code mutation, code refactoring iv
Resumo O objetivo principal de testes de segurança de software consiste em avaliar os riscos de segurança de uma aplicação para que os programadores possam eliminar todas as vulnerabilidades o mais cedo possível, antes que sejam exploradas por atacantes. Existem várias ferramentas no mercado que permitem realizar estes testes durante o processo de desenvolvimento de software para garantir que não existam falhas de segurança no produto final. Porém, tal como todas as ferramentas, estas também podem apresentar imperfeições, sendo uma delas não conseguir detetar fraquezas em software vulnerável. O projeto desta dissertação pretende combater este problema, de modo a que seja possível encontrar e corrigir falhas nos testes de segurança para, consequentemente, aumentar a eficácia das ferramentas que pretendem certificar a segurança das aplicações. Para isto, a solução estudada neste documento passa por aplicar transformações sintáticas em amostras de código vulneráveis sem interferir na presença das vulnerabilidades que deverão, posteriormente, ser detetadas. Este processo baseia-se: 𝑖) nas técnicas de refatoração de código que permitem melhorar a qualidade interna do software; 𝑖𝑖) no sistema de testes de mutação usado para avaliar a qualidade de testes de software. Para implementar esta ideia, uma ferramenta chamada VSG foi desenvolvida com a funcionalidade de produzir novas amostras de código com falhas de segurança. Neste documento é descrito todo o processo de desenvolvimento, desde a arquitetura até à implementação da ferramenta. No final, existe uma análise com os resultados obtidos ao tentar detetar as vulnerabilidades presentes nas amostras produzidas através da aplicação CxSAST da empresa Checkmarx, da qual esta dissertação surgiu. Palavras-chave: teste de segurança de aplicações, mutação de código, refatoração de código v
Contents List of Figures viii List of Tables ix Listings x 1 Introduction 1 1.1 The Goal ...................................... 2 1.2 A Proposed Solution ................................ 2 1.3 Document Structure ................................ 2 2 Background 3 2.1 Checkmarx SAST .................................. 4 3 State of The Art: Refactoring 6 3.1 Definition of Refactoring ............................... 6 3.2 Refactoring Example ................................ 7 3.3 Refactoring Techniques ............................... 8 3.4 Automated Refactoring ............................... 11 4 State of The Art: Mutation Testing 14 4.1 The Process of Mutation Analysis .......................... 15 4.2 Mutation Operators ................................. 17 4.2.1 Operators for Specific Programming Languages ............... 17 4.2.2 Operators for Specific Categories of Programming Languages ........ 18 4.2.3 Operators for Specific Categories of Applications .............. 18 4.2.4 Operators for Specific Categories of Bugs .................. 19 5 VSG - Vulnerable Samples Generator 21 5.1 A Samples Generation Tool ............................. 21 vi
CONTENTS 5.2 VSG Architecture .................................. 23 5.3 Parsing with ANTLR ................................. 24 5.4 Symbol Table .................................... 26 5.4.1 Symbol Table in VSG ............................ 27 5.5 Vulnerability Flow .................................. 30 5.6 Code Transformation ................................ 32 5.6.1 Implementing a Mutation Rule ....................... 33 5.6.2 Applying the Mutations and Rules Composition ............... 37 6 VSG Tests 40 6.1 Original code sample vs Generated samples ..................... 40 6.2 Testing VSG against Checkmarx SAST ........................ 42 7 Conclusion 45 7.1 Future Work .................................... 46 Bibliography 47 vii
CHAPTER 2. BACKGROUND 2.1 Checkmarx SAST Although the objective may also be useful for other types of security analysis, it’s in the static code analysis domain that this dissertation is concerned. In this context, Checkmark SAST is a static analysis solution used to identify security vulnerabilities in custom code that can be fixed early in the software development life cycle. Supports more than 25 coding and scripting languages (Java, Kotlin, Python, JavaScript, Scala, Ruby, Swift, TypeScript, Pearl, iOS, Android, COBOL, VBScript, among others) and its frameworks without the need of extra configurations to scan any language. Without building or compiling the source code of a software project, CxSAST works by building a logical graph of the elements and flows in the code. Against this structure, CxSAST offers an extensive list of preconfigured queries that are executed to detect known security vulnerabilities in the internal code graph for each programming language. Using the CxSAST Auditor tool, the user can configure additional queries for security, best coding practices, QA, and business logic purposes. It can run scans and generate security reports at any given point in a software project’s development life cycle. Scan results can be obtained in CxSAST either by static reports or by an interactive interface that allows the user to observe the behavior of each vulnerability through the code. Figure 2.1 is an example of the scan results (for CxSAST v8.9.0 and up) showing an SQL Injection vulnerability. When the user selects a specific instance of the vulnerability in the Results pane (bottom, center and right), CxSAST displays the instance’s code details at the top of the pane and a path of code elements in the Path pane (top right). This path shows the flow of code elements leading from the user input to the SQL query. The user can select each element in the path which in turn CxSAST displays the element in the code context in the Source Code pane (top, left and center). The vulnerability needs to be eliminated somewhere along the path. More information about Checkmarx and their SAST product can be found at their website [2]. 4
CHAPTER 2. BACKGROUND Figure 2.1: Screenshot of CxSAST scan results, showing an SQL Injection vulnerability detected in a C# project. The Queries pane (bottom left) shows that 27 instances of the SQL Injection vulnerability were found. 5
C h a p t e r 3 State of The Art: Refactoring 3.1 Definition of Refactoring In his book [11], Martin Fowler defines refactoring as a process of modifying a software system in such a way that the source code is improved but the external behaviour is not changed. This term was originally introduced in 1990 by William Opdyke and Ralph Johnson [38], but it was through Martin Fowler’s book that it was most represented. As a system’s software evolves according to new requirements, the code becomes more and more complex and, with this, more susceptible to the introduction of bugs by programmers. According to Fowler, refactoring is the opposite of this practice. During the development of a program, its design remains firm through transformations that increase the internal quality of the software and keep the same external behaviour. Refactoring works essentially by looking for bad smells in the code. According to Sandeep Kaur [15], bad smells represent potential problems in the code that make it difficult to understand and modify. Duplicate code is an example of a bad smell that can be solved by replacing all occurrences of the code for a function with the same functionality. Not only is the code easier to understand but also more sustainable and with better quality. Furthermore, refactored code reduces the code maintenance cost and the chance of introducing bugs [14]. Other definitions of refactoring are more abstract. In his dissertation [41], Donald Roberts defines refactoring as a pair (𝑝𝑟𝑒,𝑇 ), where 𝑝𝑟𝑒 is the set of pre-conditions that a program must satisfy to perform a transformation, and 𝑇corresponds to the transformation. This definition emerged so that transformations that do not preserve external behaviour were also included. 6
CHAPTER 3. STATE OF THE ART: REFACTORING 3.2 Refactoring Example The impact of a transformation on the program differs from the type of refactoring applied. While some refactorings make localized changes to the code, others operate at higher levels and in a larger scale [31]. A common example of a localized transformation is the extraction of a code snippet to its own method. Listing 3.1: Code snippet before the Extract Method transformation public void printNumberOfLines(String filePath) { int noOfLines = 0; LineIterator lineIterator = FileUtils.lineIterator(new File(filePath)); while (lineIterator.hasNext()) { lineIterator.nextLine(); noOfLines++; } System.out.println(”Number of lines: ” + noOfLines); } When applying the Extract Method refactoring to the code fragment corresponding to the functionality of calculating the number of lines in a file, the final result is: Listing 3.2: Code snippet after the Extract Method transformation public void printNumberOfLines(String filePath) { int noOfLines = numberOfLines(filePath); System.out.println(”Number of lines: ” + noOfLines); } public int numberOfLines(String filePath) { int noOfLines = 0; LineIterator lineIterator = FileUtils.lineIterator(new File(filePath)); while (lineIterator.hasNext()) { lineIterator.nextLine(); noOfLines++; } return noOfLines; } With a simple change, not only we made the methods more refined, but also increased the chances of being reused by others. The opposite refactoring (Inline Method) also exists and can be useful when we have a method whose body is as clear as the method name. Therefore, it is necessary to evaluate the context to know if a refactoring will have a positive or negative impact on the code. In terms of global transformations, we can look at the effect of Fowler’s Tease Apart Inheritance 7
CHAPTER 3. STATE OF THE ART: REFACTORING InputStream File InputStream ByteArray InputStream Video InputStream OutputStream File OutputStream ByteArray OutputStream Video OutputStream Stream Input Stream Output Stream Storage ByteArray Storage File Storage Video Storage Figure 3.1: A Stream class hierarchy in java.io before and after applying Tease Apart Inheritance refactoring. The gray boxes represent the changes needed in each version to add the same functionality. refactor. The top of figure 3.1 shows a hierarchy of classes from java.io for streaming data. Suppose we want to add the features of reading and writing to a video stream with this structure. Unfortunately, it would be difficult because we would have to add two new classes, VideoInputStream and VideoOutputStream, probably with duplicate code between the two. The problem with this class hierarchy is the mixture of two concerns: the direction of the flow (input or output) and the type of storage in which it is performed. Not only is it difficult to make changes, as the resulting code is hard to understand. However, we can solve this inconvenience by applying the refactoring Tease Apart Inheritance, in order to create two different hierarchies, as we can see at the bottom of figure 3.1. With this structure, to add streaming video, all we need to do is add the VideoStorage class as a subclass of Storage. 3.3 Refactoring Techniques In 1992, William Opdyke developed the first detailed refactoring elaboration in his doctoral thesis. In this dissertation [37], he presented 23 primitive refactorings, shown in the table 3.1, together with a set of preconditions for each one that would ensure the behaviour of the software after the transformation. This collection was achieved by looking at various systems and pointing out the types of refactorings that would apply in object-oriented programming. All this work made it possible for other elaborated techniques to emerge in the refactoring field. 8
CHAPTER 3. STATE OF THE ART: REFACTORING Table 3.1: List of primitive refactorings identified by Bill Opdyke creating an empty class creating a member variable creating a member function deleting an unreferenced class deleting an unreferenced variable deleting a set of member functions changing a class name changing a variable name changing a member function name changing the type of a set of variables and functions changing access control mode adding a function argument deleting a function argument reordering function arguments adding a function body deleting a function body convert an instance variable to a variable that points to an instance convert variable references to function calls replacing statement list with function call inlining a function call change the superclass of a class moving a member variable to a superclass moving a member variable to a subclass A refactoring technique refers to a procedure in which a set of steps is taken in order to achieve the desired transformation. After identifying where the software has bad smells, it is necessary to determine which refactoring techniques to apply to keep the source code as clean as possible. In Martin Fowler’s book [11] we can find a long catalog of refactorings techniques and, for each one, their steps and motivation. This list is divided into 8 groups. Composing Methods The composition of methods is one of the most common groups in refactoring techniques. The objective is, in most cases, to restructure long and difficult to understand methods. For example, the refactoring Extract Method shown above is one of the techniques belonging to this group. Also, when we want to compose methods, one of the biggest concerns corresponds to temporary variables, so this group also includes techniques related to these variables and the parameters of the methods. 9
CHAPTER 3. STATE OF THE ART: REFACTORING Moving Features between Objects These refactorings are used to decide where to place responsibilities between different classes in order to make the best decisions in object design. Through them we can move functionality between classes, create new classes and hide the implementation details from public access. Most problems can be solved with the Move Method and Move Field refactorings, as well as the Extract Class that allows you to create a new class from another. Organizing Data In object-oriented programming, one of the most important aspects is the definition of new types from primitive types. This characteristic, despite being fundamental in problem-solving, brings, in itself, an increase in potential disorders to keep the data structure clean as complexity increases in level. These refactoring techniques make handling information easier. For example, when we have a simple information value that would be more useful as an object, we can apply the Replace Data Value with Object refactoring to create a new class that stores the value and all its behaviour. Simplifying Conditional Expressions As the name implies, these refactoring techniques are intended to facilitate the logic of conditions that, at times, becomes complicated and confusing. The main refactoring is Decompose Conditional which allows you to extract all parts of a complicated conditional sentence (if-then-else) in separate methods. This makes the code more readable and easier to maintain by a different programmer. Simplifying Method Calls These techniques are related to the importance of interfaces in the development of object-oriented programs. One of the simplest techniques is to rename methods, variables and classes so that the code is as readable as possible. Other concerns include the method parameters, the class constructors and the error handling mechanism. Dealing with Generalization Generalization raises a set of refactoring techniques that influence functionalities along a class hierarchy. The most common techniques in this group are to promote and descend methods or instance variables among classes in the hierarchy. In addition to moving functions, there are also techniques, such as Extract Subclass,Extract Superclass and Extract Interface, that change the hierarchy by adding 10
CHAPTER 3. STATE OF THE ART: REFACTORING new elements at various points. In case there are unnecessary classes in the hierarchy, we can use the refactoring Collapse Hierarchy to remove them. Big Refactorings In his last group, Fowler presents 4 major refactorings. While the latter groups consisted of individual refactoring changes, this group intends to ”play”at a higher level through a lot of transformations that take longer to finish. One of the refactoring techniques included corresponds to the one presented in section 3.2, which, as we have seen, exerts an enormous change in terms of the program structure. 3.4 Automated Refactoring Although it is possible to apply refactorings manually, tool support is considered crucial. During refactoring, users need to synthesize and analyze large collections of code to identify bad smells, decide the best solutions to eliminate undesirable characteristics and apply potentially complex and error-prone transformations without changing the external behaviour of the system. If we take, as an example, the simple renaming of a method, the user needs to propagate this change throughout an entire system. This becomes tedious and costly when developing a project, making automated refactoring software essential in a time-consuming and error-prone manual task. Nowadays, a wide range of tools is available that automate various aspects of refactoring [18]. The refactoring process is divided in distinct activities that can be supported by different tools: 1. Analyze the software to determine where it should be refactored (detecting bad smells). 2. Determine which refactoring(s) should be applied to the identified places in order to remove the code smells. 3. Assure that the applied refactoring preserves the external behaviour of the software. 4. Apply the refactoring. 5. Evaluate the result of the refactoring on quality characteristics of the software (e.g., complexity, understandability, maintainability) or the process (e.g., productivity, cost, effort). “Fully-automatic tools complete the multi-stage refactoring process without user interaction, from the initial identification of where it is needed through the selection and application of a specific refactoring.” [24] Although these tools assist software developers, the absence of user input along the steps is the root of worthless identifier names, lack of customizability, and negative impacts on a user’s understanding of a system [4,9]. On the contrary, semi-automated refactoring tools attempt to address these problems 11
CHAPTER 3. STATE OF THE ART: REFACTORING by using user input to value the refactoring process whilst automating the tedious, error-prone and complex sub-tasks. This single-stage focus makes the balance between automated and manual tasks essential to readable and well-designed code. Examples of semi-automated refactoring tools include Eclipse’s refactoring transformation support, and jDeodorant’s code smell detection. In the next sections, I will explore the different characteristics that affect the usability of an automated refactoring tool and that can be interesting for the tool we want to create in this dissertation. Reliability The reliability of a refactoring tool is related to the ability to ensure that, after a transformation, the external behaviour of the program remains similar. Most tools provide this feature by checking a set of preconditions before applying the refactoring and running tests on the system’s functionalities after applying the refactoring. In this dissertation, the reliability of the tool will be more relaxed since the objective is to preserve a vulnerability of the system and not its external behaviour. Configurability and Openness Most refactoring tools are integrated into industrial IDEs through their extensibility mechanisms that sometimes make it impossible to configure the tools with specific user preferences. Some of the attributes that a user should be able to control are: • refactorings and bad smells specifications, • the link between bad smells and refactorings [45], • definitions of composite refactorings from primitive ones [33]. For this dissertation, having an open configurable tool is essential to control the different versions we can produce from a code sample. Coverage This attribute is fundamental for refactoring tools because it indicates how comprehensive the tool is in terms of the types of activities it can perform. The more complete the tool is, the easier it is for the user to improve the code. Unfortunately, most tools tend to focus on just one aspect of the refactoring process. Scalability and Performance The ability to combine a sequence of primitive refactorings into a composite refactoring increases the scalability and performance of a refactoring tool. This characteristic allows solving problems at higher 12
CHAPTER 3. STATE OF THE ART: REFACTORING levels and, in the case of this dissertation, it allows transformations on larger scales. The performance gain is related to the fact that the tool only needs to check the preconditions of the composite refactoring once, instead of checking separately for each primitive refactoring in the sequence [25,41]. Language Independence Like coverage, the tool’s range for different programming languages should be as complete as possible and in addition, the tool should provide the necessary hooks to add language-specific behaviour [27]. There are several techniques for achieving language independence: •Meta modelling is a technique presented by both Tichelaar et al. [44] and Mens et al. [26] • The notion of generic program refactoring introduced by Lämmel [22] • Ward and Bennett suggested translating the code into the formal intermediate language WSL, where it can be restructured, refined and abstracted, and then translated back into the original language [48]. For any language, just create an automatic translator in both directions for WSL. 13
CHAPTER 4. STATE OF THE ART: MUTATION TESTING Table 4.4: 15 security-aware mutation operators proposed by Loise et al. [21] for Java Use predictable pseudo random number generator Remove path traversal sanitization Use weak message digest Remove host name verification Make XML parser vulnerable to XML Entity Expansion attack Make XML parser vulnerable to XML eXternal Entity attack Remove encryption in socket Unsecure cookie Remove HTTP-only flag from cookie Use RSA with short key Use Blowfish with short key Permit SQL injection Use DES in symmetric encryption Use ECB in symmetric encryption Remove regex sanitization 20
Chapter 5 VSG - Vulnerable Samples Generator This chapter represents the core of this dissertation by introducing the VSG tool, together with all the steps and decisions taken during its development. It is in this section that we can find a path to the solution of the problem presented at the beginning, describing the whole development process from the tool architecture to its implementation. Within the topics presented in the state of the art, this tool will focus on the application of transformations in the code, both present in refactoring 3and mutation testing 4. The most important point will be how syntactic transformations will be applied to vulnerable code samples in order to obtain the greatest possible diversity regarding the presence of vulnerabilities. Therefore, the first part of this chapter gives an introduction to the tool by describing what it is intended to achieve and how it will be achieved. The second section explores the tool’s architecture, explaining how it is structured and what technologies have been used. Finally, the remaining sections present the main components of the tool and the implementation of syntactic transformations on code samples. 5.1 A Samples Generation Tool As previously mentioned, the main objective of this project is the development of a tool that generates code samples with a security flaw that is known by the user. The path chosen to achieve this goal involves an initial sample of code, provided by the user as input, with a known vulnerability. The tool must then apply several syntactic transformations to the sample code without losing the security flaw, thus obtaining a set of code samples sharing the same characteristic: having the same vulnerability 5.1. To ensure that all the transformations applied to the code have an impact on the vulnerability, the user must also provide a metadata file with information about the flow of the vulnerability in the code sample. This file will be an XML file containing a path with all the nodes that define the behavior of the security 21
CHAPTER 5. VSG - VULNERABLE SAMPLES GENERATOR VSG Tool Vulnerability Flow Vulnerable Code Samples Produced Vulnerable Code Sample Figure 5.1: The inputs and the outputs of the VSG Tool flaw. If the transformations were applied anywhere in the code, the result would be a large percentage of the code samples produced with an identical vulnerability, in terms of behavior, to the one present in the initial sample, so we can assume that its presence would not be difficult to detect since we know that the initial vulnerability was also detected at the beginning (remember the main problem of this project). Each type of syntactic transformation that can be applied over the code will have the name of mutation rule. One of the key aspects for this tool will be how different mutation rules can be combined in order to vary the set of code samples obtained at the end of the process. This feature allows exploring the multiple case where a vulnerability is present, making the role of a security testing tool more difficult to assume. In addition, a mutation rule can be applied at various points in a code sample, so this aspect will also be used in favor of the tool. The initial step of the process is to parse the sample code in order to identify the places where the transformations can be applied. For this purpose, the ANTLR parser generator was used for the lexical and syntactic analysis of the code, which will be described in the section 5.3. As for the language, the tool will be written in C#, an object-oriented language that easily links ANTLR to the development of the mutation rules and which the author is comfortable to work with. In this first version, only code samples written in the Java language will be accepted as input for the tool. This choice is due to the fact that Java is one of the most used languages by programmers and therefore needs more concern from security testing applications. 22
CHAPTER 5. VSG - VULNERABLE SAMPLES GENERATOR 5.2 VSG Architecture Before jumping to the implementation, this section will explain how the tool is structured internally and what is the interaction between the different components that allow the whole process to be executed. The figure 5.2 introduces an abstract overview of this structure through a diagram with the main VSG components. Although there are other elements in this structure, such as the component that allows loading the code samples together with their vulnerability flows, the most important ones that allow the magic to happen are represented in the diagram. VSG RulesApplier Grammar Symbol Table ParserVisitor Code Samples Generated Code Samples Rule Figure 5.2: The internal structure of the VSG Tool As stated in the previous section, it is necessary to analyze the code samples in order to identify the places where a mutation rule can be applied. In this sense, through the grammar that specifies the language in which the samples are written, the application uses ANTLR to generate a recognizer for that language. The grammar only needs to be compiled once to create a parser written in C#. This way, ANTLR replaces the work of having to create a parser manually that can be used by the mutation rules. This parser, which will be explained further in section 5.3, constitutes one of the components of this structure. The next component represents the mutation rule itself. Each rule will be a component that will use the parser to find all the places where it can be applied and collect all the applicable transformations on the code sample. The way how all possible locations will be detected and transformations executed represents the main focus of this dissertation and will be described in detail in section 5.6. The set of components consisting of the mutation rules and the parser represents the RulesApplier which, fed by the initial code samples, will generate the output with the code samples produced. 23
CHAPTER 5. VSG - VULNERABLE SAMPLES GENERATOR Finally, the whole structure was assembled to obtain the initial code samples from a directory instead of receiving one at a time to execute the whole process. For this, the directory must follow a predefined structure so that the tool can correctly load the code samples together with the corresponding vulnerability flows. In the end, all the code samples produced will be exported to another directory that will also follow a structure that facilitates the correspondence between the initial code sample and those that were generated from it. 5.3 Parsing with ANTLR The development of a parser for a certain language can be a difficult and time-consuming task, requiring several skills before starting to write one. For this purpose, Terence Parr, together with other colleagues, created ANTLR (ANother Tool for Language Recognition) to speed up this process. This tool receives as input a grammar specification and automatically produces a parser that can build and walk parse trees. No effort is required in the analysis of structured texts such as program source code. This tool is an important part of the VSG and this section tries to explain a little of its process and why it is important for the mutation rules. For ANTLR to work, it is necessary to provide a grammar with two types of rules that describe the language syntax: parser and lexer rules. Lexer rules are responsible for lexical analysis, i.e. the process of identifying tokens in a character stream. Parser rules focus on recognizing the structure of the input sentence by building the abstract syntax tree from the identified tokens. Diagram 5.3 demonstrates the process of a language recognizer for an arithmetic expression with an example. By entering the input sentence 5+4, the lexer will recognize the INT (integers) and PLUS tokens and feed them to the parser, which in turn, will produce a parse tree with the arithmetic expression structure. Language recognizer 5 + 4 LEXER PARSER INT 5 INT 4+ Parse tree expr +expr expr 5 4 Chars Tokens Figure 5.3: The process of a language recognizer A grammar must follow the syntax defined by ANTLR to specify other languages. Listing 5.1 is an example of a grammar for traditional arithmetic expressions (addition, subtraction, multiplication and division) with the name Expr. This language has only one parser rule called expr with four alternatives to define an arithmetic expression. The remaining rules are lexer rules intended to recognize operators 24
CHAPTER 5. VSG - VULNERABLE SAMPLES GENERATOR (MUL,DIV,ADD,SUB) and integers (INT) with one or more digits. Note that all parser rules start with a lowercase letter and all lexer rules start with an uppercase letter. Listing 5.1: Grammar for traditional arithmetic expressions written in ANTLRv4 grammar Expr; expr : expr (MUL|DIV) expr | expr (ADD|SUB) expr | INT | '(' expr ')' ; ADD : '+'; SUB : '-'; MUL : '*'; DIV : '/'; INT : [0-9]+ ; The parse tree is a useful data structure that contains complete information on how the parser has grouped the recognized tokens. From another point of view, when analyzing a program source code, the result would be a tree with an easy to process structural representation of the program. However, a mechanism is still needed to walk this tree in order to take the desired actions at the correct nodes. One of the tree-walking mechanisms that ANTLR offers is tree visitors. When provided with a grammar, ANTLR is able to generate a visitor interface with a visit method for each rule that will be called along a depth-first walk on the parse tree. In other words, this mechanism follows a visitor pattern on the parse tree. As an example, figure 5.4 demonstrates the order of method calls among the visitor methods for the parse tree obtained in the input sentence 5+4. Expr (1) visitExpr(ExprContext) + (4) visitTerminal(TerminalNode) Expr (2) visitExpr(ExprContext) Expr (5) visitExpr(ExprContext) 5 (3) visitTerminal(TerminalNode) 4 (6) visitTerminal(TerminalNode) Visitor API visitExpr(ExprContext) visitTerminal(TerminalNode) Figure 5.4: The sequence of visit method calls in a parse tree Each visit method will take as argument a context object. According to Terence Parr, ”each context 25
CHAPTER 5. VSG - VULNERABLE SAMPLES GENERATOR object knows the start and stop tokens for the recognized phrase and provides access to all elements of that phrase” [40]. This means that for the example in figure 5.4, the first ExprContext has access to the expression subtrees. For the matter of this project, the ParserVisitor generated by ANTLR for each programming language will be an important component for the mutation rules. Each rule needs to explore the structure of a program in order to evaluate and apply the transformations in the right places. Therefore, ParserVisitor enables rules to take actions at the correct nodes of a program’s parse tree. For example, imagine a rule that wants to make changes to if statements in a program. All it needs is to override the visitIfStatement method (assuming the grammar contains a parser rule for the if statement) provided by the ParserVisitor and explore the context to find out how the transformation will be applied. Having the ability to parse the code, the next step was to start implementing the rules. However, it was quickly realized that a data structure would be needed to assist the rules in code analysis and correct application of transformations. Thus, the next section presents the symbol table. 5.4 Symbol Table One of the problems that arose during the implementation of the mutation rules was the situation when new identifiers were added within a scope. If, for example, a mutation rule adds a new variable within a method, it is necessary to verify that the name of that variable is not already being used within the scope of the method. Otherwise, the result would be conflicts of identifiers, which in turn would result in the production of non-compilable code samples. In addition to this problem, other complications emerged, such as mutation rules that needed to infer the type of an identifier so that its transformation could be successfully applied. In this context, it was important to implement an auxiliary data structure with all the information about the symbols and scopes defined in the source code of a program. Being widely used in compiler design to achieve compilation time efficiency, the symbol table proved to be the solution to these problems. A symbol table consists of a data structure with the purpose of storing identifiers (symbols) present in the source code of a program, such as classes, methods and variables, and associating to each one its information and relationship with other identifiers. There are several types of data structures that can be used to implement a symbol table, the most commonly used being lists, hash tables and trees. The main purposes of a symbol table are: • Inference of an identifier type • Verification of the existence of a symbol within a scope • Getting the scope of a symbol 26
CHAPTER 5. VSG - VULNERABLE SAMPLES GENERATOR The two most common operations in a symbol table are: insert() Used during the code analysis to insert a new entry in the table with the symbol identifier and its information. lookup() Used to search for a name in the symbol table and, if it exists, return its information. 5.4.1 Symbol Table in VSG The first step in implementing the symbol table used in the VSG tool was choosing the information that would be added for each entry in the table. This decision was made by the mutation rules that were implemented, which means that new mutation rules in the future may require more information about each symbol. Each entry contains the information present in the table 5.1. For example, for the next variable declaration, the entry stored in the symbol table would be: <”firstName”, Variable, String>. Listing 5.2: Example of a variable declaration String firstName = ”John”; Table 5.1: Attributes for each entry in the Symbol Table Name Symbol’s identifier Kind Represents the symbol’s kind in the program (e.g. Class, Variable, Parameter, Method) Type Stores the symbol’s type (e.g., int, float, boolean, String) The next decision was how the scopes would be defined and represented in the symbol table. Taking advantage of the rich C# library, each scope became a dictionary in which the key consists of the symbol identifier and its value represents the additional information of the symbol. In addition, each scope also has access to the scope in which it is contained so that it is possible to return to the previous scope. The reason for this is that to implement the lookup operation it is necessary to look for the symbol in the outer scopes in case it is not present in the current one. Each symbol will thus be associated with a scope that will only be initialized if it is appropriate to its kind. For example, a symbol that represents a variable does not need a scope. Let’s look at the following example: figure 5.5 shows the symbol table represented from the sample code present in listing 5.3. This sample consists of a simple class with two fields and a method to get the full name of a person. By looking at the table, we can confirm that certain kinds of symbols have no scope, in this case the Field and Variable kinds. We can also verify that the Class kind entry does not have a defined type since the symbol itself is a type. Finally, as mentioned, we can see that from each scope it is possible to go back to the outer scope, except for the root scope. 27
CHAPTER 5. VSG - VULNERABLE SAMPLES GENERATOR Listing 5.3: Example of a code sample to build the symbol table class Person { private String firstName; private String lastName; public String getFullName() { String fullName = firstName + ” ” + lastName; return fullName; } } Root Scope NAME KIND TYPE SCOPE "Person" Class (null) Class Scope NAME KIND TYPE SCOPE "firstName" Field String (null) "lastName" Field String (null) "getFullName" Method String Method Scope NAME KIND TYPE SCOPE "fullName" Variable String (null) Outer Scope Outer Scope Figure 5.5: Example of the symbol table constructed from the listing 5.3 The symbol table will then be defined by the root scope, the scope it is currently in, and the last added symbol that will be used during construction to know where the next scope will be open. As for its operations (Table 5.2), the symbol table built for VSG presents operations for the construction phase (OpenScope,AddSymbol and ExitScope) and for the exploration phase (EnterScope,ExitScope,Lookup and Exists). 28
CHAPTER 5. VSG - VULNERABLE SAMPLES GENERATOR Listing 5.4: Symbol Table construction when visiting a method declaration public override void VisitMethodDeclaration(MethodDeclarationContext context) { string methodName = context.methodName().GetText(); string methodReturnType = context.returnType().GetText(); SymbolTable. AddSymbol (methodName, methodReturnType, SymbolKind.Method); SymbolTable. OpenScope (); Visit(context.formalParameters()); Visit(context.methodBody()); SymbolTable. ExitScope (); } Table 5.2: Operations provided by the Symbol Table OpenScope() Initialize a new scope in the last added symbol and move the current scope to there AddSymbol(name, type, kind) Add a new symbol to the current scope ExitScope() Move to the outer scope of the current scope EnterScope(name) Move to the scope of a symbol if present in the current scope Lookup(name) Search a symbol in the current and outer scopes and return its information Exists(name) Check if a symbol name already exists in the current, outer and all inner scopes The construction of the symbol table takes place from a ParserVisitor who performs the specific operations in the appropriate visit methods. Listing 5.4 is an example of how a new method is stored in the table. At first, it is necessary to collect additional information about the method, in this case the name of the method and the return type. Then, a new symbol is added with the collected information and a new scope is opened (remember that a scope is opened in the last symbol added, in this case the method symbol). The next order is to visit the child nodes of the method declaration. One possibility would be to invoke the VisitChildren method to visit all the nodes below. However, ANTLR visitors allows you to define the path to follow through the parse tree. In this context, it is only necessary to visit the parameters and the body of the method (we can exclude, for example, the list of exceptions that are thrown by the method). In the end, it is important to leave the scope so you can then visit, for example, the next method and open a new scope in the right place. Let us now turn to the most important part of the symbol table: how the mutation rules will explore the table. As in construction, it is mandatory to enter and exit the scopes in the appropriate places of the parse tree. The only difference is that no symbols will be added and instead of opening a scope, you enter a scope. Thus, a mutation rule will have to perform operations on the symbol table at the same points in 29
CHAPTER 5. VSG - VULNERABLE SAMPLES GENERATOR Listing 5.8: The definition of the FindAllMutations method for the Rule class. The Visitor variable is the visitor created for the rule. public List<Mutation> FindAllMutations() { List<Mutation> mutations = new List<Mutation>(); foreach (var file in Sample.Files) { var parser = new ParserBuilder().Parse(file.Value); var typeInferecenceVisitor = new BuildSTVisitor(); typeInferecenceVisitor.Visit(parser); Visitor.Filename = file.Key; Visitor.SymbolTable = typeInferecenceVisitor.SymbolTable; List<Mutation> fileMutations = Visitor.VisitCompilationUnit(parser); fileMutations = Sample.Flow.PathContains(fileMutations); mutations.AddRange(fileMutations); } return mutations; } 5.6.1.2 Creating a new Rule After creating the Visitor that will collect all the mutations present in a code sample, the next step is to create the rule itself. The goal is to take the information about the mutations and apply it to the source code. For this, there is a class called Rule that will serve as the basis for all rules to be created. The purpose of this class is to define the basic functionality that will traverse all the mutation rules that are created. Each rule will be defined by two features: the name of the rule and the Visitor used to search for all mutations present in a code sample. Furthermore, every rule will have two methods: the FindAllMutations() method (listing 5.8) and the Apply() method (listing 5.9). The FindAllMutations method, as the name implies, will search for all mutations present in a code sample. It is at this stage that the Visitors, explained and built in the previous chapters, will finally come into play. For each file present in the sample, the same process will be performed: parsing the contents of the file to get the parsing tree, visiting the tree to build the symbol table, visiting the tree with the Visitor defined for the rule to collect the list of mutations, and finally filtering only the mutations that contain transformations with impact on the vulnerability flow present in the code sample. As for the Apply method, the goal is to apply a specific collected mutation to the code sample. To achieve this, it is necessary to go through the stack of mutation transformations (keep in mind that the order in which transformations are applied is important) and, depending on their information, remove the portion of the target code in the indicated file and replace it with the new code. To finish, it is important to 36
CHAPTER 5. VSG - VULNERABLE SAMPLES GENERATOR Listing 5.9: The definition of the Apply method for the Rule class public CodeSample Apply(Mutation mutation) { CodeSample newSample = new CodeSample(Sample.Files, Sample.Flow?.Clone()); Stack<Transformation> transformations = mutation.Transformations; while (transformations.Count > 0) { var transformation = transformations.Pop(); if (Sample.Files.ContainsKey(transformation.Filename)) { StringBuilder code = new StringBuilder(newSample.Files[transformation.Filename]); int start = transformation.Start; int stop = transformation.Stop; int length = stop - start; code.Remove(start, length); code.Insert(start, transformation.NewCode); newSample.Flow.UpdatePath(transformation.Filename, start, stop, transformation. ↩→NewCode.Length); newSample.Files[transformation.Filename] = code.ToString(); } } return newSample; } update the vulnerability flow according to the transformation information so that all subsequent mutation rules know the correct flow locations in the new code sample. To create the example rule that separates the declaration of a variable from its assignment, all one needs to do is create a Rule instance with the name of the rule and the Visitor that was built in the previous chapter 5.6.1.1. Listing 5.10: Creating the SeparateVariableDeclarationFromAssign rule new Rule(”SeparateVariableDeclarationFromAssign”, new ↩→SeparateVariableDeclarationFromAssignVisitor()) 5.6.2 Applying the Mutations and Rules Composition Finally, after the entire process of creating a mutation rule, the main goal of this thesis is close to being achieved. Only the last step is missing, that is, taking a set of developed rules and actually applying them to a set of code samples. With this, this chapter presents the last component of the VSG tool’s internal structure, the RulesApplier. 37
CHAPTER 5. VSG - VULNERABLE SAMPLES GENERATOR At the beginning of this dissertation, it was stated that one of the essential points for this tool would be that all the generated samples be as diverse as possible to cover as many cases of vulnerable code as possible. Having diversified code samples for the same vulnerability makes it more difficult for security analysis tools to detect them. A simple solution would be to generate a code sample for each mutation detected in each rule. However, following this path, the generated samples would have only one difference from the original sample, and the difficulty of detecting the vulnerability present would be low. Therefore, the best option was to compose the different rules in order to obtain more diversity in the generated samples. So, the last step consists not only in applying the rules, but also in combining them. Two possible paths were considered for rule composition. The first would be to collect all mutations of all rules directly from the original sample and make combinations with at least one mutation from each rule. Unfortunately, this path presented a problem when two or more mutations from different rules had to be applied in the same zones of the code. When applying the first mutation, the information of the transformations of the following mutations would be wrong and the generated code would be syntactically wrong. One way to avoid this would be to separately apply each of the mutations that present conflicts. However, not only would the number of generated samples be low, but also there would not be much diversity between the samples. Therefore, this was not the chosen solution. The second way to compose the rules is similar to the previous solution, however, the rules are applied by phases in each original sample. According to a predefined list of rules, in each phase, one of the rules will be applied to the samples generated by the previous rule. This means that mutations will be collected from the code modified by one of the mutations of the rule that was applied before. In this way, all mutations are applied to the same code sample from which they were collected, so there is no conflict with mutations from previous rules. At the end of the process, if all rules are applicable, all generated samples will have one mutation from each rule and all will be different. Figure 5.7 shows this procedure for 3 rules from start to finish. The goal of the RulesApplier component is to receive a set of code samples, a list of rules, and to follow the explained process to produce the mutated code samples. While doing so, this component will also update the user with information about the rules applied for each original code sample. 38
CHAPTER 5. VSG - VULNERABLE SAMPLES GENERATOR Rule 1 Rule 2 Rule 2Rule 2 Rule 3 Rule 3Rule 3 Original Sample Generated Samples Rule 3 Rule 3 Figure 5.7: Rules Composition Schema. In this example, a list of 3 rules is applied to an original sample generating 11 different versions at the end 39
Chapter 6 VSG Tests This chapter is divided in two parts. The first part shows a simple test where a single code sample is used as input to the VSG tool and then compared to all generated samples. This will be interesting to observe where all mutations from different rules are applied in the samples. For the second part, this chapter will meet the main objective of this dissertation: test how VSG can be used to find false negative results in a static application security testing tool which, in this case, will be Checkmarx SAST tool. Since Java is the only language supported, all samples are in Java source code. 6.1 Original code sample vs Generated samples Before jumping to the differences between the original and generated samples, the following board presents the textual output of VSG. VSG output during the process Generating samples for vulnerability: Command_Injection Sample 'original_sample': -> Applying rule ExtractExpressionStatement -> Applying rule ReplaceArrayInitialization Done! Generated 1 new sample! 40
CHAPTER 6. VSG TESTS This shows that two rules were applied to the original sample and only one code sample was generated from the transformations. The first rule, ExtractExpressionStatement, is similar to the known refactoring rule ”Extract method”that extracts an expression statement to a new method. The second rule, ReplaceArrayInitialization, transforms an array initialization into a list with the same elements that is converted to the respective array. The listing 6.1 presents the original code sample given as input for this test. It’s a simple program that removes and creates files indicated by the user input. Since there is no sanitization for the input, this program has a Command Injection vulnerability, which means the user can execute arbitrary commands on the host operating system. To check the impact of the transformations in the vulnerability, the listing highlights all the flow nodes identified by Checkmarx SAST. It starts on the args parameter of the main method and ends in the exec invocation of the Shell class. Listing 6.1: Original code sample import java.io.IOException; import java.util.Arrays; public class CleanAndCreate { static class Shell { public void execute(String arg ) throws IOException { Runtime.getRuntime(). exec ( arg ); } } public static void main(String[] args ) { String[] params = { ”rm”, args [1], ”;”, ”touch”, args[2] }; String res = Arrays.stream( params ).reduce(” ”, String::concat); new Shell().execute( res ); } } The code sample generated in this test is displayed on listing 6.2. The highlighted green lines represent the differences between the original code sample and, therefore, where the mutations were applied by VSG. The first rule applied was the ExtractExpressionStatement rule which, in this case, extracted the exec invocation expression to a new method within the Shell class. The second rule, ReplaceArrayInitialization, transformed how the params array is initialized. Instead of a simple initialization with all elements, the array is created from a temporary list to which each element has been added before, including the first element of the args parameter which belongs to the flow. This test, not only shows the transformations applied to a code sample, but also how these mutations affect the presence of a vulnerability, since every rule have an impact in, at least, one element of the flow. 41
CHAPTER 6. VSG TESTS Listing 6.2: Generated code sample import java.io.IOException; import java.util.Arrays; public class CleanAndCreate { static class Shell { public void execute(String arg) throws IOException { ffsQXMp(arg); } private void ffsQXMp(String arg) throws IOException { Runtime.getRuntime().exec(arg); } } public static void main(String[] args) { String[] params = {}; List<String> params_temp = new ArrayList<String>(); params_temp.add(”rm”); params_temp.add(args[1]); params_temp.add(”;”); params_temp.add(”touch”); params_temp.add(args[2]); params = params_temp.toArray(params); String res = Arrays.stream(params).reduce(” ”, String::concat); new Shell().execute(res); } } 6.2 Testing VSG against Checkmarx SAST Following the main goal of this dissertation, a set of code samples, each with an identified vulnerability, were used as input to test the resulting VSG tool against Checkmarx SAST. Not only different samples were tested, but also multiple kinds of vulnerabilities were used to check if there were any differences in terms of false negative results detected. All vulnerabilities considered of high risk in Java by Checkmarx were chosen to test VSG. The test was simple. Each initial code sample with a type 𝐴vulnerability (detected by Checkmarx SAST) was provided as input to the VSG tool. After this, all generated code samples were analyzed by Checkmarx SAST to detect type 𝐴vulnerabilities. If not found, it means that there is a false negative result in the analyzed sample. In other words, for each initial code sample, the number of false negative results detected in the samples generated by the VSG tool was evaluated. Table 6.2 shows the results obtained in the tests. Using only the 6 mutation rules present in table 6.1, VSG was able to generate more than the initial number of samples provided as input for almost all vulnerabilities. As discussed in chapter 5.6.2, not only 42
CHAPTER 6. VSG TESTS Listing 6.3: Main program of VSG using the list of transformations in table 6.1 static void Main(string[] args) { var sampleSet = Load(initialSamplesDirectory); var rules = new List<Rule> { new Rule(”ExtractExpressionStatement”, new ExtractExpressionStatementVisitor()), new Rule(”ExtractIfCondition”, new ExtractIfConditionVisitor()), new Rule(”AddReturnVariable”, new AddReturnVariableVisitor()), new Rule(”StringFormat”, new StringFormatVisitor()), new Rule(”ReplaceExplicitTypeWithVar”, new ReplaceExplicitTypeWithVarVisitor()), new Rule(”ReplaceArrayInitialization”, new ReplaceArrayInitializationVisitor()), }; RulesApplier.Apply(sampleSet, rules); int generatedSamples = sampleSet.ExportToFiles(generatedSamplesDirectory); Console.WriteLine($”Generated {generatedSamples} new samples!”); } is this possible by applying the rules, but also in the combination of applicable mutations each rule has in a code sample. Table 6.1: Mutation rules used for the test AddReturnVariable Change a return expression by declaring a new variable for the return value and returning the variable itself ExtractIfCondition Extract the condition of an if statement to a new variable ReplaceArrayInitialization Create a new ArrayList using the values of an initialized array and convert it back to an array ReplaceExplicitTypeWithVar Whenever possible, replace an explicit type in a variable declaration by the keyword var StringFormat Replace a string interpolation expression by a string format expression ExtractExpressionStatement Extract an expression statement into a new method Each of these mutation rules has its own parsing tree visitor from where all the transformations are detected in a code sample. All it’s necessary for the whole process is to create a rule from each of these visitors and use them in the RulesApplier, together with the initial code samples provided. So, the main program of VSG will have a similar look as in listing 6.3. Finally, after running VSG and scanning each generated sample with Checkmarx SAST searching for the vulnerability present in the original sample from where it was created, the results in table 6.2 were obtained. The last column of the table shows that false negative results were detected for 6 of the 43
CHAPTER 6. VSG TESTS vulnerabilities used in the initial code samples. Table 6.2: Results after using Checkmarx SAST to detect in the generated samples the same vulnerability present in the original Vulnerability # of initial samples # of generated samples # of false negatives detected Command Injection 10 20 5 Connection String Injection 11 13 0 Deserialization of Untrusted Data 15 7 0 LDAP Injection 10 9 0 Reflected XSS All Clients 70 129 42 Second Order SQL Injection 13 14 1 Stored XSS 15 29 5 XPath Injection 13 20 2 SQL Injection 71 102 20 44
C h a p t e r 7 Conclusion This last chapter will be a summary of all the information that was presented throughout this document in order to recall the main goal of the project and how it was achieved. Any tool that seeks to identify some characteristic in a given object, whether it is detecting a certain protein in a substance, or looking for flaws in production material in a factory, suffers from the possibility of failing its purpose and not being able to find what they are looking for when it exists, which results in false negative results. The same is true for application security testing tools. The problem with these results is that, for the most part, they go unnoticed and do not end up being corrected. The main idea of static code security analysis tools is to identify vulnerabilities in an application by analyzing the source code. The thesis of this dissertation suggests using code transformation to produce vulnerable code samples that can be used to test the capabilities of these tools. Therefore, this project aims to help discover false negative results and, consequently, failures in the analysis of these security tools. So, it was necessary to design a tool, which was called VSG, whose function would be to receive code samples and apply transformations that would not interfere with the presence of the vulnerability. In order for the transformations not to be random in the sample body, the vulnerability flow was also introduced as an input to the tool to identify the places where the mutations would be better applied to change the way of detecting the vulnerability. The next step consisted of using ANTLR to parse the code according to the language grammar. For each mutation rule, there is a Visitor that will traverse the parsing tree generated by ANTLR, and will collect all possible transformations. For some rules, a type inference mechanism was needed, so a symbol table was implemented that works as an auxiliary data structure with the purpose of storing identifiers present in the analyzed code. 45