Full text
Universidade do Minho Escola de Engenharia Departamento de Informática Marco Avelino Teixeira Pereira Type Annotation for SAST December 2023
Universidade do Minho Escola de Engenharia Departamento de Informática Marco Avelino Teixeira Pereira Type Annotation for SAST Master dissertation Master Degree in Informatics Engineering Dissertation supervised by Pedro Rangel Henriques Alberto Simões December 2023
i AUTHOR COPYRIGHTS AND TERMS OF USAGE BY THIRD PARTIES This is an academic work which can be utilized by third parties given that the rules and good practices internationally accepted, regarding author copyrights and related copyrights. Therefore, the present work can be utilized according to the terms provided in the license bellow. If the user needs permission to use the work in conditions not foreseen by the licensing indicated, the user should contact the author, through the RepositóriUM of University of Minho. License provided to the users of this work Attribution-NonCommercial CC BY-NC https://creativecommons.org/licenses/by-nc/4.0/
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 University of Minho. Marco Avelino Teixeira Pereira
ABSTRACT This document describes the work done to understand the impact of implementing a type annotation algorithm plugged into the Static Application Security Testing (SAST) engine used by Checkmarx. The main goal is to upgrade the Checkmarx’s SAST tool allowing the execution of vulnerability detection taking into account expression types. This means that every result of an expression needs to have a specific type assigned accordingly to the kind of operation and to the different operand types. Along with the assigned type, information on the size of the variable and signedness should be available. As a case study, the C/C++ Programming Language was used. Then an extension to deal with expansion to the C# language was developed and a study of the implications of expanding the system to multiple languages was carried out. A proof of concept was implemented, using a language agnostic approach, that allows for expressions type annotation previous to the analysis of code vulnerabilities. That tool developed supports languages C, C++ and C# and the annotation of their base types. It was possible to re implement some of the vulnerability analysis queries previously created and in use at Checkmax so that they use the implemented expression types. This led to a significant increase in readability of the queries, an increase in the amount of vulnerability results found by those queries as well as a minimum efficiency increase. Keywords: SAST, Static Application Security Testing, Type Annotation, C, C++, C#, Unit Testing, Automation Testing, CxQL iii
RESUMO Este documento descreve o trabalho realizado para compreender o impacto da implementação de um algoritmo de anotação de tipos integrado ao mecanismo de Teste de Segurança de Aplicativos Estáticos (SAST) utilizado pela Checkmarx. O principal objetivo é aprimorar a ferramenta SAST da Checkmarx, permitindo a detecção de vulnerabilidades levando em consideração os tipos de expressões. Isso significa que cada resultado de uma expressão deve ter um tipo específico atribuído de acordo com o tipo de operação e os diferentes tipos de operandos. Juntamente com o tipo atribuído, informações sobre o tamanho da variável e a sinalização devem estar disponíveis. Como caso de estudo, foi utilizada a linguagem de programação C/C++. Em seguida, foi desenvolvida uma extensão para lidar com a expansão para a linguagem C# e foi realizado um estudo das implicações da expansão do sistema para várias linguagens. Foi implementada uma prova de conceito, usando uma abordagem agnóstica à linguagem, que permite a anotação de tipos de expressões antes da análise das vulnerabilidades do código. A ferramenta desenvolvida suporta as linguagens C, C++ e C# e a anotação dos seus tipos base. Foi possível reimplementar algumas das queries de análise de vulnerabilidades previamente criadas e usadas na Checkmarx, para que utilizem os tipos de expressões implementados. Isso resultou num aumento significativo na legibilidade das queries, um aumento na quantidade de resultados de vulnerabilidades encontrados por essas queries, bem como um aumento mínimo na eficiência. Palavras-chave: SAST, Teste de Segurança de Aplicativos Estáticos, Anotação de Tipos, C, C++, C#, Teste Unitário, Teste de Automação, CxQL iv
CONTENTS 1Introduction 1 1.1Checkmarx 1 1.2Static Application Security Testing 1 1.3Type Annotation 2 1.4Objectives 2 1.5Document structure 3 2Compilation and Type Systems 4 2.1Type Anotation 4 2.2Comparing Language Data Types 5 2.3Parsers, Compilers and Interpreters 7 2.3.1Compiler 8 2.3.2Interpreter 8 2.3.3Hybrid Approaches 8 2.3.4Comparison 9 2.3.5Parsing Component 9 2.3.6Semantic Component 10 2.4Summary 11 3Checkmarx’s Pipeline 12 3.1Current pipeline state 12 3.1.1Type Inference 13 3.1.2UAST Creation 13 3.1.3UAST to DOM Conversion 13 3.1.4Resolver 14 3.2CxQL 15 3.2.1SQL Injection Example 16 3.2.2SQL Injecion Problem 16 3.2.3SQL Injection Detection Query 17 3.3Quality Assurance 18 3.3.1Unit Tests 18 3.3.2Automations 19 3.3.3Query Results Comparison 20 3.4Summary 21 4Proposed Approaches 22 v
contents vi 4.1Introduction 22 4.2Approach 123 4.3Approach 224 4.4Approach 324 4.5Assigning Types 25 4.5.1Using Enum combination 25 4.5.2Using Engine Types 25 5Development 27 5.1Initial issues found 27 5.1.1Fixing Type Homogenization for C/C++ 27 5.1.2Integer signedness problem 28 5.2C Type Analysis 29 5.3Approach chosen 30 5.3.1First progress and consecutive halt 30 5.3.2Resolver 31 5.4Scaling-up Type Annotation do C# 36 5.4.1C Language Support 36 5.4.2C# Language Support 38 6Testing 40 6.1Resolver rule unit tests 40 6.1.1Binary Expression’s unit test 40 6.1.2Object Create Expression’s unit test 42 6.2Added CxList Extensions 43 6.2.1FindExpressionWithCustomType method 43 6.2.2FindExpressionByType method 44 6.3Queries Case Studies 45 6.3.1MISRA C Contextualization 45 6.3.2MISRA C 2012 Rule 10.347 6.3.3MISRA C 2012 Rule 10.453 6.3.4MISRA C 2012 Rule 10.558 6.4Performance Testing 62 6.4.1Testing Environment Specifications 63 6.4.2Resolver rule 63 6.4.3CxQL queries 64 7Conclusion 66
LIST OF FIGURES Figure 1Syntax Analyzer output adapted from Aho et al. (2007)10 Figure 2Checkmarx source code parsing pipeline 12 Figure 3 Information on type modifiers for unsigned long after the Type Inference stage 13 Figure 4DOM information on type modifiers for unsigned long 14 Figure 5Resolver Architecture 14 Figure 6Automation Checker application 20 Figure 7Swissknife presentation of query results 21 Figure 8Type Annotation proposals sections 23 Figure 9Type information before C type info integration 27 Figure 10 Type information after C type info integration 28 Figure 11 Resolver architecture 31 Figure 12 Essential type category table (MISRA,2019)47 Figure 13 Query 10.03 automation runner report 52 Figure 14 Query 10.05 automation runner report 58 Figure 15 Essential type inappropriate cast table (MISRA,2019)58 Figure 16 Query 10.04 automation runner report 63 vii
2.2. Comparing Language Data Types 6 Data Type Size(bytes) int8_t 1 uint8_t 1 int16_t 2 uint16_t 2 int32_t 4 uint32_t 4 int64_t 8 uint64_t 8 Table 2: C "Portable" Language Data Types Due to architecture differences the C language provides some definitions that are considered more portable, presented in Table 2 C# Language As it is to be expected the C# language has a large amount of crossover with C in terms of data types. Data Type Size(bytes) sbyte 1 byte 1 bool 1 short 2 ushort 2 char 2 int 4 uint 4 float 4 pointer 8 long 8 ulong 8 double 8 decimal 16 Table 3: C# Language Atomic Types When using C#’s compiler for a simple program that writes the size of data types using the same function used for C (sizeof) the results presented in Table 3are obtained. When compared to C, this language does not have architecture dependant sizes for its data types.
2.3. Parsers, Compilers and Interpreters 7 Java Language Java is a very well typed language which allows for good correlation with the two previously presented languages. Data Type Size(bytes) byte 1 boolean 1 short 2 char 2 int 4 float 4 long 8 double 8 Table 4: Java Language Atomic Types The biggest difference between this language’s types and the other languages’ mentioned is that Java does not have a way of declaring a type as signed or unsigned, all of them being signed. Correlations When comparing these languages’ types to one another some types can be correlated across different languages. Table 5presents the types that have equivalent sizes and range across the presented languages. C Designation C# Designation Java Designation Size(bytes) Signedness signed char sbyte byte 1signed bool (_Bool) bool boolean 1N.A. short int short short 2signed int int int 4signed float float float 4signed long long int and long int long long 8signed double double double 8signed Table 5: Language Data Types Correlations 2.3 parsers,compilers and interpreters A tool that processes programs needs to perform its recognition. To recognize the meaning of a sentence of a given language three complex but standard steps shall be executed: Lexical
2.3. Parsers, Compilers and Interpreters 8 analysis, Syntax analysis, and Semantic analysis (Aho et al.,2007). This process usually builds a tree-like memory representation to contain the meaning of the code, known as Abstract Syntax Tree (AST). Whether the processing tool used is a compiler or an interpreter they always have two different stages, these are represented by the parsing component, where the Lexical and Syntax analysis occurs, and the semantic component, where the Semantic analysis happens. 2.3.1Compiler A compiler is a computer program whose purpose is to transform code from a human readable structure into machine code that has a binary structure(1’s and 0’s) (Cooper and Torczon,2011). The steps a compiler takes are done to all the code, independently from usage, a program will be translated to machine code if and only if there are no errors in the syntax of the program. This means that if the program compiles, independently from the flow that the program takes, no syntax errors related errors will happen. Examples of programming languages that use a compiler are C, C++ and Scala. 2.3.2Interpreter An interpreter is a computer program that executes instructions written in the source code directly without needing to convert the language to machine code. The high level coding language can get translated to an intermediate representation that is more efficient and executed that way. The interpreters parse the source code line by line only parsing the lines that are being used, so if a program flow does not pass through certain lines or functions these won’t be parsed or converted into machine executable code. This means that the code can be ran even if some syntax errors exist in it, as long as the program flow never encounters a line with a syntax error no exceptions are raised. Examples of programming languages that use an interpreter are Perl, Python and Ruby 2.3.3Hybrid Approaches Some programming languages, leverage a combination of both compilation and interpretation. Java, for instance, compiles code into bytecode for the Java Virtual Machine (jvm)
2.3. Parsers, Compilers and Interpreters 9 (Holmes,1999) and then interprets this bytecode within the JVM. This hybrid approach blends the advantages of both compiler-only and interpreter-only languages. Other examples of programming languages that use compilation to intermediate code are C#, using Common Language Runtime (CLR) (Richter,2012) and Scala, using JVM (sca). 2.3.4Comparison While a compiler needs to traverse the AST to produce assembly or byte-code, an interpreter traverses the AST and performs tasks accordingly with the tree structure. This traversal means that the compiler will produce faster running code however there will be some time spent compiling every piece of code, on the other hand, the interpreter runs code slower because each line is processed in run time but in exchange ofr that there is no dedicated time for compiling code before running it (Smith,2022). As for the SAST tools, the tree is traversed for the detection of specific vulnerabilities. 2.3.5Parsing Component As the first step of any compiler/interpreter, the parsing component is responsible for the lexical and syntax analysis, this constitutes the division of the input into tokens and the verification of the correctness in the order of appearance of these tokens. Lexical Analysis The lexical analysis step of the parsing component is responsible for dividing the input into groups of characters, named lexemes, with each representing a previously defined token, this step is usually called tokenization because of its nature (Lutkevich,2022). The tool that does this process is usually named lexical analyzer and it takes as input the source code which may have passed through preprocessing for Macro substitutions and such. For example, if given the code below: position = initial + rate *60; The symbol table would start to be generated having indexes pointing to the correspondent identifier. The variable "position" would be replaced with <id,1>, with id meaning identifier and 1being the index that contains it in the symbol table. The symbols "=", "+" and "*" would be replaced with the corresponding token, <=> , <+> , <*> , and finally the constant "60" would be mapped as a lexeme to the token <60> (Aho et al.,2007).
2.3. Parsers, Compilers and Interpreters 10 At the end of this stage the output is now a list of all the tokens that replaced source code like so: <id,1> <=> <id,2> <+> <id,3> <*> <60> Syntax Analysis The syntax analysis phase of the component is responsible for taking the linear tokenized version of the source code and create a parse tree built according to the grammar’s rules for the language. The created parse tree is named a syntax tree resulting in the previously mentioned AST, however this version of the AST gets augmented and transformed in later phases. Looking at the output example from the previous phase: <id,1> <=> <id,2> <+> <id,3> <*> <60> This phase defines the order in which the operations should be performed, so the output of this phase would end up being a tree that represents the above data as shown on Figure 1. Figure 1: Syntax Analyzer output adapted from Aho et al. (2007) 2.3.6Semantic Component This component contains the last of the three main steps mentioned before. The semantic analysis is responsible for using the symbol table to verify the semantic consistency of the produced syntax tree. Semantic Analysis As the name implies, semantic analysis is mostly responsible for analysing the semantic composition of the parsing tree it receives as input. This semantic analysis is associated with checks like object binding, association of a variable or function calls with the respective
2.4. Summary 11 definitions, and definitive assignment, making sure every local variable is rightly initialized before any uses. One of the most interesting, in terms of this thesis purpose, parts of the semantic checking is type checking. Type checking verifies if array accesses use integers for example and not floating points. Some languages use type coercion to allow for operations between 2 different types. For example, let’s consider the code below: float a = 30.2; float b = a*20; In this expression before calculating the value of a*20 , the number 20 is coerced into a floating point representation, turning into 20.0(Lutkevich,2022). This means that this checking phase could be explored to allow for type annotation of expressions and such. 2.4 summary During this section, the type annotation subject was explored and a comparison of types between different languages was made, this comparison aimed at providing context to one of the approaches that will be explored in a future section. The latter section of this chapter had the purpose of adding context to how languages are compiled, parsed and interpreted.
3 CHECKMARX’S PIPELINE In this chapter some information on the current state of Checkmarx’s pipeline will be provided for context. This chapter’s main focus is to describe the various parts of the Checkmarx’s Engine that will directly impact type annotation when implemented. 3.1 current pipeline state Figure 2: Checkmarx source code parsing pipeline Initially the source code gets parsed by ANTLR, generating a simple semantic tree, this stage is named Type Inference. This tree then gets transformed into the Universal Abstract Syntax Tree (UAST) which goes through the last part of the processing stage, creating the Domain Object Model (DOM) as seen on Figure 2. After this third and final stage of processing there is a number of services that take the information present on the created DOM to provide useful features when finding and designing vulnerability detecting queries. 12
3.1. Current pipeline state 13 3.1.1Type Inference The first stage of the pipeline is responsible for using the respective language grammar while generating the symbol table and the first iteration of a tree. Each language has an ANTLR written grammar using visitors to allow for higher level of control over the grammar tree crossing. At the end of this stage, information on types, as well as modifiers of said types, is already present in the final product. On the next stages of the pipeline this information gets further processed and saved in more suitable structures for services to use without having to adapt the data. Figure 3shows the type information for an unsigned long variable stored in the global symbol table. Figure 3: Information on type modifiers for unsigned long after the Type Inference stage 3.1.2UAST Creation After the generation of the initial tree with the respective global symbol table, comes the creation of the second stage in the pipeline where every language code is saved in a structure that can be iterated over by the same program. This stage is composed by traversing the previously generated tree and adding/editing information accordingly. At the end of this stage a new tree is produced, this tree contains a lot more useful information , however certain portions of this tree are still disorganized and for that reason a new stage was created, the generation of a much more polished tree structure where the information is well separated and much more easily accessible. It is also worth noting that even though the UAST is Universal, there exists language specific data that ends up being converted or deleted in the conversion to DOM. 3.1.3UAST to DOM Conversion This stage crosses the UAST in order to create the last and most well defined tree in the pipeline, knwon as DOM. Take Figure 4as an example, this image shows the type information
3.1. Current pipeline state 14 on a unsigned long variable. Instead of having a list of modifiers as the previous trees, now clear cut information on signedness and size of the variable is presented, this is done through conversions applied when traversing the UAST. Figure 4: DOM information on type modifiers for unsigned long 3.1.4Resolver The Resolver is one of the complementary services that uses the information present on the DOM to resolve the types of variable references (referred to as Unknown References) using the variable declaration statements and the functions/methods return types which already contain the relevant information, including the type name, signedness and size. ResolverRule The Resolver is composed of Resolver Rules, as seen in Figure 5, each resolve rule must contain an Initiate method alongside an Execute method. The Initiate method is called for all of the rules when creating the Resolver, the method is responsible for initiating all the structures needed for the rule to be ready to be executed. The Execute is called for each of the rules, one by one, in the order by which they were added to the resolver. This is the more relevant method of the Resolver rule. It is responsible for applying the rule’s objective to the DOM structure. Figure 5: Resolver Architecture
3.2. CxQL 15 Examples As presented previously, the Resolver rules are responsible for resolving the types and references of the DOM. example 1 One of the Resolver rules is responsible for resolving the method references. When a method is called from a different file, the original reference gets annotated in the DOM, this reference is then used to replace the relevant method data with the data that is present in the original declaration. This rule makes it so that the flows between different points of the engine can still be found and trusted since all the references of methods get resolved, assuming the original method is present in the project. example 2 Other resolver rules like the UnknownReference resolver rule, an unknown reference, is, as explained previously, a variable usage. Looking at the code in Listing 3.1, the variable c is declared, and that declaration will count as an AssignExpression where the left side of the assignment will be a variable declaration. However, in the case of the declaration below it, of variable x , which is also an AssignExpression, the right side will be a Binary Expression using an UnknownReference and a Literal. At this stage, cwill simply be a default UnknownReference only referencing it’s declaration statement. Upon the Resolver stage, c , will be resolved using the reference assigned to it. This resolve will allow the user to access the type of the c variable without having to search for its assignment. 1int c = 1; in t x = c + 3; Listing 3.1: Unknown Reference Expression 3.2 cxql Checkmarx Query Language (CxQL) is a Domain Specific Language (DSL) used by the Checkmarx product. It resembles a framework that is used with C# to query the generated DOM with the intuit of finding vulnerabilities. It provides methods and the structures used in the DOM so that queries can be written looking for specific properties in the DOM. CxQL allows users to create custom queries to identify specific patterns or coding practices that may indicate security issues.
4 PROPOSED APPROACHES This chapter will delve into the proposed approaches and their advantages/disadvantages for the implementation of type annotation in the Checkmarx’s pipeline. 4.1 introduction The existence of three different stages means that there are various places where the type annotation could be added. If implementing type annotation on the initial parts of the processing stage, working with a language specific action allows for as much detail as needed. However this would mean that the additions will be language dependent and will signify that it would have to be implemented differently for each language. As an alternative, the implementation and solution can be done towards the end of the processing stage. This would convey that all the information would be kept in the same way on the DOM, then the implementation would be general for any and all languages. However this creates some concessions, since the information present is very general the type annotation would have to use the Engine defined types like int even though the name of this type on the language may be integer . Furthermore for languages whose types are not compatible with the Engine types some conversions or exception cases would have to be made. Figure 8contains the current architecture with numbers identifying the section to which each one of the three proposals for implementation discussed in this chapter refers to (1,2 and 3). 22
4.2. Approach 1 23 Figure 8: Type Annotation proposals sections 4.2 approach 1 The first proposed approach is to use the creation of the global symbol table to save each expression’s type, size and signedness, when applicable. This approach consists of using the information present when iterating each variable declaration in the source code. This solution would lead to some issues however, the implementation of type annotation for sub expressions would cause some problems as the type would be saved for the expression and not the sub expressions present in it since during that stage only expressions are iterable. Consider the following example: int x = 10 + 12.0 + 14 Fully implementing type annotation would mean that a user could access the type of 10 + 12.0 + 14 but also the type of 10 + 12.0 is desired, and this first implementation would require adding symbols for each sub expression to the global symbol table and would, introduce a big increment on an already large overhead. Also, the goal of a symbol table is not to keep information about expressions. The sub expressions are determined by the order of operations. This solution would allow for a more in depth adaptation of types for each language, so more detail around each type would be available since the processing of types is happening closer to the initial moments of the parsing stages. This solution was not chosen either because there is no information about function return types, etc., at the moment when the symbol table is generated.
4.3. Approach 2 24 4.3 approach 2 As an alternative to developing a type annotation solution in a very language dependent environment, the possibility of implementing a solution when creating the DOM arises. This solution consists of using the Universal AST traversal to add information about the types when processing Variable Declarations and Expressions, taking advantage of every child node’s type to define the current type along with their modifiers. For example, in the expression f(x) + y, the conversion from UAST to DOM will first convert f(x) and y to DOM, thus invoking the process recursively, which in turn would annotate the types of these two sub-expressions. Therefore, the visit to the binary operation ends up taking advantage of the types that were inferred during the conversion of its children. As an advantage, this solution provides the possibility of implementing type annotation for every language at once as it is happening in a stage where it uses universal input independent of language. However this advantage comes at a cost of having the types be more general instead of being language specific. The setback on this approach is that a default case, that would be used for comparing all direct types between languages would be created and for some languages, an exceptional case would have to be made when the default case can’t be applied. Examples of these would be languages like python which are dynamically typed and very few information on the types exists currently. Another setback to this approach is that the types of various variables are not present at this stage and need to be recalculated, the types of variables are only associated during the resolver phase. Similar to the first approach, there would be no information about types when they depend on the work of the resolver, which finds the definition of variables or functions. 4.4 approach 3 Finally, a third approach was considered, the possibility of adding a new rule to the Resolver stage. Since the rules in the resolver stage are responsible for resolving statements like imports, variable calls and methods, the new rule would be ran only after all other rules, to make sure all of the information needed would already be present. This new rule would annotate expressions with the respective annotation type. This solution’s advantage is that it is done at stage most to the right of the pipeline, so any implementation at this point is language agnostic and therefore automatically works for all languages. Along with this, since it is a whole new resolver rule, there is full control on the development side to shape the solution as fitting as need be without worrying about how the other code will react to the changes since this rule works in a sandbox environment.
4.5. Assigning Types 25 The biggest setback against this approach is that unlike the previous one, since the new resolver rule is in a sandboxed environment there are no traversals happening that can be piggy backed on, making it so that there needs to be an explicit traversal through all of the expression nodes. 4.5 assigning types When it comes to assigning types, there are two different possibilities on how the types can be saved. The types used can be the same as the ones present in the DOM, generic types used in all languages or using types from a new enum file containing every combination of types. 4.5.1Using Enum combination The first idea was creating an enum file with every possible type and modifier combination saving every needed information. An simple example of this is presented in 4.1. This created enum types could then be used to identify the types of the expressions. This solution allows for a lower overhead increase which would translate to small effects performance wise. As a cons however this solution is not very elegant, it does not take advantage of the already existing types on the Engine. 1public enum DataType 2{ 3Int = "int", 4String = "string", 5Char = "char", 6Float = "float", 7Bool = "bool", 8Double = "double" 9} Listing 4.1: Example of enum typing 4.5.2Using Engine Types The current Checkmarx’s Engine provides processing for types in declarations, this would mean that the same types and modifiers can be used. This types allow for information on
4.5. Assigning Types 26 signedness and size when applicable which means that the information on short int and long int would be saved and available at any point. This solution is much more elegant than the previously discussed one, however it will require the analysis of the current Engine to fix existing problems, presented in the next section. This implementation would not create any overhead other than the one created on the type annotation as the type information is already saved whether it is used or not.
5 DEVELOPMENT After having decided on which of the proposed approaches was the most promising to explore first, the intricacies of creating the type annotation system can now be described. This chapter starts with fixes made to issues found in the C types, followed by an analysis of C types, explaining the modifications done. After that comes the development process exploration, and the shedding of light on the challenges that arise during its implementation. 5.1 initial issues found In this section, initial existing problems with C/C++ are explained and fixed in preparation to the implementation of the proposed solution. 5.1.1Fixing Type Homogenization for C/C++ When trying to gather more information on how types are currently assigned to variables on the Checkmarx’s Engine, it was found that for the C/C++ language the homogenization of the types (u)int16_tand (u)int64_t) was not happening correctly. When homogenizing types they are put in the general categories like int , float and char . When these types have a modifier behind them like short or long in the case of int’s, these modifiers are added as a member of the correspondent DOM node. In the case of long long types, this modification was harder since a whole new “type” had to be added, longlong. This can be seen in Figure 9. Figure 9: Type information before C type info integration 27
5.1. Initial issues found 28 The first thing to do when trying to solve this problem is finding out where this attributions are being made, the easiest way to do so is to go into the C++ language parsing project and find out all the references to the types that are not well homogenized, like (u)int(size)_t . This can be easily done using the grep/findstr command. After finding out all the places these types are mentioned, the analysis of the assumptions made for them and their respective fix can be applied, now the same example is presented as shown in Figure 10. Figure 10: Type information after C type info integration In addition to solving this problem some unit tests were added as a way of checking if everything was working correctly for those types as well as for the modifiers of simple types, like short int. After all these tests being added and every existing test being adapted to how it should be, before this changes could be merged to the main branch a series of automations and existing queries had to be adapted so that they continued to work as they did up until this moment. 5.1.2Integer signedness problem After fixing all of the problems described in the previous section, a different problem arised. In C, when declaring an integer, if no signedness modifiers are added, the default modifier will be signed, meaning that, in Listing 5.1, when declaring variable x and variable y , both integers will be signed. However, in the current version of the Checkmarx Engine, although yis being correctly attributed the signed modifier, xis not, the signedness modifier for xis Unknown, used when the signedness is not applicable or can’t be deduced. 1void main() { 2int x = 1; 3signed int y = 1; 4} Listing 5.1: Integer signedness problem The fix for this problem was not very complex, it passed by looking into previously modified components and adding a new condition so that the modifier was correctly added.
5.2. C Type Analysis 29 Left/Right _Bool char int float double _Bool _Bool char int float double char char char int float double int int int check Table 7float double float float float float float double double double double double double check Table 7 Table 6: C Type Name Ranking Left/Right long long long short long long check Table 8long long long long long long long check Table 8long short long long long check Table 8 Table 7: C Type Size Ranking There was the need to make sure that no other signedness modifier had been added, so this fix was placed when the statement modifiers were all already processed. After implementation came the phase of testing, the addition of unit tests and finally the creation of automations and result checking. Of all of these phases, the more complex one was the result checking, this change though simple comes with a very high amount of changes in vulnerabilities detected for projects. Meaning that a lot of time was spent analyzing the changed results and making sure that all the results produced were consistent to what its query was trying to detect before marking them as good results. 5.2 c type analysis The C/C++ case study requires a research of implicit type conversions. Every type in C/C++ along with its modifiers has a rank associated as part of the C99 documentation (C99,2005), meaning that when two types are compared, one of them will prevail and the other will be converted. This decision is based on the rank associated with each type: the lower the rank, the higher the amount of match ups in which this type will be converted when compared to other types. Take bool as an example, this type has the lowest rank, therefore, when matched against any other type, it will always be converted and never prevail. Left/Right signed unsigned signed signed unsigned unsigned unsigned unsigned Table 8: C Type Signedness Ranking
5.3. Approach chosen 30 For the case study in question (C/C++) it was concluded that the operator has no effect on the ranking of the types, therefore, Tables 6,7,8represent all the combinations of type conversions possible. As can be seen in C99 (2005), the initial comparison is made using Table 6, and on the cases of int and double, Table 7may be needed, finally the last comparison made is only used for the int type as double types do not store signedness information. This means that the most important comparison comes in the form of type, with double being the most “powerful” out of them all, in case two types are equal for int and double, Table 7is checked, containing the comparisons of size modifiers, and lastly, the comparisons of signedness modifiers are made on Table 8, for int values that have the same size modifiers. This explains why when dividing two integers, the result is an integer (and the decimal part is lost), but when one of the operands is a float or double, the result is also a float or double. 5.3 approach chosen 5.3.1First progress and consecutive halt The idea of this approach rests on using the UAST2DOM traversal that happens when generating the DOM. The first expression tackled was the unary expression, this is a simple and good starting point to see what can be automated when generating the code for type annotation. A unary expression is any expression with an operator on their left. An example of these expressions for the C language would be ++x , -x , !x , *x , &x , etc. The type of any of these expressions, except for the ! (not) operator, will be influenced by the left operand, in the case of ! (not) operator the the expression will always be of type int and therefore independent of the operand type. Expressions like & (address) and * (pointer), require calculating the type of the operand, this operand can be another expression which will eventually map onto a variable or a literal. The type of a literal is easily determined through the text or type of the expression at hand. The type of a variable was assumed to be present at this stage of the pipeline, this means that each variable (named as UnknownReference) will have a Type containing member on the class (named DeclaratorType). However upon further testing it was discovered that this member was not yet filled and therefore it meant that we would have to either calculate it or move our implementation to a further stage in the pipeline, calculating the types would mean duplicate code that was already done in the resolving stage, so the decision taken was to explore the resolver stage and try to move our work to that point in the pipeline. This meant the exploration of approach 3, and with it comes the exploration of a new stage in the pipeline, the resolver.
5.3. Approach chosen 31 5.3.2Resolver As explained previously in the Checkmarx’s pipeline section, there are complementary services that run on top of the final DOM product, on of those services is the Resolver. The Resolver service is responsible for attributing, among others, the types associated with variable and function calls, using the context in which they are called and their initial declaration. The Resolver is a service composed by resolver rules, each of them responsible for a different area, one of them is responsible for the attribution of types to variable, function and method calls. If a new rule is added, and runs after this rule, the information on the types would already be present and allow for the expression type annotation with all the information needed. The creation of a new Resolver rule was the chosen solution, this way the infrastructure for type annotation is set for all languages, and since a new rule is created, all the control over what happens is present which means that the code can be written so that future improvements and additions can be made more easily. This solution has, as a drawback, to create a new traversal, however this traversal is already optimized to only traverse expression statements which mitigates this negative aspect. ResolveExpressionTypes Rule Figure 11: Resolver architecture Following the diagram on Figure 11, as explained earlier, the Resolver is composed by a dozen rules, each of them implements the IResolverRule interface. This interface’s main point is the Execute method, which is called by the Resolver for each one of the rules. Along
5.4. Scaling-up Type Annotation do C# 38 Member Access Expression The C language accepts structures, these are used to group variables related to the same area, for example, take the struct in Listing 5.4. 1struct Car { 2char make[20]; // Make of the car 3char model[20]; // Model of the car 4int year; // Year of the car 5double price; // Price of the car 6int mileage; // Mileage of the car 7}; Listing 5.4: C struct example When accessing a member of this struct, like shown in int yearOfCar = car.year , the right side of this assignment expression is a member access expression to the member year on a variable of the type struct for the struct Car. 5.4.2C# Language Support After having all the infrastructure mounted, also having the C language support implemented, the exploration to implement the C# language can begin. The implementation for the C# language requires the addition of support for the C# usable expressions. the majority of expressions are already supported from the C language, however, in C#, there is an expression that can be used on the right side of an “AssignExpr” expression. Switch Case Expression In C#, the switch case expression can be used as the value of an assignment. Take for example the code presented in Listing 5.5. 1string result = number switch 2{ 35=>"Five", 410 => "Ten", 515 => "Fifteen", 6_=> "Other" 7}; Listing 5.5: SwitchCaseExpr example
5.4. Scaling-up Type Annotation do C# 39 In this example, the variable result is initiated with the value of a switch case expression, depending on the value of the variable number, result will take the corresponding value defined in the switch case section. Problems found The adaptation to C# was very fast and it worked without any issues, the biggest problem faced was the differentiation in types for C# and C C++, in C, after applying the initial fixes, the resulting types used the Signedness and the Size properties of the type, this made it more organized. When expanding the implementation do C#, the biggest change noticed when creating the respective unit tests for the expressions was that the types for this language were not taking advantage of the structure of the TypeRef class. 1{ 2static void Main() 3{ 4long myLong = 1000000000000L; 5short myShort = 500; 6uint myUnsigned = 2000000U; 7int mySigned = -100; 8} 9} Listing 5.6: C# variables Take the example presented in the Listing 5.6, since the variables are declared using different names than in C, and the support for the C# types is not taking full advantage of the TypeRef class, the types in C# end up using only the resolvedTypeName to store the type.
6 TESTING This chapter presents all the work done related to testing. As mentioned previously, one of the most important parts to assure the quality of the developed solution is testing. Various unit tests were added and many manual tests were performed to verify performance changes, results variations and also unhandled exceptions that caused the program to crash. This chapter will explore all the added functions and discuss some modified CxQL queries that take advantage of type annotation. For each one of these queries, a comparison stage is present where the results, their number, the performance and quality of the scan are compared. 6.1 resolver rule unit tests As explained in previous sections, one of the most important parts of software development is the testing phase. This phase is usually characterized by a list of manual tests and a list of automated tests, that verify the behavior of the program on simple functions and inputs, maintaining the scope of a unit test as small as possible. This section will touch on the created unit tests related to the expressions type annotation added for each language. All of the tests built follow the same format so only two of them will be shown and discussed in this section. However, all of the expressions that are supported contain at least one unit test related to its type and language being well calculated. 6.1.1Binary Expression’s unit test The test presented in Listings 6.1,6.2, relates to the C++ implementation of the addition of types to all binary expressions. In C#, Datarows can be used as a way to simplify unit tests so that a lot of repeated code is exchanged by simple test inputs. A user can write multiple Datarows with different values and each of the Datarows will be a unique unit test. Using as the method’s arguments, the ones passed as part of the Datarow declaration, simplifying 40
6.1. Resolver rule unit tests 41 hardcoded comparisons inside the test. The remaining code should be simple to understand as unit tests were already explored previously. 1[DataRow("const int*x;const int*y;const char *z=x+y;", 2"int", 3TypeSizeModifiers.LongLong, 4TypeSignednessModifiers.Unsigned)] Listing 6.1: BinaryExpression’s CPP unit test Datarow Listing 6.1contains this tests DataRow example. The first entry of the DataRow is the code sample that the test will parse, after that is the expected type name, followed by the expected type size modifier and finally the type signedness modifier. 1public void TypeAnnotation_BinaryExpressionTests(string code, string typeName, 2TypeSizeModifiers typeSize, TypeSignednessModifiers typeSignedness) 3{ 4var domSymbolRepository = new DOMSymbolRepository(); 5var resolveContext = code.ResolveLanguage(ProjectType.CPP, domSymbolRepository); 6var symbols = domSymbolRepository.GetSymbolsIndex(ProjectType.CPP); 7var allBinaryExprs = domSymbolRepository.GetAllNodes().OfType<BinaryExpr>(); 8 9Assert.AreEqual(1, allBinaryExprs.Count()); 10 11 BinaryExpr binaryExpr = allBinaryExprs.First(); 12 var varType = (binaryExpr.CustomAttributes. 13 First(attr => attr.Name == "AnnotatedType") 14 .Parameters[0] as TypeOfExpr).Type; 15 Assert.IsInstanceOfType<PointerTypeRef>(varType); 16 17 var pointerType = ((PointerTypeRef)varType).PointerType; 18 19 Assert.AreEqual(typeName, pointerType.ResolvedTypeName); 20 Assert.AreEqual(typeSize, pointerType.TypeSize); 21 Assert.AreEqual(typeSignedness, pointerType.TypeSignedness); 22 } Listing 6.2: BinaryExpression’s CPP unit test In Listing 6.2, a few variables are declared and then used to initiate the value of variable z . Both variables declared are of type pointer to int , and therefore, the resulting type of the binary expression should be a pointer type pointing to an int . Along with this test, more complicated tests are present that test the same functionality using different variable names, other expression types and binary operands.
6.1. Resolver rule unit tests 42 6.1.2Object Create Expression’s unit test The test presented in Listing 6.3, relates to the C# implementation of the type annotation of object creations (ObjectCreateExpression).. This expression’s main component is the creation of a class or struct using the new keyword for the creation. The test bellow follows the same logic as the one presented above and checks if the ResolvedTypeName of the annotated type is the name of the struct/class. The size and signedness are also verified merely as a security measure to make sure that no value has been altered other than the name. 1[DataRow("public class MyClass{} 2public class Program{ 3public static void Main(){ 4MyClass myObject = new MyClass() 5} 6}", 7"MyClass", 8TypeSizeModifiers.Default, 9TypeSignednessModifiers.Unknown)] 10 public void TypeAnnotationObjectCreateExprExprTests_Default(string code, 11 string typeName, TypeSizeModifiers typeSize, 12 TypeSignednessModifiers typeSignedness) 13 { 14 var domSymbolRepository = new DOMSymbolRepository(); 15 var resolveContext = code.ResolveLanguage(ProjectType.CSharp, domSymbolRepository) 16 var symbols = domSymbolRepository.GetSymbolsIndex(ProjectType.CSharp); 17 var allnodes = domSymbolRepository.GetAllNodes(); 18 var objectCreateExprs = allnodes.OfType<ObjectCreateExpr>(); 19 Assert.AreEqual(1, objectCreateExprs.Count()); 20 21 ObjectCreateExpr objectCreateExpr = objectCreateExprs.First(); 22 var varType = (objectCreateExpr.CustomAttributes. 23 First(attr => attr.Name == "AnnotatedType"). 24 Parameters[0] as TypeOfExpr).Type; 25 26 Assert.AreEqual(typeName, varType.ResolvedTypeName); 27 Assert.AreEqual(typeSize, varType.TypeSize); 28 Assert.AreEqual(typeSignedness, varType.TypeSignedness); 29 } Listing 6.3: ObjectCreateExpression’s C# unit test
6.2. Added CxList Extensions 43 6.2 added cxlist extensions The first thing needed to be able to take full advantage of the work produced is the creation of new CxQL methods. One of them looks into the custom attribute Annotated Type of an Expression and returns all the expressions that had a given type. The other additions use is to return all the expressions with the AnnotatedType attribute. 6.2.1FindExpressionWithCustomType method Instead of adding a method that looks for all of the expressions which had an annotated type, the approach taken was more general. It looks for all of the expressions that contain a custom attribute of the name given as an argument. This way, this method can later be used for other custom attributes that may be added to expression nodes. The method is portrayed in Listing 6.4. 1public override CxList FindExpressionWithCustomAttribute(string Name) { 2CxList retList = NewEmptyList(); 3try { 4foreach (KeyValuePair<int, IGraph> cml in this.data) 5{ 6try { 7if (cml.Value is Expression expr && expr.CustomAttributes. 8Any(attr => attr.Name == Name)) 9{ 10 retList.data.Add(cml.Key, cml.Value); 11 } 12 } 13 catch (Exception exc) when (!(exc is OperationCanceledException)) { 14 LocalLog("AtomicQuery tested " + exc.TargetSite + ":"+ exc.Message); 15 } 16 } 17 } 18 catch (Exception exc) when (!(exc is OperationCanceledException)) { 19 LocalLog("AtomicQuery tested " + exc.TargetSite + ":"+ exc.Message); 20 } 21 return retList; 22 } Listing 6.4: FindExpressionWithCustomAttribute method
6.2. Added CxList Extensions 44 The method referenced is part of the on the CxList implementation, and thanks to that method, a list of all the expressions that have an annotated type can now be fetched when writing a CxQL query. The method’s logic is iterating all of the nodes that are expressions from the list it was called for and then keeping on the return list only the ones that have a custom attribute with the same name as the argument passed. In the cases of testing shown in the future, the name of that attribute will be ”AnnotatedType“ as it is known that that attribute will only be present in Expression’s whose type was calculated fully. 6.2.2FindExpressionByType method Along with the previous referenced method a different method has been added, shown in Listing 6.5. This method is responsible for retrieving all of the Expressions of a certain type, as its arguments the method takes information on the type at hand, this meaning, the type name, the signedness and the size. 1public override CxList FindExpressionByType(string resolvedTypeName, 2TypeSizeModifiers typeSize, TypeSignednessModifiers typeSignedness) 3{ 4CxList retList = NewEmptyList(); 5try 6{ 7foreach (KeyValuePair<int, IGraph> cml in this.data) 8{ 9cancellationToken.ThrowIfCancellationRequested(); 10 try 11 { 12 if (cml.Value is Expression expr 13 && expr.CustomAttributes. 14 Any(attr => attr.Name =="AnnotatedType")) 15 { 16 TypeRef annotatedType =(expr.CustomAttributes. 17 First(attr => attr.Name =="AnnotatedType") 18 .Parameters[0] as TypeOfExpr).Type; 19 if (annotatedType.ResolvedTypeName ==resolvedTypeName && 20 annotatedType.TypeSize == typeSize && 21 annotatedType.TypeSignedness ==typeSignedness) 22 { 23 retList.data.Add(cml.Key, cml.Value); 24 } 25 }
6.3. Queries Case Studies 45 26 } 27 catch (Exception exc) when (!(exc isOperationCanceledException)) 28 { 29 LocalLog("AtomicQuery tested " + 30 exc.TargetSite + ":"+ exc.Message); 31 } 32 } 33 } 34 catch (Exception exc) when (!(exc isOperationCanceledException)) 35 { 36 LocalLog("AtomicQuery tested " + exc.TargetSite + ":"+exc.Message); 37 } 38 return retList; 39 } Listing 6.5: FindExpressionByType method This method iterates all of the expressions in the CxList it was called for and returns a list only with the Expressions that both, contain the AnnotatedTypeCustomAttribute and also have the type with the argument given characteristics. Since these types of methods are available to the user all of the Exceptions should be caught and handled, that is the reason why the code presented is so large compared to the actual functionality described. 6.3 queries case studies As part of the testing for this solution, after its implementation, it was decided to test the possibility of upgrading existing queries using the implemented mechanism. Rewriting an existing query will allow to compare speed and readability but also to compare the results, understanding if the new query is able to get better coverage of existing vulnerabilities. 6.3.1MISRA C Contextualization MISRA C is a set of coding guidelines and standards developed by the Motor Industry Software Reliability Association (MISRA). These guidelines are specifically focused on the development of software written in the C programming language for embedded systems, particularly in the automotive industry. Checkmarx has clients in the automotive industry and therefore the set of guidelines of MISRA C is supported in the form of various queries. These queries are usually not
6.3. Queries Case Studies 46 indicative of a vulnerability in the sense that the program is subject to a cyberattack but more in the sense that if they are not taken into consideration there is the possibility of a vehicle failure, for example due to wrong type assertions and conversions. The MISRA C standard also includes a set of rules that are just best practices for readability or reducing the ambiguity of the written code. Taking into account the amount of rules that deal with the analysis of types and conversion rules, it was decided that the queries of this section would be the ones where the Expression type annotation system would come in handy the most. Essential Types The type related MISRA rules discussed and upgraded in the following parts of this document refer to Essential Types. This concept is defined by MISRA C. A variable’s essential type is defined as one of the following: • Essentially char • Essentially bool • Essentially signed • Essentially unsigned • Essentially floating • Essentially enum Any int type, is, independently of size, either essentially a signed or essentially an unsigned, depending on the signedness associated with the variable at the point of declaration. All char declarations are considered essentially chars, the same applies to booleans. Essentially floating is the designation chosen to any variable of type float, double or long double. Each enumerated type is a unique essentially enum type, and should be identified as enum<i>. This essential type is not currently supported by the implemented annotation system in a way that can be detected and therefore it will not be considered for the queries upgraded. Table 12 represents the essential type category table mapping to standard C99 types, table taken from (MISRA,2019). After analyzing the queries that use this kind of information, it was decided to create a function that, from a TypeRef , returns a string, being its essential type. Listing 6.6shows the first version of this function that is used in all of the modified queries. 1Func <TypeRef, string> getEssentialType = (TypeRef type) => { 2string typename; 3 4typename = type.ResolvedTypeName switch
6.3. Queries Case Studies 47 Figure 12: Essential type category table (MISRA,2019) 5{ 6"float" or "double" => "floating", 7"char" => "char", 8"bool" => "bool", 9_=> type.TypeSignedness switch 10 { 11 TypeSignednessModifiers.Signed => "signed", 12 TypeSignednessModifiers.Unsigned => "unsigned", 13 _=> "unknown" 14 } 15 }; 16 return typename; 17 } Listing 6.6: GetEssentialType function 6.3.2MISRA C 2012 Rule 10.3 Rule 10.3from MISRA 2012 states the following: ”The value of an expression shall not be assigned to an object with a narrower essential type or of a different essential type category.“. Expected Results 1uint8_t u8a, u8b, u8f; 2uint16_t u16a; 3uint32_t u32a; 4const uint8_t*pu8a, *pu8b; 5 6u8a = 2; // Compliant 7pu8a = pu8b; // Compliant - Same essential type 8u8a = u8b; // Compliant - Same essential type 9u8f = 1.0f; // Non-compliant - unsigned and floating
6.3. Queries Case Studies 54 8handleOperand = (el) => 9{ 10 CSharpGraph elGraph = el.TryGetCSharpGraph<CSharpGraph>(); 11 12 int nodeId = elGraph.NodeId; 13 if (cache.ContainsKey(nodeId)) return cache[nodeId]; 14 15 string type = CxUnknown; 16 17 switch (elGraph) 18 { 19 case MemberAccess ma: 20 CxList structDef = All.FindDefinition 21 (el.CxSelectDomProperty<MemberAccess>(x => x.Target)); 22 string memberName = ma.MemberName; 23 CxList fieldDef = fieldDecl.FindByShortName(memberName). 24 GetByAncs(structDecls.FindByShortName( 25 objCreateExpr.GetByAncs(structDef))); 26 if (fieldDef.Count > 0) { 27 type = handleOperand(fieldDef); 28 } 29 break; 30 31 case UnknownReference: 32 case IndexerRef: 33 [...] 34 break; 35 36 [...] 37 38 case UnaryExpr: 39 case BinaryExpr: 40 case TernaryExpr: 41 [...] 42 break; 43 44 default: 45 break; 46 }; 47 48 cache[nodeId] = type; 49 return type; 50 };
6.3. Queries Case Studies 55 51 52 checkOperands = (lhs, rhs) => 53 { 54 [...] 55 return lType == rType || 56 rType == CxUnknown || 57 ((lType == "signed" || lType == "unsigned") && rType == "char") || 58 ((rType == "signed" || rType == "unsigned") && lType == "char") || 59 ((lType == "signed" || lType == "unsigned") && (rType == "signed" || rType == "unsigned")); 60 }; 61 62 [...] 63 64 foreach (CxList binOp in binaryExpressions) 65 { 66 CxList lhs = binOp.CxSelectDomProperty<BinaryExpr>(exp => exp.Left); 67 CxList rhs = binOp.CxSelectDomProperty<BinaryExpr>(exp => exp.Right); 68 if (!checkOperands(lhs, rhs)) 69 { 70 result.Add(binOp); 71 } 72 } 73 74 [...] Listing 6.11: Excerpt from the R10_04.cxql query. The query begins by defining constants, initializing variables, and declaring helper functions. These functions include GetEssentialTypeName , handleOperand , and checkOperands , which are utilized to analyze types and operands within expressions. The GetEssentialTypeName function determines the essential type name of a given type. It handles cases such as pointer types and different primitive types like char , short , int , long , double , and float . For other types defined within the codebase, it searches for their definitions and delegates the handling to the handleOperand function. The handleOperand function examines different expressions to determine their type and whether they violate MISRA 2012 C Rule 10.4. It considers various scenarios, such as member accesses, unknown references, method invocations, variable declarations, field declarations, parameter declarations, constant declarations, literals, and more. By analyzing these expressions, it identifies potential violations.
6.3. Queries Case Studies 56 The checkOperands function compares the types of two operands to determine if they are compatible. It is used to verify that the operands in a binary expression conform to MISRA 2012 C Rule 10.4. If the types are incompatible or if there is a risk of information loss during type conversion, a violation is flagged. The query then proceeds to analyze binary expressions, binary operators as assignments, and ternary operators. It iterates through these expressions and checks if the operands involved violate MISRA 2012 C Rule 10.4by calling the checkOperands function. Any expressions that fail this check are considered violations and are added to the result set. Rewritten Query 1CxList expressionsWithAnnotatedType = All.FindExpressionWithCustomAttribute(" AnnotatedType"); 2CxList binaryExprs = Find_BinaryExpressions(); 3CxList literals = All.NewCxList(); 4literals.Add(Find_BooleanLiteral(), Find_IntegerLiterals(), Find_CharLiteral(), Find_String_Literal()); 5 6foreach (CxList binaryExpr in binaryExprs) { 7[...] 8if ((expressionsWithAnnotatedType *binaryExprTypes).Count == 2 && 9(binaryExprTypes *literals).Count == 0) { 10 [...] 11 try { 12 string leftEssentialType = getEssentialType(leftAnnotatedType); 13 string rightEssentialType = getEssentialType(rightAnnotatedType); 14 if (leftEssentialType != rightEssentialType && 15 leftEssentialType != "unknown" && 16 rightEssentialType != "unknown") 17 { 18 result.Add(binaryExpr.Clone()); 19 } 20 } 21 catch (Exception e) { 22 } 23 } 24 [...] 25 } Listing 6.12: Rule new_R10_04.xql
6.3. Queries Case Studies 57 Listing 6.12 contains the new version of the query, being much more readable and easy to understand. The query begins by finding expressions that have a custom attribute called AnnotatedType using the FindExpressionWithCustomAttribute method and storing them in the variable named expressionsWithAnnotatedType . It also retrieves all binary expressions using the FindByType<BinaryExpr> method and stores them in the binaryExprs variable. Additionally, it creates an empty list called literals and adds various types of literals to it, such as boolean literals, integer literals, character literals, and string literals. Next, the query defines a helper function called getEssentialType . This function takes a TypeRef as input and determines its essential type name based on the resolved type name and signedness . It handles specific cases for float, double, char, and bool types. If the type does not match any of these cases, it falls back to checking the signedness to determine if it is signed or unsigned. The query then iterates through each binary expression using a foreach loop. For each binary expression, it extracts the left and right types using CxSelectDomProperty and combines them into a list called binaryExprTypes . It then checks if both the left and right types have the AnnotatedType custom attribute and if neither the left nor right types are literals. If these conditions are met, it proceeds with further analysis. Within the loop, it retrieves the annotated types of the left and right expressions by extracting the custom attribute value using CxSelectDomProperty and manipulating the expression’s structure. It then attempts to determine the essential types of the left and right annotated types using the getEssentialType function. If the essential types are different, not "unknown," and both annotated types have been successfully obtained, the binary expression is considered a violation of the rule. The violating expression is then added to the result set. Results Comparison When comparing the previous version of this query to the new version of this query, there is an increase of two in the results that it finds. There are however a couple of results that are true and were previously found that are not found anymore, this can be due to the new version of the query needing tweaks and input from more experienced CxQL programmers to be able to understand the possible failures in it. This is still a good query to update since it is a lot simpler and it provides new results, the worst case scenario is using both queries together to be able to provide as many true positive results as possible. Automations comparison This new query, passed the automation associated with it, as can be seen in Figure 14
6.3. Queries Case Studies 58 Figure 14: Query 10.05 automation runner report This means that this query can be trusted as well since it passes the required tests to be able to be applied to the production product. 6.3.4MISRA C 2012 Rule 10.5 MISRA C 2012 Rule 10.5states “The value of an expression should not be cast to an inappropriate essential type”. An inappropriate cast is a cast between two types shown in Table 15, this table has been taken from (MISRA,2019) Figure 15: Essential type inappropriate cast table (MISRA,2019)
6.3. Queries Case Studies 59 Expected Results 1bool bna; 2char cha; 3enum ena { ENUM_0, ENUM_1, ENUM_2 }; 4int32_t si; 5 6bna = ( bool )false;// Compliant - C99 'false' is essentially Boolean 7si = ( int32_t ) 3U; // Compliant 8bna = ( bool ) 0; // Compliant - by exception 9bna = ( bool ) 3U; // Non-compliant 10 bna = ( bool ) ena; // Non-compliant 11 si = ( int32_t ) ena; // Compliant 12 enc = ( enum_t ) 3; // Non-compliant 13 cha = ( char ) enc; // Compliant Listing 6.13: Examples of MISRA Rule 10.5violations. MISRA (2019) Listing 6.13 contains a few code samples that violate MISRA Rule 10.5, any expression whose essential type is being cast through a cast expression to an inappropriate essential type, following the table shown in 15. When inspecting the expression bna = ( bool ) 3U; , the cast expression present in this assignment, ( bool ) 3U , the essential type of casting is ”bool“, while the type of the expression being cast 3U , is an unsigned literal, of essential type ”unsigned“, following the ”from“ and ”to“ of 15 we get ”Avoid“, meaning that this cast expression ascertains a violation of MISRA Rule 10.5is present and this expression should be added to the set of results for this vulnerability. Existing Query The existing version of this query, presented in Listing 6.14, is not as complex to understand as the previously shown queries, it is still however prone to adjustments. The main problem with it being the calculation of the types of the expressions, that are now present in each one of them due to the implemented expression type annotation system. 1Func<CxList, CxList, List<string>, CxList> getCastExprs = null; 2getCastExprs = (declRefs, toRemoveRefs, castList) => 3{ 4CxList cast = Find_TypeRef().FindByShortNames(castList).GetFathers(). 5FindByType<CastExpr>(); 6 7if (toRemoveRefs != null) 8declRefs -= toRemoveRefs; 9
6.3. Queries Case Studies 60 10 CxList castRefs = declRefs.GetByAncs(cast); 11 12 // Get list of all composite expressions 13 CxList compositeOp = All.NewCxList(); 14 compositeOp.Add(binaryExprs, unaryExprs, ternaryExprs); 15 16 // Remove casted composite expressions from cast list 17 castRefs -= castRefs.GetByAncs(compositeOp); 18 19 return castRefs.GetFathers().FindByType<CastExpr>(); 20 }; 21 22 addToRefs.Add(charDeclRefs, enumDeclRefs, signedDeclRefs, unsignedDeclRefs, integerLiterals, realLiterals, floatDeclRefs); 23 toRemove.Add(integerLiterals.FindByShortNames("0","1")); 24 result.Add(getCastExprs(addToRefs, toRemove, new List<string>{"bool","bool_t" })); 25 26 [...] 27 28 addToRefs.Add(boolDeclRefs, charDeclRefs); 29 result.Add(getCastExprs(addToRefs, null,new List<string>{"float","double", 30 "long double" })); Listing 6.14: Rule R10_05.xql The query begins by initializing various CxList variables to hold specific types of code elements such as declarators, unknown references, enum declarations, literal values, and different types of expressions (binary, unary, ternary). Next, the query identifies essential types such as bool, char, enum, signed, unsigned, and float by filtering the declarators and finding the references to those types. A function named getCastExprs is defined to extract inappropriate cast expressions for specific essential type references. It takes the references, a list of references to remove, and a list of cast types as parameters. Inside the function, it retrieves cast expressions of the specified types and excludes any references that should be removed, such as composite expressions. The query proceeds to identify inappropriate cast expressions for bool, char, enum, signed, unsigned, and float types. It populates a addToRefs CxList with references that should be included in the cast expressions. The getCastExprs function is then invoked with the appropriate parameters to retrieve the cast expressions for each essential type and add them to the result CxList. The rule violating cast expressions are then added to the result CxList.
6.3. Queries Case Studies 61 Rewritten Query 1CxList expressionsWithAnnotatedType = All.FindExpressionWithCustomAttribute(" AnnotatedType"); 2CxList castExprs = All.FindByType<CastExpr>(); 3 4foreach (CxList castExpr in castExprs) { 5CxList exprTypeList = castExpr.CxSelectDomProperty<CastExpr>(x => x.Expression); 6 7if ((exprTypeList *expressionsWithAnnotatedType).Count == 1) { 8 9TypeRef castAnnotatedType = 10 castExpr.CxSelectDomProperty<CastExpr>(x => x.TargetType).GetFirstGraph() as 11 TypeRef; 12 TypeRef exprAnnotatedType = 13 exprTypeList.CxSelectDomProperty<Expression> 14 (x => (x.CustomAttributes.First(attr => attr.Name == "AnnotatedType"). 15 Parameters[0] as TypeOfExpr).Type).GetFirstGraph() as TypeRef; 16 17 try { 18 string castTypeName = getEssentialType(castAnnotatedType); 19 string exprTypeName = getEssentialType(exprAnnotatedType); 20 21 if (castTypeName != "unknown" && exprTypeName != "unknown" && 22 castTypeName!=exprTypeName) { 23 if ((exprTypeName == "char" && castTypeName == "floating") || 24 (exprTypeName == "floating" && castTypeName == "char") || 25 castTypeName == "bool" 26 ) { 27 result.Add(castExpr.Clone()); 28 } 29 } 30 }catch (Exception e) { 31 } 32 } 33 } Listing 6.15: Rule new_R10_05.xql The query begins by searching for expressions in the code that have the custom attribute AnnotatedType , added by the implemented type annotation system. Next, it finds all occurrences of type-casting operations ( CastExpr nodes) in the code.For each type-casting operation found, it determines the expression being casted.
6.4. Performance Testing 62 If the expression being casted has the AnnotatedType attribute, then it can be used for the purpose of this query. The query then retrieves the target type of the cast operation as well as the type annotated in the expression being casted. Afterwards, it checks if the annotated types of both the original expression and the target type are not ”unknown“ (i.e., their types are known). If the types are known and the original expression’s annotated type differs from the target type’s annotated type, it implies that there is a type mismatch and therefore a possibility for inappropriate casting. The expression’s essential type is then checked with the casting type to make sure that no inappropriate casting is occurring, following the table shown in Figure 15 If any of these conditions are met, it suggests that there might be a violation of MISRA C 2012 Rule 10.5, adding the corresponding CastExpr node to the result set. Results Comparison The old version of the query that finds violations of rule 10.5from MISRA C 2012, does not find any results in the test file used for the other queries, this query was ran against a bigger project and it finds no results. After further investigation, it was discovered that there are currently no projects used for testing that contain vulnerabilities of this query. Since the new query also does not find new results, the only way to measure its successfullness is the usage of the automation associated with the query. Automations comparison This new query, passed the automation associated with it, as can be seen in figure 16 This is a good sign and gives the query more merit since it is the only way to compare it to the old one. After conversations with internal developers assuming that the implemented system is working properly, as proven by previous examples, the new version of this query is also well written and therefore can be trusted. 6.4 performance testing This section will focus on the testing of the performance of the added Resolver rule and also on the performance impact of the modifications made to queries. The testing was done using projects of different sizes and languages to make sure that the obtained time results are independent of these variables. An important note to be made is that, the times presented
6.4. Performance Testing 63 Figure 16: Query 10.04 automation runner report are the average obtained time from ten runs where the lowest and highest times are removed to better concentrate the results verified. 6.4.1Testing Environment Specifications The results presented in this section were obtained while parsing the projects using Checkmarx’s internal tool, CxAudit. This program was ran in an idle charging computer with the following specifications: • Processor: Intel(R) Core(TM) i7-8565U CPU @ 1.80GHz 1.99 GHz • RAM: 32.0GB • System: 64-bit Windows 11 Pro Operating System 6.4.2Resolver rule This testing section shows the differences in performance between the parsing of projects of different languages, lines of code (LOC), and the usage or not of the added resolver rule. The goal is to understand the impact of the added feature in terms of performance, the results obtained are shown in Table 9for C/C++ and Table 10 for C#.