text
stringlengths 64
2.99M
|
---|
Docker images are defined by templates called Dockerfiles that consist of commands which specify how a container is assembled [37]. The docker build command, as visualized in figure 4.3, instructs the Docker daemon to build an image from a Dockerfile. Listing 4.1 9https://mcr.microsoft.com 10A feature to run a Linux system inside Windows4.4. IMPLEMENTATIONS OF OS-LEVEL VIRTUALIZATION 61 shows a sample Dockerfile which compiles and deploys an ASP.NET Core web application into a container. The Dockerfile consists of two different stages, which are defined by the FROM ..... AS statements: one named build, and another unnamed stage (that can be implicitly referred to by an integer, starting with 0). Each statement in the file adds another layer to the image. Since Docker caches images internally in a build cache, unchanged layers are reused on subsequent docker build calls, reducing the time required to update and rebuild images [36]. 1 # Set base image for building project 2 FROM mcr.microsoft.com/dotnet/sdk:7.0 AS build 3 WORKDIR /source 4 5 # Copy project files and restore packages 6 COPY exampleProject//*.csproj . 7 RUN dotnet restore ---use-current-runtime 8 9 # Copy remaining source of application and publish it 10 COPY exampleProject/. . 11 RUN dotnet publish -c Release -o /outputFolder ---use-current-runtime ---self-contained false ,→ ---no-restore 12 13 # Set base image for runtime project and copy published application from build stage 14 FROM mcr.microsoft.com/dotnet/aspnet:7.0 15 WORKDIR /outputFolder 16 COPY ---from=build /outputFolder . 17 ENTRYPOINT ["dotnet", "exampleProject.dll"] Listing 4.1: Dockerfile for compiling and deploying an ASP.NET Core application. Modified from [38] The FROM statement defines what image will be the base image for the container. Since the build stage compiles the ASP.NET Core project, it will be based on the most recently available .NET SDK version (7.0) image. In the next step, the project files (*.csproj) are copied to the image, and the packages containing dependencies for all projects are restored. Astheprojectfilesusuallyonlychangewhendependenciesareaddedorupdated, the image only changes infrequently up to this point and is thus cached and reused by Docker. After the dependencies are restored, the remaining source files are copied to the image and the application is compiled and published to an output folder. Running the application does not require the full .NET SDK; the second, unnamed stage is thus based on the aspnet:7.0 image, which contains only the required the ASP.NET Core and .NET runtime libraries. The published application is then copied from the previous build stage into the final image. The ENTRYPOINT statement defines a default command that is executed when the container is run, in this case dotnet exampleProject.dll, which starts62 CHAPTER 4. CODE SECURITY IN LOW-CODE APPLICATIONS the application on a local web server. Dockerfiles can run arbitrary programs and scripts using the RUN statement, which enables to set up containers with any complexity. However, it is recommended to keep the containers as stateless and ‘ephemeral’ [35] as possible, since they should be able to be started, customized and stopped with minimal configuration effort. Data that needs to be saved persistently should be stored by a dedicated, separate service, such as a database, which in turn can be stored on the host’s filesystem using volumes [41]. By default, Docker puts no constraints on the usage of resources by containers. If a container begins to exhaust system resources, the underlying operating system can act to ensure that no process compromises the availability of the system. For example, the Linux kernel will start to kill processes based on individual runtime and memory usage when not enough memory is available [52, p. 194]. As this may cause the termination of any process (potentially a non-container process) on the system, Docker allows to put limits on memory-, CPU-, and GPU-usage per container [39]. Usage Based on the threat model from section 4.2, a generated LCA should not be able to interfere with other users or data on the server during its development time. Deployment of the generated application to the container works similar to the process described in the previous section. A generic Dockerfile using a suitable base image with commands to build the LCA from source and deploy it into the container is created once and can be used for all customers of the LCDP, provided the generation of the LCA, including all dependencies, is standardized across the platform. Since Dockerfiles can be parameterized, variablevalueslikefileorfoldernamescanbesetasplaceholdersandpassedwhenbuilding the image [37]. If customers can extend their LCA with custom dependencies or require special set up steps, the Dockerfile could be expanded with additional scripts, that are executed at fixed steps during the creation of the container (for example before publish or after copying build artefacts) and act as extension points. After the image is built by the docker build command, it can be shared among multiple clients. Images can either be exported and imported manually, or stored in a public or private registry. A client can then pull and run images, as shown in figure 4.3. docker pull instructs the daemon to find a specific image in a registry and download it to the host. Alternatively, docker run can be used directly to instantiate a container, whose image is automatically pulled from the registry as needed. During the active development of a LCA, frequent code changes and rebuilds, as with traditionally developed applications, are to be expected. This means that containers are relatively short-lived and often stopped, reconfigured and restarted. Depending on the scale of the LCDP and the number of concurrent users, a single server may not be enough to run containers from all users at the same time. Since one container usually only4.4. IMPLEMENTATIONS OF OS-LEVEL VIRTUALIZATION 63 runs one process, and an application may consist of several processes (such as a database server and a web server) [116], redeploying a LCA can become more complex, as multiple containers have to be coordinated. Management of multiple containers at scale is the task of container orchestration |
engines, such as Docker Swarm11 and Kubernetes12. Common features are scheduling, grouping and moving containers between different machines, health- and integrity moni- toring, and guaranteeing their availability [116]. Evaluation Architecturally, Docker is much more suited to quickly deploy and test generated LCA on-demand than the previously discussed Windows Sandbox. The ability to define and build images that include the required dependencies for generated applications provides a deterministic way to run a stable system environment. The availability of different operating systems as base images, and images of various programming frameworks and runtime environments that build upon them, make it easy to offer the user a variety of platforms to deploy their application on. As the images are built with layers, which also support caching, recompiling only the changed components of a LCA enables quick recreation of a container after changes are made to an application. To get an estimate of the amount of time required, the basic commands required to set up a Docker container were benchmarked. The components of the testing system are described in section 4.4. Each command was run three times to determine the median and average. The example Dockerfile from listing 4.1 with a minimal ASP.NET Core web application was used to perform the tests. The timing was determined by the built-in measurements each docker commands prints after it has finished. The results are shown in table 4.1. The time required to build and run a containerlargely depends on two factors: the size ofthebaseimage,andthecomplexityoftheapplicationtobuild. Asoncedownloadedbase images and unchanged layers are cached, subsequent builds of a container are much faster. While the building of the initial image took around one minute, updates to the image were finished in a reasonable 7 seconds. Running the container was practically instantaneous, the integrated web server run by the dotnet command was started and available almost immediatelyafterstartupofthecontainer. Morecomplexapplications, thatrequirelonger compile or build times, will, of course, result in longer container deployment times, but the overhead incurred by docker in this simple example was within reasonable bounds. Whether Docker is an appropriate approach to run generated LCAs depends mostly on the kind of application. By default, most container images only provide a command line interface to interact with the system running in a container instance. This means that 11https://docs.docker.com/engine/swarm 12https://kubernetes.io64 CHAPTER 4. CODE SECURITY IN LOW-CODE APPLICATIONS Command Description Median/Average Build a docker image docker builder prune -f without using caches or 58.7s/60.3s docker build ---pull ---no-cache . existing base images Build a docker image with docker build . 7s/7.1s trivial source code change No measurement Start the previously built provided by docker run thesis/bench:1.0 image named docker, but less thesis/bench:1.0 than a second. Table 4.1: Benchmark of basic Docker commands applications requiring interaction via a user interface are generally not directly usable, as there is no desktop environment available that a client can connect to. Applications that are primarily server-based (such as an ASP.NET Core application running on a web server, similar to the environment defined in listing 4.1), and can be accessed, for example, via browser or network, are better suited to run on this infrastructure. There are however tools available to make GUI access available for Linux containers, for example x11docker13, which involves starting a display server inside the container and then connecting via a window client or other remote control software. This is not possible with Windows containers. However, Microsoft provides a Windows Server image with desktop experience, which makes UI APIs available inside the container. While there is still no GUI to interact with, it enables applications to utilize the GPU and consume the newly provided APIs [5]. Similarly to virtual machines, Docker containers need a dedicated system to run on, as users of the LCDP cannot be expected to host containers on their own machines. Containers are more lightweight than VMs, as downloaded base images and layers can be shared among multiple instances of a container. Since each container shares the kernel of the host OS, a compromised host kernel can potentially affect all containers running on a system. Virtual machines provide more isolation in that scenario, as the entire OS and kernel is contained inside the VM. However, running a VM for only a single application is inefficient and requires significantly more resources [74]. If the reduced isolation and lack of options to run GUI applications in containers is an acceptable tradeoff compared to the large overhead of VMs, containers are the more optimal solution when hosting a LCDP and building generated LCA for its users. 13https://github.com/mviereck/x11docker4.5. SECURELY RUNNING CODE IN C# 65 4.5 Securely running code in C# The .NET Framework, .NET Core and .NET contain several APIs that aim to provide security policies for and isolation between applications. Most of these technologies were usedhistoricallytomanageaccessandpermissionsofassemblies,orseparationofprocesses in memory. Microsoft discourages use of these APIs and recommends to use security features on operating system level, such as containers or virtualization [91]. This section gives a short overview over these deprecated APIs, and introduces a modern alternative that can be used instead. 4.5.1 Code Access Security Code Access Security (CAS) is an, from .NET Core onwards obsolete [48], API that controls execution of code based on evidence and permissions [76]. Evidence contains information about the origin of the code, such as a website, directory, publisher, or a hash code. Permissions define what resources the code is allowed to access, such as printers, file input/output,ortheWindowsregistry. Tomatchevidencetopermissions, code groups can be created, so that, for example, applications originating from a web source are disallowed access to local files by default. CAS was deemed as too complicated to configure correctly by Microsoft [101], and since it is also limited to managed code, it does not affect native applications running |
outside the CLR, making the security guarantees it aims to provide flawed. 4.5.2 Application domains Application domains (usually referred to as AppDomains) are logical containers that can be used to run multiple applications inside a single process [85]. Domains can be used to load assemblies, either neutral, for all domains with the same security parameters, or only for the current domain. Applications inside a domain are isolated from the other domains in a process, they cannot directly communicate, and faults in one domain do not affect others. Individual domains can also be loaded and unloaded at runtime, which is useful for isolating untrusted code in a domain and only allowing it to communicate with other domains via common inter-process mechanisms, such as pipes or remote procedure calls (RPC). Support for application domains was dropped from .NET Core onwards for being resource intensive [84] and not providing adequate security boundaries [117]. 4.5.3 AppContainer Compared to CAS and application domains, which are limited to applications running with the CLR, an AppContainer provides security and isolation on operating system level and can be used with existing and new applications. The Windows version of Google’s Chromium browser uses AppContainers as part of its security infrastructure [51].66 CHAPTER 4. CODE SECURITY IN LOW-CODE APPLICATIONS This section provides an overview on how AppContainers work, explains the basic steps necessary to run an arbitrary application inside an AppContainer using C# and evaluates its usage as a viable option to isolate applications. The full source code of the example is also available on GitHub [17]. Background Current versions of Windows use mandatory integrity control (MIC) [96], an implementa- tion of mandatory access control for processes, to define an integrity level (IL) for objects, which represent their trustworthiness [111]. Objects in this context generally refer to system resources, such as files, processes, or devices [94]. Four integrity levels are used: low, medium, high, and system. System is reserved for system processes, high integrity is assigned to administrators and elevated users, medium is the default level. Low-integrity processes are thus heavily constrained in their functionality, since they cannot access objects above their integrity level, unless they are explicitly granted rights to do so. Windows uses secure identifiers (SIDs) to identify users and groups as trustees for an object [102]. SIDs are generated when a user or group is created and consists of several components, the most important being the value for a subauthority, which identifies a user in a domain and is represented by a globally unique identifier (GUID). A complete SID might look as follows: S-1-5-21-4159745769-645805219-203622070-1001. In addition to these generated SIDs, a number of constant well-known SIDs exist, which are used to identify special entities, such as a group that contains all users, or all administrators in a domain. An AppContainer is assigned a SID as well, however it is not randomly generated, but calculated by a cryptographic hash function based on its name [26]. As this enables the SID to be persistent and reproducible, the identity of an AppContainer can be used to explicitly put applications into a specific container. What a process inside a container is allowed to do is defined by a set of capabilities, that are also represented by well-known SIDs14. These capabilities are similar to the permissions assigned to apps in operating systems for smartphones, such as access to the internet or the music or picture library. More Windows-specific capabilities are the permission to access removable devices, or usage of user credentials. Access to specific files and folders can be granted by adding the SID of the container to the access control list (ACL) of an object. 14Afulllistofavailablecapabilitiescanbederivedfrom[109],butasthereisnoconclusivedocumentation, the author assumes that the enum values 84 through 94 apply to AppContainers, as they are explicitly mentioned for these SIDs4.5. SECURELY RUNNING CODE IN C# 67 Implementation of an AppContainer AppContainers were originally used for Windows Store applications that were introduced inWindows8andthenknownasMetro apps[107], ormorerecentlyasUniversalWindows Platform (UWP) apps. These apps are automatically run in an AppContainer and don’t have to specifically implement it. As there exist no managed APIs to create or manipulate AppContainers, the majority of the code requires usage of Platform Invoke (P/Invoke) [97], to call functions from the unmanaged Windows-API. Since there is very little documentation on how to use AppContainers for non-UWP executables (besides a rough outline of the concept [95]), the correct usage of the un- managed API of the following sample implementation is partially based on an existing demonstration project [27]. The sample implementation uses the Vanara15 library, a thin wrapper around the native API, to simplify the otherwise verbose object declarations without changing their original names. The following samples omit error handling to improve readability. 1 private AdvApi32.SafeAllocatedSID CreateOrGetAppContainerProfile(string containerName, string ,→ containerDisplayName, string containerDescription) 2 { 3 var result = UserEnv.CreateAppContainerProfile(containerName, containerDisplayName, ,→ containerDescription, null, 0, out var sid); 4 5 if (result === HRESULT.S_OK) return sid; 6 7 UserEnv.DeriveAppContainerSidFromAppContainerName(containerName, out var existingSid); 8 return existingSid; 9 } Listing 4.2: Creation or retrieval of an AppContainer SID The first step, shown in listing 4.2, is to retrieve the SID of the AppContainer to use. Dependingonwhetherthecontaineralreadyexists,eitheranewcontaineriscreated,orthe SIDoftheexistingcontainerisderivedfromitsname. Theresultofthemethodisahandle to the SID of the container. The next step is to build an instance of the STARTUPINFOEX structure, which is later used to pass initialization data, including information about the AppContainer, to the process that will run in the container. The capabilities are stored in |
a SECURITY_CAPABILITIES structure, which has to be populated before being used later in the process creation. As shown in listing 4.3, the SID of the container gets assigned to the SECURITY_CAPABILITIES structure. The desired capability is then translated to another, computer-specific SID in line 8. Since the AppContainer operates on ACLs, the SID of the capability is wrapped in a SID_AND_ATTRIBUTES structure along with the attribute 15https://github.com/dahall/Vanara68 CHAPTER 4. CODE SECURITY IN LOW-CODE APPLICATIONS SE_GROUP_ENABLED, that allows the SID to be included in access checks. The final step before the sandboxed process can be created is the initialization of a list of attributes that is added to the STARTUPINFOEX structure. Listing 4.4 shows the creation of a process attribute list, which is then updated with the security capabilities created in listing 4.3. Listing 4.5 shows how the STARTUPINFOEX structure is then used to pass the capability information to the new process. It is created under the identity of the current user, albeit with a low integrity level. To verify whether an application is indeed running in an AppContainer, tools like Process Explorer16 can be used to check the group membership of a sandboxed process. In this example, the Notepad program shipped with Windows was started using the sample implementation of an AppContainer from this section. As shown in figure 4.4, Process Explorer reports the integrity as AppContainer, and the group Mandatory Label shows that the process runs on a low integrity level governed by MAC. Figure 4.4: Process Explorer showing a sandboxed instance of Notepad While the user can normally write text in this Notepad instance, trying to open a document or save the current text fails as expected. Since no explicit file or folder access was granted to the process, it is unable to even access the Documents directory of the current user, as shown in figure 4.5a. Trying to navigate to other directories or volumes fails with the same error message. By default, the only accessible folders are the working directory of the sandboxed application (with at least read access), and some common environment directories like %temp%, which are redirected to a folder specific for the container so that it can’t interfere with non-sandboxed applications, as well as specific locations in the Windows Registry [90]. In comparison, a non-sandboxed instance of Notepad, shown in figure 4.5b, has regular access to the filesystem. Note that the 16An application that lists detailed properties of running processes — https://docs.microsoft.com/ en-us/sysinternals/downloads/process-explorer4.5. SECURELY RUNNING CODE IN C# 69 1 private void SetSecurityCapabilities(ref Kernel32.SECURITY_CAPABILITIES capabilities, ,→ AdvApi32.SafeAllocatedSID appContainerSid, AdvApi32.WELL_KNOWN_SID_TYPE capabilitySid) 2 { 3 capabilities.AppContainerSid = appContainerSid.DangerousGetHandle(); 4 var capabilitiesBuffer = new ,→ SafeHandleBuffer(Marshal.SizeOf(typeof(AdvApi32.SID_AND_ATTRIBUTES))); 5 var sidSize = (uint)AdvApi32.SECURITY_MAX_SID_SIZE; 6 var safePsid = new AdvApi32.SafePSID(sidSize); 7 8 AdvApi32.CreateWellKnownSid(capabilitySid, IntPtr.Zero, safePsid, ref sidSize); 9 10 var attributes = new AdvApi32.SID_AND_ATTRIBUTES 11 { 12 Attributes = (uint)AdvApi32.GroupAttributes.SE_GROUP_ENABLED, 13 Sid = safePsid.DangerousGetHandle() 14 }; 15 16 Marshal.StructureToPtr(attributes, capabilityBuffer.DangerousGetHandle(), false); 17 capabilities.Capabilities = capabilitiesBuffer.DangerousGetHandle(); 18 } Listing 4.3: Building a capability from a SID 1 private void SetProcessAttributes(ref Kernel32.STARTUPINFOEX startupinfo, ,→ Kernel32.SECURITY_CAPABILITIES capabilities) 2 { 3 var capabilitySize = Marshal.SizeOf(capabilities); 4 var capabilityBuffer = new SafeHandleBuffer(capabilitySize); 5 var processAttributeList = Kernel32.SafeProcThreadAttributeList.Create( 6 Kernel32.PROC_THREAD_ATTRIBUTE.PROC_THREAD_ATTRIBUTE_SECURITY_CAPABILITIES, ,→ capabilities); 7 8 Marshal.StructureToPtr(capabilities, capabilityBuffer.DangerousGetHandle(), false); 9 10 Kernel32.UpdateProcThreadAttribute( 11 processAttributeList.DangerousGetHandle(), 12 0, 13 Kernel32.PROC_THREAD_ATTRIBUTE.PROC_THREAD_ATTRIBUTE_SECURITY_CAPABILITIES, 14 capabilityBuffer.DangerousGetHandle(), 15 capabilityBuffer.BufferSize); 16 17 startupinfo.lpAttributeList = processAttributeList.DangerousGetHandle(); 18 } Listing 4.4: Adding the capabilities to the process attribute list70 CHAPTER 4. CODE SECURITY IN LOW-CODE APPLICATIONS 1 private void CreateSandboxedProcess(ref Kernel32.STARTUPINFOEX startupinfo, string processName) 2 { 3 using var currentIdentity = WindowsIdentity.GetCurrent(); 4 using var currentToken = new GenericSafeHandle(currentIdentity.Token, Kernel32.CloseHandle, ,→ false); 5 6 var res = AdvApi32.CreateProcessAsUser( 7 new HTOKEN(currentToken.DangerousGetHandle()), 8 processName, null, null, null, false, 9 Kernel32.CREATE_PROCESS.EXTENDED_STARTUPINFO_PRESENT, 10 null, null, in startupinfo, out var processInfo); 11 } Listing 4.5: Creating the sandboxed process sandboxed version has so little access to the system, that it doesn’t even have permission to retrieve the names of the volumes under This PC. (a) Open dialogue in a sandboxed instance of (b) Open dialogue in a regular instance of Notepad Notepad Figure 4.5: Open dialogue of Notepad in a sandboxed and non-sandboxed instance Unless the application should have intentionally only minimal access to the file system, itneedstobegrantedexplicitpermissionstoreadandwriteotherfilesandfolders. Listing |
4.6 shows how the ACL of a file or folder can be modified to give full permissions to an AppContainer.4.5. SECURELY RUNNING CODE IN C# 71 1 private void GrantObjectAccess(AdvApi32.SafeAllocatedSID appContainerSid, string path) 2 { 3 var type = AdvApi32.SE_OBJECT_TYPE.SE_FILE_OBJECT; 4 var access = new AdvApi32.EXPLICIT_ACCESS 5 { 6 grfAccessMode = AdvApi32.ACCESS_MODE.SET_ACCESS, 7 grfAccessPermissions = ACCESS_MASK.GENERIC_ALL, 8 grfInheritance = AdvApi32.INHERIT_FLAGS.SUB_CONTAINERS_AND_OBJECTS_INHERIT, 9 Trustee = new AdvApi32.TRUSTEE 10 { 11 MultipleTrusteeOperation = ,→ AdvApi32.MULTIPLE_TRUSTEE_OPERATION.NO_MULTIPLE_TRUSTEE, 12 ptstrName = appContainerSid.DangerousGetHandle(), 13 TrusteeForm = AdvApi32.TRUSTEE_FORM.TRUSTEE_IS_SID, 14 TrusteeType = AdvApi32.TRUSTEE_TYPE.TRUSTEE_IS_WELL_KNOWN_GROUP 15 } 16 }; 17 18 AdvApi32.GetNamedSecurityInfo(path, type, SECURITY_INFORMATION.DACL_SECURITY_INFORMATION, ,→ out var ppsidOwner, out var ppsidGroup, out var ppDacl, out var ppSacl, out var ,→ ppSecurityDescriptor); 19 AdvApi32.SetEntriesInAcl(1, new[] { access }, ppDacl.DangerousGetHandle(), out var newAcl); 20 AdvApi32.SetNamedSecurityInfo(path, type, SECURITY_INFORMATION.DACL_SECURITY_INFORMATION, ,→ ppsidOwner, ppsidGroup, newAcl.DangerousGetHandle(), ppSacl); 21 } Listing 4.6: Adding the SID of the container to the ACL of a file or folder72 CHAPTER 4. CODE SECURITY IN LOW-CODE APPLICATIONS Evaluation AppContainersenableanyapplicationtoberunasaprocesswithlowintegritylevel. Since regular users operate by default on a medium integrity level, and Windows implements mandatory access control, low IL processes are effectively prohibited by interfering with objects with a higher IL. In comparison to CAS and AppDomains, AppContainers are not limited to managed code and are subject to operating system-level security enforcement by being integrated into existing ACLs of objects. Their integration as part of widely used software like Chromium gives credibility to their security in real-world applications. The disadvantage comes with their complicated creation for applications that are not automatically containerized (like Windows Store apps are). The lack of a managed API requires use of sparsely documented and difficult to implement native Windows functions. Access to files and folders that are required for the normal operation of a sandboxed application has to be assigned manually. Granting access to entire volumes17 is more difficult, as their ownership usually lies with the operating system, and requires elevated permissions to alter them. While existing applications can be put into a container, it may impede their functionality as they assume to be run at medium integrity level. Applications that are not designed to run at low IL, especially if their source code is unavailable or not readily modifiable, have to be analysed for possible locations that they are allowed to access. Communication with processes of higher IL is, intentionally due to the usage of MAC, another issue, as a low IL process cannot simply call more trusted processes and has to communicate via other means, such as IPC techniques. Microsoft generally recommends distrusting low IL processes [90]. If a sandboxed application deals withcriticalorsensitiveinformation,orispronetoattacksfrommaliciousactors,incoming and outgoing data has to be carefully validated to prevent circumvention of the container. For example, a low IL process could create an object in shared memory (such as a named pipe, or a memory-mapped file) that it knows will be opened by a process with higherIL. The lowIL process could fill theobject with data thatwill cause, if not properly validated, the higher IL process to crash or execute arbitrary code, thus breaking out of the limitations of its integrity level. This type of attack, also called a squatting attack [133], requires knowledge about the vulnerable process and also shows that, depending on the threat model, multiple levels of security may be necessary. 4.6 Summary and discussion Chapter 4 provided a general overview of process isolation and approaches on how appli- cations can run alongside each other while minimizing accidental or malicious interference. In the context of LCDPs, a threat model was introduced that served as the basis for the evaluation of two concrete implementations of OS-level virtualization. Additionally, three 17For example, a partition such as C:4.6. SUMMARY AND DISCUSSION 73 currently available mechanisms for code security in C# were discussed, where AppCon- tainers, which use Windows’ MIC, were the most viable and widely used option. This chapter served as a basis for answering RQ III, and, in a broader sense, also RQ II. While supporting CDs may help to reduce usage of potentially insecure code, there is always the possibility that certain APIs are missed or advice is ignored. Additional security on a lower, OS-level, therefore also alleviates security problems that slipped through preventive measures on a higher, user-code level. Implementing OS-level security requires additional infrastructure and systems to deploy and run the applications to be secured. Section4.4.2detailedtheusageofDockerforthedeploymentofasmallASP.NET Coreapplication, whichrequiredatminimumavirtualization-capableserverandtheeffort to create a Dockerfile to build the application and install all their dependencies. At scale, additional services to orchestrate the instantiation and management of containers are needed. While there are different APIs to provide code security in .NET are available, the only currently viable and supported implementation are AppContainers, which limit the access of applications to the rest of the system using integrity levels. AppContainers are implementedinwidely usedapplicationssuchas Chromium, butare difficultto implement and configure correctly. They also require bootstrapping, that is, the sandboxed process has to be specifically started inside an AppContainer, which has to be done by a separate |
process. Configuration involves setting the desired security capabilities, which are not well documented, and controlling access to files and folders via an ACL. While any application can be placed in an AppContainer, imposing external limits can lead to unexpected behaviour if the application is not aware that access to normally available resources is suddenly restricted.Chapter 5 Maintenance and management of custom code Mechanisms for the support of citizen developers when writing code were presented in chapter 3, and implementations for securely running that code were discussed in chapter 4. This chapter introduces two topics that are routinely part of the maintenance and management of existing code: debugging and versioning. 5.1 Debugging Debugging is an indispensable activity in software development that allows developers to inspect a particular piece of code and analyse the state of the program during runtime [160]. Modern IDEs such as Visual Studio or IntelliJ IDEA include extensive support for debuggers that allow the user, for example, to place breakpoints at specific lines in the code to pause execution and examine the contents of variables and step through the code statement by statement. However, a much simpler and widely adopted technique colloquially called printf debugging is still often employed as the first step in debugging code issues [11]. Printf debugging, named after the set of printf() functions in the C programming language, involves inserting statements that output information during program runtime, such as the values of variables or simple messages indicating the control flow. The developer then observes the output and can reason about the state of the program at the time of the output. The advantage of this technique is that it is virtually always available, as most programming languages support some form of output, and requires no additional tools or familiarization with a more complex debugger. 5.1.1 Usage in low-code applications Debugging low-code applications is considered as a challenge by developers [3, 75], as the focus on graphical development environments makes it more difficult to employ traditional 7576 CHAPTER 5. MAINTENANCE AND MANAGEMENT OF CUSTOM CODE means of debugging. Generated applications can still produce code that can be debugged with external tools, for example with Eclipse1 in the case of Mendix’s Java Actions [80]. However, thisrequiresdevelopmentexperienceandwouldlikelyinvolveadditionaltraining for citizen developers. Another available piece of information for debugging is the output of the compiler that builds an application. In the context of generated LCAs, this output is available on at least two different occasions: when the entire LCA is compiled, and when a user writes additional code for the application. The latter case requires that the LCDP supports selective compilation of user-written code. The compiler output of the entire generated LCA is likely not helpful to the CD, since it will contain messages about all parts of the application, even those the CD never worked on, and probably can’t fix – for example because it’s a bug in the code generator. Compiler output is also generally fairly technical, and geared towards experts [137]. Limiting the compiler output to the code the CD has written and currently debugging has, independently of the difficulty of understanding it, some advantages. For one, it provides more focused messages, as compared to building a whole application, a smaller amount of code is compiled. It also enables a much faster feedback loop. Users can apply changes to the code more frequently and can experiment more, as they don’t have to wait until the application is recompiled, since compiling only several lines of code is faster than rebuilding the entire LCA. Enhancing compiler output messages seems like an obvious way to improve their comprehensibility for citizen developers. The effectiveness of enhanced compiler error messages (ECEMs) is, while studied, not conclusively answered. Multiple studies [33, 119, 127] suggest that ECEMs have little effect in aiding novices when encountering errors. However, they contributed in reducing the most commonly received Java compiler errors for a group of students [10], and were generally found helpful by participants [129]. As previously mentioned, printf debugging is still frequently used by experienced developers and easy to learn for novices. Providing citizen developers with the facilities to show the results of simple output statements gives them the opportunity to debug their code with minimal teaching effort. Additional written code for SCOPELAND is usually limited to small functions and statements applied to the current page, without complex object hierarchies [120, p. 47]. Thus, the absence of more advanced debugging options is compensated by smaller and simpler amounts of code. Section 5.3.1 details the implementation and usage of compilation and debugging features for small C# scripts in an application. 1A Java-based IDE for a wide variety of programming languages — https://eclipseide.org5.2. VERSIONING 77 5.2 Versioning Another integral part of software development is the usage of version control systems (VCSs) [58], such as Git, Subversion or Perforce. VCSs allow developers to store and manage changes to a code base. Changes to files and folders are incrementally committed orchecked in,alongwithmetadatasuchastheauthor’sname,atimestamp,andamessage, into either a central or distributed repository. Maintaining a VCS allows developers to view a history of changes and switch between different revisions as necessary, for example to compare modifications to a file or go back to a previous version. Additionally, VCSs enable collaboration between multiple developers or teams across a single code base. New features or bugfixes can be worked on independently, without affecting others, until the implementation is finished and can be merged into the central repository. Conflicting changes can be detected, revised and resolved before potentially inconsistent code is committed to the shared code base. 5.2.1 Usage in low-code applications Studies indicate that VCSs are difficult to use, even for professional developers. Yang et al. [159] evaluated the difficulties associated with Git, and find that trained developers still can have issues using Git and that further research in assisting them is needed. |
Isomöttönen et al. [63] describe the experience of introducing Git to computer science students and conclude that the challenges encountered are independent of the concrete VCS. They report that most of the problems the students ran into were related to the intricacies of the Git command-line syntax, and difficulties in seeing the advantages of a rather complicated VCS in short-term coursework usage with a lack of authentic use cases. As both skilled developers and computer science students can struggle in employing a VCS as part of their work, citizen developers will require assistance to version their applications. Version control systems usually provide a command line interface to interact with them. Applications with GUI support are available as well, often from third parties. Git, for example, is directly shipped with git-gui2. External tools can provide integration with other services, such GitHub Desktop3 for GitHub or GitKraken4 for a variety of issue- trackers. Integration in development tools and IDEs is often specifically shipped as part of them, or is available through add-ons. Unless a LCDP directly supports integration of a VCS (such as Mendix [83]), or provides an API to do so (like OutSystems [124]), a citizen developer would have to manually manage versioning their applications. Besides the inherent difficulty of using a VCS that was described previously, this might not even be possible, as the end-user has no access to the inner structure of a LCDP. While the 2https://git-scm.com/docs/git-gui 3https://desktop.github.com 4https://www.gitkraken.com78 CHAPTER 5. MAINTENANCE AND MANAGEMENT OF CUSTOM CODE source code may be available as part of generated LCAs (see section 2.2.3), this may not be the case in hosted applications. As such, if a LCDP supports a VCS, its usage needs to be abstracted for a citizen developer. Another point to consider is what to version. The application components developed in LCDPs can be stored by the platform itself. For example, the pages developed in SCOPELAND are not stored as code, but as structured metadata inside the internal meta database [120, p. 48]. Any additionally written code is also embedded in this metadata [120, p. 47]. In this case, the application components (pages) exist as an entity in a database and can be managed and versioned by the LCDP. For instance, it can offer the CD to open a previously saved version of the application. The issue with this approach is, that the code is not stored independently of the rest of the LCA. To look at a previous version of their code, users have to go back to a previous version of the page. Changes to the other content of the page are thus also reverted. As design aspects of a page can be stored globally with reusable stylesheets in SCOPELAND [120, p. 55], several visual elements, such as colours and font settings, are already independent of the page. A similar pattern can be applied to the code embedded in the pages. Integrating a simple VCS into the LCDP enables citizen developers to gain quickly access to previous versions of their code, along with a history of changes, without having to go back to a previous version of the entire page. An example application showing the implementation and usage of such a system is shown in section 5.3.2. 5.3 Implementation Todemonstratethefeasibilityofprovidingcitizendeveloperswithbasicdebuggingfacilities and a simplified version control system, the author implemented a Code Management Sample application (CMSA) that is open source and publicly available on GitHub [18]. The application consists of two major features. The first is the ability to compile and execute console-based C# code, without requiring any external tools, and giving the CD access to the compiler- and console output for debugging purposes. The other allows storing and retrieving the currently active code in a Git repository without the need to learn any specific Git commands. The history of the file is displayed in a simple table, and older versions can be previewed and restored as necessary. 5.3.1 Debugging Running and debugging the user-written scripts requires compilation of the code. As the citizendeveloperscannotbeexpectedtodeveloptheircodeinaseparateenvironment(like anexternalIDEoreditor),thecompilationneedstohappenaspartoftheirusualworkflow. On-demand compilation of code during the runtime of a program can be achieved with the APIs provided by the Roslyn compiler, specifically with its scripting functions of the5.3. IMPLEMENTATION 79 CSharpScript class [99]. A simplified example is shown in listing 5.1. 1 public async Task CompileAndRunScript() 2 { 3 string sourceCode = "System.Console.WriteLine(\"Hello World\");"; 4 var script = CSharpScript.Create( 5 sourceCode, 6 ScriptOptions.Default 7 .WithReferences(Assembly.GetAssembly(typeof(Console))); 8 script.Compile(); 9 await script.RunAsync(); 10 } Listing 5.1: Compiling and executing a script with Roslyn Line 3 contains the code that is compiled and executed, in this case Hello World is printed to the console output. In the following lines, a Script instance is created, and the required references, assemblies that are used in sourceCode (the System.Console.dll assembly from .NET in this example), are added. The script is compiled in line 8 and asynchronously executed in line 9. The System.Console.WriteLine() method call used in this listing can be used for printf debugging, as it writes the passed arguments to the console. Running this example doesn’tproduceanyvisibleoutput, asnoconsolewindowisopen. Tocapturetheconsole’s contents, the standard output has to be redirected to an object that can be used by the application to provide it to the user. Listing 5.2 shows how the standard output can be captured by redirecting it to a StringWriter, a .NET class to sequentially write data to a string. 1 try 2 { 3 await using var writer = new StringWriter(); 4 Console.SetOut(writer); 5 ScriptState<object> scriptResult = await Script.RunAsync(); 6 await writer.FlushAsync(); 7 var consoleOutput = writer.GetStringBuilder().ToString(); 8 } 9 finally 10 { |
11 Console.SetOut(Console.OpenStandardOutput()); 12 } Listing 5.2: Capturing and redirecting console output to a string80 CHAPTER 5. MAINTENANCE AND MANAGEMENT OF CUSTOM CODE In line 4, the console output is redirected to an instantiated StringWriter. Afterwards, thescriptisexecuted,andfollowingitscompletion, writer.FlushAsync()forcesremaining buffered data to be written to the StringWriter. Any text that is written during the script execution is now present in the consoleOutput string. Finally, the default standard output is restored. This captures the console output, but there are two more sources of information that need to be considered: exceptions (errors) and return values. If an unhandled exception occurs during debugging of an .NET application, the execution is halted and the developer is notified of the error. To check if an error occurs, the ScriptState object, returned upon executionofScript.RunAsync(),providesanExceptionpropertythatcontainsinformation about the error. This needs to be passed to the user as well. Otherwise, the script will simply exit without notifying the user. Similarly, the return value, provided by any top- level return statements in the script, can be retrieved from the ReturnValue property of the ScriptState object. Figure 5.1: Debugging example showing console and return value output Figure 5.1 shows the example application implemented for this chapter. In the centre column, the citizen developer can input C# code. This example contains a simple script to calculatethefacultyofanumber. Uponclickingthemiddle(Compile and Execute)button, the script is built and run. Any strings emitted by Console.WriteLine() statements are printed to the text area in the right column. The return value, provided by the statement in line 3 is printed to the text area in the left column. In case of an error in the script, the output provided by the compiler is also printed in the left column. In figure 5.2, a spelling error (retrn instead of return in line 3) was made in the code, and the resulting compiler error message is displayed on the left. The interface of the example application is deliberately designed to be as minimal and5.3. IMPLEMENTATION 81 Figure 5.2: Debugging example showing compiler error output easily understandable as possible. As previously mentioned in section 5.1.1, the scripts written for LCA are expected to be relatively small. Compilation is therefore expected to be quick as well, and the user is provided with both a button to only compile the code, and check it for errors, and to compile and immediately run it. However, citizen developers are unlikely to exclusively write trivial scripts like the faculty calculation algorithm shown in figures 5.1 and 5.2. The code that is added to low code applications covers special cases that can’t be expressed by the LCDP by default. Thesecanbe, forexample, integrationswithotherapplications, connectivitywithexternal services [120, p. 69] or special parsing logic for data present in the LCA. As such, being able to immediately execute scripts might not be beneficial in all cases and can depend on the context. Suppose the script depends on external data, for example from a web service or a database, that is passed during runtime of the application. While the citizen developer can run and test the script isolated in the editor, it can only be fully integrated when it is run as part of the entire LCA. Another aspect to consider are the external libraries that are available to the CD. In listing 5.1, only the System.Console assembly is made available to the editor. In a more sophisticated application, many more assemblies may be required, such as for database access or the wrapped APIs introduced in section 3.4.1. While more references can be added to Roslyn either by default or at the runtime of the LCA, this needs to be done as transparently as possible for the CDs, as deciding what additional references they need is not within their usual expertise.82 CHAPTER 5. MAINTENANCE AND MANAGEMENT OF CUSTOM CODE 5.3.2 Versioning As explained in section 5.2.1, versioning control systems can be difficult to use. A simple abstraction layer, that internally operates on a Git repository, was developed as part of the CMSA and is shown in figure 5.3. This provides CDs with basic versioning features without having to learn the intricacies of a VCS. Figure 5.3: Versioning window of the CMSA The example consists of three parts: A history browser on the left side shows all previousversionsofthescript, alongwithatimestamp, theauthor, andacommitmessage. Below are several controls to store and restore versions to and from the repository. On the right side is a preview area that shows the content of the script from the selected version in the history browser. The user can browse through the different versions via the history, and preview and restore a specific version. They can also store the current version of the script, and enter a message that details the changes and will appear as part of the history. The abstraction layer is implemented with libgit2sharp5, a library enabling access to Git repositories from .NET, and several direct invocations of the Git executable, to work around authentication limitations in libgit2sharp. The CMSA operates on a single, existing Git repository. There are no special require- ments towards the repository, it can be either used locally, or connected to a remote host with internal or external services such as GitHub or Bitbucket6. As the script does not directly exist as a file on the local filesystem, it needs to be packaged in a format that 5https://github.com/libgit2/libgit2sharp 6A hosting service for source code, similar to GitHub - https://bitbucket.org5.3. IMPLEMENTATION 83 can be stored in the repository. As Git stores its data internally in a content-addressable filesystem, essentially a key-value store [23], the script doesn’t need to exist as a file. The CMSA serializes the script into a JSON object, using .NET’s JsonSerializer class, and stores it as a blob [23] in the repository. Each script is assigned a GUID that is used to identify and address its blob representation in Git’s filesystem. 1 public record VersioningModel(string Author, string Email, Guid BlobId, string Script, string ,→ RepositoryPath); 2 |
3 public void CommitCode(VersioningModel model) 4 { 5 var blob = SerializeBlob(model.BlobContent); 6 7 using var repo = new Repository(model.RepositoryPath); 8 9 var committer = new Signature(model.Author, model.Email, DateTime.Now); 10 11 repo.Index.Add(blob, model.BlobId.ToString(), Mode.NonExecutableFile); 12 repo.Index.Write(); 13 repo.Commit(CommitMessage, committer, committer); 14 } Listing 5.3: Committing code using libgit2sharp. Based on [70] Listing5.3showshowablobiscreatedandcommittedtotherepository. Theparameter model is a record, its definition shown in line 1, containing context-specific information about the repository, such as the path to the repository or author of the commit. After the blob is serialized and the repository initialized, a Signature object is instantiated to connect the identity of the author of the commit with the commit itself. Lines 11 and 12 add the blob to Git’s index, also called the staging area, where changes are collected, before line 13 commits them to the repository. At this point, the blob is only present in the local repository. Since Git is a distributed VCS, an additional remote repository can be configured. This allows multiple developers to push their work to a single, centralized point on a remote server, which is essential for collaboration. A public example repository was set up for the CMSA by the author and can be found on GitHub [19]. When multiple developers work with a common repository, some kind of user management and authentication is necessary [24]. Thus, operations on the remote repository, such as pushing changes to and pull changes from it, requires the user to authenticate with the server the repository resides on. Integration in existing enterprise authentication is out of scope for this thesis, however libgit2sharp generally also supports simple authentication with username and password. As hardcoding and exposing these in the source code presents a significant security issue, the CMSA relies84 CHAPTER 5. MAINTENANCE AND MANAGEMENT OF CUSTOM CODE on the Git Credential Manager for Windows [25], that can be installed as part of a standard Git installation and uses Windows’ built-in credential management. After the credentials for a certain server are entered once and stored, Git can use them implicitly when communicating with a remote repository. As there is no native API in .NET to access the credential manager, the library CredentialManager[152]isusedintheCMSA,whichprovidesawrapperofthenativeAPI [112]. The credentials are identified by an application-dependent key. The Git Credential Manager uses a format of {namespace}:{service} [49], where namespace defaults to git and service consists of the URL of the host of the repository. A full key might look like, for example, git:https:///github.com. 1 private static NetworkCredential GetOrAskCredentials(string credentialIdentifier) 2 { 3 var existingCredentials = CredentialManager.GetCredentials(credentialIdentifier); 4 5 if (existingCredentials !!= null) return existingCredentials; 6 7 var rememberCredentials = false; 8 return CredentialManager.PromptForCredentials(credentialIdentifier, ref rememberCredentials, ,→ $"Enter credentials to access {credentialIdentifier}.", "Credentials Request"); 9 } Listing 5.4: Retrieving credentials from the Windows credential store Retrieving the credentials is shown in listing 5.4. If the credentials with the specified key are not already present in the credential store, the user is asked to provide them. The stored username and password can then be used with libgit2sharp to authenticate requests to the remote repository, which is shown in listing 5.5 It should be noted that the NetworkCredential.SecurePassword property used for the password in listings 5.4 and 5.5 is of the type SecureString, which tries to minimize the exposure of sensitive data during runtime of an application. While it is more secure than a regular variable of type string, there are still instances where the password may be exposed in memory [100]. If the risk of exposing passwords in memory is deemed too large, authentication needs to be conducted outside the application, since there is no alternative to SecureString in .NET. Another option may be to not use libgit2sharp for communication with the remote repositories, and instead work with Git and its configured authentication directly, by invoking its executable with the appropriate arguments (such as git pull or git push). This is implemented in the CMSA as well and can be enabled via the advanced options shown in figure 5.3.5.4. SUMMARY AND DISCUSSION 85 1 private static void Push(NetworkCredential credentials, Repository repo) 2 { 3 var options = new PushOptions 4 { 5 CredentialsProvider = (_, _, _) =>= 6 new SecureUsernamePasswordCredentials 7 { 8 Username = credentials.UserName, 9 Password = credentials.SecurePassword 10 } 11 }; 12 repo.Network.Push(repo.Head, options); 13 } Listing 5.5: Pushing changes to a remote repository with libgit2sharp 5.4 Summary and discussion Chapter 5 demonstrated how techniques that are common in traditional software devel- opment processes can be integrated in LCDPs. These techniques require experience and familiarization with tools and can be challenging to learn even for professional developers. The CMSA shows how debugging and versioning tools can be used in a simplified way to enable citizen developers to benefit from them without the need for extensive training. The results from this chapter contribute towards an answer to RQ I, namely that assistance in debugging and versioning, by providing limited and clearly defined access to these tools, can be a viable way of supporting CDs. The CMSA only presents some of the ideas that could be implemented in a LCDP. The concrete implementation depends on external factors, namely the requirements of a LCDP towards debugging and versioning, the amount of technical details the target group of citizen developer can be exposed to, and the underlying technology stack. Debugging |
While printf debugging is a simple and widely used method to analyse issues with code, it is also the only option the CMSA offers. Other debugging techniques, such as breakpoints, inspecting the call stack or watching local variables are not supported. Of the previously discussed LCDPs that offer code extensions, both OutSystems [43] and Mendix [79] only support debugging via an external IDE. Microsoft’s Power Apps platform provides the Monitor tool [89], that enables detailed tracing of events that occur in the LCA, which is essentially a more advanced and automated version of debugging with output statements. Depending on the used libraries in the script, the assemblies containing them need to be added as references to Roslyn’s scripting engine. Although this is easily done from86 CHAPTER 5. MAINTENANCE AND MANAGEMENT OF CUSTOM CODE code (shown in listing 5.1), this means that either all references have to be hard-coded before use (potentially adding too many or too few libraries), or added on demand during runtime (which requires someone with that specific knowledge, or shifts the responsibility to the citizen developers). Compiler errors are returned and shown to the CD verbatim, without any special processing. As shown in section 5.1.1, it is inconclusive whether enhanced compiler output messages are helpful to users or not. A compromise may be to add more helpful messages incrementally for the most encountered compiler errors, based on real-world experience. The augmentation framework introduced in section 3.3 could be used to visualize errors directly in the editor. Versioning The CMSA is currently limited to a single script that can be edited and versioned. An actual application would have many scripts that need to be managed individually. The blob representing the code is stored with a unique, but otherwise nondescript ID in the repository, making usage outside the CMSA inefficient. Since the repository is not specific to the application, it can be used from external Git clients and services as well. This necessitates a better storage system with more descriptive names and a file and folder structure that is both human-readable for access from outside clients and can be reliably interacted with from external services. For example, the repository could be integrated into an existing issue-tracking system, connecting commits with task and bug tickets, or keeping a reference to the blob from a database, to map a script to a certain element of the LCA. The Git repository also has to be set up beforehand, including initialization and potentially hosting on a remote server; the CMSA cannot initialize a new or clone an existing repository. Git also has to be installed on all client machines or the server (depending on the type of LCDP) and prepared for multiple users. Authorization must be configured as well, so that commits are distinguishable between users. Collaboration between multiple developers inadvertently results in merge conflicts, caused by overlapping edits to code [20]. These conflicts have to be resolved before code is pushed or pulled to or from the repository. When Git encounters a change that cannot be automatically resolved, it will pause the merge operation and wait for the user to choose which of the conflicting lines of code are to be used. The CMSA doesn’t offer any special facilities to handle merge conflicts, they have to be resolved via other means, such as the command line or an external tool. Since the CMSA is primarily used for demonstration purposes, conflicts are not likely unless changes are made to the repository from the outside. A LCDP would, however, require a user-friendly option to show and resolve conflicts that can be handled by citizen developers.Chapter 6 Conclusions and future work 6.1 Summary This thesis presented approaches to extend code editors in LCDPs to support their users with context-based visual augmentations. These augmentations can be used, for example, to detect potentially insecure method calls and suggest more secure alternatives, or high- light statements based on regular expressions, to provide the user with additional feedback or information. To securely run different LCAs concurrently on a server, currently avail- able technologies to isolate applications from each other on OS- and process-level were evaluated. Theresultsdevelopedduringthisthesiscanbesuccessfullyusedtoanswertheresearch questions posed in section 1.4: RQ I: How can citizen developers in low-code environments that offer C#-based extension of their applications be supported? Theaugmentationframeworkcreatedaspartofchapter3providescustomizablevisual clues on a syntactic level. Augmentations can change the appearance of predefined state- ments, based on strings or regular expressions, by altering their typographic properties, displaying geometric elements or images, or replacing them with more meaningful identifi- ers. The code itself remains unchanged, the display is purely visual. On a semantic level, an approach of integrating custom Roslyn analyzers and code fixes into the RoslynPad code editor control, embeddable into any WPF application, was demonstrated. Chapter 5 provided examples how debugging and version control, two commonly used techniques in traditional software development, can be simplified and integrated in LCDPs in ways that are easy to use and understand for CDs. 8788 CHAPTER 6. CONCLUSIONS AND FUTURE WORK RQ II: How to guard against malicious or unintended harmful C# code that is written to extend low-code applications? Detecting potentially insecure or harmful code can be achieved by detecting specific statements, types or, method calls with either the augmentation framework or Roslyn analyzers, and emitting warnings or hints when found. However, the targeted APIs have to be known in advance and need to be routinely administered and updated. Wrapping complicated or security-critical libraries with a custom API can reduce the chance for misconfiguration of services. Neither of these will protect against actors that try to inject malicious code into a LCA. The examined API-level protections, CAS and AppDomains, are considered obsolete and offered no full protection in the first place. The threat model used in section 4.2 assumes that an attacker tries to compromise other applications |
hosted on the same server, and since there are no viable code-level security solutions, the alternative is to isolate applications against each other and the system on a lower level, which leads to RQ III: RQ III: How can the execution of low-code applications be isolated in a way, that additionally written C# code cannot adversely affect foreign resources on a system? For this purpose, both AppContainers and OS-level virtualization with Docker offered adequate options, the choice depends on the kind of applications (with or without UI) that need to be run, as well as requirements for scalability and platform-independence. AppContainers need to be bootstrapped by a separate process and are limited to Windows operating systems and applications. Since they can be configured to prevent sandboxed applications from using defined system services or only allowing access to certain files and folders, this is best suited for applications where these usages are known or can be altered to respond accordingly. Otherwise, applications may exhibit undesirable behaviour, when they don’t assume that they are run with limited integrity and encounter unexpected restrictions when accessing the system. Docker can be used to provide applications with a customizable, deterministicandcontainerizedenvironment, whilealsolimitingtheiraccess to the underlying operating systems and its resources. This enables multiple containers to be run on the same operating system concurrently, without the need for a completely virtualized operating system in a VM. Containers can be integrated into orchestration engines that provide management and scalability features for multiple containers. While Docker can work on multiple operating systems, it is primarily suited to run server-side applications without a GUI.6.2. OUTLOOK 89 6.2 Outlook Since the augmentation framework currently targets only a single editor component, a natural extension is the adaptability to other code editor controls. As the extensibility points of other editors can be expected to be different, more limited or less restricted, the concrete implementation for an editor could be abstracted away from an augmentation. It wouldbereducedtoasimple,data-holdingclasscontainingonlytheinformationdescribing how an augmentation should look to a user. The concrete editor implementations for rendering the augmentations reside in encapsulated classes, and are independent of the builder methods to configure an augmentation. The framework can also be expanded to support different kinds of input data, such as multiple image formats or importing analytics from an external sources, like databases. Similarly, the CMSA from section 5.3 could be adapted to support other version control systems than Git. As long as the functionality is kept to a common feature set (history, pushing and retrieving data from the VCS), the difficulty lies primarily in the availability of native libraries of other VCS. An alternative can be the implementation of a wrapper for the command-line interfaces most VCS provide. Using different compiler platforms for languages apart from those supported by Roslyn (C# and Visual Basic .NET) is dependent on the targeted language and whether suitable tools are available. For example, interoperability with Python code is possible with IronPython [62].List of Figures 2.1 Examples for LCDPs with different LCA output types . . . . . . . . . . . 14 2.2 Design view of the Asset Checkout app . . . . . . . . . . . . . . . . . . . . 15 2.3 Power Apps Asset Checkout on Windows 11 . . . . . . . . . . . . . . . . . 17 2.4 A table opened in SCOPELAND Direct Desk . . . . . . . . . . . . . . . . 20 2.5 Examples of hosted and generated SCOPELAND applications . . . . . . . 22 3.1 Replica of a Visual Studio static code analysis suggestion . . . . . . . . . 25 3.2 Visual features in different code editors . . . . . . . . . . . . . . . . . . . . 26 3.3 Rendering pipeline of AvalonEdit . . . . . . . . . . . . . . . . . . . . . . . 29 3.4 Syntax highlighting augmentation for Smalltalk code . . . . . . . . . . . . 30 3.5 Augmentation warning of the use of a SHA-1 method . . . . . . . . . . . . 30 3.6 Augmentation framework class diagram . . . . . . . . . . . . . . . . . . . 32 3.7 Simple relation between products and categories . . . . . . . . . . . . . . 33 3.8 Two different display modes for identifiers in code . . . . . . . . . . . . . . 33 3.9 A star glyph and a floppy disk image shown to the left and right of the code area in the editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35 3.10 Calling the example wrapper API in RoslynPad . . . . . . . . . . . . . . . 39 3.11 Advice augmentation triggered by the usage of an unsupported escape sequence. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41 3.12 Roslyn’s syntax visualizer showing the structure of a string literal variable assignment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43 3.13 Custom analyzer and code fix in RoslynPad . . . . . . . . . . . . . . . . . 46 4.1 Sandboxing architecture in Chromium . . . . . . . . . . . . . . . . . . . . 51 4.2 Types of virtualization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55 4.3 Architecture of Docker . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60 4.4 Process Explorer showing a sandboxed instance of Notepad . . . . . . . . 68 4.5 Open dialogue of Notepad in a sandboxed and non-sandboxed instance . . 70 5.1 Debugging example showing console and return value output . . . . . . . 80 5.2 Debugging example showing compiler error output . . . . . . . . . . . . . 81 5.3 Versioning window of the CMSA . . . . . . . . . . . . . . . . . . . . . . . 82 91List of Listings 2.1 Example of scaffolding code for a click event on a button in WPF . . . . . 19 3.1 Signature of the String.Concat() method overload for two strings in C# . 24 |
3.2 Ignoring the return value of the String.Concat() function . . . . . . . . . 25 3.3 Implementation of the SmalltalkHighlighting class . . . . . . . . . . . . 31 3.4 Implementation of the SHA-1 warning augmentation . . . . . . . . . . . . 32 3.5 Implementation of the augmentation for the clear text mode . . . . . . . . 34 3.6 Hashing a string with SHA512 in C# . . . . . . . . . . . . . . . . . . . . . 37 3.7 Integration of an external library in RoslynPad . . . . . . . . . . . . . . . 39 3.8 ImplementationofaRoslynanalyzertodetectunescapednewlinesequences in string literals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42 3.9 ImplementationofaRoslyncodefixtoreplaceunescapednewlinesequences in string literals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44 3.10 Adding an analyzer to the RoslynPad editor . . . . . . . . . . . . . . . . . 45 4.1 Dockerfile for compiling and deploying an ASP.NET Core application . . 61 4.2 Creation or retrieval of an AppContainer SID . . . . . . . . . . . . . . . . 67 4.3 Building a capability from a SID . . . . . . . . . . . . . . . . . . . . . . . 69 4.4 Adding the capabilities to the process attribute list . . . . . . . . . . . . . 69 4.5 Creating the sandboxed process . . . . . . . . . . . . . . . . . . . . . . . . 70 4.6 Adding the SID of the container to the ACL of a file or folder . . . . . . . 71 5.1 Compiling and executing a script with Roslyn . . . . . . . . . . . . . . . . 79 5.2 Capturing and redirecting console output to a string . . . . . . . . . . . . 79 5.3 Committing code using libgit2sharp . . . . . . . . . . . . . . . . . . . . . 83 5.4 Retrieving credentials from the Windows credential store . . . . . . . . . 84 5.5 Pushing changes to a remote repository with libgit2sharp . . . . . . . . . 85 93List of Tables 4.1 Benchmark of basic Docker commands . . . . . . . . . . . . . . . . . . . . 64 95Bibliography [1] Adobe. Adobe Flash Player End of Life. 13th Jan. 2021. url: https://www.adobe. com/products/flashplayer/end-of-life.html (visited on 27/01/2023). [2] Mark Aiken et al. ‘Deconstructing Process Isolation’. In: Proceedings of the 2006 Workshop on Memory System Performance and Correctness. MSPC ’06. New York, NY, USA: Association for Computing Machinery, 22nd Oct. 2006, pp. 1–10. isbn: 978-1-59593-578-6. doi: 10.1145/1178597.1178599. [3] Md Abdullah Al Alamin et al. ‘An Empirical Study of Developer Discussions on Low-Code Software Development Challenges’. In: 2021 IEEE/ACM 18th Interna- tional Conference on Mining Software Repositories (MSR) (May 2021), pp. 46–57. doi: 10.1109/MSR52588.2021.00018. arXiv: 2103.11429. [4] FaisalAlAmeiriandKhaledSalah.‘EvaluationofPopularApplicationSandboxing’. In:2011InternationalConferenceforInternetTechnologyandSecuredTransactions. 2011 International Conference for Internet Technology and Secured Transactions. Dec. 2011, pp. 358–362. [5] Vinicius Apolinario. Nano Server x Server Core x Server - Which Base Image Is the Right One for You? 12th Oct. 2021. url: https://techcommunity.microsoft. com/t5/containers/nano-server-x-server-core-x-server-which-base-image-is- the-right/ba-p/2835785 (visited on 27/01/2023). [6] Eli Arbel. Default Analyzers · Issue #238 · Roslynpad/Roslynpad. GitHub. 28th Feb. 2019. url: https://github.com/roslynpad/roslynpad/issues/238 (visited on 27/01/2023). [7] Eli Arbel. RoslynPad. RoslynPad, 10th Nov. 2022. url: https://github.com/ roslynpad/roslynpad (visited on 27/01/2023). [8] Michael Bargury, Ben Kliger and Ory Segal. OWASP Top 10 Low-Code/No-Code Security Risks. url: https://owasp.org/www-project-top-10-low-code-no-code- security-risks/ (visited on 27/01/2023). [9] Adam Barth, Charles Reis and Collin Jackson. The Security Architecture of the Chromium Browser. 2008. url: https://seclab.stanford.edu/websec/chromium/ chromium-security-architecture.pdf (visited on 27/01/2023). 9798 BIBLIOGRAPHY [10] Brett A. Becker. ‘An Effective Approach to Enhancing Compiler Error Messages’. In: Proceedings of the 47th ACM Technical Symposium on Computing Science Edu- cation. SIGCSE ’16. New York, NY, USA: Association for Computing Machinery, 17th Feb. 2016, pp. 126–131. isbn: 978-1-4503-3685-7. doi: 10.1145/2839509. 2844584. [11] Moritz Beller et al. ‘On the Dichotomy of Debugging Behavior Among Program- mers’. In: 2018 IEEE/ACM 40th International Conference on Software Engineering (ICSE). 2018 IEEE/ACM 40th International Conference on Software Engineering (ICSE). May 2018, pp. 572–583. doi: 10.1145/3180155.3180175. [12] David Beserra et al. ‘Performance Evaluation of OS-Level Virtualization Solu- tions for HPC Purposes on SoC-Based Systems’. In: 2017 IEEE 31st International Conference on Advanced Information Networking and Applications (AINA). 2017 IEEE 31st International Conference on Advanced Information Networking and Applications (AINA). Mar. 2017, pp. 363–370. doi: 10.1109/AINA.2017.73. [13] Ashish Bijlani, Umakishore Ramachandran and Roy Campbell. ‘Where Did My 256 GB Go? A Measurement Analysis of Storage Consumption on Smart Mobile Devices’. In: Proceedings of the ACM on Measurement and Analysis of Computing Systems 5.2 (3rd June 2021), 28:1–28:28. doi: 10.1145/3460095. [14] David Binkley. ‘Source Code Analysis: A Road Map’. In: Future of Software En- gineering (FOSE ’07). Future of Software Engineering (FOSE ’07). May 2007, |
pp. 104–119. doi: 10.1109/FOSE.2007.27. [15] Thomas Bläsing et al. ‘An Android Application Sandbox System for Suspicious Software Detection’. In: 2010 5th International Conference on Malicious and Un- wanted Software. 2010 5th International Conference on Malicious and Unwanted Software. Oct. 2010, pp. 55–62. doi: 10.1109/MALWARE.2010.5665792. [16] Kathleen Broome Williams. Grace Hopper: Admiral of the Cyber Sea. Naval Insti- tute Press, 2012. isbn: 978-1-59114-978-1. [17] LennartBrüggemann.Lennartb-/AppContainerSample.5thJan.2023. url:https: //github.com/lennartb-/AppContainerSample (visited on 27/01/2023). [18] Lennart Brüggemann. Lennartb-/ThesisSamples. 17th Nov. 2022. url: https: //github.com/lennartb-/ThesisSamples (visited on 27/01/2023). [19] Lennart Brüggemann. Lennartb-/VersioningSampleRepo. GitHub. 27th Oct. 2022. url: https://github.com/lennartb-/VersioningSampleRepo (visited on 27/01/2023).BIBLIOGRAPHY 99 [20] Yuriy Brun et al. ‘Proactive Detection of Collaboration Conflicts’. In: Proceedings of the 19th ACM SIGSOFT Symposium and the 13th European Conference on Foundations of Software Engineering - SIGSOFT/FSE ’11. The 19th ACM SIG- SOFT Symposium and the 13th European Conference. Szeged, Hungary: ACM Press, 2011, p. 168. isbn: 978-1-4503-0443-6. doi: 10.1145/2025113.2025139. [21] BundesamtfürSicherheitinderInformationstechnik.IT-Grundschutz-Kompendium –WerkzeugfürInformationssicherheit.BundesamtfürSicherheitinderInformation- stechnik. 1st Feb. 2022. url: https://www.bsi.bund.de/DE/Themen/Unternehmen- und-Organisationen/Standards-und-Zertifizierung/IT-Grundschutz/IT- Grundschutz-Kompendium/itgrundschutzKompendium.html (visited on 27/01/2023). [22] NavaKiranButhukuri.WhatAreCodeComponents?-PowerApps.13thMar.2022. url: https://docs.microsoft.com/en-us/power-apps/developer/component- framework/custom-controls-overview (visited on 27/01/2023). [23] ScottChaconandBenStraub.‘10.2GitInternals-GitObjects’.In:Pro Git.2nded. 2014. url: https://git-scm.com/book/en/v2/Git-Internals-Git-Objects (visited on 27/01/2023). [24] Scott Chacon and Ben Straub. ‘4.2 Git on the Server - Getting Git on a Server’. In: Pro Git. 2nd ed. 2014. url: https://git-scm.com/book/en/v2/Git-on-the- Server-Getting-Git-on-a-Server (visited on 27/01/2023). [25] Scott Chacon and Ben Straub. ‘7.14 Git Tools - Credential Storage’. In: Pro Git. 2nd ed. 2014. url: https://git-scm.com/book/en/v2/Git-Tools-Credential- Storage (visited on 27/01/2023). [26] Raymond Chen. What Are These SIDs of the Form S-1-15-2-xxx? The Old New Thing. 2nd May 2022. url: https://devblogs.microsoft.com/oldnewthing/ 20220502-00/?p=106550 (visited on 27/01/2023). [27] Brad Cleaver. ManagedSandbox. 5th Oct. 2019. url: https://github.com/ ificator/ManagedSandbox/blob/7148573d4489160b1310aebc848af4a1eba3ff46/ src/AppContainer/AppContainer.cs (visited on 10/02/2023). [28] Theo Combe, Antony Martin and Roberto Di Pietro. ‘To Docker or Not to Docker: A Security Perspective’. In: IEEE Cloud Computing 3.5 (Sept. 2016), pp. 54–62. issn: 2325-6095. doi: 10.1109/MCC.2016.100. [29] David Coulter. Run Canvas App and Model-Driven Apps on Power Apps Mobile - Power Apps. 14th Apr. 2022. url: https://docs.microsoft.com/en-us/power- apps/mobile/run-powerapps-on-mobile (visited on 27/01/2023). [30] CVE. CVE - CVE-2010-2897. 28th July 2010. url: https://www.cve.org/ CVERecord?id=CVE-2010-2897 (visited on 27/01/2023).100 BIBLIOGRAPHY [31] CVE. CVE - CVE-2010-2898. 28th July 2010. url: https://www.cve.org/ CVERecord?id=CVE-2010-2898 (visited on 27/01/2023). [32] Vijay D’Silva, Daniel Kroening and Georg Weissenbacher. ‘A Survey of Automated Techniques for Formal Software Verification’. In: IEEE Transactions on Computer- Aided Design of Integrated Circuits and Systems 27.7 (July 2008), pp. 1165–1178. issn: 1937-4151. doi: 10.1109/TCAD.2008.923410. [33] Paul Denny, Andrew Luxton-Reilly and Dave Carpenter. ‘Enhancing Syntax Error MessagesAppearsIneffectual’.In:Proceedingsofthe2014ConferenceonInnovation & Technology in Computer Science Education. ITiCSE ’14. New York, NY, USA: Association for Computing Machinery, 21st June 2014, pp. 273–278. isbn: 978-1- 4503-2833-3. doi: 10.1145/2591708.2591748. [34] Docker. Docker Overview. Docker Documentation. url: https://docs.docker. com/get-started/overview/ (visited on 27/01/2023). [35] Docker. Dockerfile Best Practises - Create Ephemeral Containers. 24th June 2022. url: https://github.com/docker/docker.github.io/blob/master/develop/ develop-images/dockerfile_best-practices.md#create-ephemeral-containers (visited on 27/01/2023). [36] Docker. Dockerfile Best Practises - Leverage Build Cache. 24th June 2022. url: https://github.com/docker/docker.github.io/blob/master/develop/develop- images/dockerfile_best-practices.md#leverage-build-cache (visited on 27/01/2023). [37] Docker. Dockerfile Reference. Docker Documentation. url: https://docs.docker. com/engine/reference/builder/ (visited on 27/01/2023). [38] Docker. Dotnet-Docker/Dockerfile at Main. .NET Platform, 16th Aug. 2022. url: |
https://github.com/dotnet/dotnet-docker/blob/afae431a7488a5912f6217cc148 cc86e2593116b/samples/aspnetapp/Dockerfile (visited on 02/02/2023). [39] Docker. Runtime Options with Memory, CPUs, and GPUs. Docker Documentation. url: https://docs.docker.com/config/containers/resource_constraints/ (visited on 09/02/2023). [40] Docker. Seccomp Security Profiles for Docker. Docker Documentation. url: https: //docs.docker.com/engine/security/seccomp/ (visited on 27/01/2023). [41] Docker. Use Volumes. Docker Documentation. url: https://docs.docker.com/ storage/volumes/ (visited on 27/01/2023).BIBLIOGRAPHY 101 [42] Hector A. Duran-Limon et al. ‘Using Lightweight Virtual Machines to Run High Performance Computing Applications: The Case of the Weather Research and Forecasting Model’. In: 2011 Fourth IEEE International Conference on Utility and CloudComputing.2011FourthIEEEInternationalConferenceonUtilityandCloud Computing. Dec. 2011, pp. 146–153. doi: 10.1109/UCC.2011.29. [43] G. Andrew Duthie. Video: How to Debug a .NET Extension | OutSystems. 1st Feb. 2019. url: https://www.outsystems.com/forums/discussion/44849/video-how- to-debug-a-net-extension/# (visited on 27/01/2023). [44] Diogo A. B. Fernandes et al. ‘Security Issues in Cloud Environments: A Survey’. In: International Journal of Information Security 13.2 (1st Apr. 2014), pp. 113–170. issn: 1615-5270. doi: 10.1007/s10207-013-0208-7. [45] Simon Ferquel. Docker � WSL 2 - The Future of Docker Desktop for Windows - Docker. 16th June 2019. url: https://www.docker.com/blog/docker-hearts-wsl- 2/ (visited on 15/09/2022). [46] Ulrich Frank, Pierre Maier and Alexander Bock. Low Code Platforms: Promises, Concepts and Prospects: A Comparative Study of Ten Systems. Essen, Dec. 2021. doi: 10.17185/DUEPUBLICO/75244. [47] Meg Fryling. ‘Low Code App Development’. In: Journal of Computing Sciences in Colleges 34.6 (1st Apr. 2019), p. 119. issn: 1937-4771. [48] Genevieve Warren. Code Access Security Policy Compatibility and Migration. 30th Mar. 2017. url: https://docs.microsoft.com/en-us/previous-versions/ dotnet/framework/code-access-security/code-access-security-policy- compatibility-and-migration (visited on 27/01/2023). [49] git-credential-manager. Git-Credential-Manager/Configuration.Md at Main · GitCredentialManager/Git-Credential-Manager. 14th Oct. 2022. url: https : //github.com/GitCredentialManager/git-credential-manager/blob/main/docs/ configuration.md#credentialnamespace (visited on 27/01/2023). [50] Ian Goldberg et al. ‘A Secure Environment for Untrusted Helper Applications Con- fining the Wily Hacker’. In: Proceedings of the 6th Conference on USENIX Security Symposium, Focusing on Applications of Cryptography - Volume 6. SSYM’96. USA: USENIX Association, 22nd July 1996, p. 1. [51] Google. Chromium Design Docs - Sandbox. url: https://chromium.googlesource. com/chromium/src/+/HEAD/docs/design/sandbox.md (visited on 27/01/2023). [52] Mel Gorman. Understanding The Linux Virtual Memory Manager. 9th July 2007. url: https://www.kernel.org/doc/gorman/pdf/understand.pdf (visited on 09/02/2023).102 BIBLIOGRAPHY [53] Peter Leo Gorski et al. ‘”I Just Looked for the Solution!” - On Integrating Security- Relevant Information in Non-Security API Documentation to Support Secure Cod- ing Practices’. In: IEEE Transactions on Software Engineering (2021), pp. 1–1. issn: 1939-3520. doi: 10.1109/TSE.2021.3094171. [54] Peter Leo Gorski et al. ‘Developers Deserve Security Warnings, Too: On the Ef- fect of Integrated Security Advice on Cryptographic API Misuse’. In: Fourteenth Symposium on Usable Privacy and Security (SOUPS 2018). 2018, pp. 265–281. isbn: 978-1-939133-10-6. url: https://www.usenix.org/conference/soups2018/ presentation/gorski (visited on 27/01/2023). [55] Chris Greamo and Anup Ghosh. ‘Sandboxing and Virtualization: Modern Tools for Combating Malware’. In: IEEE Security Privacy 9.2 (Mar. 2011), pp. 79–82. issn: 1558-4046. doi: 10.1109/MSP.2011.36. [56] Daniel Grunwald. RenderingPipeline.Png. 6th Oct. 2009. url: https://github. com/icsharpcode/AvalonEdit/blob/fa0b33097d14c56120b31f63a05a7ad10b74566 c/Documentation/Media/RenderingPipeline.png (visited on 27/01/2023). [57] Daniel Grunwald. Using AvalonEdit (WPF Text Editor). CodeProject. 1st Apr. 2013. url: https://www.codeproject.com/Articles/42490/Using-AvalonEdit- WPF-Text-Editor (visited on 27/01/2023). [58] Lassi Haaranen and Teemu Lehtinen. ‘Teaching Git on the Side: Version Control System as a Course Platform’. In: Proceedings of the 2015 ACM Conference on Innovation and Technology in Computer Science Education. ITiCSE ’15. New York, NY,USA:AssociationforComputingMachinery,22ndJune2015,pp.87–92. isbn: 978-1-4503-3440-2. doi: 10.1145/2729094.2742608. [59] John Hoopes. Virtualization for Security - 1st Edition. 1st Dec. 2008. url: https: //www.elsevier.com/books/virtualization-for-security/hoopes/978-1-59749- 305-5 (visited on 27/01/2023). [60] George F. Hurlburt. ‘Low-Code, No-Code, What’s Under the Hood?’ In: IT Pro- fessional 23.6 (Nov. 2021), pp. 4–7. issn: 1941-045X. doi: 10.1109/MITP.2021. 3123415. [61] Alex Ilgayev. Playing in the (Windows) Sandbox. Check Point Research. 11th Mar. 2021. url: https://research.checkpoint.com/2021/playing-in-the-windows- sandbox/ (visited on 27/01/2023). |
[62] IronPython. IronPython.Net. url: https : / / ironpython . net/ (visited on 27/01/2023).BIBLIOGRAPHY 103 [63] Ville Isomöttönen and Michael Cochez. ‘Challenges and Confusions in Learning Version Control with Git’. In: Information and Communication Technologies in Education, Research, and Industrial Applications. Ed. by Vadim Ermolayev et al. Vol. 469. Communications in Computer and Information Science. Cham: Springer International Publishing, 2014, pp. 178–193. isbn: 978-3-319-13205-1. doi: 10. 1007/978-3-319-13206-8_9. [64] Alexandre Jacinto, Miguel Lourenço and Carla Ferreira. ‘Test Mocks for Low-Code Applications Built with OutSystems’. In: Proceedings of the 23rd ACM/IEEE Inter- national Conference on Model Driven Engineering Languages and Systems: Com- panion Proceedings. New York, NY, USA: Association for Computing Machinery, 16th Oct. 2020, pp. 1–5. isbn: 978-1-4503-8135-2. doi: 10.1145/3417990.3420209. [65] Wayne Jansen, Theodore Winograd and Karen Scarfone. Guidelines on Active ContentandMobileCode.NISTSpecialPublication(SP)800-28Version2.National Institute of Standards and Technology, 7th Mar. 2008. doi: 10.6028/NIST.SP.800- 28ver2. [66] S.C. Johnson. Lint, a C Program Checker. Bell Laboratories, 26th July 1978. [67] Uwe Jugel. ‘Generating Smart Wrapper Libraries for Arbitrary APIs’. In: Software Language Engineering. Ed. by Mark van den Brand, Dragan Gašević and Jeff Gray. Lecture Notes in Computer Science. Berlin, Heidelberg: Springer, 2010, pp. 354– 373. isbn: 978-3-642-12107-4. doi: 10.1007/978-3-642-12107-4_24. [68] Faezeh Khorram, Jean-Marie Mottu and Gerson Sunyé. ‘Challenges & Opportuni- ties in Low-Code Testing’. In: Proceedings of the 23rd ACM/IEEE International Conference on Model Driven Engineering Languages and Systems: Companion Proceedings. MODELS ’20: ACM/IEEE 23rd International Conference on Model DrivenEngineeringLanguagesandSystems.VirtualEventCanada:ACM,16thOct. 2020, pp. 1–10. isbn: 978-1-4503-8135-2. doi: 10.1145/3417990.3420204. [69] Gaëtan Leurent and Thomas Peyrin. ‘SHA-1 Is a Shambles: First Chosen-Prefix Collision on SHA-1 and Application to the PGP Web of Trust’. In: 29th USENIX Security Symposium (USENIX Security 20). 2020, pp. 1839–1856. isbn: 978-1- 939133-17-5. url: https://www.usenix.org/conference/usenixsecurity20/ presentation/leurent (visited on 27/01/2023). [70] libgit2sharp. Make a Commit to a Bare Repository. 29th Sept. 2022. url: https: //github.com/libgit2/libgit2sharp/wiki/git-commit (visited on 27/01/2023). [71] Linux Kernel Organization. SECure COMPuting with Filters. url: https:// www.kernel.org/doc/Documentation/prctl/seccomp_filter.txt (visited on 27/01/2023).104 BIBLIOGRAPHY [72] LinuxProgrammer’sManual.Namespaces(7) - Linux Manual Page.27thAug.2021. url: https://man7.org/linux/man-pages/man7/namespaces.7.html (visited on 27/01/2023). [73] P. Louridas. ‘Static Code Analysis’. In: IEEE Software 23.4 (July 2006), pp. 58–61. issn: 1937-4194. doi: 10.1109/MS.2006.114. [74] Michael J De Lucia. A Survey on Security Isolation of Virtualization, Containers, and Unikernels. US Army Research Laboratory Aberdeen Proving Ground United States, 2017. url: https://apps.dtic.mil/sti/pdfs/AD1035194.pdf (visited on 27/01/2023). [75] Yajing Luo et al. ‘Characteristics and Challenges of Low-Code Development: The Practitioners’ Perspective’. In: Proceedings of the 15th ACM / IEEE Interna- tional Symposium on Empirical Software Engineering and Measurement (ESEM) (11th Oct. 2021), pp. 1–11. doi: 10.1145/3475716.3475782. arXiv: 2107.07482. [76] Joe Mayo. ‘Managing .NET Code Access Security (CAS) Policy’. In: CODE Magazine 5.3 (2004). url: https://www.codemag.com/article/0405031/Managing- .NET-Code-Access-Security-CAS-Policy (visited on 27/01/2023). [77] Paul Menage. Control Groups — The Linux Kernel Documentation. url: https: //www.kernel.org/doc/html/latest/admin-guide/cgroup-v1/cgroups.html (visited on 27/01/2023). [78] Mendix. Building Progressive Web Applications in Mendix | Mendix Evalu- ation Guide. Mendix. url: https://www.mendix.com/evaluation-guide/app- capabilities/native-mobile-apps/ (visited on 02/02/2023). [79] Mendix. Debug Java Actions. 4th Jan. 2023. url: https://docs.mendix. com/howto/monitoring-troubleshooting/debug-java-actions/ (visited on 27/01/2023). [80] Mendix. Extend Your Application with Custom Java. 5th Jan. 2023. url: https: //docs.mendix.com/refguide/extending-your-application-with-custom-java/ (visited on 27/01/2023). [81] Mendix. Install Mendix Studio Pro. 4th Apr. 2022. url: https://docs.mendix. com/howto/general/install/ (visited on 27/01/2023). [82] Mendix. Private Cloud. 15th Mar. 2022. url: https://docs.mendix.com/ developerportal/deploy/private-cloud/ (visited on 27/01/2023). [83] Mendix. Version Control. 16th Sept. 2022. url: https://docs.mendix.com/ refguide/version-control/ (visited on 27/01/2023). [84] Microsoft. .NET Framework Technologies Unavailable on .NET Core and .NET 5+. 26th May 2022. url: https://docs.microsoft.com/en-us/dotnet/core/porting/ net-framework-tech-unavailable (visited on 27/01/2023).BIBLIOGRAPHY 105 [85] Microsoft. Application Domains Overview. 16th Nov. 2012. url: https://docs. microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2008/ |
2bh4z9hs(v=vs.90) (visited on 27/01/2023). [86] Microsoft. CA1806: Do Not Ignore Method Results. 21st May 2022. url: https: //docs.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality- rules/ca1806 (visited on 02/02/2023). [87] Microsoft. CA3001: Review Code for SQL Injection Vulnerabilities. 19th May 2021. url: https://docs.microsoft.com/en-us/dotnet/fundamentals/code- analysis/quality-rules/ca3001 (visited on 27/01/2023). [88] Microsoft. CA5351: Do Not Use Broken Cryptographic Algorithms. 15th Sept. 2021. url: https://docs.microsoft.com/en-us/dotnet/fundamentals/code- analysis/quality-rules/ca5351 (visited on 27/01/2023). [89] Microsoft.DebuggingCanvasAppswithMonitor-PowerApps.15thFeb.2022. url: https://docs.microsoft.com/en-us/power-apps/maker/monitor-canvasapps (visited on 27/01/2023). [90] Microsoft. Designing Applications to Run at a Low Integrity Level. 5th July 2007. url: https://docs.microsoft.com/en-us/previous-versions/dotnet/articles/ bb625960(v=msdn.10) (visited on 27/01/2023). [91] Microsoft. Ensure Security Isolation for Web Sites. 23rd Mar. 2022. url: https:// docs.microsoft.com/en-us/iis/manage/configuring-security/ensure-security- isolation-for-web-sites (visited on 27/01/2023). [92] Microsoft. FAQ’s about Windows Subsystem for Linux. url: https://docs. microsoft.com/en-us/windows/wsl/faq (visited on 27/01/2023). [93] Microsoft. Get Started with Syntax Analysis (Roslyn APIs). 15th Sept. 2021. url: https://learn.microsoft.com/en-us/dotnet/csharp/roslyn-sdk/get-started/ syntax-analysis (visited on 27/01/2023). [94] Microsoft. Handles and Objects - Win32 Apps. 8th Feb. 2022. url: https://docs. microsoft.com/en-us/windows/win32/sysinfo/handles-and-objects (visited on 27/01/2023). [95] Microsoft. Implementing an AppContainer - Win32 Apps. 7th Jan. 2021. url: https://docs.microsoft.com/en-us/windows/win32/secauthz/implementing-an- appcontainer (visited on 27/01/2023). [96] Microsoft.Mandatory Integrity Control - Win32 Apps.25thMar.2021. url:https: //docs.microsoft.com/en-us/windows/win32/secauthz/mandatory-integrity- control (visited on 27/01/2023).106 BIBLIOGRAPHY [97] Microsoft. Platform Invoke (P/Invoke). 11th Mar. 2022. url: https://docs. microsoft.com/en-us/dotnet/standard/native-interop/pinvoke (visited on 27/01/2023). [98] Microsoft. Power Apps (Preview). Microsoft Store. url: https://www.microsoft. com/en-us/p/power-apps-preview/9mvc8p1q3b29 (visited on 27/01/2023). [99] Microsoft. Roslyn/Scripting-API-Samples.Md at Main · Dotnet/Roslyn. 24th Jan. 2020. url:https://github.com/dotnet/roslyn/blob/main/docs/wiki/Scripting- API-Samples.md#multi (visited on 27/01/2023). [100] Microsoft. SecureString Class (System.Security). url: https://learn.microsoft. com/en-us/dotnet/api/system.security.securestring?view=net-7.0 (visited on 27/01/2023). [101] Microsoft. Security Changes in the .NET Framework 4. 4th Feb. 2013. url: https: //docs.microsoft.com/en-us/previous-versions/dotnet/netframework-4.0/ dd233103(v=vs.100) (visited on 27/01/2023). [102] Microsoft. Security Identifiers - Win32 Apps. 12th July 2022. url: https:// docs.microsoft.com/en-gb/windows/security/identity-protection/access- control/security-identifiers (visited on 27/01/2023). [103] Microsoft. SHA512 Class (System.Security.Cryptography). url: https://docs. microsoft.com/en-us/dotnet/api/system.security.cryptography.sha512 (vis- ited on 27/01/2023). [104] Microsoft. SHA512Managed Class (System.Security.Cryptography). url: https: //docs.microsoft.com/en-us/dotnet/api/system.security.cryptography. sha512managed (visited on 27/01/2023). [105] Microsoft. System.Windows.Media.TextFormatting Namespace. url: https:// learn.microsoft.com/en-us/dotnet/api/system.windows.media.textformatting? view=windowsdesktop-7.0 (visited on 27/01/2023). [106] Microsoft. The .NET Compiler Platform SDK (Roslyn APIs). 15th Sept. 2021. url: https://learn.microsoft.com/en-us/dotnet/csharp/roslyn-sdk/ (visited on 27/01/2023). [107] Microsoft. Understanding Enhanced Protected Mode. 23rd Mar. 2012. url: https: //docs.microsoft.com/en-us/archive/blogs/ieinternals/understanding- enhanced-protected-mode (visited on 27/01/2023). [108] Microsoft. User Mode and Kernel Mode - Windows Drivers. 15th Dec. 2021. url: https://docs.microsoft.com/en-us/windows-hardware/drivers/ gettingstarted/user-mode-and-kernel-mode (visited on 27/01/2023).BIBLIOGRAPHY 107 [109] Microsoft.WELL_KNOWN_SID_TYPE (Winnt.h) - Win32 Apps.31stJan.2022. url: https://docs.microsoft.com/en-us/windows/win32/api/winnt/ne-winnt- well_known_sid_type (visited on 27/01/2023). [110] Microsoft. What Is Configuration Manager? - Configuration Manager. 20th Jan. 2022. url: https://docs.microsoft.com/en-us/mem/configmgr/core/ understand/introduction (visited on 27/01/2023). [111] Microsoft. What Is the Windows Integrity Mechanism? 5th July 2007. url: https: //docs.microsoft.com/en-us/previous-versions/dotnet/articles/bb625957(v= msdn.10) (visited on 27/01/2023). [112] Microsoft. Wincred.h Header - Win32 Apps. 28th July 2022. url: https://learn. |
microsoft.com/en-us/windows/win32/api/wincred/ (visited on 27/01/2023). [113] Microsoft. Windows Sandbox - Windows Security. 3rd Aug. 2022. url: https: //docs.microsoft.com/en-us/windows/security/threat-protection/windows- sandbox/windows-sandbox-overview (visited on 27/01/2023). [114] Microsoft.WindowsSandboxArchitecture-WindowsSecurity.25thJuly2022. url: https://docs.microsoft.com/en-us/windows/security/threat-protection/ windows-sandbox/windows-sandbox-architecture (visited on 27/01/2023). [115] Microsoft. Windows Sandbox Configuration - Windows Security. 25th July 2022. url: https://docs.microsoft.com/en-us/windows/security/threat- protection/windows-sandbox/windows-sandbox-configure-using-wsb-file (visited on 27/01/2023). [116] MarekMoravcikandMartinKontsek.‘OverviewofDockerContainerOrchestration Tools’. In: 2020 18th International Conference on Emerging eLearning Technolo- gies and Applications (ICETA). 2020 18th International Conference on Emerging eLearning Technologies and Applications (ICETA). Nov. 2020, pp. 475–480. doi: 10.1109/ICETA51985.2020.9379236. [117] Dan Moseley. Migration Story for Running Untrusted Code in CoreCLR without AppDomains · Issue #4108 · Dotnet/Runtime. GitHub. 21st Nov. 2019. url: https://github.com/dotnet/runtime/issues/4108#issuecomment-556912494 (visited on 27/01/2023). [118] netblue30.Firejail.5thAug.2022. url:https://github.com/netblue30/firejail (visited on 27/01/2023). [119] Marie-Hélène Nienaltowski, Michela Pedroni and Bertrand Meyer. ‘Compiler Error Messages: What Can Help Novices?’ In: ACM SIGCSE Bulletin 40.1 (12th Mar. 2008), pp. 168–172. issn: 0097-8418. doi: 10.1145/1352322.1352192. [120] Karsten Noack. Thinking Scopeland. 2017. url: https://www.scopeland.de/ downloads/de/Thinking_SCOPELAND.pdf (visited on 27/01/2023).108 BIBLIOGRAPHY [121] nuget.org. AvalonEdit 6.1.3.50. url: https://www.nuget.org/packages/ AvalonEdit/ (visited on 27/01/2023). [122] Marten Oltrogge et al. ‘The Rise of the Citizen Developer: Assessing the Security Impact of Online App Generators’. In: 2018 IEEE Symposium on Security and Privacy (SP). 2018 IEEE Symposium on Security and Privacy (SP). San Francisco, CA: IEEE, May 2018, pp. 634–647. isbn: 978-1-5386-4353-2. doi: 10.1109/SP. 2018.00005. [123] Oracle.JDK9ReleaseNotes-DeprecatedAPIs,Features,andOptions. url:https: //www.oracle.com/java/technologies/javase/9-deprecated-features.html (visited on 27/01/2023). [124] OutSystems. Can I Integrate OutSystems with SVN, TFS or GitHub? | Evaluation Guide. url: https://www.outsystems.com/evaluation-guide/can-i-integrate- outsystems-with-svn-tfs-or-github/ (visited on 27/01/2023). [125] OutSystems. OutSystems System Requirements - OutSystems 11 Documenta- tion. OutSystems. 4th Oct. 2022. url: https://success.outsystems.com/ Documentation/11/Setup_and_maintain_your_OutSystems_infrastructure/ Setting_Up_OutSystems/OutSystems_system_requirements(visitedon27/01/2023). [126] OWASP. OWASP Top 10:2021. url: https://owasp.org/Top10/ (visited on 27/01/2023). [127] Raymond S. Pettit, John Homer and Roger Gee. ‘Do Enhanced Compiler Error Messages Help Students? Results Inconclusive.’ In: Proceedings of the 2017 ACM SIGCSE Technical Symposium on Computer Science Education. SIGCSE ’17. New York,NY,USA:AssociationforComputingMachinery,8thMar.2017,pp.465–470. isbn: 978-1-4503-4698-6. doi: 10.1145/3017680.3017768. [128] Herbert Prähofer et al. ‘Opportunities and Challenges of Static Code Analysis of IEC61131-3Programs’.In:Proceedingsof2012IEEE17thInternationalConference on Emerging Technologies Factory Automation (ETFA 2012). Proceedings of 2012 IEEE17thInternationalConferenceonEmergingTechnologiesFactoryAutomation (ETFA 2012). Sept. 2012, pp. 1–8. doi: 10.1109/ETFA.2012.6489535. [129] James Prather et al. ‘On Novices’ Interaction with Compiler Error Messages: A HumanFactorsApproach’.In:Proceedings of the 2017 ACM Conference on Interna- tional Computing Education Research. ICER ’17. New York, NY, USA: Association for Computing Machinery, 14th Aug. 2017, pp. 74–82. isbn: 978-1-4503-4968-0. doi: 10.1145/3105726.3106169. [130] Clay Richardson and John R. Rymer. New Development Platforms Emerge For Customer-Facing Applications. 9th June 2014. url: https://www.forrester.com/ report/New-Development-Platforms-Emerge-For-CustomerFacing-Applications/ RES113411 (visited on 02/02/2023).BIBLIOGRAPHY 109 [131] Thomas Ristenpart et al. ‘Hey, You, Get off of My Cloud: Exploring Informa- tion Leakage in Third-Party Compute Clouds’. In: Proceedings of the 16th ACM Conference on Computer and Communications Security. CCS ’09. New York, NY, USA: Association for Computing Machinery, 9th Nov. 2009, pp. 199–212. isbn: 978-1-60558-894-0. doi: 10.1145/1653662.1653687. [132] Luis Rodero-Merino et al. ‘Building Safe PaaS Clouds: A Survey on Security in Multitenant Software Platforms’. In: Computers and Security 31.1 (2012), p. 96. doi: 10.1016/j.cose.2011.10.006. [133] Mark Russinovich. PsExec, User Account Control and Security Boundaries. Mi- crosoftTechCommunity.12thFeb.2007. url:https://techcommunity.microsoft. com/t5/windows-blog-archive/psexec-user-account-control-and-security- |
boundaries/ba-p/723551 (visited on 27/01/2023). [134] Apurvanand Sahay et al. ‘Supporting the Understanding and Comparison of Low- Code Development Platforms’. In: 2020 46th Euromicro Conference on Software Engineering and Advanced Applications (SEAA). 2020 46th Euromicro Conference on Software Engineering and Advanced Applications (SEAA). Aug. 2020, pp. 171– 178. doi: 10.1109/SEAA51224.2020.00036. [135] Raquel Sanchis et al. ‘Low-Code as Enabler of Digital Transformation in Manufac- turing Industry’. In: Applied Sciences 10.1 (18th Dec. 2019), p. 12. issn: 2076-3417. doi: 10.3390/app10010012. [136] Sandboxie. How Does Sandboxie Protect Me, Technically? Sandboxie Documen- tation. url: https://sandboxie-plus.github.io/sandboxie-docs/Content/ FrequentlyAskedQuestions.html#how-does-sandboxie-protect-me-technically (visited on 27/01/2023). [137] M. Satratzemi, S. Xinogalos and V. Dagdilelis. ‘An Environment for Teaching Object-Oriented Programming: objectKarel’. In: Proceedings 3rd IEEE Interna- tional Conference on Advanced Technologies. Proceedings 3rd IEEE International Conference on Advanced Technologies. July 2003, pp. 342–343. doi: 10.1109/ ICALT.2003.1215114. [138] Gian Luca Scoccia and Marco Autili. ‘Web Frameworks for Desktop Apps: An Exploratory Study’. In: Proceedings of the 14th ACM / IEEE International Sym- posium on Empirical Software Engineering and Measurement (ESEM). ESEM ’20. NewYork,NY,USA:AssociationforComputingMachinery,5thOct.2020,pp.1–6. isbn: 978-1-4503-7580-1. doi: 10.1145/3382494.3422171. [139] Scopeland Technology GmbH. SCOPELAND Code Generator for NET | Scopeland Technology GmbH. url: https://www.scopeland.com/scopeland-asp (visited on 27/01/2023).110 BIBLIOGRAPHY [140] Scopeland Technology GmbH. SCOPELAND Version 6.4. 2017. url: https:// www.scopeland.de/downloads/de/WhitePaper_Version_6.4.pdf (visited on 27/01/2023). [141] ScopelandTechnologyGmbH.TheLow-CodeMethod|ScopelandTechnologyGmbH. url: https://scopeland.com/lowcode (visited on 27/01/2023). [142] Andrey Shchekin. Environment.FailFast() Can Be Used to Crash the Container · Issue #1204 · Ashmind/SharpLab. 19th Sept. 2022. url: https://github. com/ashmind/SharpLab/issues/1204#issuecomment-1250841920 (visited on 27/01/2023). [143] Bundesamt für Sicherheit in der Informationstechnik. Sichere Nutzung von Cloud- Diensten. Bundesamt für Sicherheit in der Informationstechnik. 9th Aug. 2016. url: https://www.bsi.bund.de/SharedDocs/Downloads/DE/BSI/Publikationen/ Broschueren/Sichere_Nutzung_Cloud_Dienste.html?nn=132646 (visited on 27/01/2023). [144] Jim Smith and Ravi Nair. Virtual Machines: Versatile Platforms for Systems and Processes (The Morgan Kaufmann Series in Computer Architecture and Design). San Francisco, CA, USA: Morgan Kaufmann Publishers Inc., 2005. isbn: 978-1- 55860-910-5. [145] James Starkey. True Story of BLOBs. 22nd Jan. 1997. url: https://web.archive. org/web/20110723065224/http://www.cvalde.net/misc/blob_true_history.htm (visited on 27/01/2023). [146] Matúš Sulír et al. ‘Visual Augmentation of Source Code Editors: A Systematic Mapping Study’. In: Journal of Visual Languages & Computing 49 (1st Dec. 2018), pp. 46–59. issn: 1045-926X. doi: 10.1016/j.jvlc.2018.10.001. [147] Sari Sultan, Imtiaz Ahmad and Tassos Dimitriou. ‘Container Security: Issues, Challenges, and the Road Ahead’. In: IEEE Access 7 (2019), pp. 52976–52996. issn: 2169-3536. doi: 10.1109/ACCESS.2019.2911732. [148] Andrew S. Tanenbaum and Herbert Bos. Modern Operating Systems. 4th ed. USA: Prentice Hall Press, 2014. 1136 pp. isbn: 978-0-13-359162-0. [149] IgorTasevskiandKireJakimoski.‘OverviewofSQLInjectionDefenseMechanisms’. In: 2020 28th Telecommunications Forum (TELFOR). 2020 28th Telecommunic- ations Forum (TELFOR). Nov. 2020, pp. 1–4. doi: 10.1109/FOR51502.2020. 9306676. [150] CraigTorres.Demand for Programmers Hits Full Boil as U.S. Job Market Simmers. Bloomberg. 8th Mar. 2018. url: https://www.bloomberg.com/news/articles/ 2018-03-08/demand-for-programmers-hits-full-boil-as-u-s-job-market- simmers (visited on 27/01/2023).BIBLIOGRAPHY 111 [151] David Ungar, Henry Lieberman and Christopher Fry. ‘Debugging and the Experi- ence of Immediacy’. In: Communications of the ACM 40.4 (1st Apr. 1997), pp. 38– 43. issn: 0001-0782. doi: 10.1145/248448.248457. [152] Adarsha Vishweshwara. CredentialManager. Adys Tech, 19th Oct. 2022. url: https://github.com/AdysTech/CredentialManager (visited on 27/01/2023). [153] Robert Wahbe et al. ‘Efficient Software-Based Fault Isolation’. In: Proceedings of the Fourteenth ACM Symposium on Operating Systems Principles. SOSP ’93. New York, NY, USA: Association for Computing Machinery, 1st Dec. 1993, pp. 203–216. isbn: 978-0-89791-632-5. doi: 10.1145/168619.168635. [154] Web Platform Incubator Community Group. WebUSB API. 25th Feb. 2022. url: https://wicg.github.io/webusb/ (visited on 27/01/2023). [155] Anja Weber. IT-Fachkräftelücke wird größer: 96.000 offene Jobs. Bitkom Research. 3rd Jan. 2022. url: https://www.bitkom-research.de/de/pressemitteilung/it- |
fachkraefteluecke-wird-groesser-96000-offene-jobs (visited on 27/01/2023). [156] WikiWikiWeb. Smalltalk Syntax In a Postcard. 28th Feb. 2014. url: https:// wiki.c2.com/?SmalltalkSyntaxInaPostcard (visited on 27/01/2023). [157] Wissenschaftliche Dienste des Deutschen Bundestages. DSGVO und Nutzung US- amerikanischer Cloud-Dienste. 3rd June 2021. url: https://www.bundestag.de/ resource/blob/852984/692120a134f9e79999c6f4170a47859a/WD-3-102-21-pdf- data.pdf (visited on 27/01/2023). [158] Zhaohang Yan. The Impacts of Low/No-Code Development on Digital Transforma- tion and Software Development. 28th Dec. 2021. arXiv: 2112.14073. url: http: //arxiv.org/abs/2112.14073 (visited on 27/01/2023). [159] Wenhua Yang et al. ‘Do Developers Really Know How to Use Git Commands? A Large-scale Study Using Stack Overflow’. In: ACM Transactions on Software Engineering and Methodology 31.3 (9th Apr. 2022), 44:1–44:29. issn: 1049-331X. doi: 10.1145/3494518. [160] Qin Zhao et al. ‘How to Do a Million Watchpoints: Efficient Debugging Using Dynamic Instrumentation’. In: Compiler Construction. Ed. by Laurie Hendren. Lecture Notes in Computer Science. Berlin, Heidelberg: Springer, 2008, pp. 147– 162. isbn: 978-3-540-78791-4. doi: 10.1007/978-3-540-78791-4_10. [161] Zeineb Zhioua, Stuart Short and Yves Roudier. ‘Static Code Analysis for Software Security Verification: Problems and Approaches’. In: 2014 IEEE 38th Interna- tional Computer Software and Applications Conference Workshops. 2014 IEEE 38th International Computer Software and Applications Conference Workshops (COMPSACW). Vasteras, Sweden: IEEE, July 2014, pp. 102–109. isbn: 978-1- 4799-3578-9. doi: 10.1109/COMPSACW.2014.22. |
2307.06616 1 SecureFalcon: Are We There Yet in Automated Software Vulnerability Detection with LLMs? Mohamed Amine Ferrag∗§, Ammar Battah∗, Norbert Tihanyi∗, Ridhi Jain∗, Diana Maimu¸t∗, Fatima Alwahedi∗, Thierry Lestable∗, Narinderjit Singh Thandi∗, Abdechakour Mechri∗, Merouane Debbah†, and Lucas C. Cordeiro‡ ∗Technology Innovation Institute, UAE †Khalifa University of Science and Technology, UAE ‡University of Manchester, UK §Corresponding author: mohamed.ferrag@tii.ae Abstract—Software vulnerabilities can cause numerous prob- software [4]. Furthermore, the datasets used by these tools lems, including crashes, data loss, and security breaches. These are often too small [5] or have a skewed distribution of issuesgreatlycompromisequalityandcannegativelyimpactthe vulnerable programs [6], hampering the accuracy of static market adoption of software applications and systems. Tradi- analyzer tools. Although the advancements in deep learning tional bug-fixing methods, such as static analysis, often produce falsepositives.Whileboundedmodelchecking,aformofFormal (DL)seempromisingforvulnerabilitydetection[7]–[10],their Verification(FV),canprovidemoreaccurateoutcomescompared accuracy heavily relies on the data quality as well [6], [11]. to static analyzers, it demands substantial resources and signif- Most of the popular datasets are either fully synthetic [12], icantly hinders developer productivity. Can Machine Learning [13], non-compilable [14]–[16], or have an unfair distribu- (ML) achieve accuracy comparable to FV methods and be used tion of vulnerable vs non-vulnerable code [11], [15], [17]. in popular instant code completion frameworks in near real- time? In this paper, we introduce SecureFalcon, an innovative Moreover,thelabelsassociatedwiththesedatasetsaresubject model architecture with only 121 million parameters derived to the detection method used. For instance, manual labeling fromtheFalcon-40Bmodelandexplicitlytailoredforclassifying is affected by human errors, whereas using static analysis software vulnerabilities. To achieve the best performance, we tools to label the data can result in high false positives [18], trainedourmodelusingtwodatasets,namelytheFormAIdataset [19]. While the DL-based approaches are often employed for and the FalconVulnDB. The FalconVulnDB is a combination of recent public datasets, namely the SySeVR framework, Draper quick inference, they may compromise the model’s accuracy VDISC, Bigvul, Diversevul, SARD Juliet, and ReVeal datasets. indetectingbugs.FormalVerification(FV)approachessuchas These datasets contain the top 25 most dangerous software Model Checking (MC) are preferred for verification in safety- weaknesses, such as CWE-119, CWE-120, CWE-476, CWE-122, critical systems [20]. Even though MC provides safety assur- CWE-190, CWE-121, CWE-78, CWE-787, CWE-20, and CWE- ancesforsoftwaresystems[21],[22],theyareoftenexpensive, 762.SecureFalconachieves94%accuracyinbinaryclassification andupto92%inmulticlassification,withinstantCPUinference even for a small piece of code. Bounded Model Checking times. It outperforms existing models such as BERT, RoBERTa, (BMC) [23], [24] improves the traditional MC techniques by CodeBERT, and traditional ML algorithms, promising to push restricting the exploration to a predefined bound or depth. To the boundaries of software vulnerability detection and instant prove safety in BMC for programs, we must compute the code completion frameworks. completeness threshold (CT), which can be smaller than or Index Terms—FalconLLM, Large Language Model, Software equal to the maximum number of loop iterations occurring in Security, Security, Generative Pre-trained Transformers. theprogram.AlthoughBMCoffersperformanceimprovement to some extent, it is still expensive. I. INTRODUCTION Code completion tools are gaining popularity in software As we are undoubtedly passing through a digital age, engineering, where rapid inference is essential. For example, technology affects every aspect of our lives [1]. In such a toolssuchasGitHubCopilot1 andAmazonCodeWhisperer2 context, vulnerability detection tools are essential safeguards suggest code snippets based on contextual analysis and train- in our continuously evolving digital landscape [2], [3]. With ingdata,which,accordingtorecentstudies,canalsointroduce theemergenceofnewtechnologies,thepaletteofcyberthreats vulnerabilities[25].Thisraisesacriticalquestion:Canwede- becomes wider and more sophisticated in terms of employed velopamodelthatdetectsvulnerabilitiesefficientlywithoutthe techniques. Vulnerability detection tools assist in scanning, lengthy processing times associated with BMC methods while probing, and inspecting software, identifying weaknesses that stillmaintaininghighaccuracy?Thisisessentiallyatrade-off could serve as entry points for potential malicious users between accuracy and speed. BMC methods can achieve high or attackers. While integral to software security measures, accuracy by eliminating false positives with counterexamples vulnerability detection tools encounter inherent limitations in and providing stack traces. Despite this, verifying the entire their scope and efficiency. Such tools typically depend on knownpatternsandsignaturesderivedfromsyntheticdatasets, 1https://github.com/features/copilot/ making them less effective for detecting bugs in real-world 2https://aws.amazon.com/codewhisperer/ 4202 yaM 92 ]RC.sc[ 2v61660.7032:viXrastatespaceofevensimpleprogramscantakehours.Thisissue is illustrated in Figure 1, where the red line represents the |
BMC method achieving high accuracy over several hours – an impractical timeframe for real-time code completion tools. Conversely, the blue line represents a Large Language Model (LLM),which,whilenotreachingthesameaccuracyasBMC methods,stillpredictshighreliabilityandcanquicklyidentify software vulnerabilities. 0 hour 1 hours 2 hours 3 hours 4 hours 5 hours 6 hours Time etaR noitceteD edoC elbarenluV checker ESBMC [24], 2 contains compilable programs, 3 evenly distributes vulnerable and neutral programs, and 4 is generatedbyLLMtrainedonreal-worldopensourcesoftware, thus,mimickingtheprominentdevelopererrorsandmakingit a highly suitable dataset for training a vulnerability detection model.Theoriginalcontributionsofourworkaresummarized as follows: • We introduce SecureFalcon, a lightweight and inno- vative LLM model with only 121 million parameters, Vulnerable Code Detection Rate Comparison built on the foundational 40B-parameter FalconLLM ar- High Detection rate using BMC methods Lower Detection rate using LLM chitecture. This model offers significant enhancements and optimizations specifically tailored for security anal- ysis. SecureFalcon underwent fine-tuning with the introduction of the FormAI dataset, a specialized collec- tion designed to accurately classify vulnerabilities within C/C++ code samples. This process was supported by using the Efficient SMT-based Context-Bounded Model Training Checker (ESBMC) tool, enhancing the model’s detection Phase capabilities. • SincetheformalverificationtoolscannotdetectallCom- mon Weakness Enumerations (CWEs), such as CWE-78, we created an aggregated dataset called FalconVulnDB, incorporating the SySeVR framework, Draper VDISC, Bigvul, Diversevul, SARD Juliet, and ReVeal datasets, to enrich SecureFalcon’s training by leveraging an extensivecompilationofpublicdatasets.Theseresources Fig. 1: Vulnerable Code Detection Rate (BMC vs LLMs). collectively cover examples of the top 25 most critical softwareweaknessesidentifiedbytheCommonWeakness Thered-highlightedarearepresentsthegapthatcanonlybe Enumeration (CWE), including but not limited to CWE- closedthroughrigorousmathematicalformalverification[26]. 119, CWE-120, CWE-476, CWE-122, CWE-190, CWE- However, overall, formal program verification is undecid- 121, CWE-78, CWE-787, CWE-20, and CWE-762. The able [27], [28]. We cannot devise a computational method FalconVulnDB dataset was used to compensate for the to decide whether an arbitrary program is error-free. Much lack of real project data in the FormAI dataset. progress has been made in program verification. Nowadays, • In terms of performance, SecureFalcon showcases verification methods create abstractions to determine whether exceptionalproficiencyinbinaryclassification,achieving the program is error-free. Still, for an arbitrary program that an accuracy rate of 94% in identifying vulnerabilities in includes unbounded memory usage, we cannot give 100% C/C++ code. Moreover, the model maintains a robust certainty that it is error-free due to the well-known halting accuracy rate of 92% across diverse code samples in problem[27].However,toachievehighaccuracydetectionrate multi-classification, underscoring its effectiveness and for vulnerable code almost instantly with a fine-tuned model reliability in vulnerability detection. With these results, would be a significant achievement. We aim to minimize this we outperformed traditional ML algorithms like KNN, gap (red-highlighted area) as much as possible and dramati- LR, NB, SVM, RRF, DT, and LDA by 11% (with RF cally reduce vulnerability detection times, making it practical achieving 81%), and existing LLM models like BERT, for real-time code completion frameworks. While it is unreal- CodeBERT, and RoBERTa by 4% (with CodeBERT istictoexpectLLMstomatchtheresultsofBMCverification achieving 88%). This advancement promises to push the tools at this stage, there is promise in using ML techniques boundariesofsoftwarevulnerabilitydetectionandinstant to swiftly identify the most vulnerable programs. Integrating code completion frameworks. a robust BMC tool with a pre-trained LLM can enhance the paceofvulnerabilitydetection,benefitingtheoverallsoftware The rest of this paper is structured as follows. Section II development process. The success of a vulnerability detection outlines the main motivation behind our research. Section III model greatly depends on the quality and relevance of the overviews the research literature relevant to software vul- dataset it uses. Thus, a dataset that provides a balanced dis- nerability detection. Section IV discusses the methodology tribution of vulnerable and non-vulnerable programs, mirrors and approach employed to create SecureFalcon. Sec- real-world coding, and is labeled with a reliable method can tion VI presents the experimental setup and the evaluation of enhance the model’s accuracy. In contrast to most available SecureFalcon’s performance. Finally, we conclude with C/C++ vulnerability datasets, the FormAI dataset [29] 1 has Section VII summarizing the key concepts, findings, and highlabelingaccuracyasitislabeledbyanunboundedmodel contributions with their corresponding implications. 2II. MOTIVATION (i and j both range from 0 to 99,999). Within each iteration, the product of i * j is added to the sum variable. Since the As software development accelerates, so does the com- sum variable accumulates these products (sum += i * j;), it is plexity of codebases, making identifying vulnerabilities a possibleforthesumtoexceedthemaximumvaluerepresented paramountconcern.Atoolthatexpeditiouslypinpointsvulner- by an int. When this happens, it causes arithmetic overflow, |
able code offers a proactive defense against potential exploits, whichmeanstheresultisbeyondtherangerepresentedbythe minimizingthewindowofsusceptibilityandenhancingoverall data type, resulting in an incorrect value being stored in the software security [30]. Rapid vulnerability detection not only sum variable. safeguards against cyber threats but also instills confidence in software reliability, ensuring the delivery of secure and Arithemtic overflow example trustworthy applications within tight development schedules. Bounded Model Checking (BMC) is a formal verification #include <stdio.h> 1 technique used in computer science and software engineering int main() { 2 toverifythecorrectnessofcriticalhardwareandsoftwarecom- int i, j; 3 ponents within a finite number of steps. The BMC technique 4 int sum = 0; for (i = 0; i < 1000000; ++i) { extracts the program code, the basis for generating a control- 5 for (j = 0; j < 1000000; ++j) { flow graph (CFG) [31]. In this CFG, each node represents 6 7 sum += i * j; either a deterministic or non-deterministic assignment or a }} 8 conditional statement. The next step involves converting the printf("Sum:%ld\n", sum); 9 CFG into a Static Single Assignment (SSA) form and trans- 10 return 0; } forming it into a State Transition System (STS). The resultant 11 STScansubsequentlybeconvertedintoanSMT(Satisfiability Listing 1: Arithmetic overflow on line number 7. Modulo Theories) formula that can be understood by an SMT solver, such as CVC5 [32], Bitwuzla [33] or Z3 [34]. SMT solver tools can ascertain whether a counterexample exists for Verifying this program with BMC can take hours due to certainpropertieswithinaspecifiedboundk.Formallywritten, nestedloopsrequiringcarefulunwinding.Forexample,apply- given a program P, consider its finite state transition system, ingtheEfficientSMT-basedContext-BoundedModelChecker TS = (S,R,I). Here, S is the set of states, R ⊆ S × S (ESBMC) took more than seven hours using k-induction. In represents the set of transitions, and (s ,··· ,s ) ∈ I ⊆ S contrast, a suitably trained ML algorithm, such as a Large n m represents the set of initial states. A state s ∈ S includes Language Model (LLM), can quickly pinpoint such issues. the program counter value, pc, and program variables. The LLMshaveseveraladvantagesovertraditionalformalmethods initial state s assigns the starting program location, and each like BMC: they can learn from vast amounts of code and 1 transitionT =(s ,s )∈Rhasalogicalformuladescribing vulnerabilitypatterns,enablingthemtogeneralizeandidentify i i+1 the constraints between states. In BMC, we define properties errors efficiently. LLMs are also capable of handling diverse with logical formulas: ϕ(s) for safety/security properties and codebases and detecting vulnerabilities without the extensive ψ(s) for program termination. Notably, termination and error manualsetuprequiredforBMC.Thisexampleunderscoresthe are exclusive: ϕ(s)∧ψ(s) is always unsatisfiable. A state is necessity for a compact model that can swiftly identify com- a deadlock if T(s ,s )∨ϕ(s) is unsatisfiable. The BMC mon errors in C programs, enabling quicker detection across i i+1 problem, ∆ can be expressed as: various scenarios. Additionally, LLMs can be integrated into k code completion frameworks with near-instant inference time, providing real-time feedback to developers and significantly k−1 k accelerating the development process. This makes LLMs a (cid:94) (cid:95) ∆ =I(s )∧ T(s ,s )∧ ¬ϕ(s ). (1) superior choice over BMC for many practical applications in k 1 i i+1 i i=1 i=1 software detection and vulnerability analysis. where I is the initial states set, and T(s ,s ) the transition III. RELATEDWORK i i+1 relationofTS.ThisformulacapturesTS executionsoflength In recent research, LLMs have been employed for source k, and if it is satisfied, a state violates ϕ within the k limit. code summarization [35], [36], which can aid in vulnerabil- A counterexample, or trace, for a violated ϕ is a sequence ity detection. Further, contrastive learning techniques have of states s ,...,s . If Equation (1) is unsatisfiable, no error been applied to LLMs to improve vulnerability detection 1 k state exists within k steps, indicating no vulnerabilities in the accuracy [37]. Similarly, transfer learning has been widely programuptothekbound.Checkingpropertyviolationsusing used in vulnerability detection and repair with LLMs [38], BMC techniques can be time-consuming even for relatively [39]. Researchers have significantly improved vulnerability small programs due to lengthy loops that require unwinding detection performance by pre-training models on large code or intricate function calls [24]. Consider Listing 1 where an corporaandfine-tuningthemonvulnerability-specificdatasets. arithmetic overflow occurs due to the nature of the nested Neural machine translation techniques employed to trans- loopsandtheaccumulationofvaluesinthesumvariable.The late code snippets into natural language aid in vulnerabil- code consists of two nested loops iterating from 0 to 999,999 ity detection [40], [41]. By translating code into human- 3readable descriptions, models can help developers understand IV. MODELARCHITECTURE code snippets’ behavior and potential risks. SySeVR [42] A. FalconLLM Model uses DL to detect slice-level vulnerability by preserving The FalconLLM40B [54] is one of the best performing semantic and syntactic knowledge about the vulnerabilities. open-source models3 that underwent an extensive training Similarly, VulDeePecker [7] also extracts program slices to |
procedure on 384 GPUs (A100 40GB). The model’s training detect vulnerabilities. However, as these models are trained procedureincorporateda3Dparallelismstrategythatinvolved on semi-synthetic datasets, they fail to detect real-world vul- tensor parallelism of 8 (TP=8), pipeline parallelism of 4 nerabilities [11]. Devign [43] uses a Graph Neural Network (PP=4), and data parallelism of 12 (DP=12). This approach (GNN) trained on manually labeled datasets for vulnerability was used in conjunction with ZeRO (Zero Redundancy Opti- identification. The Devigen dataset is constructed from the mizer) to enhance the efficiency of the training procedure. Linuxkernel,QEMU,Wireshark,andFFmpeg,whichgenerate around58,000graphs.However,thedatasetonlycontainsnon- The training hyperparameters used for FALCONLLM40B were specifically selected to optimize the model’s learning compilablefunctions.Severalworkshavealsousedtransform- process. The precision of the model was set to bfloat16 to ers’vulnerabilitydetectionduetotheirremarkablecapabilities balancecomputationalefficiencyandnumericalprecision.The in understanding and processing natural language and code AdamW! [55] optimizer was chosen for its proven ability to structures [10], [44], [45]. Their attention mechanisms enable achieve good results in less time. The learning rate was set at them to capture complex relationships and patterns within 1.85e-4 during the warm-up phase involving 4 billion tokens, text and programming languages. LLMs such as GPT-3 [46] followedbyacosinedecayto1.85e-5,whichallowsthemodel havebeenexploredforcodesecurityanalysisandvulnerability toconvergemoreefficiently.Theweightdecaywassetat1e-1 detection. Researchers have used GPT to generate vulnerable topreventoverfitting,whileZ-losswassetat1e-4tominimize code snippets and identify potential security flaws. Code- the discrepancy between the model’s predictions and the true BERT [44], a pre-trained language model, has been applied values. Finally, the batch size was fixed at 1152 with a 100 to vulnerability detection in source code. By fine-tuning billion token ramp-up to maximize computational throughput the model on labeled vulnerability data, researchers have and stabilize the learning process. achieved promising results in identifying vulnerabilities such as SQL injection, cross-site scripting (XSS), and buffer over- flow [47], [48]. Transformer-based models, like BERT [49] B. SecureFalcon Model Architecture and RoBERTa [45], have also been utilized for vulnerability The SecureFalcon model, derived from the 40B parameter detectioninvarioussoftwareartifacts.Despitearecentsurgein FalconLLM, includes components shown in Fig. 2, featuring theapplicationofDLforvulnerabilitydetection[7],[42],[50], out_features=12formulti-classificationandout_features=2for [51], a comprehensive solution with high confidence remains binary classification. elusive[11],[52].MostDLapproachessufferfromfourmajor The architecture comprises four primary components: Word issues: 1 inadequate model, 2 learning irrelevant features, Embeddings,EncoderLayers,FinalLayerNormalization,and 3 data duplication, 4 data imbalance [11]. the Scoring Layer. 1) Word Embeddings: Word Embeddings serve as the initial transformation layer in the language model. This layer transforms discrete words into dense, continuous vectors, To address these challenges, we employed a modern trans- which encapsulate semantic and syntactic information of the former model, the 40B parameter FalconLLM, which aids words [56]. Their dimension is 768, and the model is trained in comprehending semantic dependencies through extensive with a vocabulary size 65024. training (addressing problem 1 ). Falcon’s architecture has Let’sdenotethei-thwordinaninputsequenceasinput[i]. demonstrated superior performance to GPT-3, achieving im- The corresponding word embedding, e , is a row vector ob- pressive results while utilizing only a portion of the training i tained from the embedding matrix E, which can be expressed compute budget and requiring less computation at inference as: time. We fine-tuned the transformer model, leveraging the ob- tainedunderstandingofnaturallanguageandlearningdirectly from the source code (addressing problem 2 ). Further, we e =E(input)[i,:] (2) i carefully pre-process the data to ensure no duplications or ir- relevantfeaturesandminimizetheclassimbalance(addressing Here, E represents the embedding matrix with dimen- problems 3 and 4 ). We utilize only a configured portion of sions vocabulary size × embedding dimension, which in this the Falcon-40B model for a light and compact model that fits case is 65024×768. Each row in E corresponds to the vector the assigned task. Such a design choice stems from language representation of a word in the vocabulary. models [53] and thorough experimentation, pushing us to Therefore, an input sequence input of length n is trans- take a modest approach to the scale of the model to combat formedintoasequenceofwordvectorseofdimensionn×768. overfitting concerns. We fine-tune the model on C/C++ code This transformation can be depicted as: samples to be able to differentiate between vulnerable and non-vulnerable samples. The final model, which we named 3https://huggingface.co/spaces/HuggingFaceH4/open_llm_leaderboard - 10 SecureFalcon, consists of only 121 million parameters. July2023 4Output Software Vulnerability Probabilities Score : Linear(in_features=768, out_features=2, |
bias=False) LayerNorm((768,), eps=1e-05, elementwise_affine=True) Dense : Linear layer(in_features=3072, out_features=768, bias=False) Gaussian Error Linear Unit (GELU) Dense : Linear layer(in_features=768, out_features=3072, bias=False) Attention Dropout Layer Dense : Linear Layer (in_features=768, out_features=768, bias=False) Q_K_V: Linear layer (in_features=768, out_features=896, bias=False) RotaryEmbedding() Input : LayerNorm((768,), eps=1e-05, elementwise_affine=True) Embedding Layer (65024, 768) reyaL redoceD x 21 nortpecreP reyalitluM gniddebmE yratoR htiw noitnettA fleS its effectiveness within the Transformer architecture, of- fering valuable supervision for dependency modeling be- tweenelementsatdifferentsequencepositions.Inthepur- suitofintegratingpositionalinformationintothelearning process of Transformer-based language models, a novel method, termed Rotary Position Embedding (RoPE), has been proposed by Su et al. [59]. RoPE uniquely encodes the absolute position using a rotation matrix while incor- porating explicit relative position dependency in the self- attention formulation. RoPE’s implementation involves applyingtherotationtothequery(Q)andkey(K)vectors: Q′,K′ =rotate(Q,K,RoPE) (5) Where rotate is a function that applies RoPE to the vec- tors. The self-attention function is subsequently defined as: (cid:18) Q′K′T(cid:19) Att(Q′,K′,V)=softmax √ V (6) d k Where d denotes the dimension of the key vectors. The k softmaxfunctionensuresthattheaggregateweightofdif- √ ferentvaluesequals1.Divisionby d isascalingfactor k to maintain gradient stability during optimization. RoPE exhibits several beneficial properties, such as sequence Fig. 2: SecureFalcon model architecture. length flexibility, a decay in inter-token dependency with increasingrelativedistances,andthecapabilityofendow- ing linear self-attention with relative position encoding. • MLP (Multilayer Perceptron): The MLP is a type of e=[e ,e ,...,e ],wheree =E(input)[i,:] (3) neuralnetworkthatcomprisesaminimumofthreelayers 1 2 n i of nodes: an input layer, one or more hidden layers, and an output layer [60]. Each layer is fully connected These word embeddings, e , are fed into subsequent layers i to the subsequent layer, signifying that every node in in the model. They encapsulate rich information about the one layer is connected with every node in the following semantics and syntactic roles of the words and their context, layer. In this case, the MLP includes an input layer. This providing a dense representation that assists in better under- hidden layer uses a Gaussian Error Linear Unit (GELU) standing and generating language. activation function [61] to introduce non-linearity and 2) Decoder Layers: These constitute the main portion of an output layer. This non-linearity allows the model to the language model and comprise four stacked transformer captureandlearncomplexpatternsinthedata.TheMLP layers [57]. Each layer includes the following components: can be represented as: • Layer Normalization: This regularization technique stan- dardizes the inputs across the feature dimension, making the model more stable and faster to train [58]. The MLP(x)=Lin (GELU(Lin (x))) (7) parametersforthislayerare768-dimensionalvectors.It’s out hidden computed using the formula: In this equation, Lin is the linear transformation hidden x−µ corresponding to the hidden layer, GELU represents xˆ= (4) σ the Gaussian Error Linear Unit activation function, and Lin denotes the linear transformation of the output out layer. The variable x represents the input to the MLP. where x is the input, µ is the mean, σ is the standard deviation, and xˆ is the normalized output. This operation Each of the above components is essential to the function- is applied to each feature independently. ality of the decoder layer. The layer normalization stabilizes • Self-Attention with Rotary Position Embedding (RoPE): theinputstotheself-attentionandMLPcomponents,theself- Recent advancements in position encoding have shown attention module allows the model to consider different parts 5oftheinputwhengeneratingeachword,andtheMLPprovides prediction. Being fine-tuned from the FalconLLM model, this the additional representative capacity to the model. architecture has proven effective for software vulnerability 3) Final Layer Normalization: The output from the last detection by capturing the complex syntax and semantics of decoder layer undergoes an additional layer normalization programming languages, which will be demonstrated in the operation to standardize the outputs before the final linear Experimental Evaluation Section. transformation and softmax operation. This operation follows thesamemathematicalprinciplesasthelayernormalizationin V. DATASETSFORFINE-TUNINGSECUREFALCON thedecoderlayers.Theparametersforthislayerarealso768- Todeveloparobustmodel,thechoiceofdatasetisessential. dimensionalvectors.Thislayermaintainsaconsistentdistribu- During the training phase, we utilized two datasets: the For- tionofactivationsandgradientsacrossthenetwork,improving mAI dataset [29] and FalconVulnDB, an aggregated dataset model performance. In the context of language models, this we created for fine-tuning SecureFalcon, compiled from all helpspreservethequalityofthegeneratedtext.Theoperation relevant datasets found in the literature. of the final layer normalization can be represented as: 1) FormAIdataset: SecureFalconusestheFormAIdataset4 [29] for fine-tuning the model. The FormAI dataset includes |
y−µ 112,000 compilable C code snippets created using the GPT- yˆ= (8) σ 3.5-turbo model through a dynamic zero-shot prompting method. Since this GPT model from OpenAI5 is trained Where y is the input to the final layer normalization, µ is usingreal-worldopen-sourcesoftwarerepositories,thecodeit the mean, σ is the standard deviation, and yˆis the normalized generates closely mimics real-world code behavior. The pro- output.Similartothelayernormalizationinthedecoderlayers, duced C samples are subsequently verified using the Efficient this operation is applied to each feature independently. After SMT-based Context-Bounded Model Checker (ESBMC) [?]. the final layer normalization, the 768-dimensional vectors ESBMC is set with a verification timeout of 30 seconds per are passed into the final linear layer and softmax function sample.Accordingtothe2023SV-COMPresults6,thisverifier to generate the output probabilities for each word in the has successfully addressed the most significant number of vocabulary. verification tasks. The generated C samples are classified into 4) Scoring layer: The scoring stage involves a linear layer threecategories:verificationsuccessful,verificationunknown, that generates vulnerability scores for the input software code and verification failed. The verification failed class is further [62]. This layer is engineered to transform the normalized divided into specific vulnerability types: arithmetic overflow, decoderoutputof768dimensionsintoa2-dimensionalvector, buffer overflow, array bounds violation, NULL pointer deref- aligning with the vulnerability classes ("vulnerable" and "not erence, division by zero, and others. The dataset provides vulnerable").Similarly,theoutputfeaturesareexpandedto12 insights into the distribution of vulnerabilities and serves as dimensions for multiclass classification. a valuable resource for vulnerability analysis and testing. In the FormAI dataset, the classification of C programs Let’s represent the decoder output, which has a dimension based on vulnerability reveals that out of a total of 112,000 of 768, as d. In a binary classification scenario, we denote the programs, the verification process was performed on 106,139 weightmatrixasW withdimensions768x2,andformulticlass programs. Among these, 57,389 unique programs were clas- classification,asW withdimensions768x12.Additionally,we sified as vulnerable, resulting in 197,800 vulnerabilities (vul- denote the bias vector as b. Then, the score can be computed nerablefunctions).TableIprovidesanoverviewofthenumber with the linear transformation as: of samples of the FormAI dataset in two classes, ‘NOT VULNERABLE’ (Class 0) and ‘VULNERABLE’ (Class 1), Score=WTd+b (9) before and after a data pre-processing stage. TABLE I: Data Distribution FormAI dataset. Where WTd represents the matrix multiplication of the transpose of the weight matrix W and the decoder output Beforepre-processing Afterpre-processing Class Samples Training Testing Training Testing vector d. The score vector is then passed through a sigmoid 0 45275 40747 4528 40745 4528 function to convert the scores into probabilities. The sigmoid 1 197800 178020 19780 55374 15533 function can be defined as: 0:NOTVULNERABLE,1:VULNERABLE Initially,the‘NOTVULNERABLE’classhad40,747train- 1 P(class )= (10) ing and 4,528 testing samples, out of a total of 45,275, with i 1+e−Scorei the figures remaining almost the same post-pre-processing. The ‘VULNERABLE’ class starts with significantly more Where P(class i) is the probability of the i-th class, and samples, 178,020 in training, and 19,780 in testing out of Score isthescoreforthei-thclass.Thefinaloutputrepresents i the model’s prediction of the vulnerability status of the input 4https://ieee-dataport.org/documents/formai-dataset-large-collection-ai- code. generated-c-programs-and-their-vulnerability 5https://openai.com/ The model outputs a score for each category of vulnerabili- 6https://sv-comp.sosy-lab.org/2023/results/results-verified/quantilePlot- ties.Theclasswiththehighestscoreisconsideredthemodel’s Overall.svg 6197,800. However, training samples reduce to 55,374 after ·104 29,843 pre-processing, and testing samples decrease to 15,533. Table 3 II presents the key statistical measurements of the FormAI 2.5 dataset. The dataset comprises 243,075 observations in total. 2 The average or mean value of these observations is 271.69, 1.5 withastandarddeviation(Std)of162.25,indicatingthespread or variability of the dataset. The dataset’s minimum (Min) 1 6,187 5,436 v Ta hl eue di as ta9 s, ew t’shi qle uath rte ilm ea dx ii sm triu bm uti( oM na ix s) av la sl oue po reb ss ee nrv tee dd ,i ws2 it, h05 th9 e. 0.5 2,959 2,500 2,000 1,000 900 625 580 0 25thpercentile(25%)at160,themedianorthe50thpercentile BOS DFA DFN DFI AOS AOA AOF AOD BOF AOM (50%) at 235, and the 75th percentile (75%) at 343. These Vulnerabilitytype figureshelpdescribethedataset’scentraltendency,dispersion, and distribution shape. TABLE II: Statistics of FormAI dataset’s distribution. Statistic Value Count 243,075 Mean 271.69 Std 162.25 Min 9 25% 160 50% 235 75% 343 Max 2,059 In addition, the vulnerabilities in the dataset are associated withregisteredCommonWeaknessEnumeration(CWE)iden- tifiers, where each vulnerability class may map to multiple CWEs. The dataset comprises nine categories that address the most common vulnerabilities across 42 unique CWEs, includ- ing an "others" category containing various other instances with fewer occurrences. ⃝1 Arithmetic overflow ⃝2 Buffer overflow on scanf()/fscanf() ⃝3 Array bounds violated ⃝4 Dereference failure: NULL pointer |
⃝5 Dereference failure: forgotten memory ⃝6 Dereference failure: invalid pointer ⃝7 Dereference failure: array bounds violated ⃝8 Division by zero ⃝9 Other vulnerabilities Each category is associated with specific CWE numbers that capture the weaknesses leading to those vulnerabilities. For example, arithmetic overflow is associated with CWE- 190, CWE-191, CWE-754, CWE-680, and CWE-681. The dictionaryoftheCWE-IDsassociatedwithvulnerabilitytypes is maintained by the MITRE Corporation7. The pre-processing steps performed on the FormAI dataset are crucial for preparing the data before feeding it into a FalconLLM model. The pre-processing includes removing header information and cleaning the text by removing HTML tags, links, and email addresses. These steps help standardize the text data and eliminate noise or irrelevant information hindering the subsequent analysis. In addition, we calculate the number of words in each text entry and add a new column for the word count. This new column calculates the maximum length of an input sequence that the tokenizer will accept. We convert the categorical ‘label’ column to a numerical representation using label encoding. Generally, this 7https://cwe.mitre.org/ ycneuqerF BOS-Bufferoverflowonscanf() DFA-Dereferencefailure:arrayboundsviolated DFN-Dereferencefailure:NULLpointer DFI-Dereferencefailure:invalidpointer AOS-Arithmeticoverflowonsub AOA-Arithmeticoverflowonadd AOF-ArithmeticoverflowonF-Pmul AOD-ArithmeticoverflowonF-Pdiv BOF-Bufferoverflowon(f)scanf() AOM-Arithmeticoverflowonmul Fig. 3: Top 10 most frequent vulnerabilities categories in the FormAI dataset. pre-processing stage guarantees that the dataset is sanitized, standardized, and prepared for the fine-tuning process of FalconLLM using the FormAI dataset. Figure 3 presents the top 10 most frequent vulnerability categories in the For- mAI dataset after the pre-processing. Specifically, we find that ’buffer overflow on scanf’ is the most prevalent vulnera- bility,recorded29,843times.Thisisfollowedby’dereference failure:arrayboundsviolated’and’dereferencefailure:NULL pointer’ with 6,187 and 5,436 instances, respectively. Other notable vulnerabilities include ’dereference failure: invalid pointer’ and several types of ’arithmetic overflow’ errors, such as on ’sub’, ’add’, ’floating-point ieee_mul’, ’floating- point ieee_div’, and ’mul’, with counts ranging from 2,959 to 580. ’Buffer overflow on fscanf’ also emerges as a significant vulnerability with 625 instances. 2) FalconVulnDB Dataset: We also fine-tuned SecureFalcon using datasets cited in the literature, specifically: the SySeVR framework [42], Draper VDISC [16], Bigvul [15], Diversevul [17], SARD Juliet [13], andReVeal [11]. Each dataset consisted of varying elements: thefirstincluded1,591programs,thesecondheld1.27million functions, the third contained over 264,000 functions, the fourth had more than 348,000 functions, the fifth comprised over 64,000 test cases, and the sixth featured more than 22,000 functions. Except for data from Juliet, the data is scraped from open-source projects. Test cases in Juliet are vulnerable by design and have their associated patch with them. Furthermore, we obfuscate the function and variable names as they were explicit and would affect the model’s training. As for other datasets, limited pre-processing was done on them, such as function extraction, dealing with line breaks, removing comments, CWE mapping, and unifying their features. While several datasets have CWE mapping, some are missing CWE and have a CVE instead. In the case of ReVeal, it has no CWEs and is just labeled as vulnerable or not. At the same time, the Draper dataset is the only multi-labeled dataset. The amalgamation of the dataset resulted in the outcome presented in Table III. The dataset initially contained 1.7 million samples. However, there is an overlap between the 7TABLE III: Data Distribution of FalconVulnDB. Beforepre-processing Afterpre-processing Class Samples Training Testing Training Testing 0 1,611,613 1,289,217 322,396 497,116 124,679 1 139,616 111,766 27,850 116,404 28,702 0:NOTVULNERABLE,1:VULNERABLE different datasets, which we remove after the pre-processing. We employ more than 750,000 samples to train the model, with20%beingatestset.ThefollowingCWEs8 areincluded in FalconVulnDB. • CWE-20:ImproperInputValidation-Occurswhensoftwaredoes notvalidateorimproperlyvalidatesinput,affectingaprogram’scontrol ordataflow.Thiscanleadtounauthorizedaccess,denialofservice, orprivilegeescalation. • CWE-78: OS Command Injection - An application allows the executionofarbitraryOScommandsduetoinadequateinputvalidation, whichcanresultinacompletesystemtakeover. • CWE-119:ImproperRestrictionofOperationswithintheBounds of a Memory Buffer - A buffer overflow occurs when a program operatesonmoredatathanthesizeofitsmemorybuffer.Itcanallow arbitrarycodeexecution,controlflowalteration,orsystemcrash. • CWE-120:BufferCopywithoutCheckingSizeofInput(’Classic BufferOverflow’)-Aspecificinstanceofbufferoverflowcausedby buffercopyoperationswithoutadequatesizechecksoftheinput. • CWE-121:Stack-basedBufferOverflow-Occursinstackmemory, potentially leading to arbitrary code execution or manipulation of programexecutionflowbyoverwritingcriticaldata. • CWE-122:Heap-basedBufferOverflowSimilartostack-basedbut occurs in heap memory, leading to data corruption or unexpected behaviorthroughmanipulatedpointers. • CWE-190: Integer Overflow or Wraparound - Happens when an integeroperationproducesavaluetoolargetobeheldbytheinteger |
type,causingthevaluetowrapandcreateunintendedvalues,leading toerrorsorvulnerabilities. • CWE-476:NULLPointerDereference-Itoccurswhenaprogram dereferences a pointer, which it expects to be valid but is NULL, leadingtocrashesorcodeexecution. • CWE-762: Mismatched Memory Management Routines - Arises when memory is allocated and deallocated with different routines, potentiallyleadingtoheapcorruptionorcrashes. • CWE-787:Out-of-boundsWrite-Ithappenswhensoftwarewrites dataoutsidetheintendedbufferboundaries,leadingtodatacorruption, crashes,orcodeexecutionvulnerabilities. The most common vulnerability categories in FalconVul- nDB are displayed in Figure 4. ·104 7 66,761 6 5 4 3 25,011 22,213 2 11,499 1 3,509 3,307 3,041 2,872 2,621 2,200 2,072 0 other other 119 120 476 122 190 121 78 787 20 762 762 CommonWeaknessEnumeration ycneuqerF presented in Fig. 5. First, we collect a large and diverse dataset of software code from the FormAI and the aggregated datasets (FalconVulnDB), where instances of vulnerable and non-vulnerable code are correctly labeled. Once we have the datasets, we pre-process them by transforming the raw source code into a format suitable for the SecureFalcon model, tokenizing the code into appropriate separate sub- strings. Next, we initiate the SecureFalcon model with the desired architecture using the Transformers library. Then, we define the training and evaluation settings, which involve setting various hyperparameters like learning rate, batch size, andnumberofepochs.Westartthefine-tuningprocess,where the model will learn from the labeled dataset to differentiate between vulnerable and non-vulnerable code. We evaluate the modelregularlyduringtrainingtotrackitsprogressandadjust hyperparameters when necessary. After training the model, we test it on separate data amalgamated from the different datasets to verify its effectiveness. Lastly, after fine-tuning, the resulting model should be able to predict whether a given piece of code is vulnerable or not. A. Experimental Setup TABLE IV outlines the experimental setup and parameters used for fine-tuning SecureFalcon for software security. The SecureFalcon model features 121 million parame- ters, a hidden size of 768, twelve hidden layers, and twelve attention heads. This model employs an intermediate size of 3072 and supports up to 514 position embeddings. Tokeniza- tion was performed using a left-padding approach, with a paddingtokenID,BOS(beginningofsentence)tokenID,and EOS (end of sentence) token ID all set to 11. The tokenizer settings enforced truncation and padding, producing PyTorch tensor outputs and including an attention mask, while token typeIDswerenotreturned.Wesetthemaximumtokenlength to 2048. For training, batch sizes were set to 256, utilizing 32 Nvidia A100 40GB GPUs to ensure efficient processing. We employed the AdamW optimizer with learning rates set at 2e- 2 and 2e-5 and an epsilon value of 1e-8. The training was carried out over ten epochs to prevent overfitting, with early CWE-119:ImproperRestriction stoppingenabledafterthreeepochswithoutimprovement.For CWE-120:BufferCopy CWE-476:NULLPointerDereference loss computation, we utilized cross-entropy loss. The model CWE-122:Heap-basedBufferOverflow CWE-190:IntegerOverfloworWraparound was evaluated based on accuracy, precision, recall, and the F1 CWE-121:Stack-basedBufferOverflow CWE-78:OSCommandInjection score, with metrics averaged using the ’micro’ method to re- CWE-787:Out-of-boundsWrite CWE-20:ImproperInputValidation flectthecontributionofeachinstancetotheoverallmetric.The CWE-762:MismatchedMemoryManagement additional configuration included setting the hidden activation function to GELU, an initializer range of 0.02, and a layer norm epsilon of 1e-5. The dropout probabilities for attention and hidden layers were set to 0.1. The models were run Fig. 4: Top 11 most frequent vulnerability categories in under a float32 torch data type setting, ensuring compatibility FalconVulnDB. and optimal performance on the specified transformer library version 4.30.2. B. Experimental Results VI. PERFORMANCEEVALUATION Tables V and VI present the classification report of PerformanceevaluationofSecureFalconmodelforsoft- SecureFalcon-121MwithLR=2e-5andLR=2e-2.With ware vulnerability detection involves a series of steps, as an LR of 2e-5, the model yields the highest accuracy of 0.94, 8https://cwe.mitre.org/top25/archive/2023/2023_kev_list.html supported by a high precision, recall, and F1-score for both 8Fig. 5: Performance evaluation steps of SecureFalcon model. classes(0.89,0.84,0.86for‘NOTVULNERABLE’and0.95, in weight, leading to instability or overfitting. 0.97, 0.96 for ‘VULNERABLE’) (see Tables V) The multi-classification report of the SecureFalcon Thisperformanceconsiderablydropswhenthelearningrate model, as presented in Table X, exhibits a comprehensive is increased to 2e-2. Although the precision for ‘VULNERA- evaluation of the model’s performance across various Com- BLE’remainshigh(0.94),the‘NOTVULNERABLE’metrics mon Weakness Enumerations (CWEs) on FalconVulnDB. We take a substantial hit, decreasing overall accuracy to 0.87. conducted several experiments to determine the model’s ra- Tables VII, VIII, IX present the training and validation tionale for the classification. One of the interpretability tools9 accuracy and loss over several epochs for SecureFalcon used was a library highlighting the distribution of attention, |
model with differing configurations. With a Learning Rate indicatingsomediscrepanciesinourmodelresults.Toenhance (LR) of 2e-5 (Table VII), accuracy consistently increases, and theknowledgeofthemodelofthesyntacticandlexicalnature lossdecreasesovertheepochsforbothtrainingandvalidation. of the programming language, we embed the tokens shown in However,withanLRof2e-2(TableVIII),loweraccuracyand TableXI.Thetokensarekeywords,punctuation,andAPIcalls higher loss indicate that a larger learning rate could lead to defined in the C/C++ manual and its extended libraries1011, sub-optimal learning. an approach similar to work [10]. Testing with the new Figure 6 illustrates the confusion matrix for the binary tokens included in the fine-tuning, in turn, updating the em- classification performed by SecureFalcon. From the pro- bedding layer has yielded higher precision and recall. This is vided confusion matrices, we can make some observations due to maintaining the syntax of the pre-defined tokens rather regarding the performance of the SecureFalcon models thangoingthroughthesubwordtokenizationprocess.Assuch, with different configurations. A decrease in performance is themeaningoftheseessentialpre-definedtokensinthesource observedwhenthelearningrateisraisedto2e-2.Thenumber code is preserved. offalsenegativesdrasticallyincreasedfrom483to1805,with The model demonstrates high precision and recall for most false positives rising from 740 to 895. Correspondingly, the categories,particularlyexcellinginidentifyingnon-vulnerable true positives and negatives decreased from 15050 to 13728 instances with a precision of 0.93, recall of 0.97, and an F1- and from 3788 to 3633, respectively. This shows that a larger learning rate, in this case, led to more misclassifications, 9https://github.com/cdpierse/transformers-interpret(accessed9May2024) indicating an over-optimistic learning process that possibly 10https://www.gnu.org/software/libc/manual/pdf/libc.pdf (accessed 15 May 2024) led to overfitting or instability during training. This is due 11https://learn.microsoft.com/en-us/cpp/cpp/cpp-language-reference to the high learning rate contributing to more drastic changes (accessed15May2024) 9TABLE VI: Classification report of SecureFalcon 121M TABLE IV: Configuration of SecureFalcon. with LR = 2e-2 using FormAI dataset. Parameter Value Precision Recall F1-Score Support PretrainedmodelID FalconLLM40B 0 0.67 0.80 0.73 4528 Numberofparameters 121M 1 0.94 0.88 0.91 15533 Hiddensize 768 Accuracy 0.87 Numberofhiddenlayers 12 Macroavg 0.80 0.84 0.82 20061 Numberofattentionheads 12 Weightedavg 0.88 0.87 0.87 20061 Intermediate-size 3072 0:NOTVULNERABLE,1:VULNERABLE Maximumpositionembeddings 514 Numberoflabels 2/12 TABLE VII: Training and Validation Accuracy and Loss Tokenizerpaddingside Left Across Epochs of SecureFalcon 121M with LR = 2e-5 PaddingtokenID 11 BOStokenID 11 using FormAI dataset. EOStokenID 11 Training Validation Maximumlengthoftokens 2048 Epoch Accuracy Loss Accuracy Loss Tokenizertruncation True 1 0.82 0.39 0.88 0.27 Tokenizerpadding True 2 0.87 0.29 0.89 0.25 Returntensorformat PyTorchtensors(’pt’) 3 0.89 0.25 0.90 0.23 ReturntokentypeIDs False 4 0.91 0.21 0.91 0.21 Returnattentionmask True 5 0.93 0.17 0.93 0.19 Batchsize 256 6 0.95 0.12 0.93 0.19 GPU 32A10040GB 7 0.97 0.09 0.94 0.19 Optimizer AdamW AdamWLearningRate(LR) 2e-2and2e-5 AdamWEpsilon 1e-8 The aggregated accuracy of 0.92 and the weighted aver- Numberoftrainingepochs 10 Earlystopping Enabled(patience=3) age precision, recall, and F1 score reflect the model’s high Randomseedvalue 42 competence in vulnerability classification across diverse vul- Maximumgradientnorm 1.0 nerabilities.However,thevaryingperformanceacrossdifferent Losscomputation Cross-entropyloss Hiddenactivationfunction "gelu" CWEs underscores the importance of continued model refine- Initializerrange 0.02 ment and targeted training to enhance the model’s sensitivity Layernormepsilon 1e-5 and specificity, particularly for those vulnerabilities where it Attentionprobsdropoutprob 0.1 currently underperforms. The confusion matrix for multiclass Hiddendropoutprob 0.1 Torch_dtype float32 classification on the FalconVulnDB Dataset is shown in Fig- Transformers_version 4.30.2 ure 7. SMDDP_version 2.1.0 Pytorch_version 2.1.0 Python_version 3.10 C. Comparison of SecureFalcon Table XII compares various machine learning (ML) models andtheiraccuracyinperformingmulticlassandbinaryclassifi- TABLE V: Classification report of SecureFalcon 121M cationtasksontheFormAIandFalconVulnDBdatasets.Large with LR = 2e-5 using FormAI dataset. Language Models (LLMs) such as RoBERTa, BERT, Code- BERT, and SecureFalcon show a notable performance Precision Recall F1-Score Support 0 0.89 0.84 0.86 4528 difference compared to traditional ML models for multiclass 1 0.95 0.97 0.96 15533 classification. SecureFalcon, in particular, stands out with Accuracy 0.94 the highest accuracy of 0.92 on both datasets, significantly Macroavg 0.92 0.90 0.91 20061 outperforming other LLM models like RoBERTa and BERT, Weightedavg 0.94 0.94 0.94 20061 0:NOTVULNERABLE,1:VULNERABLE which achieve accuracies of around 0.70-0.85. Among the traditionalMLmodels,RandomForest(RF)performsthebest withaccuraciesof0.77ontheFormAIdatasetand0.81onthe |
score of 0.95, indicating robustness in distinguishing non- FalconVulnDB dataset, although it still lags behind the LLM vulnerable cases. Remarkably, it achieves perfect or near- models. perfectperformanceinidentifyingCWE-78,CWE-121,CWE- The trend remains similar in binary classification, with 122, and CWE-762 vulnerabilities, showcasing its effective- SecureFalcon leading with an accuracy of 0.94 on the ness in detecting specific types of vulnerabilities with high FormAI dataset and 0.92 on the FalconVulnDB dataset. Other accuracy.However,themodelshowslimitationsinrecognizing LLM models, such as RoBERTa, BERT, and CodeBERT, also certain vulnerabilities, notably CWE-20 and CWE-787, with perform well, achieving accuracies between 0.81 and 0.89 notablylowerprecisionandrecallvalues,suggestingareasfor acrossbothdatasets.TraditionalMLmodelsshowcompetitive improvement in future iterations. The low F1-score for CWE- resultsinthistask,withRandomForestachievinganaccuracy 20 (0.22) and CWE-787 (0.26) highlights the model’s chal- of0.91ontheFormAIdatasetand0.89ontheFalconVulnDB lenge in accurately classifying these vulnerabilities, possibly dataset, which is relatively close to the performance of some due to the complexity of the patterns associated with these LLMs. However, the consistently superior performance of CWEs or a limited representation in the training data. SecureFalcon highlights the advantages of fine-tuning 10TABLE VIII: Training and Validation Accuracy and Loss Across Epochs of SecureFalcon 121M with LR= 2e-2 using FormAI dataset. Training Validation Epoch Accuracy Loss Accuracy Loss 1 0.70 0.61 0.82 0.43 2 0.78 0.48 0.80 0.42 3 0.80 0.44 0.85 0.34 4 0.83 0.38 0.81 0.41 5 0.82 0.40 0.86 0.31 6 0.84 0.36 0.86 0.30 (a) SecureFalcon with LR = 7 0.85 0.34 0.86 0.30 2e-5 8 0.85 0.34 0.87 0.30 TABLEIX:TrainingandValidationAccuracyandLossAcross Epochs of SecureFalcon 121M with LR = 2e-5 using FalconVulnDB dataset Training Validation Epoch Accuracy Loss Accuracy Loss 1 0.91 0.30 0.91 0.31 2 0.92 0.26 0.91 0.32 (b) SecureFalcon with LR = large models specifically for software vulnerability detection 2e-2 tasks,makingitarobustchoiceforbothmulticlassandbinary 0: NOT VULNERABLE, 1: VULNERABLE classification in cybersecurity contexts. Fig. 6: Confusion matrix of SecureFalcon 121M/44M classification using FormAI dataset. D. Future Works As future work, SecureFalcon, a fine-tuned Large Lan- TABLE X: Classification report of SecureFalcon 121M with guageModel(LLM)forsoftwarevulnerabilitydetection,aims LR = 2e-5 using FalconVulnDB dataset. to enhance its capabilities by providing comprehensive expla- Precision Recall F1-Score Support nationstodevelopers.Theseenhancementsincludegenerating Not-Vulnerable 0.93 0.97 0.95 124355 detailed reports describing detected vulnerabilities, highlight- CWE-20 0.46 0.14 0.22 440 ing the affected code snippets, and analyzing the potential CWE-78 1.00 0.98 0.99 574 impact. Furthermore, SecureFalcon will outline steps to CWE-119 0.75 0.75 0.75 5002 CWE-120 0.63 0.84 0.72 4443 reproduce the issues, including environment setup, input data, CWE-121 0.99 0.99 0.99 608 and execution steps, and offer remediation guidance with fix CWE-122 1.00 0.99 0.99 702 CWE-190 0.97 0.78 0.87 662 recommendations and secure coding practices. By integrating CWE-476 0.64 0.45 0.53 2300 these features with development tools, SecureFalcon will CWE-762 1.00 1.00 1.00 414 ensurereal-timefeedbackandautomatedcodereviews,signif- CWE-787 0.27 0.26 0.26 524 Other 0.89 0.54 0.67 13352 icantly aiding developers in understanding, reproducing, and resolving security issues effectively. Accuracy 0.92 MacroAvg 0.79 0.72 0.74 153376 WeightedAvg 0.91 0.91 0.90 153376 VII. CONCLUSION Our study highlights the significant potential of LLMs in detecting software vulnerabilities, especially in cybersecurity. the vulnerabilities. Such a system could make software more By fine-tuning FalconLLM, we developed SecureFalcon, a resilient against potential threats, thus enhancing overall cy- novel model capable of distinguishing between vulnerable bersecurity.AfastinferencetimemodellikeSecureFalcon and non-vulnerable C/C++ code samples. Tested on different has the potential to be highly effective in automated software datasets from the literature, our model achieved a remark- completion frameworks. We plan to continue our research in able 94% accuracy rate in binary classification and 92% in this direction. multiclassification, highlighting its efficacy. Furthermore, we accomplish these results by utilizing a relatively small set of parameters, totaling 121 million, within the SecureFalcon TABLE XI: List of special tokens added in the Falcon40b model. We believe further advancements will enhance such tokenizer models’ capabilities, expand with distinct vulnerability types, Tokens Count Examples and extend to other programming languages to strengthen Punctuation 72 !=,++,= software system security and foster a more secure digital Keywords 123 char,const,continue realm. A promising extension of this work would include APIcalls 394 malloc,strncpy,atoi an automated self-healing system that identifies and remedies |
11TABLE XII: Comparison of SecureFalcon with LLM models and traditional machine learning using the FormAI dataset and FalconVulnDB dataset. Accuracy Task MLtype Model FormAIdataset FalconVulnDBdataset RoBERTa 0.70 0.85 BERT 0.70 0.85 LLMmodels CodeBERT 0.71 0.88 SecureFalcon 0.92 0.92 KNN 0.76 0.80 MulticlassClassification LR 0.73 0.77 NB 0.64 0.68 TraditionalMLmodels SVM 0.73 0.77 RF 0.77 0.81 DT 0.72 0.60 LDA 0.73 0.77 RoBERTa 0.82 0.86 BERT 0.81 0.87 LLMmodels CodeBERT 0.83 0.89 SecureFalcon 0.94 0.92 KNN 0.76 0.86 BinaryClassification LR 0.86 0.86 NB 0.76 0.81 TraditionalMLmodels SVM 0.86 0.89 RF 0.91 0.89 DT 0.87 0.86 LDA 0.86 0.85 ML:Machinelearning,KNN:k-NearestNeighbors,LR:LogisticRegression,NB:NaiveBayes,SVM:SupportVectorMachine,RF:RandomForest,DT: DecisionTree,andLDA:LinearDiscriminantAnalysis. ing llms’ vulnerability reasoning,” arXiv preprint arXiv:2401.16185, 2024. [6] R.Jain,N.Gervasoni,M.Ndhlovu,andS.Rawat,“Acodecentricevalu- ationofc/c++vulnerabilitydatasetsfordeeplearningbasedvulnerability detectiontechniques,”inProceedingsofthe16thInnovationsinSoftware EngineeringConference,2023,pp.1–10. [7] Z. Li, D. Zou, S. Xu, X. Ou, H. Jin, S. Wang, Z. Deng, and Y. Zhong, “Vuldeepecker: A deep learning-based system for vulnerability detection,” CoRR, vol. abs/1801.01681, 2018. [Online]. Available:http://arxiv.org/abs/1801.01681 [8] N. Ziems and S. Wu, “Security vulnerability detection using deep learning natural language processing,” in IEEE INFOCOM 2021 - IEEEConferenceonComputerCommunicationsWorkshops(INFOCOM WKSHPS),2021,pp.1–6. [9] X.Duan,J.Wu,S.Ji,Z.Rui,T.Luo,M.Yang,andY.Wu,“Vulsniper: Focusyourattentiontoshootfine-grainedvulnerabilities.” [10] H.HanifandS.Maffeis,“Vulberta:Simplifiedsourcecodepre-training for vulnerability detection,” in 2022 International joint conference on neuralnetworks(IJCNN). IEEE,2022,pp.1–8. [11] S. Chakraborty, R. Krishna, Y. Ding, and B. Ray, “Deep learning basedvulnerabilitydetection:Arewethereyet,”IEEETransactionson SoftwareEngineering,2021. [12] P. E. Black, “A Software Assurance Reference Dataset: Thousands of Programs With Known Bugs,” Journal of Research of the National Institute of Standards and Technology, vol. 123, pp. 1–3, Apr. Fig. 7: Confusion Matrix of SecureFalcon 121M Multi- 2018. [Online]. Available: https://www.ncbi.nlm.nih.gov/pmc/articles/ classification using FalconVulnDB Dataset. PMC7339570/ [13] F. E. B. Jr and P. E. Black, “The Juliet 1.1 C/C++ and Java Test Suite,” NIST, vol. 45, no. 10, pp. 88–90, Oct. 2012, last Modified: 2021-10-12T11:10-04:00 Publisher: Frederick E. Boland Jr., REFERENCES Paul E. Black. [Online]. Available: https://www.nist.gov/publications/ juliet-11-cc-and-java-test-suite [1] D. J. Solove, The digital person: Technology and privacy in the [14] Y.Zhou,S.Liu,J.Siow,X.Du,andY.Liu,Devign:EffectiveVulnera- informationage. NyUPress,2004,vol.1. bilityIdentificationbyLearningComprehensiveProgramSemanticsvia [2] M.A.Hlatshwayo,“Cybersecurityinthedigitalspace.” GraphNeuralNetworks. RedHook,NY,USA:CurranAssociatesInc., [3] M.Abdel-Rahmanetal.,“Advancedcybersecuritymeasuresinitservice 2019,pp.10197–10207. operations and their crucial role in safeguarding enterprise data in a [15] J. Fan, Y. Li, S. Wang, and T. N. Nguyen, “A C/C++ Code connectedworld,”EigenpubReviewofScienceandTechnology,vol.7, Vulnerability Dataset with Code Changes and CVE Summaries,” in no.1,pp.138–158,2023. Proceedings of the 17th International Conference on Mining Software [4] Z. Li, Z. Liu, W. K. Wong, P. Ma, and S. Wang, “Evaluating c/c++ Repositories, ser. MSR ’20. New York, NY, USA: Association for vulnerability detectability of query-based static application security Computing Machinery, Sep. 2020, pp. 508–512. [Online]. Available: testingtools,”IEEETransactionsonDependableandSecureComputing, https://doi.org/10.1145/3379597.3387501 2024. [16] L. Kim and R. Russell, “Draper VDISC Dataset - Vulnerability [5] Y.Sun,D.Wu,Y.Xue,H.Liu,W.Ma,L.Zhang,M.Shi,andY.Liu, Detection in Source Code,” 2018, publisher: OSF. [Online]. Available: “Llm4vuln:Aunifiedevaluationframeworkfordecouplingandenhanc- https://osf.io/d45bw/ 12[17] Y. Chen, Z. Ding, X. Chen, and D. Wagner, “DiverseVul: A New [35] T.AhmedandP.Devanbu,“Few-shottrainingllmsforproject-specific VulnerableSourceCodeDatasetforDeepLearningBasedVulnerability code-summarization,” in Proceedings of the 37th IEEE/ACM Interna- Detection,” Apr. 2023. [Online]. Available: http://arxiv.org/abs/2304. tionalConferenceonAutomatedSoftwareEngineering,2022,pp.1–5. 00409 [36] A. Tarassow, “The potential of llms for coding with low- [18] A. Habib and M. Pradel, “How many of all bugs do we find? a resource and domain-specific programming languages,” arXiv preprint |
study of static bug detectors,” in Proceedings of the 33rd ACM/IEEE arXiv:2307.13018,2023. InternationalConferenceonAutomatedSoftwareEngineering,2018,pp. [37] X. Cheng, G. Zhang, H. Wang, and Y. Sui, “Path-sensitive code 317–328. embeddingviacontrastivelearningforsoftwarevulnerabilitydetection,” [19] J.Park,I.Lim,andS.Ryu,“Battleswithfalsepositivesinstaticanalysis inProceedingsofthe31stACMSIGSOFTInternationalSymposiumon ofjavascriptwebapplicationsinthewild,”inProceedingsofthe38th SoftwareTestingandAnalysis,2022,pp.519–531. International Conference on Software Engineering Companion, 2016, [38] Z.Chen,S.Kommrusch,andM.Monperrus,“Neuraltransferlearning pp.61–70. for repairing security vulnerabilities in c code,” IEEE Transactions on [20] V. Hartonas-Garmhausen, S. V. A. Campos, A. Cimatti, E. M. SoftwareEngineering,vol.49,no.1,pp.147–165,2022. Clarke, and F. Giunchiglia, “Verification of a safety-critical railway [39] J. Yin, M. Tang, J. Cao, and H. Wang, “Apply transfer learning to interlockingsystemwithreal-timeconstraints,”Sci.Comput.Program., cybersecurity:Predictingexploitabilityofvulnerabilitiesbydescription,” vol. 36, no. 1, pp. 53–64, 2000. [Online]. Available: https: Knowledge-BasedSystems,vol.210,p.106529,2020. //doi.org/10.1016/S0167-6423(99)00016-7 [40] P.Mahbub,O.Shuvo,andM.M.Rahman,“Explainingsoftwarebugs [21] C. Heitmeyer, J. Kirby, B. Labaw, M. Archer, and R. Bharadwaj, leveraging code structures in neural machine translation,” in 2023 “Using abstraction and model checking to detect safety violations in IEEE/ACM 45th International Conference on Software Engineering requirements specifications,” IEEE Transactions on software engineer- (ICSE). IEEE,2023,pp.640–652. ing,vol.24,no.11,pp.927–948,1998. [41] N. Ito, M. Hashimoto, and A. Otsuka, “Feature extraction methods [22] J. Lahtinen, J. Valkonen, K. Björkman, J. Frits, I. Niemelä, and for binary code similarity detection using neural machine translation K.Heljanko,“Modelcheckingofsafety-criticalsoftwareinthenuclear models,”IEEEAccess,2023. engineeringdomain,”ReliabilityEngineering&SystemSafety,vol.105, [42] Z. Li, D. Zou, S. Xu, H. Jin, Y. Zhu, and Z. Chen, “Sysevr: A pp.104–113,2012. framework for using deep learning to detect software vulnerabilities,” [23] A.Biere,A.Cimatti,E.M.Clarke,O.Strichman,andY.Zhu,“Bounded IEEETransactionsonDependableandSecureComputing,vol.19,no.4, modelchecking.”Handbookofsatisfiability,vol.185,no.99,pp.457– pp.2244–2258,2021. 481,2009. [43] Y.Zhou,S.Liu,J.Siow,X.Du,andY.Liu,Devign:EffectiveVulnera- [24] R.S.Menezes,M.Aldughaim,B.Farias,X.Li,E.Manino,F.Shmarov, bilityIdentificationbyLearningComprehensiveProgramSemanticsvia K.Song,F.Brauße,M.R.Gadelha,N.Tihanyi,K.Korovin,andL.C. GraphNeuralNetworks. RedHook,NY,USA:CurranAssociatesInc., Cordeiro, “ESBMC v7.4: Harnessing the power of intervals - (compe- 2019. titioncontribution),”inToolsandAlgorithmsfortheConstructionand [44] Z.Feng,D.Guo,D.Tang,N.Duan,X.Feng,M.Gong,L.Shou,B.Qin, AnalysisofSystems(TACAS),ser.LNCS,vol.14572. Springer,2024, T.Liu,D.Jiangetal.,“Codebert:Apre-trainedmodelforprogramming pp.376–380. andnaturallanguages,”arXivpreprintarXiv:2002.08155,2020. [25] N. Nehorai, “Analyzing common vulnerabilities in- [45] Y.Liu,M.Ott,N.Goyal,J.Du,M.Joshi,D.Chen,O.Levy,M.Lewis, troduced by code-generative ai | hacker- L. Zettlemoyer, and V. Stoyanov, “Roberta: A robustly optimized bert noon,” 2024. [Online]. Available: https://hackernoon.com/ pretrainingapproach,”arXivpreprintarXiv:1907.11692,2019. analyzing-common-vulnerabilities-introduced-by-code-generative-ai [46] T.Brown,B.Mann,N.Ryder,M.Subbiah,J.D.Kaplan,P.Dhariwal, [26] E.M.Clarke,T.A.Henzinger,H.Veith,andR.Bloem,Eds.,Handbook A.Neelakantan,P.Shyam,G.Sastry,A.Askelletal.,“Languagemod- ofModelChecking. Springer,2018. els are few-shot learners,” Advances in neural information processing [27] A. M. Turing, “On computable numbers, with an application to the systems,vol.33,pp.1877–1901,2020. entscheidungsproblem,”ProceedingsoftheLondonMathematicalSoci- [47] J. Zhou, M. Pacheco, Z. Wan, X. Xia, D. Lo, Y. Wang, and A. E. ety,vol.s2-42,no.1,pp.230–265,1936. Hassan, “Finding a needle in a haystack: Automated mining of silent [28] M. Sipser, Introduction to the Theory of Computation. Cengage vulnerability fixes,” in 2021 36th IEEE/ACM International Conference Learning,2012. onAutomatedSoftwareEngineering(ASE). IEEE,2021,pp.705–716. [29] N. Tihanyi, T. Bisztray, R. Jain, M. A. Ferrag, L. C. Cordeiro, and |
[48] K.Singh,S.S.Grover,andR.K.Kumar,“Cybersecurityvulnerability V. Mavroeidis, “The formai dataset: Generative ai in software security detection using natural language processing,” in 2022 IEEE World AI through the lens of formal verification,” in Proceedings of the 19th IoTCongress(AIIoT). IEEE,2022,pp.174–178. International Conference on Predictive Models and Data Analytics in SoftwareEngineering,2023,pp.33–43. [49] J.Devlin,M.-W.Chang,K.Lee,andK.Toutanova,“Bert:Pre-training [30] H. Hanif, M. H. N. M. Nasir, M. F. Ab Razak, A. Firdaus, and of deep bidirectional transformers for language understanding,” arXiv N.B.Anuar,“Theriseofsoftwarevulnerability:Taxonomyofsoftware preprintarXiv:1810.04805,2018. vulnerabilities detection and machine learning approaches,” Journal of [50] S.Kim,S.Woo,H.Lee,andH.Oh,“Vuddy:Ascalableapproachfor NetworkandComputerApplications,vol.179,p.103009,2021. vulnerablecodeclonediscovery,”in2017IEEESymposiumonSecurity [31] A.V.Aho,M.S.Lam,R.Sethi,andJ.D.Ullman,Compilers:Principles, andPrivacy(SP),2017,pp.595–614. Techniques,AndTools,2nded. Addison-WesleyLongmanPublishing [51] Z. Li, D. Zou, S. Xu, H. Jin, H. Qi, and J. Hu, “Vulpecker: An Co.,Inc.,2006. automated vulnerability detection system based on code similarity [32] H. Barbosa, C. W. Barrett, M. Brain, G. Kremer, H. Lachnitt, analysis,”inProceedingsofthe32ndAnnualConferenceonComputer M. Mann, A. Mohamed, M. Mohamed, A. Niemetz, A. Nötzli, Security Applications, ser. ACSAC ’16. New York, NY, USA: A. Ozdemir, M. Preiner, A. Reynolds, Y. Sheng, C. Tinelli, and Association for Computing Machinery, 2016, p. 201–213. [Online]. Y. Zohar, “cvc5: A versatile and industrial-strength SMT solver,” in Available:https://doi.org/10.1145/2991079.2991102 Tools and Algorithms for the Construction and Analysis of Systems [52] P. Zeng, G. Lin, L. Pan, Y. Tai, and J. Zhang, “Software vulnerability - 28th International Conference, TACAS 2022, Held as Part of the analysisanddiscoveryusingdeeplearningtechniques:Asurvey,”IEEE European Joint Conferences on Theory and Practice of Software, Access,vol.8,pp.197158–197172,2020. ETAPS 2022, Munich, Germany, April 2-7, 2022, Proceedings, Part [53] J.Kaplan,S.McCandlish,T.Henighan,T.B.Brown,B.Chess,R.Child, I, ser. Lecture Notes in Computer Science, D. Fisman and G. Rosu, S. Gray, A. Radford, J. Wu, and D. Amodei, “Scaling laws for neural Eds., vol. 13243. Springer, 2022, pp. 415–442. [Online]. Available: languagemodels,”arXivpreprintarXiv:2001.08361,2020. https://doi.org/10.1007/978-3-030-99524-9_24 [54] E. Almazrouei, H. Alobeidli, A. Alshamsi, A. Cappelli, R. Cojocaru, [33] A.NiemetzandM.Preiner,“Bitwuzla,”inComputerAidedVerification M.Debbah,E.Goffinet,D.Heslow,J.Launay,Q.Malartic,B.Noune, -35thInternationalConference,CAV2023,Paris,France,July17-22, B.Pannier,andG.Penedo,“Falcon-40B:anopenlargelanguagemodel 2023, Proceedings, Part II, ser. Lecture Notes in Computer Science, withstate-of-the-artperformance,”2023. C. Enea and A. Lal, Eds., vol. 13965. Springer, 2023, pp. 3–17. [55] I. Loshchilov and F. Hutter, “Decoupled weight decay regularization,” [Online].Available:https://doi.org/10.1007/978-3-031-37703-7_1 arXivpreprintarXiv:1711.05101,2017. [34] L. de Moura and N. Bjørner, “Z3: An efficient smt solver,” in Tools [56] T. Mikolov, I. Sutskever, K. Chen, G. S. Corrado, and J. Dean, and Algorithms for the Construction and Analysis of Systems, C. R. “Distributed representations of words and phrases and their composi- RamakrishnanandJ.Rehof,Eds. Berlin,Heidelberg:SpringerBerlin tionality,” Advances in neural information processing systems, vol. 26, Heidelberg,2008,pp.337–340. 2013. 13[57] A.Vaswani,N.Shazeer,N.Parmar,J.Uszkoreit,L.Jones,A.N.Gomez, Ł. Kaiser, and I. Polosukhin, “Attention is all you need,” Advances in neuralinformationprocessingsystems,vol.30,2017. [58] J. L. Ba, J. R. Kiros, and G. E. Hinton, “Layer normalization,” arXiv preprintarXiv:1607.06450,2016. [59] J. Su, Y. Lu, S. Pan, A. Murtadha, B. Wen, and Y. Liu, “Roformer: Enhanced transformer with rotary position embedding,” arXiv preprint arXiv:2104.09864,2021. [60] D. E. Rumelhart, G. E. Hinton, and R. J. Williams, “Learning repre- sentations by back-propagating errors,” nature, vol. 323, no. 6088, pp. 533–536,1986. [61] D.HendrycksandK.Gimpel,“Gaussianerrorlinearunits(gelus),”arXiv preprintarXiv:1606.08415,2016. [62] C. M. Bishop and N. M. Nasrabadi, Pattern recognition and machine learning. Springer,2006,vol.4,no.4. 14 |
2307.08549 G-Scan: Graph Neural Networks for Line-Level Vulnerability Identification in Smart Contracts Christoph Sendner∗, Ruisi Zhang†, Alexander Hefter∗, Alexandra Dmitrienko∗, and Farinaz Koushanfar† ∗University of Wu¨rzburg, Germany †University of California San Diego, USA Abstract—Due to the immutable and decentralized nature of Many prior works explored vulnerability detection algo- Ethereum(ETH)platform,smartcontractsarepronetosecurity rithms on Ethereum smart contracts, and most of them can risks that can result in financial loss. While existing machine be categorized into two types: (1) contract-level vulnerability learning-based vulnerability detection algorithms achieve high detection and (2) line-level/node-level vulnerability detection. accuracy at the contract level, they require developers to manu- Contract-level vulnerability detection takes the detection as ally inspect source code to locate bugs. To this end, we present a classification problem and uses symbolic execution [21], G-Scan, the first end-to-end fine-grained line-level vulnerability [23],[24],fuzzing[12],[16],[35],andmachinelearningalgo- detection system evaluated on the first-of-its-kind real world rithms [19], [27], [37], [38], [43] to find vulnerable contracts. dataset. G-Scan first converts smart contracts to code graphs in a dependency and hierarchy preserving manner. Next, we train These methods achieve over 90% F1 scores in classification, a graph neural network to identify vulnerable nodes and assess but developers are still required to examine the contract line- security risks. Finally, the code graphs with node vulnerability by-line to localize buggy statements. predictions are mapped back to the smart contracts for line- level localization. We train and evaluate G-Scan on a collected More recently, SCScan [14] proposed a vulnerability de- real world smart contracts dataset with line-level annotations on tection system at the line level, while MANDO [26] pro- reentrancy vulnerability, one of the most common and severe posed a node-level detection system with the aim of reducing types of smart contract vulnerabilities. With the well-designed the development burden. SCScan first uses a support vector graph representation and high-quality dataset, G-Scan achieves machine (SVM) to detect vulnerable contracts and then a 93.02% F1-score in contract-level vulnerability detection and pattern matching algorithm to determine the exact positions 93.69%F1-scoreinline-levelvulnerabilitylocalization.Addition- of the vulnerabilities. However, SCScan is primitive which ally, the lightweight graph neural network enables G-Scan to can only accept fix-size contracts as inputs to SVM, and the localizevulnerabilitiesin6.1klinesofcodesmartcontractwithin patternmatchingalgorithmfailstoscaleasnewattacksappear. 1.2 seconds. MANDO[26],ontheotherhand,onlydetectedvulnerabilities in the code graph but failed to map them back to the source I. INTRODUCTION code. MANDO employs a two-stage graph neural network (GNN) training to identify node-level vulnerabilities, where TherecentsuccessofBitcoin[25]andEthereum(ETH)[8] the first stage trains a graph classification model to assess the has brought decentralized platforms, which allow users to vulnerability of contracts, and the second stage utilizes node transact and interact in a trustless manner, to the forefront embeddings updated from a topology graph neural network of attention. Bitcoin, as the first generation blockchain plat- to classify whether a specific node is vulnerable. MANDO form,facilitatespeer-to-peerdigitalcurrencytransactionsusing can handle contracts of varying sizes, but after getting the proof-of-work consensus algorithms. However, due to the node-level predictions, it cannot map vulnerabilities back to limited functionality of Bitcoin scripting languages, ETH and the smart contract for localization. its smart contracts introduced a broader scenario where users can encode complex agreement terms directly into codes to Notwithstanding that node classification is widely studied enable automated and trustless transactions. by the machine learning community, localizing vulnerable nodes within the code graph itself is non-trivial and challeng- ETH has been widely applied in various domains, from ingforthefollowingreasons.Firstofall,thereisalackofreal- financial services to supply chain management and beyond. world datasets for fine-grained1 vulnerability detection model Developersintheopen-sourceETHplatformwritetheiragree- training. MANDO [26] trains its GNN model on a simulated ments into smart contracts code using Solidity and publish dataset by injecting vulnerabilities into clean contracts. These them on the blockchain to facilitate transactions with third injections fail to represent some corner cases in real-world parties. Like any other programming language, vulnerabilities contracts and result in lower detection accuracy. Secondly, also reside in ETH contracts, potentially leading to loss of code graph construction in prior work [19], [20], [43] mainly funds or theft of sensitive information. The security risks extracts the semantic information in source code but fails to arise from the two main aspects: First, due to the distributed capture the code dependencies and hierarchies. Thirdly, as the nature of blockchain platforms, malicious third parties may contract grows, efficiently identifying vulnerable statements publishtheirsmartcontractstoexploitvulnerabilitiesforprofit. with regard to time and computation cost is crucial to save Second,asanewlydevelopedprogramminglanguage,Solidity developers’ time and resources. has limited research on formal verification to ensure the smart contracts are written properly. Even minor mistakes in smart 1throughout the paper, we use “localize” and “fine-grained detection” |
contract code can result in significant financial loss. interchangeably. 3202 luJ 71 ]RC.sc[ 1v94580.7032:viXraTo tackle these challenges, we present G-Scan, the first II. BACKGROUNDANDCHALLENGES end-to-end fine-grained line-level vulnerability detection sys- A. Smart Contracts Vulnerability temwithevaluationsonthefirst-of-its-kindrealworlddataset. Our G-Scan converts the contracts to code graphs by first get- Smart contracts are self-executing programs in Ethereum tingtheirabstractsyntaxtree(AST)representationsandadding that enables developers to create decentralized blockchain extra edges to reflect data dependencies and code hierarchies. applications, including financial services. These contracts are Then, it assigns node features by including function types like written in Solidity, a high-level programming language, and While and For, variable properties like visibility and storage compiled into Ethereum Virtual Machine (EVM) bytecode for location,andnodememberaccesslikesendandtransfer.Each deployment on the Ethereum network. Despite their benefits, node also processes a src attribute which memorizes the lines smartcontractscanalsobevulnerabletosecurityrisks,which, where the nodes are extracted when constructing AST. ifnotidentifiedintime,canleadtosignificantfinanciallosses. In this context, we outline some of the vulnerabilities related G-Scan trains a GCN model on the converted graphs and tofinancialtransactions,includingthereentrancyattack,which learns the hidden features carrying the vulnerabilities. In the is widely regarded as the most common and dangerous vul- inferencestage,G-Scanisusedtopredictthenodelabelsofun- nerability (e.g., DAO [22]). seencodegraphsandmapbacktothecontractstatementswith src attributes. We train and evaluate G-Scan on the first real- Reentrancy Attack: The adversary performs reentrancy world fine-grained reentrancy vulnerability annotation dataset attacks[9]byrepeatedlycallingbackintoavulnerablecontract consisting of 13,773 smart contracts and achieve 93.02% F1- before the previous invocation has been completed. It allows score in contract-level vulnerability detection and 93.69% F1- the adversary to repeatedly siphon funds. score in line-level vulnerability localization. Integer Overflow/Underflow Attack: The adversary per- Our contributions to the community are summarized as forms overflow/underflow attacks [2] on vulnerable smart follows: contracts doing mathematical operations on unsigned integers. It allows the adversary to transfer excessive funds from the • WepresentG-Scan,thefirstend-to-endalgorithmthat overflow/underflow. leverages graph neural networks for fine-grained line- level detection of smart contract vulnerabilities. Access Control Attack: The adversary performs access control attacks [1] on vulnerable smart contracts that do not • G-Scan is a scalable and efficient framework that is properlycontrolaccesstosensitivefunctionsordata.Itallows agnostic to contract size and localizes vulnerability the adversary to steal sensitive private information from the within 1.2 seconds for contracts with more than 6.1k vulnerable smart contract. lines of code. • Proof of concept evaluation is demonstrated on the B. Graph Neural Networks first-of-its-kindrealworlddatacollectionconsistingof 13,773 smart contracts and a total of 5,363,793 lines Given a graph G = (V,E,A) consists of a set of nodes of code. Each data line is labeled to indicate whether V = {v ,v ,...,v } and a set of edges E = {e ,e ,...,e }. 1 2 n 1 2 m they contain reentrancy vulnerabilities or not. For every node, v ∈ V has a k dimension feature vector i h ∈ Rk. The connections between nodes are deposited into i • Our results show that G-Scan can achieve 93.02% the adjacency matrix A where a nonzero number in row i and F1-score in contract-level vulnerability detection and column j means a connection from node i to node j. 93.69% F1-score in line-level vulnerability localiza- tion by incorporating variable dependencies and code TheobjectiveofGNNistolearnafunctiongthatmapsthe hierarchies into graph modeling. feature embedding h of the i-th node v to a new embedding i i vector hˆ ∈ Rh which capture the node’s local and global i Insummary,G-Scanprovidesanefficientandprecisefine- information.Foramulti-layerGNNmodel,themappingabove grained vulnerability detection solution to smart contracts. G- is performed iteratively to help nodes update their feature Scan also contributes the first-of-its-kind large-scale real word embeddings with the information from their neighbors via smart contract dataset with fine-grained reentrancy vulnerabil- message passing. For every node v , it performs message i ityannotations.Ournovelgraphrepresentationandlightweight passingbyreceivingthefeatureembeddingsfromitsneighbors GNN-based node classification model trained on the real- j ∈ N , where N is the set of nodes adjacent to v . The i i i world dataset enable line-level vulnerability detection with messages are then aggregated using a customized function to both efficiency and accuracy compared with prior arts. We obtain an updated representation hˆ . i will open-source the code along with our collected dataset to promote research in this area. The computations are formulated in Equation 1 where f, g, and ⊕ are customizable functions, e.g., convolution. Here, Paper Organization: For the rest of the paper, we will h( vl) and h( ul) are the node features at layer l, N(v) are the introducevulnerabilitylocalizationbackgroundandchallenges set of neighbors for node v, e is the edge feature between uv in Section II; the goal of G-Scan and the threat models nodes u and v, and h( vl+1) is the updated features of node v in Section III; the detailed design pipeline of G-Scan in |
at layer (l+1). SectionVI-SectionV;theexperimentsdemonstratingG-Scan’s effectiveness in Section VIII; and the conclusion and future h(l+1) =g(h(l) ⊕ f(h(l),h(l),e )) (1) work in Section X. v v u∈N(v) u v uv 2C. Challenges A. Goal To perform fine-grained line-level smart contract vulnera- Our goal is to localize the vulnerabilities within smart bility detection, we identify the following challenges. contracts. While many works [19], [27], [37], [38], [43] have used machine learning models to detect contract vulnerabil- Lack of Dataset: Many real-world contract-level vulner- ities, few explored how to localize them. Nevertheless, it ability detection datasets [38] are open-sourced for scientific is crucial to accurately and efficiently identify which line research. However, these datasets lack line-level annotations contains the vulnerability for both developers and end-users. that pinpoint the exact location of vulnerabilities. It brings Fordevelopers,identifyingthespecificlineofcodecontaining challenges to the fine-grained detection model training, as the bug, instead of just contract-level detection and examining high-quality data, like real-world contracts with annotations, the code line-by-line, can improve working efficiency. Smart is essential for the machine learning models to learn hidden contracts can be inevitably complex, with intricate user agree- patterns and achieve optimal performance. ments and transaction logics, making debugging a challenging task, even when developers know that vulnerabilities exist in Graph Representation: The second challenge is rep- the codebase. G-Scan helps the developers to focus on fixing resenting code graphs with both semantic and structural in- the risky part instead of changing the entire codebase, which formation. Previous approaches such as MANDO [26] and saves time and resources. For end users, with G-Scan, fine- DR-GCN [19] extract heterogeneous code graphs based on grained vulnerability detection with low inference overhead semantic information from the source code, such as critical opens a more transparent door to facilitate them to analyze functioncalls/variablesandtemporalexecutiontrace.However, security concerns within contracts and avoid transactions with they did not consider the structural information that indicates malicious parties. the code execution orders and relationships between data ele- ments, which are where many vulnerabilities originate. Apart In summary, G-Scan contributes to improving the security from the edge connections, designing node feature embedding of the transaction life-cycle from the following two aspects: representations that depict function or expression types and • Before publishing the smart contract, with G-Scan, properties helps GNN models learn better local and global one can analyze the vulnerabilities within the smart codeinformation.Therefore,developingappropriategraphrep- contracts at line-level and fix them in time. resentations is crucial in improving fine-grained vulnerability detection model performance. • When making transactions with untrusted third par- ties, with G-Scan, one can analyze the vulnerabilities Efficiency: Achieving efficiency in terms of inference within the smart contracts efficiently without costing time and cost is also challenging as the size of contracts too much computation resources. scales. For time efficiency, line-level detection algorithms like MANDO [26] use a two-level detection algorithm, where it B. Threat Model first classifies if a smart contract is vulnerable and then uses the node embeddings obtained from a topology graph neural As depicted in Figure 1, a Solidity developer first publish network for line-level vulnerability classification. However, a vulnerable contract to the blockchain. Then, an adversary performing inference over three multi-level graph neural net- exploits the vulnerabilities by publishing an attacking contract works results in significant localization overheads. For cost tocallthevulnerablecontracttostealfunds.G-Scansafeguards efficiency, prior arts detect contract-level vulnerability via smartcontractsbyhelpingSoliditydevelopersidentifyandfix DNN based models [13], [15], [27] are parameter-heavy and possible security risks promptly. require significant computation resources when contract users intend to verify if a specific contract is vulnerable. Attack Mapping between Node and Statement: Another chal- Adversary Contract lenge is establishing the relationship between nodes in the code graph and statements in the smart contract. This is because localizing which line is vulnerable relies heavily on identifying the node representing the code block in the graph representation and accurately mapping it back to the corresponding line. While prior work such as MANDO [26] classifies vulnerable nodes within code graphs, they did not BlockChain explicitly mention how the vulnerable nodes are mapped back Solidity Vulnerable line by line. In contrast, G-Scan proposed the first end-to- Developer Contract endvulnerabilitylocalizationsystembyleveragingASTtrees, which enables us to accurately map vulnerable nodes back to Fig. 1: Attack Scenario. When solidity developer publishes a specific lines in the smart contract. vulnerable contract to the blockchain, the adversary leverages another attack contract to exploit the vulnerabilities in the III. GOALANDTHREATMODEL vulnerable contract and steal funds from the developer. In this section, we will first introduce the goal of our proposedG-Scanandthenintroducethepotentialthreatmodels Adversary’s Objective The adversary is the malicious that our G-Scan aims to defend. party in the blockchain and attempts to perform an attack on |
3the Ethereum platform. In this paper, we use the reentrancy a GNN-based node classification model on the code graphs attack as an example, but note that G-Scan can be adapted to classify vulnerable nodes and clean nodes. The training is to detect any other vulnerability types. In the reentrancy performedonacollectedreal-worldsmartcontractdatasetwith attack, the adversary deploys an attacking contract designed eachdatalineannotatedaseitherreentrancyvulnerableornot. to exploit the vulnerabilities in the vulnerable contract. The The code graph representation construction consists of vulnerablecontractcontainsafunctionthatallowsittotransfer three steps, namely, AST generation, code graph edge gener- funds to other contracts. The adversary adds itself as one ation, and node feature embedding generation. We will also of the vulnerable contract recipients by first depositing the illustrate how the code graph is constructed by giving an vulnerable contract funds and then withdrawing them. During example in the end of this section. the withdrawal execution, the attack contract repeatedly re- enters the vulnerable contract and calls the transfer function A. AST Generation multiple times until all funds are stolen. WeuseSoliditycompiler[10]toconvertthesmartcontract In Solidity, the above fund transfer is implemented by intotreeformat,wherethenoderepresentssyntacticconstructs the following three subtype data structures, where <CA> in the source code, such as statements and expressions, and indicates the recipient’s contract or account address and x each edge represents relationships between these constructs, describes the amount of fund to be transferred. suchasfunctioncallsandvalueassignments.Thenodeswithin AST have two sets of node attributes: node type and source • call: <CA>.call{value: x} src. The node type describes the functionality of the source • transfer: <CA>.transfer(x) code, while the source src stores which part of the source codethenodecomesfrom.TheedgesinASTarenotexplicitly • send: <CA>.send(x) definedbutaregeneratedbythenestedchildnodeswithineach node. The difference among the three subtypes mainly arises from their implementations: Firstly, the upper transaction B. Code Graph Edge Generation limit of transfer or send is 2,300 gas (a unit to measure funds in ETH platform), while call has no such limitations. In addition to the edges being implicitly defined by the Therefore, if an adversary exploits the call subtype, it can hierarchically nested nodes in the AST, we also add the result in a greater loss of funds. Secondly, call cannot following edges to represent the structure and semantics of automaticallyhandleexceptionsthrownbythecalledcontract, the underlying source code. These edges aim to obtain the which increases the potential for reentrancy attacks. Thirdly, representation by adding control flow, hierarchy between the due to the transaction limitations in transfer and send, nodes, and existing data dependencies between the nodes into some developers may opt to use call without mitigating the the code graph. Specifically, we add the following edges reentrancy vulnerabilities. into the code graph: (1) AST Hierarchy Edges; (2) Control FlowandOrderingEdges;(3)ReferenceEdges;(4)Branching However,possiblereentrancyattackscanstillbeperformed Edges; (5) Loop Edges; and (6) Break, Continue, and Return ontransferandsendforseveralreasons.Firstly,ifthesetwo Edges.Afteraddingtheseedgestothecodegraph,weconvert subtypesrequestscallvulnerablecontractsforfundsexceeding it into a directed homogenous graph for future classification theupperlimit,exceptionscanstillhappen,andifnothandled in Section V. properly, reentrancy attacks can be executed to steal funds. Secondly, if Ethereum Virtual Machine is upgraded and the AST Hierarchy Edges: The first type of edges are the maximum fund transaction limit changes, reentrancy attacks hierarchy edges generated by AST. Each node in the AST can canstillbringfundloss.Additionally,transferwillthrowan have other child nodes defined in its node types, meaning the exceptionifgasisdepleted,leadingtoastatechangereversal. node and its child nodes have hierarchical relationships. As shown in Figure 3, for example, for node Block, it has node Adversary’sCapacityWeconsiderthemostgeneralattack types related to statements 1 to statements k and Block case where the adversary is one of the contract creators. He istheparentnodeofthesechildnodes.Torepresenttheparent- or she has access to the public data structure on the chain and child relationship in the code graph, we add two edges, one canuploadhisorhercontracttotheEthereumsystembutdoes from the parent to the child and vice versa. not have access to the detection of G-Scan. Control Flow and Ordering Edges: Apart from the hierarchyinformationdefinedbyAST,wealsoaddthecontrol IV. GRAPHREPRESENTATION flow edges indicating the relationship between statements In this and subsequent sections, we will first present how in the child nodes. There are three node types containing smart contracts are converted into code graphs, how to train function statements, namely, Block, UncheckedBlock, and GNN models to classify nodes as vulnerable or not, and YulBlock. The function statements in the node types are then introduce how we collected our reentrancy vulnerability given by the order they are executed in the original smart dataset, along with detailed statistics. contracts. As shown in Figure 3, for example, if a Block contains k statements, in addition to the AST edges added A more general pipeline of our G-Scan is shown in to indicate their hierarchy information, we also add edges Figure 2. We begin by converting the smart contract into between statements to explain the order they are executed. a code graph through AST representations that extract code structural information. We then add extra edges and node When a given node in the AST has the same child node |
feature embeddings to reflect code hierarchies. Next, we train belonging to two or more node types, ordering edges are 4GNN GNN Training SmartContract Abstract Syntax Tree CodeGraph Graph Representation Unseen Line: 12, 31 Contract Line: 35, 67 GNN Real-world Line-levelReentrancy VulnerableNode Contracts Vulnerability Annotation CleanNode GNN Inference Data Collection Fig. 2: G-Scan overview. First, we obtain the graph representation of the smart contract by converting it into an Abstract Syntax Tree(AST)representationandaddingadditionaledgesandnodefeatureembeddingstoreflectcodehierarchiesanddependencies. Next, we train a Graph Neural Network (GNN) model on the code graphs to classify vulnerable nodes and perform inference on unseen smart contracts. We train and evaluate the GNN model on a collected real-world smart contract dataset, with each data line annotated to indicate whether it contains reentrancy vulnerability. NodeType Start End Block IndexAccess baseExpression indexExpression AST AST baseExpression startExpression AST AST IndexRangeAccess startExpression endExpression FunctionCall arguments expression Statement1 Statement2 Statement3 Statementk FunctionTypeName parameterTypes returnParameterTypes ··· CF CF CF CF Assignment leftHandSide rightHandSide BinaryOperation leftHandSide rightHandSide Fig.3:Controlflowedgesbetweenkstatementsinsideablock FunctionDefinition parameters returnParameters YulFunctionDefinition parameters returnVariables TABLE I: Ordering edge directions introduced to distinguish each connection. For example, node type Mapping connects keys node A to values node B, where A and B can be either the same or different. In its AST dependency between the usage of the same variable without a representation, the key node connects with the value node variable name, we introduce a new edge type called reference by attribute keyType defined in key node type. The value edge.Theidentifiernodetypesarelinkedwiththeirdeclaration node connects with its key node with valueType defined node by the reference edge, which is always added in both in the value node type. When building AST, the connection directions, from the identifier node to the declaration node is replaced by the undirected AST edges, which is hard and vice versa. Functions are treated in the same manner as to represent the mapping relationship between keyType and variables, where reference edges are added from the identifier valueType. Therefore, we add an ordering edge to from node to its declaration nodes and vice versa. keyType node to valueType node to represent the mapping Branching Edges: In the code graph representation, relationship. branchingcodeblocksareonlymappedtochildnodeswithout Apart from Mapping, we summarize other node types further representation of the contexts between child nodes. which also have similar ordering problems and how to add To handle the branching, we add edges between the nodes ordering edges in Table I representing the condition, the true branch, and the false branch.Figure4showshowbranchconditionsarehandledfor Reference Edges: To ensure two smart contracts with the differentfunctions.InthecaseofIfstatementsandConditional same functionality but different function or variable names statements, three child nodes connect to the statement. One have the same code graph, we introduce reference edges. At node represents the condition and connects the statement with variable level, AST introduced declaration node and assigned controlflowedges,onerepresentsthetruebranchandconnects it a unique identifier attribute id. If the variables are again theconditionwithtrue body edges,andtheotherrepresents used in the smart contracts, the identifier nodes representing the false branch and connects the condition with false body usedvariableswillcallthedeclarationnode.Toreflectthedata edges. 5IfStatement YulIf YulCase Conditional CF YulSwitch CF condition CF CF CF CF AST AST CF CF condition truebody AST AST AST truebody falseBody f ba ol dse y t br ou de y trueBody falseExpression f ba ol dse y t br ou de y trueExpression condition body expression YulCase1 ··· YulCasen value body (a)Ifstatement (b)Conditional (c)IfstatementofYul (d)SwitchstatementofYul (e)CasestatementofYul Fig. 4: Graph structure of the node types referring to branchings WhileStatement ForStatement DoWhileStatement false CF AST AST f ba ol dse y AST CF f ba ol dse y body AST CF YulForLoo fp alse AST truebody AST AST AST CF AST AST body pre condition body CF condition body pre condition truebody body CF AST CF body truebody condition truebody CF AST CF CF loopExpression CF CF post (a)Forloop (b)Dowhileloop (c)Whileloop (d)ForloopofYul Fig. 5: Graph structure of the four loop types ForIfstatementsinYul,whichonlyhaveatruebranchand In Do while loop and While loop, the body node is ignore the statements in the true body for false conditions, we executedfirst,andthentheconditionisevaluated.Therefore, dropthefalse body edges.InthecaseofSwitchstatements we add one false body edge from condition node either to in Yul, which consist of a switch statement with expressions theDoWhileStatementortotheWhileStatementnode;and and several case statements corresponding to the expressions, one true body edge from condition to the body node, and a the switch statements are mapped by the AST edges between control flow edge from the body to the condition node. We the node type YulSwitch and case statement nodes of type also add a control flow edge from either DoWhileStatement YulCase. node and WhileStatement node to the condition node meaning the entry point of the while loop. For Case statements in Yul, AST edges are added between the YulCase node and the two child nodes at the node prop- For the For loop of Yul, we add edges similar to the For erties body and value. Additionally, a true body edges loop. However, the attribute post gives the loop update here is added from value to body to reflect the body execution instead of the attribute loopExpression. condition. Break, Continue, and Return Edges: We also consider six node types that are related to leaving or continuing a LoopEdges:Wealsoincludefourloopedgesthatindicate loop: Break, Continue, and Return, as well as their Yul variable dependencies in the code graph. The four loop types |
counterparts YulBreak, YulContinue, and YulLeave. For inSolidityarefor,do-while,while,andforloopofYul.Figure Break and YulBreak, we add a control flow edge from 5 shows how the loop edges are added to the code graph. the break statement node to the loop node, indicating the break enforces the node to leave the loop. For Continue and For the For loop, there are four child nodes in the loop YulContinue, we add a control flow edge from the continue statement. When entering the loop, an initialization statement statement node to the loop update node to show that the loop with loop parameters is executed and saved in the pre node. variablehasbeenupdated.InthecaseofYulLeaveorReturn, The initialization statement connects to the for statement via we use control flow edges from the leave statement node to a control flow edge. Then, the loop condition is evaluated by the function definition node to represent the loop has exited. the condition node by adding a control flow edge between the pre and condition nodes. If the evaluation result is C. Node Feature Embedding Generation false, the loop is exited, as reflected by a false body edge inserted from the condition node to the ForStatement The nodes in the code graph are derived from the AST, node.Iftheevaluationresultistrue,thebodynodeisexecuted, which provides a list of attributes that describe the main and a true body edge is added from the condition node to functionalitiesofeachnodeandwhichpartofthesourcecode the body node. When the execution is finished, the loop is it comes from. Empirically, [6] has identified 73 node types, updated,andtheloopconditionisre-evaluated.Toreflectthis, but using one-hot encodings of all 73 types can introduce we add two control flow edges, one from body node to the unnecessary computation overhead since some types have loopExpression node and one from the loopExpression similarmeaningsandfunctions.Additionally,certainattributes node to the condition node. may contribute more to the vulnerability than others. 6To address these issues, we merged similar node types body node is executed, we update i following post, and then and created a 29-dimensional feature embedding. The first check if the loop condition node condition is still satisfied. 20 dimensions capture information about different function or The red and green loop edges connect the control flow edges. variable node definitions, the next eight dimensions describe If the condition node is true, a true body edge goes from node properties, and the final dimension indicates Solidity theconditionnodetothebodynodetocontinuetheloop.If member access, specifically whether it involves send or the condition node is false, a false body edge goes from transfer. the condition node to the YulForLoop node to exit the loop. Since there are no branch, return, variable, and function TableIIdisplayssomeofthedimensioninformation,where definitions in the code, we do not add these edges to the code the first column denotes which dimension it comes from, the graph. second column denotes the value of the specific node type it corresponds to in the third column, and the last column is additionaldescriptions.Forthecompletelistof29-dimensional V. GNNTRAININGANDINFERENCE vectors, please refer to the appendix. In this section, we present how we use GNN models to classify vulnerable nodes within code graphs. We train a Dim Values NodeType Description GNN-basednodeclassificationmodelonthecodegraphswith 1 DoWhileStatement annotatedgroundtruthtopredictvulnerabilities.Thedetailsof 2 WhileStatement how we acquire the dataset are summarized in Section VI. 0 Loopinformation 3 ForStatement 4 YulForLoop A. Node Classification Training 1 ’internal’ 2 ’external’ 20 3 ’private’ Differentvaluesofvisibility The objective of the node classification model is to deter- 4 ’public’ mine whether a given node is vulnerable. We train a seven- 5 unknownvalue layerGCNmodeltopredictthenodelabel,where1meansthe 28 1 ’transfer MemberaccessofattributememberName node is vulnerable and 0 means the node is clean. The GNN -1 ’send’ model is trained by minimizing the cross-entropy between predicted labels and ground truth, as shown in Equation 2. TABLE II: Description of the node feature vectors N is the total number of classes, G is the binary indicator (0 i or 1) if class i is the correct classification for this code graph, Example We demonstrate the process of generating the and P i is the predicted probability that class i is the correct code graph shown in Figure 5d from the Solidity code below. classification for this code graph. The function’s purpose is to withdraw a specified amount ( _amount)ofmoneyfromtheExampleYulcontractandtransfer N (cid:88) it to a specified target address (_to). L(G,P)=− G ilog(P i) (2) pragma solidity ^0.8.19; i=1 contract ExampleYul { function withdrawYul(address _to, uint256 ThedetailedmodelarchitectureissummarizedinTableIII, _amount) external payable { which takes the contract code graph as input and predicts the assembly { binarylabelsforeachnode.TheGNNmodelconsistsofseven for {let i := 0} lt(i, 2) {i := add(i, 1)} { GCN layers and a ReLU activation function after each layer. // loop body } Then,theupdatedfeatureembeddingsarepassedthroughthree } linear layers, followed by a Softmax activation function to //other solidity text generate binary label masks. } } Layers InputSize OutputSize ActivationFunction In the Yul Loop, variable i is initialized to 0 using let i GCNConv0 29 500 ReLU := 0; if the condition lt(i, 2) is satisfied, we increment i GCNConv1 500 500 ReLU GCNConv2 500 500 ReLU by 1 using i := add(i, 1). When i satisfies the condition, GCNConv3 500 500 ReLU the loop body is executed. GCNConv4 500 500 ReLU GCNConv5 500 500 ReLU To generate the code graph from this smart contract, we GCNConv6 500 500 ReLU Linear0 500 300 ReLU extractthefollowingnodesfromtheAST:YulForLoop,which Linear1 300 100 ReLU |
definestheloopfunction;pre,whichinitializesthevariablei; Linear2 100 2 Softmax condition,whichdetermineswhentoexittheloopinlt(i, TABLE III: GNN architecture 2); and post, which updates i using i := add(i, 1). The loop body is represented by the body node. Next, we add the following edges to the code graph. The B. Node Classification Inference first set of blue edges represents the parent-child relationships in the AST. Then, we add black control flow edges to indicate Intheinferencestage,anunseensmartcontractisfirstcon- how the code is executed. First, the pre node initializes the verted into an AST representation using the Solidity compiler. variablei,followedbycheckingifisatisfiestheloopcondition Then, we add additional edges and node features to form a node condition. When the loop body represented by the codegraphfollowingtheprocessoutlinedinSectionIV.Next, 7thecodegraphisfedintothetrainedGNNmodelforinference. the node was labeled as such; otherwise, it was labeled as ThefinalLinear2layerinTableIIIpredictsthelabelsforeach non-vulnerable.Thefinalreentrancyvulnerabilitydatasetonly node. Once we obtain the predicted node labels in the code contains smart contracts with three subtype functions with graph, we map them back to the original smart contract using 13,773 smart contracts. the node’s src attributes, which enable us to determine which linethenodecorrespondsto.Ifanodeislabeledasvulnerable, B. Dataset Statistics the corresponding line is also marked as vulnerable. The dataset is split into training, validation, and test sets, withdetailsprovidedinTableIV.Inthetable,theacronymVG VI. DATACOLLECTION representsthenumberofvulnerablegraphs,whichcorresponds This section presents how we collect smart contracts and to the number of contracts in each dataset. Similarly, the annotate the reentrancy vulnerabilities on each data line. We acronym VN represents the total number of vulnerable nodes also provide visualizations of the dataset statistics. within the corresponding Solidity code graphs. A. Dataset Construction Subtype Dataset VG non-VG VN non-VN trainingset 573 11,040 28,900 11,468,676 Our ETH smart contracts are constructed using a previous Call validationset 121 959 5,430 1,447,293 version of the SmartBugs Wild Dataset [17] called Pecu- testset 118 962 6,603 1,401,601 liar[38].Thedatasetconstructionprocessinvolvedtwostages. trainingset 1,067 10,546 61,508 11,436,068 Send validationset 200 880 10,678 1,442,045 In the first stage, we clean the collected smart contracts and testset 226 854 13,207 1,394,997 split them into training, validation, and test subsets. In the trainingset 1,572 10,041 83,469 11,414,107 secondstage,weannotateeachdatalineinthesmartcontracts Transfer validationset 320 760 16,782 1,435,941 to identify the presence of reentrancy vulnerabilities. testset 346 734 18,213 1,389,991 Preprocessing Although the previous Peculiar dataset un- TABLE IV: Dataset statistics on each subtype, VG represents derwentcleaning,theduplicationrateremainsover50%.These vulnerable graphs number, VN represents vulnerable nodes canoccurintwoways:(1)onecontractmayhavebeencopied number fromanotherbyaddingafewwhitelinesorcomments;and(2) onecontractmayhavebeencopiedfromanother,withchanges only made to variable names, function names, or variable In addition to the statistical information, we also present values. Moreover, many contracts lacked their reference files, visualizations to demonstrate the code graph data distribution. making it impossible to construct an AST tree. Figure 6 displays the code length distribution of smart con- tracts, as well as the nodes and edges distribution of each To address these issues, we adopted a two-step approach. code graph. The first and second figure provides insights into First, we generated an Abstract Syntax Tree (AST) tree from the size and complexity of the code graphs, as measured by the Solidity compiler, which removed white space characters the number of nodes and edges, respectively. The third figure andassignedcommentlinestoanignorednodetype.Next,we showsthedistributionofcontractlengthintermsofthenumber constructed the Solidity code graph by leveraging information of lines of code. on the smart contract code structure and the AST tree (refer to Section IV for details on graph construction). This step VII. IMPLEMENTATION removed intermediate values, as well as variable and function names.Afterobtainingthecodegraphs,wegroupedthesmart Inthissection,wepresentthegeneralworkflowforimple- contract codes based on the similarity of their sha256 hashes. menting G-Scan at both training and inference time. We selected one representative contract from each group, resulting in a total of 22,237 smart contracts, which are less A. G-Scan Training Implementation than half of the original dataset containing 46,057 contracts. Thepipelineforourapproachconsistsofthreemainsteps: AnnotationInthePeculiardataset[38],reentrancyvulner- (1) constructing an AST from the source files; (2) converting ability was only annotated at the contract-level for the call the AST into a code graph with vulnerability labels; and subtype. To achieve more accurate line-level annotation, we (3) training a GNN-based node classification model. In the expanded the annotation from the call subtype to include all followingsubsection,weprovideadetaileddescriptionofhow threesubtypes:call,send,andtransfer.Contractsthatdid each step is implemented. not include these three subtype functions were deemed non- AST Construction We construct ASTs from source code vulnerable. files using Solc [10]. The AST construction requires the Intheremainingcontracts,wemanuallyinspectedthedata smart contracts in one file. Therefore, if the smart contract |
lines containing the three subtype functions to determine if is written in multiple files, we merge them into a single file a state change was made after the money transfer, and if before performing AST conversion. The following is a sample there was no reentrancy lock in place. If these conditions Solidity program, where x.x.xx represents the Solidity version were met, we annotated the lines as vulnerable. We then inwhichthecontractwaswritten.ItisworthnotingthatASTs mapped these annotations to the code graphs. Each node in generated by Solc versions below 0.4.12 are not compatible the code graph was assigned an attribute src, indicating the withnewerversions,andonlyasmallnumberofcontractsare original smart contract line from which the node was derived. written in these older versions. Therefore, we did not include If the corresponding code line was marked as vulnerable, them in our dataset collection. 8(a)NodeNumberDistribution (b)EdgesNumberDistribution (c)LinesofCodeDistribution Fig. 6: G-Scan dataset visualization on code graph node number, edge number, and smart contract lines of code pragma solidity x.x.xx; from utils import dicToNodes from graph construct import createReferenceEdges , createNodeFeatureVectors We then convert the line-level annotations from smart contracts to AST node labels, as shown in the annotateLa- graph = dicToNodes(AST) bel function below. It takes AST’s node attributes src list graph = createReferenceEdges(graph , AST) (node2sourceCode), smart contract’s source code annotation graph = createNodeFeatureVectors(graph , AST) list(GTlabel),andthesourcecodeatbytelevel(codeBit)as input. The GTlabel variable stores which line in the original The dicToNodes function is used to extract nodes and smart contracts are vulnerable. edgesfromtheASTandformtheinitialcodegraph.TheAST object contains a dictionary with node mappings to the source def annotateLabel(node2sourceCode ,GTlabel ,codeBit): code,aswellasnodeandedgelists,edgetypeslists,andalist labels=[] if sum(GTlabel)==0: indicating breaks, continues, or returns in substructures. The return [0]*len(node2sourceCode) graphobject,ontheotherhand,includesanodemappingfrom the code graph id to the AST node id, as well as node and for src in node2sourceCode: src=src. split(":") edge lists. The resulting code graph is stored in a PyG data sBit=codeBit[:int(src[0])] object to facilitate future GNN training. eBit=codeBit[:(sBit+int(src[1]))] After creating the initial AST tree, we use the start=len(sBit.decode("utf−8"). splitlines ()) createReferenceEdges function to add additional edges end=len(eBit.decode("utf−8"). splitlines ()) to the code graph as described in Section IV-B. We also codeLine=[*range(start , end+1,1)] add additional node features to the code graph using the lineLabel=[GTlabel[i] for i in codeLine] createNodeFeatureVectors function, which takes the code if sum(lineLabel)>0: graph and AST node properties as inputs and adds node labels.append(1) features as described in Section IV-C. else: labels.append(0) GNN Training The GNN model for node classification is trained with the code graphs in the training set and evaluated return labels with the code graphs from the validation and test set. We add additional training details, including the hyperparameters If there are no vulnerable annotations in the current smart in Table V. The architecture information is summarized in contract, we return a set of 0 to indicate that the contract is Table III. clean. However, if the contract has vulnerable annotations, we proceed to analyze each node in the AST representation to Variables Settings obtain node-level labels. Since the src attribute in the AST Epoch 1600 representation points from each node to the corresponding Batchsize 100 position in the original contract at the byte level instead of Optimizer adam the line number, we need to decode the code byte into utf-8 Learningrate 0.0001 Lossfunction crossentropy format to determine the exact line number. We calculate the decoded line length and use this information to label each TABLE V: GNN training hyperparameters node as vulnerable (labeled as 1) if one of the corresponding lines is marked as vulnerable in the GTlabel. If none of the corresponding lines are marked as vulnerable, the node is labeled as not vulnerable (labeled as 0). B. G-Scan Inference Implementation Code Graph Generation The ASTs are then converted to We utilize the trained GNN for node classification to code graphs as described in Section IV. To generate the code predict the location of vulnerabilities. As with the training graph, we use the following functions: process for G-Scan, we first convert the source code file into 9an AST representation using the Solidity compiler, and then Simulated Dataset [26]: This dataset includes 31 smart con- transformitintoacodegraphrepresentationwithoutadditional tracts related to reentrancy vulnerability used by MANDO labels indicating vulnerability. We then feed the code graph as their test set. The contracts consist of synthetic samples into the GNN model for node classification inference and created by injecting vulnerabilities into clean smart contracts obtain a binary mask that measures whether each node is and public smart contracts. All samples include line-level vulnerable or not. If none of the nodes are vulnerable, we annotations. predict that the contract is clean. Otherwise, we predict which nodes are vulnerable. After obtaining the node prediction C. Evaluation Metrics results,weconvertthembacktocodelinesusingthesrcnode Intheexperiment,webenchmarkthemodelperformanceat propertyandmarkthevulnerablelinesonthesourcecodefile. both line-level and contract-level. For line-level classification, Theprocessofcodegraphgenerationandinferencearethe we use G-Scan to determine if a node is vulnerable. For |
same as described in Section VII-A. Here, we will focus on contract-level classification, after obtaining the classification the mapping from code graph to the original smart contract. result of each node, if there is a vulnerable node, we classify As illustrated below, mapping the node-level predictions back the contract as vulnerable; otherwise, it will be classified as to the smart contract can be viewed as a reverse process of non-vulnerable. ASTconstruction.WeusethepredictLabelfunction,which In order to evaluate the performance of different models, takes in the node predictions (NodeLabel), the source code we compared their classification results with the annotated at the byte level (codeBit), the source code length (length), ground truth from Sec.VI, and computed the confusion matrix andtheAST’snodeattributessrclist(node2sourceCode)as atboththeline-levelandcontract-level,includingTruePositive inputs to generate the line-level predictions (LineLabel). (TP), True Negative (TN), False Positive (FP), and False def predictLabel(node2sourceCode ,NodeLabel,codeBit , Negative(FN).Wethenusedthefollowingmetricstoevaluate length): the performance of the models based on the confusion matrix: labels=[0]*len(length) if sum(NodeLabel)==0: Accuracy (A): The proportion of correctly identified graphs return [0]*len(length) or nodes, which is formulated as TP+FT PP ++ TT NN +FN. for i ,src in enumerate(node2sourceCode): Recall (R): The proportion of correctly identified vulnerable src=src. split(":") graphs or nodes, which is formulated as TP . TP+FN sBit=codeBit[:int(src[0])] eBit=codeBit[:(sBit+int(src[1]))] Precision (P): The proportion of identified vulnerable graphs or nodes that are actually vulnerable, which is formulated as start=len(sBit.decode("utf−8"). splitlines ()) TP . end=len(eBit.decode("utf−8"). splitlines ()) TP+FP codeLine=[*range(start , end+1,1)] F1score:Aharmonicmeanthatcombinesprecisionandrecall, 2∗(P∗R) which is formulated as if NodeLabel[i]>0: (P+R) labels[codeLine] = 1 else: D. Baselines labels[codeLine] = 0 For contract level classification, we compare G-Scan’s return labels performance with the following baselines on Peculiar Dataset [38]. For line level classification, we compare G-Scan with MANDO on its simulated dataset. VIII. EXPERIMENTS MANDO [26]: It first uses a topology GNN to obtain node A. Experiment Setup embeddings of a heterogeneous code graph and then classifies the vulnerability at the graph level. If the code graph is G-Scan is implemented with Python 3.8.10 and bench- vulnerable, it trains a node classification model to identify the marked on Linux Mint 20.3. Our workflow is built upon vulnerable nodes. PyTorch [34] version 1.9.0 and PyG [32] version 2.0.4. The GNNmodelistrainedonNVIDIAA16graphiccardconsisting DR-GCN [43]: It first converts the contract into a symbolic of four GPUs each with 16 GB RAM, and 4 CPUs with 128 graph and normalizes the graph by performing node elimina- GB RAM. tion. The resulting code graph is classified using a degree-free GCN. B. Dataset TMP[43]:ThegraphprocessingstepisthesameasDR-GCN, butitusesatemporalmessagepropagationnetworktoclassify Toevaluatetheperformanceofvariousvulnerabilitydetec- code graphs. tion models, we employed the following three datasets: AME [20]: It utilizes a rule-based approach to extract local Peculiar Dataset [38]: This dataset consists of 46,057 smart expert patterns and convert the code into a semantic graph to contracts with contract-level reentrancy vulnerability annota- extractglobalgraphfeatures.Thesetwofeaturesarethenfused tion for subtype call. using an attention-based network to predict vulnerabilities. G-Scan Dataset: Our collected dataset of 13,773 contracts Peculiar[38]:Itfirstextractsthedataflowofimportantsource with line-level reentrancy vulnerability annotations for sub- code variables and creates a crucial dataflow graph. The types call, transfer, and send, as described in Section VI. vulnerability is then classified using GraphCodeBert. 10Asmentionedearlier,SCScan[14]alsoperformsline-level classification performance of G-Scan, along with other base- vulnerability detection. However, at the time of submission, lines. However, since prior work reported their performance SCScan’s code was not open-sourced, and their results were on the Peculiar Dataset, which only annotates reentrancy not reported on an open benchmark. Therefore, we could not subtype Call, and some of them did not open-source their compare their performance with that of G-Scan in this paper. code, we were unable to benchmark them on our extended reentrancy vulnerability dataset in Section VIII-E. Therefore, E. Results on G-Scan Dataset we benchmark G-Scan on the Peculiar Dataset and report our results in the first row of the table. We note that prior We present the graph-level and node-level classification works mainly constructed code graphs based on semantic resultsontheG-Scandataset’svalidationandtestpartinTable information, whereas G-Scan relies on AST to generate code VI. The table displays the accuracy, precision, recall, and F1- graphs. If a smart contract is missing its reference file, we score for three reentrancy subtypes: Call, Send, and Transfer. cannot construct AST and perform inference on the contract, which is reasonable as one cannot determine the vulnerability Basedontheresultspresentedinthetable,wecanmakethe withoutcheckingtheentirecontractcode.Additionally,during followingobservationsfornode-levelclassification:Firstly,the |
G-Scan inference, we removed duplicated code graphs, which classificationaccuracyforalldatasetsandreentrancysubtypes accounted for more than 50% of the total. isabove99%,indicatingthatG-Scancansuccessfullylocalize vulnerable nodes in real-world datasets. It demonstrated the Based on the results, we observe that even when the effectiveness of our proposed pipeline. Secondly, node-level duplicates are removed, G-Scan can still achieve 8% better F1-score are higher than 90% for most general vulnerable accuracy than the baseline methods. Although Peculiar [38] reentrancysubtypeCall,andhigherthan79%fortheresttwo achieves a slightly better F1-score than G-Scan, it cannot lo- subtypes,showingG-Scancanbenefitreentrancyvulnerability calizereentrancyvulnerabilities.Moreover,amongthebaseline localization in real world smart contracts. methods, only MANDO performs fine-grained vulnerability localization,andG-Scanachievesa21%betterF1-scoreatthe In terms of graph-level classification, we can find the contract level detection. It is noteworthy that even though G- following:Firstly,theclassificationaccuracyforallreentrancy Scanisdesignedtolocalizevulnerabilitiesatthenodelevel,it subtypes is higher than 89%. This indicates that even though stillachievesgoodperformanceatthecontractleveldetection. G-Scan is designed for line-level vulnerability localization, it can still effectively classify vulnerable contracts. Secondly, the F1-scores for all three reentrancy subtypes are higher Method Accuracy F1-Score than 85%, demonstrating that G-Scan can successfully detect G-Scan 98.15% 91.74% potential vulnerabilities. MANDO[26] 75.80% DR-GCN[43] 81.47% 76.39% TMP[43] 84.48% 78.11% Subtype Dataset Level Accuracy Precision Recall F1-Score AME[20] 90.19% 87.94% validationset node 99.95% 94.88% 92.52% 93.69% Peculiar[38] 99.81% 92.10% testset node 99.92% 93.23% 89.26% 91.20% Call validationset graph 98.33% 87.59% 99.17% 93.02% TABLE VII: Comparison with baselines on Peculiar Dataset. testset graph 97.31% 80.27% 100% 89.06% validationset node 99.86% 91.34% 89.05% 90.18% testset node 99.77% 92.55% 82.65% 87.32% Send validationset graph 94.72% 81.07% 98.50% 88.94% 2)Node-level Performance: We compared G-Scan with testset graph 95.46% 80.07% 99.56% 88.76% MANDO on a simulated dataset since it was not possible to validationset node 99.52% 79.58% 79.19% 79.39% directly compare the two methods on our collected G-Scan Transfer testset node 99.53% 83.61% 78.92% 81.19% Dataset. This was because MANDO did not provide explicit validationset graph 89.91% 74.71% 99.69% 85.41% details on how their contract graph is mapped back to the testset graph 90.74% 78.21% 98.55% 87.21% smartcontract,andline-levelaccuracycouldnotbecompared. TABLE VI: G-Scan performance on different reentrancy sub- Additionally, directly comparing the two methods at the node types levelwasnotpossibleasMANDOusedmetapathstoconstruct the code graph while G-Scan used the AST to generate the code graph. In Figure 7, we display the F1-scores on the train and validation datasets for the three reentrancy subtypes. From Therefore, to compare the two approaches, we use the the figure, we observe that as the training progresses, G-Scan simulated dataset collected by MANDO. One of the smart achievesanaverageF1-scoreofover90%onboththetrainand contracts could not be compiled, while another one belongs validationdatasetsforthemostcommonsubtype,Call,atboth to the subtype transfer, which was correctly identified by the node-level and graph-level. The average F1-scores for the G-Scan.AsshowninTableVIII,G-Scanachieved91.28%F1- subtypes Transfer and Send are also higher than 80%. The scoreoncallreentrancy,outperformingitsbaselineMANDO. stablecurveindicatesthatG-Scancontinuouslylearnsfromthe This result suggests that by incorporating code hierarchy traindatasetandgeneralizeswelltowardthevalidationdataset. information into graph modeling and training on real-world datasets,G-ScanoutperformedMANDOinvulnerabilitylocal- ization. We also note that MANDO’s effectiveness is heavily F. Comparison with Baselines reliant on identifying vulnerabilities at the contract level, and 1)Contract-level Performance: In Table VII, we present its classification F1-score for certain vulnerability types, such the accuracy and F1-score of the contract-level vulnerability as reentrancy, falls to 75.80%. 11(a)SubtypeCallatnodelevel (b)SubtypeSendatnodelevel (c)SubtypeTransferatnodelevel (d)SubtypeCallatgraphlevel (e)SubtypeSendatgraphlevel (f)SubtypeTransferatgraphlevel Fig. 7: The F1 score evaluated during training for train and validation dataset on three subtypes at both node and graph level Method Accuracy F1-Score LoC AST(ms) CGG(ms) Prediction(ms) Total(ms) G-Scan 97.44% 91.28% 5 3.60 1.19 5.05 9.84 Mando[26] - 86.40% 197 31.29 6.04 9.96 47.29 245 55.89 12.92 14.15 82.96 TABLE VIII: Comparison with MANDO on Simulated 5815 901.98 178.08 95.26 1175.32 6151 850.70 191.48 108.25 1150.43 Dataset. TABLE IX: G-Scan overhead on AST construction (AST), code graph generation (CGG) and prediction G. Inference Overhead We present the inference overhead of smart contracts vulnerability conditions can exist in the source code or not. |
with varying lengths in Table IX. The inference overhead is Insmartcontractvulnerabilitydetections,symbolicexecutions measuredforfivesmartcontractswithdifferentLinesofCode arealwayscombinedwithotherrule-basedalgorithmstodetect (LoC)andincludesthetimeittakesforASTconstruction,code potential security risks. Osiris [36] detects integer bugs with graphgeneration,andGNNpredictions.ASTconstructionand symbolic execution and additional taint analysis, which is a code graph generation are performed on the CPU, while GNN kind of tracking of the data across the control flow. SmarTest prediction inference is performed on the GPU. [30]appliessymbolicexecutiononthesmartcontractlanguage From the table, we can find the following: Firstly, the models and creates transaction sequences to detect bugs. majorityoftheG-ScanoverheadcomesfromASTconstruction SAILFISH[7]usesahybridapproachforsourcecodes,where using Solidity compilers. As the size of the smart contract a storage dependence graph performs analysis of side effects increases,thepercentageoftimerequiredforASTconstruction on the storage variables during the execution and follows by as a fraction of the total overhead increases. This is because the symbolic evaluation to detect vulnerabilities. thecompilerrequiresmoretimetoparselargerfiles.Secondly, Fuzzing: Fuzzing [12], [16], [28], [29], [31], [35] uses despite an LoC value as large as 6.1k, the total inference time different algorithms to automatically generate inputs poten- remains under 1.2s, demonstrating the efficiency of G-Scan. tially trigger errors or unexpected behaviors to detect smart IX. RELATEDWORK contract vulnerabilities. ContractFuzzer [16] analyzes the ABI interfaces of smart contracts to generate inputs that conform A. Smary Contract Vulnerability Detection to the invocation grammars of the smart contracts under test. Symbolic Execution: Symbolic execution [3], [18], [30], It defines new test oracles for different types of vulnerabilities [33],[36]takesthesmartcontractsbytecodeasinputanduses and instrument EVM to monitor smart contract executions symbolic expression to represent the contracts. Then, it uses to detect security vulnerabilities. Echidna [12] incorporates Satisfiability Modulo Theory (SMT) solver to prove if certain a worst-case gas estimator into a general-purpose fuzzer. 12When a property violation is detected, a counterexample is likeC/C++.ASTcanextractbetterstructureandvariable/func- automaticallyminimizedtoreportthesequenceoftransactions tion dependency from source code. Some recent work [39], that triggers the failure. [41] also applied AST based graph analysis to smart contract vulnerability detection. Allamanis et al. [4], [5] proposed a Machine Learning: Machine training [11], [37], [42] program graph based on the node connections in C#’s AST. It based algorithms take the smart contracts as text data or first transforms the C# source code into AST representation graph data and use different machine learning algorithms to using compilers. Then, the nodes in the tree are replaced classify if a smart contract is vulnerable or not. The machine by corresponding source code tokens and connected with learning algorithms enable the model to learn the hidden edges that reflect the original execution order. To represent feature representation of smart contract code that previously the control and dataflow structure, they add additional edges, introduced rule-based algorithms failed to catch. Most of forexample,betweenalloccurrencesofthesamevariableorin them [38], [42], [43] classify vulnerabilities at contract level, condition statements to indicate all valid paths. Code Property and others first perform contract level vulnerabilities detection Graphs [40] proposed to construct graphs from the C/C++’s and then localize the bugs at line level like MANDO [26] AST by combining it with edges from control flow and and SCScan [14]. SC-VDM [42] converts the bytecode into a program dependence. The control flow edges are inserted for greyscaleimageandappliesaconvolutionalneuralnetworkto subsequent statements, loops, returns, and similar constructs. classify whether a smart contract is vulnerable. Liu et al. [43] The program dependence edges are inserted to reflect the propose to apply a graph convolutional neural network on a influencesofothervariablesorpredicatesonacertainvariable, contract graph of the source code to detect bugs by graph such as the definition or variable assignment. classification. In the follow-up papers, they [19], [20] inte- grate additional expert patterns to increase detection accuracy. Peculiar[38]extractsthedataflowofimportantvariablesofthe X. CONCLUSIONANDFUTUREWORK sourcecodeinacrucialdataflowgraph.Then,thesourcecode In the paper, we present G-Scan , the first end-to-end fine- and the dataflow graph are fed into GraphCodeBERT [13] for grained line-level reentrancy vulnerability detection system reentrancy vulnerability classification. with evaluations on the first-of-its-kind real world dataset. G- Scanfirstconvertssourcecodesmartcontractstocodegraphs, B. Source Code Graphs and then trains node classification models on the graphs to In machine learning based vulnerability detection algo- localize vulnerabilities. Our experiments demonstrate that G- rithms, converting source code into image or texts may lose Scan achieves 93.02% F1-score in contract-level vulnerability structural information. Therefore, many work first convert the detectionand93.69%F1-scoreinline-levelvulnerabilitylocal- source code into graph structure, and then classify the graph ization on the real world dataset. Moreover, G-Scan processes |
using different GNN models. low inference overhead and can localize vulnerabilities within lessthan1.2sfor6kLoCsmartcontracts.Wewillopen-source Heterogeneous Code Graph Heterogeneous code G-Scanalongwithitsdatasettopromoteresearchinthisarea. graph [19], [20], [26], [43] construct graph connections based on the semantic information and program flow paths, which In the future, we plan to extend our real world dataset to is widely used in the smart contract vulnerability detection. includemultiplevulnerabilityannotationsandexploredifferent However, they failed to incorporate code dependencies and code graph representations that may improve GNN classifica- hierarchies into modeling. Liu et al. [19], [20], [43] proposed tion performance. to construct code graph based on three different node types. Major nodes represent important function invocations or critical variables. Other variables are seen as secondary nodes REFERENCES and fallback nodes symbolize a fallback function call. Edges [1] “Access control vulnerabilities in solidity smart contracts,.” [Online]. are defined by the feasible program flow paths. Additionally, Available: https://medium.com/ginger-security/access-control-vulnera an elimination step is performed to reduce the graph size, bilities-in-solidity-smart-contracts-5e0871a00d77 which removes secondary and fallback nodes and redirects [2] “Integeroverflowandunderflowattacksonsmartcontracts,.”[Online]. Available:https://blockgeeks.com/guides/smart-contracts/ the edges. This final normalized graph is fed into a GNN that detects reentrancy, timestamp dependence, and infinite loop [3] A. Ali, Z. U. Abideen, K. Ullah, and F. Ullah, “SESCon: Secure Ethereum Smart Contracts by Vulnerable Patterns’ Detection,” vulnerabilities. MANDO [26]’s code graphs are based on Secur. Commun. Networks, vol. 2021, 2021. [Online]. Available: call graphs and control flows of the source code. It first uses https://doi.org/10.1155/2021/2897565 a multi-metapaths extractor to generate metapaths from the [4] M. Allamanis, “Graph Neural Networks in Program Analysis,” in node types and their associated edges in these graphs. The Graph Neural Networks: Foundations, Frontiers, and Applications, node embeddings are created with these metapaths and fused L. Wu, P. Cui, J. Pei, and L. Zhao, Eds. Singapore: Springer, 2021. [Online]. Available: https://graph-neural-networks.github.io/gnnbook with the metapaths by a heterogeneous attention mechanism Chapter22.html at node level. Afterward, these node embeddings are fed [5] M. Allamanis, M. Brockschmidt, and M. Khademi, “Learning to into an MLP for graph classification to check whether the Represent Programs with Graphs,” CoRR, vol. abs/1711.00740, 2017. contract is vulnerable. If that is the case, the exact location [Online].Available:http://arxiv.org/abs/1711.00740 of the vulnerability inside the contract is determined by node [6] blitz 1306, “Repository solc-typed-ast,” https://github.com/ConsenSys classification with the updated node embeddings in graph /solc-typed-ast,LastAccessonDecember26,2022. classification. [7] P. Bose, D. Das, Y. Chen, Y. Feng, C. Kruegel, and G. Vigna, “SAILFISH: Vetting Smart Contract State-Inconsistency Bugs in AST based Code Graph AST [4], [5], [40] based code Seconds,” CoRR, vol. abs/2104.08638, 2021. [Online]. Available: graphgenerationiswidelyusedincodevulnerabilitydetection https://arxiv.org/abs/2104.08638 13[8] V.Buterin,“EthereumWhitePaper:ANextGenerationSmartContract Contracts,” in 34th IEEE/ACM ASE, 2019. [Online]. Available: & Decentralized Application Platform,” 2013. [Online]. Available: https://doi.org/10.1109/ASE.2019.00133 https://github.com/ethereum/wiki/wiki/White-Paper [24] B. Mueller, “Smashing Ethereum Smart Contracts for Fun and Real [9] N. Fatima Samreen and M. H. Alalfi, “Reentrancy vulnerability Profit,”in9thHITBSecConf,Amsterdam,Netherlands,2018.[Online]. identificationinethereumsmartcontracts,”in2020IEEEInternational Available:https://github.com/b-mueller/smashing-smart-contracts/blob/ Workshop on Blockchain Oriented Software Engineering (IWBOSE), master/smashing-smart-contracts-1of1.pdf 2020.[Online].Available:https://doi.org/10.1109/IWBOSE50093.2020 [25] S. Nakamoto, “Bitcoin: A peer-to-peer electronic cash system,” .9050260 Accessed2022.[Online].Available:http://bitcoin.org/bitcoin.pdf [10] E. Foundation, “Repository Solidity Compiler Solc,” Last Access on [26] H. H. Nguyen, N.-M. Nguyen, C. Xie, Z. Ahmadi, D. Kudendo, December 26, 2022. [Online]. Available: https://github.com/ethereum/ T.-N. Doan, and L. Jiang, “Mando: Multi-level heterogeneous graph solidity/releases embeddingsforfine-graineddetectionofsmartcontractvulnerabilities,” [11] J.-R. Giesen, S. Andreina, M. Rodler, G. O. Karame, and L. Davi, ArXiv,2022.[Online].Available:https://arxiv.org/abs/2208.13252 “Practical mitigation of smart contract bugs,” ArXiv, 2022. [Online]. [27] C. Sendner, H. Chen, H. Fereidooni, L. Petzi, J. Ko¨nig, J. Stang, Available:http://arxiv.org/abs/2203.00364 A.Dmitrienko,A.-R.Sadeghi,andF.Koushanfar,“Smartercontracts: |
[12] G. Grieco, W. Song, A. Cygan, J. Feist, and A. Groce, “Echidna: Detectingvulnerabilitiesinsmartcontractswithdeeptransferlearning,” Effective, Usable, and Fast Fuzzing for Smart Contracts,” in in Proceedings of the 2023 Network and Distributed System Security Proceedings of the 29th ACM SIGSOFT International Symposium on (NDSS)Symposium,ser.NDSS’23,012023. Software Testing and Analysis, ser. ISSTA 2020. New York, NY, [28] D. She, R. Krishna, L. Yan, S. Jana, and B. Ray, “MTFuzz: Fuzzing USA:ACM,2020.[Online].Available:https://doi.org/10.1145/339536 with a Multi-Task Neural Network,” in Proceedings of the 28th 3.3404366 ACM Joint Meeting on European Software Engineering Conference [13] D. Guo, S. Ren, S. Lu, Z. Feng, D. Tang, S. Liu, L. Zhou, and Symposium on the Foundations of Software Engineering, ser. N. Duan, A. Svyatkovskiy, S. Fu, M. Tufano, S. K. Deng, C. B. ESEC/FSE 2020. New York, NY, USA: ACM, 2020. [Online]. Clement, D. Drain, N. Sundaresan, J. Yin, D. Jiang, and M. Zhou, Available:https://doi.org/10.1145/3368089.3409723 “GraphCodeBERT:Pre-trainingCodeRepresentationswithDataFlow,” [29] D. She, K. Pei, D. Epstein, J. Yang, B. Ray, and S. S. Jana, CoRR,2020.[Online].Available:https://arxiv.org/abs/2009.08366 “NEUZZ: Efficient Fuzzing with Neural Program Smoothing,” IEEE [14] X. Hao, W. Ren, W. Zheng, and T. Zhu, “SCScan: A SVM-Based Symposium on Security and Privacy (SP), 2019. [Online]. Available: Scanning System for Vulnerabilities in Blockchain Smart Contracts,” https://doi.org/0.1109/SP.2019.00052 in 2020 IEEE 19th International Conference on Trust, Security [30] S. So, S. Hong, and H. Oh, “SmarTest: Effectively Hunting and Privacy in Computing and Communications (TrustCom), 2020. Vulnerable Transaction Sequences in Smart Contracts through [Online]. Available: https://doi.org/10.1109/TrustCom50675.2020.002 Language Model-Guided Symbolic Execution,” in 30th USENIX 21 SecuritySymposium. USENIXAssociation,2021.[Online].Available: [15] T.H.-D.Huang,“Huntingtheethereumsmartcontract:Color-inspired https://www.usenix.org/conference/usenixsecurity21/presentation/so inspectionofpotentialattacks,”arXivpreprintarXiv:1807.01868,2018. [31] D.Soto,A.Bergel,andA.G.Hevia,“FuzzingtoEstimateGasCosts of Ethereum Contracts,” IEEE ICSME, 2020. [Online]. Available: [16] B. Jiang, Y. Liu, and W. K. Chan, “ContractFuzzer: fuzzing smart contracts for vulnerability detection,” Proceedings of the https://doi.org/10.1109/ICSME46990.2020.00073 33rd ACM/IEEE International Conference on Automated Software [32] The PyG Team, “PyTorch Geometric,” https://www.pyg.org/, Last Engineering, 2018. [Online]. Available: http://dx.doi.org/10.1145/323 AccessonDecember26,2022. 8147.3238177 [33] S. Tikhomirov, E. Voskresenskaya, I. Ivanitskiy, R. Takhaviev, [17] Joa˜o F. Ferreira, “SmartBugs Wild Dataset,” https://github.com/smart E. Marchenko, and Y. Alexandrov, “SmartCheck: Static Analysis bugs/smartbugs-wild,LastAccessonDecember26,2022. of Ethereum Smart Contracts,” in 1st IEEE/ACM WETSEB, 2018. [Online].Available:https://ieeexplore.ieee.org/document/8445052 [18] J. Krupp and C. Rossow, “teEther: Gnawing at Ethereum to Automatically Exploit Smart Contracts,” in 27th USENIX Security [34] Torch Contributors, “PyTorch,” https://pytorch.org/, Last Access on Symposium. Baltimore, MD: USENIX Association, 2018. [Online]. December26,2022. Available: https://www.usenix.org/conference/usenixsecurity18/present [35] C. F. Torres, A. K. Iannillo, A. Gervais, and R. State, “ConFuzzius: ation/krupp Towards Smart Hybrid Fuzzing for Smart Contracts,” CoRR, vol. [19] Z. Liu, P. Qian, X. Wang, Y. Zhuang, L. Qiu, and X. Wang, abs/2005.12156,2020.[Online].Available:https://arxiv.org/abs/2005.1 “CombiningGraphNeuralNetworkswithExpertKnowledgeforSmart 2156 Contract Vulnerability Detection,” IEEE Transactions on Knowledge [36] C. F. Torres, J. Schu¨tte, and R. State, “Osiris: Hunting for Integer and Data Engineering, vol. 1, no. 01, 2021. [Online]. Available: Bugs in Ethereum Smart Contracts,” in Proceedings of the 34th https://doi.org/10.1109/TKDE.2021.3095196 Annual Computer Security Applications Conference, ser. ACSAC [20] Z. Liu, P. Qian, X. Wang, L. Zhu, Q. He, and S. Ji, “Smart Contract ’18. New York, NY, USA: ACM, 2018. [Online]. Available: Vulnerability Detection: From Pure Neural Network to Interpretable https://doi.org/10.1145/3274694.3274737 Graph Feature and Expert Pattern Fusion,” in Proceedings of the [37] W.Wang,J.Song,G.Xu,Y.Li,H.Wang,andC.Su,“ContractWard: Thirtieth International Joint Conference on Artificial Intelligence, Automated Vulnerability Detection Models for Ethereum Smart IJCAI-21, Z.-H. Zhou, Ed. International Joint Conferences on Contracts,” IEEE Transactions on Network Science and Engineering, Artificial Intelligence Organization, 2021. [Online]. Available: https: vol. 8, no. 2, 2021. [Online]. Available: https://doi.org/10.1109/TNSE //doi.org/10.24963/ijcai.2021/379 .2020.2968505 |
[21] L. Luu, D.-H. Chu, H. Olickel, P. Saxena, and A. Hobor, “Making [38] H. Wu, Z. Zhang, S. Wang, Y. Lei, B. Lin, Y. Qin, H. Zhang, Smart Contracts Smarter,” in Proceedings of the 2016 ACM SIGSAC and X. Mao, “Peculiar: Smart Contract Vulnerability Detection Conference on Computer and Communications Security, ser. CCS Based on Crucial Data Flow Graph and Pre-training Techniques,” ’16. New York, NY, USA: ACM, 2016. [Online]. Available: in 2021 IEEE 32nd International Symposium on Software Reliability https://doi.org/10.1145/2976749.2978309 Engineering (ISSRE). IEEE, 2021. [Online]. Available: https: [22] M. I. Mehar, C. L. Shier, A. Giambattista, E. Gong, G. Fletcher, //shangwenwang.github.io/files/ISSRE-21.pdf R. Sanayhie, H. M. Kim, and M. Laskowski, “Understanding a rev- [39] Y. Xu, G. Hu, L. You, and C. Cao, “A novel machine learning- olutionaryandflawedgrandexperimentinblockchain:thedaoattack,” based analysis model for smart contract vulnerability,” Security and JournalofCasesonInformationTechnology(JCIT),vol.21,no.1,pp. CommunicationNetworks,vol.2021,pp.1–12,2021. 19–32,2019. [40] F. Yamaguchi, N. Golde, D. Arp, and K. Rieck, “Modeling and [23] M. Mossberg, F. Manzano, E. Hennenfent, A. Groce, G. Grieco, Discovering Vulnerabilities with Code Property Graphs,” in 2014 J. Feist, T. Brunson, and A. Dinaburg, “Manticore: A User- IEEE Symposium on Security and Privacy, 2014. [Online]. Available: Friendly Symbolic Execution Framework for Binaries and Smart https://doi.org/10.1109/SP.2014.44 14[41] Z. Yang, J. Keung, X. Yu, X. Gu, Z. Wei, X. Ma, and M. Zhang, “A multi-modal transformer-based code summarization approach for smartcontracts,”in2021IEEE/ACM29thInternationalConferenceon ProgramComprehension(ICPC). IEEE,2021,pp.1–12. [42] K. Zhou, J. Cheng, H. Li, Y. Yuan, L. Liu, and X. Li, “SC-VDM: A Lightweight Smart Contract Vulnerability Detection Model,” in Data MiningandBigData,Y.Tan,Y.Shi,A.Zomaya,H.Yan,andJ.Cai, Eds. Singapore:SpringerSingapore,2021. [43] Y. Zhuang, Z. Liu, P. Qian, Q. Liu, X. Wang, and Q. He, “Smart Contract Vulnerability Detection using Graph Neural Network,” in Proceedings of the Twenty-Ninth International Joint Conference on Artificial Intelligence, IJCAI-20, C. Bessiere, Ed. International Joint Conferences on Artificial Intelligence Organization, 2020. [Online]. Available:https://doi.org/10.24963/ijcai.2020/454 15 |
2307.08990 An Empirical Study on Noisy Label Learning for Program Understanding WenhanWang YanzhouLi AnranLi∗ NanyangTechnologicalUniversity NanyangTechnologicalUniversity NanyangTechnologicalUniversity Singapore Singapore Singapore wwhjacob@hotmail.com yanzhou001@e.ntu.edu.sg anran.li@ntu.edu.sg JianZhang WeiMa YangLiu∗ NanyangTechnologicalUniversity NanyangTechnologicalUniversity NanyangTechnologicalUniversity Singapore Singapore Singapore jian_zhang@ntu.edu.sg ma_wei@ntu.edu.sg yangliu@ntu.edu.sg ABSTRACT ACMReferenceFormat: Recently,deeplearningmodelshavebeenwidelyappliedinpro- WenhanWang,YanzhouLi,AnranLi,JianZhang,WeiMa,andYangLiu. 2024.AnEmpiricalStudyonNoisyLabelLearningforProgramUnderstand- gramunderstandingtasks,andthesemodelsachievestate-of-the- ing.In2024IEEE/ACM46thInternationalConferenceonSoftwareEngineering art results on many benchmark datasets. A major challenge of (ICSE’24),April14–20,2024,Lisbon,Portugal.ACM,NewYork,NY,USA, deeplearningforprogramunderstandingisthattheeffectiveness 12pages.https://doi.org/10.1145/3597503.3639217 oftheseapproachesdependsonthequalityoftheirdatasets,and thesedatasetsoftencontainnoisydatasamples.Atypicalkind ofnoiseinprogramunderstandingdatasetsislabelnoise,which 1 INTRODUCTION meansthatthetargetoutputsforsomeinputsareincorrect. Withtherapiddevelopmentofartificialintelligence,moreandmore Researchershaveproposedvariousapproachestoalleviatethe deeplearningmodelsareappliedinprogramunderstanding.Deep negativeimpactofnoisylabels,andformedanewresearchtopic: learning-basedprogramunderstandingiscapableofsolvingawide noisylabellearning(NLL).Inthispaper,weconductanempirical rangeoftasksonprogramsourcecode,fromclassificationtasks studyontheeffectivenessofnoisylabellearningondeeplearn- suchasprogramclassification[28]andvulnerabilityprediction ingforprogramunderstandingdatasets.WeevaluatevariousNLL [49],togenerationtaskssuchascodesummarization[17]. approachesanddeeplearningmodelsonthreetasks:programclas- Manydeeplearningmodelsforprogramunderstandingtasks sification,vulnerabilitydetection,andcodesummarization.From areusuallytrainedinasupervisedlearningparadigm,e.g.,either theevaluationresults,wecometothefollowingfindings:1)small fromscratchorfine-tunedfromapre-trainedmodeltrainedon trained-from-scratchmodelsarepronetolabelnoisesinprogram alargetrainingdataset,andthenevaluatedonatestdataset.It understanding,whilelargepre-trainedmodelsarehighlyrobust isnecessarytoacquirehigh-qualitydatasetsforboththetraining againstthem.2)NLLapproachessignificantlyimprovetheprogram phaseandthetestingphase[19,22].Ontheonehand,noisytraining classificationaccuraciesforsmallmodelsonnoisytrainingsets, datacanleadtoseveremodelaccuracydeterioration.Ontheother buttheyonlyslightlybenefitlargepre-trainedmodelsinclassifi- hand,noisytestingdatacannotaccuratelyevaluatethecapabilityof cationaccuracies.3)NLLcaneffectivelydetectsyntheticnoisesin thetrainedmodel.However,acquiringhigh-qualityandnoise-free programunderstanding,butstruggleindetectingreal-worldnoises. datasetsforprogramunderstandingtasksisextremelychallenging We believe our findings can provide insights on the abilities of [25].Forexample,insomesoftwareengineeringapplications,such NLLinprogramunderstanding,andshedlightonfutureworksin ascodesummarizationandcodesearch,researcherscollectlarge- tacklingnoisesinsoftwareengineeringdatasets.Wehavereleased scaledatasetsfromopen-sourceplatforms,suchasGitHuband ourcodeathttps://github.com/jacobwwh/noise_SE. StackOverflow.Thosecollecteddatasetsareoftentoolargetobe thoroughlyinspectedbyhumanexperts,makingitdifficulttofilter KEYWORDS outnoises.Mostnoisesinsupervisedlearningtaskscanbetreated programunderstanding,deeplearning,noisylabellearning aslabelnoiseswhereinputsamplesdonotmatchtheirtargetlabels. Label noises widely exist in program understanding tasks with ∗Correspondingauthors differentinput-targetdatamodalities.Forexample,inclassification tasks,itreferstothesampleswithincorrectclasslabels,whilein Permissiontomakedigitalorhardcopiesofallorpartofthisworkforpersonalor generationtasks,e.g.,codesummarization,itreferstotheinputs, classroomuseisgrantedwithoutfeeprovidedthatcopiesarenotmadeordistributed forprofitorcommercialadvantageandthatcopiesbearthisnoticeandthefullcitation i.e.,codesnippets,withinconsistentsemantictotargetoutputs, onthefirstpage.Copyrightsforcomponentsofthisworkownedbyothersthanthe i.e., natural language summary. Furthermore, the proportion of author(s)mustbehonored.Abstractingwithcreditispermitted.Tocopyotherwise,or noisylabeleddatainprogramunderstandingdatasetscanbevery republish,topostonserversortoredistributetolists,requirespriorspecificpermission and/orafee.Requestpermissionsfrompermissions@acm.org. high:e.g.,insomevulnerabilitydetectiondatasets,upto70%ofthe ICSE’24,April14–20,2024,Lisbon,Portugal vulnerabilitysamplescouldbemislabeled[8]. ©2024Copyrightheldbytheowner/author(s).PublicationrightslicensedtoACM. Toovercomethenegativeimpactofnoisylabelsondeeplearn- ACMISBN979-8-4007-0217-4/24/04...$15.00 |
https://doi.org/10.1145/3597503.3639217 ing,researchersproposedagroupofnoisylabellearning(NLL) 3202 ceD 13 ]ES.sc[ 2v09980.7032:viXraICSE’24,April14–20,2024,Lisbon,Portugal approaches.Noisylabellearning,orlearningfromlabelnoises,has forsoftwareengineering.Thesemodelsincludebothsmalltrained- becomeanactivefieldinmachinelearning,whichaimstoimprove from-scratchmodelsandstate-of-the-artlargepre-trainedmodels. deeplearningmodels’robustnessagainstlabelnoiseanddetect Ourstudycoversdatasetsinthreedifferenttasks:programclassifica- mislabeledsamplesfromthedatasets[36].Recently,NLLhasat- tion,vulnerabilitydetection,andcodesummarization.Insummary, tractedtheattentionofsoftwareengineeringresearchers[7,10,25]. ourcontributionsareasfollows: AlthoughtheseworksclaimtosuccessfullyapplyNLLtosoftware engineering,theirevaluationsstillhavethefollowinglimitations: (1) Wearethefirsttoconductacomprehensiveempiricalstudy onnoisylabellearninginprogramunderstandingforboth • All of these works only consider classification tasks (e.g. classificationandgenerationtasks. programclassification,defectprediction),whilegeneration (2) WeevaluateNLLapproachesforprogramunderstandingin tasks,e.g.,codesummarization,havenotbeeninvestigated. bothdetectingnoisy-labeleddataandimprovingtheperfor- Actually,generationtaskshavelongbeenneglectedbythe manceofdownstreamtasks.Ourstudyunveilsthestrengths NLLresearchcommunity. andweaknessesofexistingNLLapproachesinprogramun- • Deeplearningmodelsforprogramunderstandingcanbecat- derstanding,andprovidessuggestionsforfutureexploration egorizedintotwotypes:trained-from-scratchmodelswith inthisfield. smallparametersize(wecancallthem“smallmodels"in brief),andlargemodelspre-trainedonmassiveprogram 2 RELATEDWORK language/naturallanguagecorpus(wecallthem“largemod- els").ManyoftheNLLworksmainlyadoptsmallmodels, 2.1 LearningfromNoisyLabeledData whilelargemodelshavealreadydominatedmanyprogram Theimportanceofdataqualityhaslongbeennoticedbyartificial understandingtasks[27]. intelligenceresearchers.Insupervisedlearning,labelnoiseinthe • Mostoftheseworksfocusontacklingtrainingdatanoise[10, trainingdatacanimpairtheperformanceofdeeplearningmodels. 25],becausetheyoftenassumethatitisnotdifficulttobuild Therefore,researchershaveproposedvariousapproachestotackle asmall-scaletestsetwithnonoisylabels.However,inmany thisissue.Table1showsataxonomyofexistingNLLapproaches. programunderstandingtasks,e.g.,vulnerabilitydetection, Theseapproachescanbecategorizedintothefollowinggroups: obtaining accuratelabels is difficultand time-consuming 1)Gradient-basedapproaches:Somemethodstriedtoimprove evenfordomainexperts.Eventhoughthetestsetsareusually therobustnessofneuralnetworksagainstlabelnoisesbymanipu- muchsmallerthantrainingsets,thetimeandmanpower latingthegradient.Forexample,Kohetal.[20]proposedInfluence costsformanuallyannotatingthesedatasetsarestilltoo Function(IF),whichmeasuresthecontributionofeachtraining highforresearchers. samplebyitsinfluenceonthegradientsoftestdata.Althoughtheir As previous works of noisy label learning for software engi- originalmotivationistoexplainthepredictionresultsofdeeplearn- neeringhavetheabovelimitations,asystematicstudyofNLLin ingmodels,researchersalsouseIFfordetectingmislabeleddata software engineering is urgently needed. In this paper, we aim [23,24].Foratrainingsetwithmislabeledsamples,thesamples tofocusonprogramunderstandingtasks,investigatehowlabel withhighinfluencescoresaremorelikelytobenoisy.Pruthietal. noisesaffectthesetasks,andhowNLLcanimprovethem.Wefirst [32]proposedasimilarapproachTracIn,whichoutperformsIFin studytheimpactofdifferenttypesofnoisesondifferentmodels detectingmislabeleddataforimageclassificationdatasets. for program understanding. To achieve this, we inject different 2)Meta-learning:Someotherapproachesusemeta-learningto syntheticnoisesintoanoise-freeprogramclassificationdataset, improverobustnessagainstnoise.Theseapproachesaimtoguide because in this way can we control the rate and pattern of the theupdateofmodelparameterswithasmall,noise-freedataset labelnoises.WefurtherstudytheperformanceofNLLindetect- [21].Shuetal.[35]proposedMeta-Weight-Net,whichusesasmall ingnoisysamplesandimprovingperformancesoncleantestset neural network (meta-net) to learn the weight of each training forprogramclassification.Theperformancesonsyntheticnoises sample.Boththemainmodelandthemetanetaretrainedona maynotaccuratelyreflectthesituationinreal-worldscenarios, metasetthatismuchsmallerthantheoriginaltrainingset.Ifthe so we take a further step to study NLL on real-world noises in metasetiscleanandclass-balanced,thenthemodellearnedwith twoprogramunderstandingtasks:vulnerabilitydetectionandcode Meta-Weight-Netisrobusttobothlabelnoiseandclassimbalance. summarization. Zhengetal.[48]furtherproposedMetaLabelCorrection(MLC), Weaimtoanswerthefollowingresearchquestions: whichaimstoidentifymislabeleddataandpredicttheircorrect class labels. The main obstacle preventing meta-learning-based • RQ1:Howdodifferenttypesofsyntheticlabelnoisesinpro- approachesfromwideapplicationisthatobtaininganoise-free |
gramclassificationaffecttheperformanceofdeeplearning metasetisdifficultorintractableformanytasks. modelswhenNLLisnotintroduced? 3)Sampleselectionduringtraining:Someapproachesaim • RQ2:HowdoexistingNLLapproachesperformondifferent todirectlyselectpossiblecleandatasamplesfromdatasetsand syntheticnoisesinprogramclassification? remove the noisy samples during training [22]. Han et al. [14] • RQ3:HowdoNLLapproachesperformonprogramunder- proposedCo-teaching,whichusestwoidenticalneuralnetworksto standingtaskswithreal-worldnoises? dynamicallyselectpossiblycleansamplesduringtraining.Yuetal. Toanswerthesequestions,weconductexperimentson5NLL [44]proposedCo-teaching+,whichfurtherimprovesCo-teaching approacheswithdifferentdeeplearningmodelsfrequentlyused byfocusingondisagreementsamplesbetweentwonetworks.LiAnEmpiricalStudyonNoisyLabelLearningforProgramUnderstanding ICSE’24,April14–20,2024,Lisbon,Portugal Table1:AtaxonomyforexistingNLLapproaches.Theseap- Task Label Noise Deep Learning Models NLL Approaches Noisy proachesdifferinthefollowingways:whethertheyrequire ClaP sr so ig ficra am tio n Synthetic Trained-from- Co-Teaching t sr ea ti sning/test noise-freeexamples(columnClean)andwhethertheyre- scratch Models RobustTrainer quiretrainingonnoisydatasets(columnTrain). V Dul en te er ca tb ioil nity Real-world Pre-trained ConfidT er na tc LIn earning NoD ise yt Se act med p les Code Models Simifeat Real-world Summarization Category Approach Clean Train Clean test sets Gradient-based TrI aF cI[ n20 [] 32] ✗ ✗ ✓ ✓ Results without NLL Results After NLL Meta-learning Meta-W Me Li Cgh [t 4- 8N ]et[35] ✓ ✓ ✓ ✓ Figure1:Anoverviewofourstudy. Co-teaching[14] ✗ ✓ Sampleselectionduringtraining Co-teaching+[44] ✗ ✓ RobustTrainer[25] ✗ ✓ codesearch.Thefilteringofhigh-qualitydatawascarriedoutin ConfidentLearning[30] ✗ ✓ twosteps:arule-basedsyntacticfilterandasemanticfilterbased Sampleselection(separate) Simifeat[50] ✗ ✗ onavariationalautoencoder(VAE).However,thisapproachonly focusesonthequalityofnaturallanguagequeries(whetherthe queryissimilartohuman-writtenqueriesinStackOverflow),but etal.[25]proposedRobustTrainer,whichisthefirstapproachfor doesnotconsiderthesemanticalrelatednessbetweensourcecode learningonsoftwareengineeringdatawithlabelnoises. andnaturallanguagetexts. 4)Sampleselection(separatetraininganddetection):An- Recently,researchershaveattemptedtoinvestigatetheeffec- othergroupofworksfocusesonseparatingnoisysampledetection tivenessoftask-agnosticNLLmethodsonsoftwareengineering withtrainingonnoisydata.Forinstance,Northcuttetal.[30]pro- tasks.Dauetal.[10]investigatedtheperformanceofinfluence posedConfidentLearning,whichutilizestheclassprobabilities function-based approaches on detecting label noise in program predictedbyatrainedmodeltoidentifypossiblemislabeledsam- classificationdatasets.Theauthorsintroducedrandomlabelnoise ples.Zhuetal.[50]proposedSimifeat,whichcandetectnoisysam- intothedatasetsandevaluatedontwocoderepresentationmod- pleswithapre-trainedmodel.Insteadofusingclassprobabilities, els:ASTNN[46]andCodeBERT[11].Theresultsshowedthatfor Simifeatemploysthefeaturesgeneratedbythefeatureextractor bothmodels,influence-basedmethodsachievedhighaccuracyin networktoidentifynoisysamples. detectingnoisy-labeledtrainingsamples.However,theauthorsdid notevaluatetheperformancegainafterapplyinginfluence-based 2.2 LabelNoiseinSoftwareEngineering approachesfortheclassificationtask.Lietal.[25]proposedRo- bustTrainerandevaluateditsperformanceontwotasks:bugreport Researchersinsoftwareengineeringhaverecognizedthenegative classificationanddefectprediction.AlthoughRobustTrainersuc- impact of label noises, and have proposed different approaches cessfullyimprovedtheclassificationmetricsonthesetwotasks,the to eliminate the noisy-labeled samples in software engineering datasetsusedbytheauthorsweresmall,containingonlyhundreds datasets.Typically,theseapproachesarespecifictoparticulartasks orthousandsofsamples,andthedeeplearningmodelsusedwere ordatasetsandcannotbegeneralizedtootherdomains. basic(simpleMLPandLSTM).Thus,itisstillquestionablewhether Theinvestigationoflabelnoisesinsoftwareengineeringdatasets RobustTrainercanbeappliedtolargerdatasetsandmorecomplex emergesfromsimplebinaryclassificationtasks,suchasbugreport models.Croftetal.[7]appliednoisylabellearningapproachesfor classification and defect prediction. Herzig et al. [15] manually detectingsecurityvulnerabilities.Theirapproachisbasedonexist- checkedover7,000issuereportsfromexistingbugdatabasesand ingNLLmethods(e.g.,confidentlearning)andanassumptionfor foundthatmorethan40%ofthemaremislabeled(e.g.,anissue thevulnerabilitydatasets:vulnerablecodesnippetsmaybelabeled reportof“Refactoring"ismisclassifiedto“Bug").Yatishetal.[43] asclean,butcleansamplesareunlikelytobelabeledasvulnera- comparedthelabelsindefectdatasetslabeledbyheuristicrules ble.Duetothesizeoftheirdatasets,theyonlyuseNLLwithdeep withsoftwaredevelopingteams,andfindoutthatmorethan50% |
learningindetectingnoisysamplesanddidnotusedeeplearning ofdefectivecodesnippetsaremislabeledbyheuristicrules.These inthevulnerabilitydetectiontask. workstriedtoprunenoisylabelsinsoftwareengineeringdatasets byhumanexperts,sotheyhighlydependondomainexpertsand 3 RESEARCHMETHOD cannotbeappliedtolarge-scaledatasets. TheoverviewofourstudyisshowninFig.1.Ourstudyaimsto Forlarge-scale“bigcode"[3]datasets(e.g.,largedatasetsforcode investigate:1)theimpactoflabelnoisesindifferentdeeplearning- summarization,codesearch),researchershaveproposedseveral basedprogramunderstandingmodels,and2)theabilitiesofexisting automaticapproachestoimprovetheirdatasetqualitybyremov- NLLapproachesinimprovingmodelrobustness(improvingperfor- ingnoises.Forexample,Shietal.[34]proposedanapproachfor mancesoncleantestsets)anddetectingnoisy-labeledsamplesin improvingthequalityofcodesummarizationdatasets.Theauthors differentprogramunderstandingtasks. identifiedseveraltypicaltypesoflow-qualitycodesummarization samplesanddevelopedrule-basedapproachestodetectthem.The 3.1 Preliminaries detectedlow-qualitysamplesareeitherremovedorrefinedforthe summarizationtask.Sunetal.[38]proposedalearning-basedap- Whenusingdeeplearningtosolveprogramunderstandingtasks, proachforfilteringhigh-qualitycode-naturallanguagepairsfor wefirstabstractthetaskintoamappingtaskfrominputspaceXICSE’24,April14–20,2024,Lisbon,Portugal Table2:Asummaryoftheprogramunderstandingtasksand 𝑦ˆ =𝑔(𝑦) (𝑔isamappingfunction).Weuseasimplemap- datasetsinthispaper.Datasetsizesareshowninthenumber pingfunctiontoimitatethesecases:werandomlychoose oftraining/validation/testsamples. 𝑘%samplesandchangetheirlabelsfrom𝑦to(𝑦+1)mod𝑁 (𝑁 isthetotalnumberofclassesintheprogramclassifica- Task Style Size Noise tiondataset).Whenadoptingfliplabelnoises,thenoiserate Programclassification classification 45,000/15,000/15,000 synthetic mustbelowerthan50%becauseotherwise,themodelwill Vulnerabilitydetection classification 21,854/2,732/2,732 real-world recognizethenoisyclassasthe“true”classlabel. Codesummarization generation 69,708/8,714/8,714 real-world 3.2.2 VulnerabilityDetection. Invulnerabilitydetection,weuse deeplearningmodelstoclassifycodesnippetsasvulnerableornon- tooutputspaceY.Inmostprogramunderstandingtasks,Xisthe vulnerable,sothistaskcanbeseenasabinaryclassificationtask. spaceofprogramsourcecode.Forclassificationtasks,Yistheset Previousstudiesinvulnerabilitydetectiondatasetsrecognizedthat ofclasslabels;forsummarizationtasks,Yisthespaceofnatural labelnoisesareprevalentinvulnerabilitydatasets,especiallyfor languagesummaries.Wetrainadeeplearningmodel𝑓(𝑥 ∈X)= non-vulnerablelabels[8,9,29].Forthistask,weadopttheDevign 𝑦 ∈YonthetrainingsetD𝑡𝑟𝑎𝑖𝑛tosolvethesoftwareengineering [49]dataset.ThecodesnippetsinDevignarecollectedfromtwo task.Weperformearlystopduringtrainingbyobservingtheresults open-sourceprojectsinC,and46%ofthemarelabeledasvulnerable. onthevalidsetD𝑣𝑎𝑙𝑖𝑑.Thetrainedmodelisfurtherevaluatedon Croftetal.[8]manuallystudied70vulnerable-labeledsamples thetestsetD𝑡𝑒𝑠𝑡. intheDevigndatasetandfoundthat20%ofthemaremislabeled. Inamislabeleddatasample𝑑 ={𝑥,𝑦,𝑦ˆ},𝑦isthegroundtruth label,and𝑦ˆisthenoisylabelfromthedataset.Noticethatinsome 3.2.3 CodeSummarization. Inthecodesummarizationtask,adeep tasks,thegroundtruthlabel𝑦isabsent.Forexample,inthecode learningmodelgeneratethenaturallanguagesummaryofagiven summarizationtask,itisnearlyimpossibletoassigna“perfectly codesnippet.Differentfromclassificationtasks,itisdifficultto correct"summaryforacodesnippet.Inthetraditionalsettingsof determinewhetheracodesnippetis“mislabelled".Inthispaper,if noisylabellearning,only D𝑡𝑟𝑎𝑖𝑛 iscorruptedwithlabelnoises, anaturallanguagesummarycannotdescribethefunctionalityof whileD𝑣𝑎𝑙𝑖𝑑 andD𝑡𝑒𝑠𝑡 areclean.However,insomesoftwareengi- thecorrespondingprogram,wetreatthisdatasampleas“noisy". neeringdatasets,D𝑣𝑎𝑙𝑖𝑑 andD𝑡𝑒𝑠𝑡 canalsobenoisy. Forthistask,weadopttheTLC[18]dataset,whichisaJavacode summarizationdatasetfrequentlyusedinpreviousworks.Apre- 3.2 TasksandDatasets viousstudy[34]claimsthattheTLCdatasetcontainsaround41% ofnoise,buttheirobservationisbasedonrule-basedpatternsand Wechoosethreedifferentprogramunderstandingtasks:program maynotreflectthestandardofhumandevelopers,soweconducta classification,vulnerabilitydetection,andcodesummarizationto humanevaluationofthisdataset.AstheoriginalTLCdatasetistoo evaluatetheperformanceofNLLapproaches.Thechoiceofthese largeforacompletehumanevaluation,werandomlysample100 threetasksallowsustoevaluateNLLunderbothclassification-style code-summarypairsfromthetrainingsetofTLCandasksixPh.D. andgeneration-styletasks,andunderbothsyntheticandreal-world studentsandpostdocsinsoftwareengineeringtoscorethequality noises.ThesummaryofthedatasetsinthisstudyisshowninTable2 ofthesedatapairsfrom0(lowest)to2(highest).Allsixlabelers 3.2.1 ProgramClassification. Intheprogramclassificationtask, areaskedtoscoreall100testsamples,andthefinalqualityscore givenasetofprograms,weneedtoclassifythemintodifferent isacquiredbyaveragingthescoresgivenbyalllabelers.Different categoriesbasedontheirfunctionalities.Forthistask,weadopt scoresaredefinedby: |
theCodeNet[33]dataset.CodeNetiscollectedfromtwoonline • 2:Thesummarydescribesthefunctionalityofthecodesnip- judgingplatforms,whereprogrammersareaskedtosolvevarious pet.Humandevelopersarepossibletogeneratethissummary programmingquestions.Fortheclassificationtask,eachprogram- withoutextracontextinformation. mingquestioncanbeseenasaclasstype.TheCodeNetdataset • 1:Thesummarypartiallydescribesthefunctionalityofthe contains four program classification benchmarks. In these four codesnippet/Thesummarymaybecorrect,butitrelies benchmarks,wechoosetheJava250datasetforourexperiments. onextracontext/Thesummarymaybecorrect,butitcon- Java250datasetcontains75,000Javacodesnippetsin250classes tainsnon-functionaldescriptions(e.g.,securityattributes, andissplitin3:1:1fortrain/validation/testsets.Thecreatorsof I/Oregulations). CodeNethavecleansedtheirdatasetstoensurethateachcodesnip- • 0:Thesummarydoesnotdescribethecode,orThesum- petexactlymatchesitsclasslabel,sothisdatasetcanbeseenas maryheavilyreliesonextracontext,makingitimpossible noise-free. todeterminewhetherthesummaryiscorrect. Toinvestigatetheimpactoflabelnoisesandtheperformanceof Fig.2showsexamplesforeachscoreintheTLCdataset.Gen- NLLapproaches,weinjectthefollowingtypesofsyntheticlabel erally,iftheaveragehumanevaluationscoreofasampleisnot noisesintotheJava250dataset: largerthan1,wecanregardthissampleas“noisy"andviseversa. • Randomlabelnoises:werandomlyselect𝑘%samplesand Fig.3demonstratesthehistogramofhumanevaluationscoreson randomlychangetheirlabel𝑦toadifferentclass𝑦ˆ≠𝑦. theaforementionedsubsetwith100samples.Theaveragequal- • Fliplabelnoises:insomerealisticcasescenarios,samples ityscoreforthesesamplesis1.42.Differentfromtherule-based inclass𝑦aremorelikelytobemislabeledintoasimilarclass analysis[34],wefindthathumanevaluatorsaregenerallysatisfiedAnEmpiricalStudyonNoisyLabelLearningforProgramUnderstanding ICSE’24,April14–20,2024,Lisbon,Portugal Code: Code: Code: public static booleanstartsWith(String s1, public S2Cap complement(){ protected void engineSetPadding(String padding) String s2){ double cHeight=isFull() ? -1 : 2 - throws NoSuchPaddingException{ if (s1 == null || s2 == null) { Math.max(height,0.0); if (!padding.equalsIgnoreCase("NoPadding")) { return false; return S2Cap.fromAxisHeight(S2Point.neg(axis),cHeight); throw new NoSuchPaddingException("Padding " } } + padding + " unknown."); return s1.startsWith(s2); } } Summary: } Return the complement of the interior of the cap. A cap and its Summary: complement have the same boundary but do not share any interior Summary: Check if one string starts with another string. points. The complement operator is not a bijection, since the should never be called. complement of a singleton cap (containing a single point) is the same as the complement of an empty cap. (a): score=2 (b): score=1 (c): score=0 Figure2:Examplesforcodesummarizationdatasampleswitheachscore.(a):atypicalexamplewithscore=2.Thesummary clearlydescribesthefunctionalityofthecodesnippet.(b):anexamplewithscore=1.Thesummarydescribesthecode,butit requiresadditionalcontext(e.g.,APIdoc)tomapthecodetothesummary.Moreover,thesummarycontainsalargeamountof non-functionaldescriptions.(c):anexamplewithscore=0.Thesummaryisirrelevanttothecodesnippet’sfunctionality.Note thatthissamplecannotbedetectedbytherule-basedapproach[34]. consistsoftwosteps:therobustlearningalgorithmforhan- dlinglabelnoises,andclass-balancedsamplingforaddress- ingdataimbalance.Asourstudyfocusesonlabelnoises,we onlyadopttherobustlearningstepofRobustTrainer.Ineach trainingepoch,afterthemodelacquiresthefeaturesforall trainingsamples,RobustTrainercalculatesthesimilarities betweensamplefeaturesandtheirclassprototypes.Theau- thorsfurtheruseaGaussianMixtureModel(GMM)tosplit thesamplesintotwodistributionsbythesimilarityscore: sampleswithhighsimilarityscoresarelikelytobecorrectly Figure3:Histogramoftheaveragehumanevaluationscores labeled,whilelowsimilarityscoresindicatethatthesample onasmallsubsetofTLC. maybenoisy.Theselectedcleansamplesareusedforthe trainingepoch. (4) ConfidentLearning[30]isanapproachforidentifying withthesummarizationqualityoftheTLCdataset.Over80%of labelnoisesinclassificationdatasets.Itisbasedontheas- code-summarypairsarescoredlargerthan1,whileheavilynoisy samples(withascore⩽0.5)onlyconsistoflessthan5%. sumptionofClassificationNoiseProcess[5]:labelnoiseis class-conditional,itonlydependsonthetrueclasslabel,not 3.3 NoisyLabelLearningApproaches thedataitself.ConfidentLearningfirstbuildstheconfidence jointmatrixbetweennoisylabelsandlatent“true"labels, WechooseatleastoneNLLapproachfromallcategoriesinTable1 andthenprunesmislabeleddatabasedontheoff-diagonals exceptMeta-learningbecauseformanyprogramunderstanding oftheconfidencejointmatrix. tasks,suchascodesummarizationandvulnerabilitydetection,it (5) Simifeat[50]isatraining-freenoisedetectionapproach isoftenunfeasibletobuildnoise-freemetasetswithenoughsizes. whichisbasedonfeaturesfrompre-trainedmodels.Asthis Namely,weadoptthefollowingNLLapproaches: approachrequiresapre-traineddeeplearningmodel,itcan (1) TracIn[32].SimilartoInfluenceFunction[20],TracInaims notbeappliedtotrained-from-scratchmodels.Simifeatuses |
topredicttheinfluencescoreofatrainingsampleonatest twodifferentalgorithms:votingandrankingtoselectthe sample.Todetectnoisy-labeledsamples,wecalculatethe mostpossible“true"labelforeachsamplebasedonitsk-NN self-influence,whichreferstotheinfluencescoreofasample neighboursinthefeaturevectorspace.Iftheselectedlabel onitself.Giventheexpectednoiserate𝑘%,wechoosethe isdifferentfromthelabel𝑦ˆfromthedataset,thissampleis 𝑘%sampleswiththehighestinfluencescoresasthenoisy considerednoisy. samplesandremovethemfromthedataset. (2) Co-teaching[14]maintainstwoseparateneuralnetworks withidenticalstructures.IneachtrainingbatchofCo-teaching, 3.4 BaseModels bothnetworksrankallthesamplesinthebatchbytheir traininglosses.Supposetheexpectednoiserateis𝑘%and WhenevaluatingtheperformanceofNLLapproaches,wemust thebatchsizeis𝐵,eachnetworkselects(1−𝑘%)𝐵samples considerthebasedeeplearningmodelsusedforpredictiontasks. withthesmallestlossandfeedsthemtoitspeernetworkfor Labelnoisesmayhavedifferentimpactsonvariousneuralmodels, furthertraining. andhence,weincludedseveraldifferentdeeplearningmodelsinour (3) RobustTrainer[25]usesthelearnedfeaturestoidentify study.Thesemodelsincludesequence-basedandtree/graph-based noisesamplesduringtraining.TheRobustTraineralgorithm modelscommonlyusedforprogramlanguagedata.ICSE’24,April14–20,2024,Lisbon,Portugal Fortheclassification-styletasks,specifically,wehaveselected Table3:Asummaryoftheprogramunderstandingbasemod- thefollowingneuralnetworkmodels: elsandtheirparametersizesusedinourstudy. (1) Trained-from-scratchsmallmodels:Intheearlydays Type Model Parameters ofdeeplearning-basedprogramunderstanding,researchers LSTM 7M oftentreatprogramsassequencesoftokensandusesimple Smalltrained-from-scratch GIN 7M neuralnetworkstomodelprogramtokensequences.One Transformer(summarization) 30M ofthemostfrequentlyusedsequentialmodelisLSTM[16], CodeBERT 125M whichwewillevaluateinourstudy. GraphCodeBERT 125M Largepre-trained Inthepastfewyears,researchershavenoticedthatpro- UnixCoder 125M PLBART 140M gramscontainrichstructuralinformation,andintegrating deepneuralnetworkswithprogramstructurescanboost theperformanceofvariousprogramunderstandingtasks. ManyworksparseprogramsintoASTsandaddcontrolor resultsoncodesummarizationdatasetsinmultipleprogram dataflowedgestobuildprogramgraphs[4,33,41].Many languages. typesofgraphneuralnetworks(GNN)havebeenadopted Table3showsthesummaryofouradoptedprogramunderstand- tolearnonprogramsgraphs,suchasgraphconvolutional ingmodelsintheir parametersizes.All thepre-trainedmodels network(GCN),gatedgraphneuralnetwork(GGNN),and includedinourstudybelongtothepre-trainandfine-tunepara- heterogeneousgraphneuralnetworks.WechooseGraph digm:amodelisfirsttrainedonalargecorpuswithself-supervised IsomorphismNetwork(GIN)[42]forourexperiments. learning,thenfine-tunedforthedownstreamtaskusingthetrain- GINhasbeenselectedasastrongbaselineformanyprogram ingsetofdownstreamtasks.Thesizesofthesemodelsrangefrom comprehensionworks,andhasoutperformedotherGNN 125Mto140Mparameters.Recently,decoder-onlylargelanguage baselinesintheprogramclassificationtask[33,47].Asthe models(LLMs)withlargerthan5Bparametershaveseensuccesses CodeNetdatasethasprovidedparsedprogramgraphs,we insomesoftwareengineeringtasks.Wedonotinvestigatethese useGINontheprogramclassificationtask. modelsinourstudyforthefollowingreasons:first,someLLMs (2) Largepre-trainedmodels:Inrecentyears,largepre-trained [6,31]areclosed-sourceandcannotbetrainedonlargelabeled modelshaveachievedsuccessinnaturallanguageandpro- datasets.Second,thoughLLMshaveshownsatisfyingresultson gramlanguage-relatedtasks.Mostofthesemodelsarebased programgenerationtasks,theystilldonotshowsuperiorityover ontheTransformer[40]architecture.Wechoosethreepre- smallerfine-tunedmodelsonsomeprogramunderstandingtasks trainedTransformerencodermodels:CodeBERT[11],Graph- [37,45]. CodeBERT[13],andUnixCoder[12].Thesethreemodels usethesamearchitectureasRoberta[26].CodeBERTisthe 4 RESEARCHQUESTIONSANDFINDINGS firstbi-modalpre-trainedTransformermodelfornaturallan- RQ1:Howdodifferenttypesoflabelnoisesinprogramclassi- guage and program language. It adopts two pre-training ficationaffecttheperformanceofdeeplearningmodelswhen objectives: masked language model (MLM) and replaced NLLisnotintroduced? tokendetection.GraphCodeBERTfurtheraugmentsCode- ExperimentSetup:ToanswerthisRQ,wefirstrunourselected BERTwithdataflowinformation:itcreatesasimpledata modelsontheoriginalnoise-freeJava250dataset.Thenweinject flowgraphforinputprogramsduringpre-training.Unix- noiseswithdifferentpatternsintotheJava250trainingdatasetand Coderusesabstractsyntaxtree(AST)informationinthe runthesemodelsagain.Weadopt8differentnoiserates:random pre-trainingstage.Furthermore,UnixCodertriedtousethe noisesrangefrom10%to50%,andflipnoisesfrom10%to40%. samemodelforbothitsencoderanddecoder,whichmeans Results:Table5demonstratetheclassificationresultsonJava250 thatitspre-trainedmodelcanbeappliedtobothprogram withdifferentmodels,noises,andNLLapproaches.Wecanobserve understandingandgenerationtasks. |
thatlabelnoiseshavedifferentimpactsondifferentneuralmodels. Smalltrained-from-scratchmodels,i.e.,LSTMandGIN,areprone Forthecodesummarizationtask,weadoptthefollowingencoder- tolabelnoisesintrainingdata.However,largepre-trainedmodels decodermodels: arehighlyrobustagainstlabelnoises,especiallyrandomnoises. (1) Transformer:weuseavanillatrained-from-scratchTrans- Evenwhenthenoiseratioreaches50%,theaccuracydropforthese formerencoder-decoderforthistask.TheTransformeren- modelsisonly1%-2%.Betweenthetwotypesofnoises,allmodelsin codertakesthecodetokensequenceasinput,andthede- ourexperimentaremorepronetolabel-dependentnoise(flipnoise) codergeneratesthenaturallanguagesummarytokens.Sim- thanlabel-independentnoise(randomnoise).Althoughpre-trained ilararchitectureshavebeenappliedtovariouscodesumma- modelsarehardlyaffectedbyrandomlabelnoises,theiraccuracy rizationdatasetsandachieveddesirableresults[1]. canstilldropover10%whentrainedwith40%flipnoises. (2) PLBART[2]isalargeTransformerencoder-decodermodel Tofurtheranalyzethedifferencesbetweensmallmodelsand pre-trainedonbimodaldatainprogramlanguagesandnat- largepre-trainedmodelsontrainingwithnoisylabels,wetake urallanguage.Itisabletocompletevarioussequencegen- adeeperlookintothetrainingprocessofdifferentmodels.Fig.4 erationtasksinsoftwareengineering,codesummarization showstheaveragetraininglossandvalidationsetaccuracyofLSTM beingoneofthem.PLBARThasachievedstate-of-the-art andCodeBERTduringtrainingonthenoisyJava250dataset.WecanAnEmpiricalStudyonNoisyLabelLearningforProgramUnderstanding ICSE’24,April14–20,2024,Lisbon,Portugal Table4:Theclassificationaccuracy(%)and(accuracydifferencewithnoise-freetrainingdata)onJava250datasetwithdifferent noiseratesanddeeplearningmodels. Model Nonoise 10%random 20%random 30%random 50%random 10%flip 20%flip 30%flip 40%flip LSTM 93.04 86.68(6.36) 82.88(10.16) 78.69(14.35) 56.57(36.47) 83.64(9.40) 77.59(15.45) 68.22(24.82) 56.32(36.72) GIN[42] 93.23 89.16(4.07) 86.72(6.51) 83.64(9.59) 78.73(14.50) 85.17(8.06) 81.51(11.72) 73.81(19.42) 61.42(31.81) CodeBERT[11] 98.05 97.57(0.48) 97.26(0.79) 96.87(1.18) 96.05(2.00) 97.43(0.62) 96.05(2.00) 91.22(6.83) 85.58(12.47) GraphCodeBERT[13] 98.26 97.62(0.64) 97.60(0.66) 97.15(1.11) 96.48(1.78) 97.77(0.49) 96.41(1.85) 92.87(5.39) 87.85(10.41) UnixCoder[12] 98.39 97.86(0.53) 97.29(1.10) 97.18(1.21) 96.67(1.72) 97.75(0.64) 96.52(1.87) 93.06(5.33) 90.21(8.18) 60 6 120 6 withtwometrics:theprogramclassificationaccuracyafterapplying 50 5 100 5 )%( ccA234 000 234 ssoL )%( ccA 468 000 234 ssoL NL FL o, ran Cd o-t th ee acp hr ie nc gis aio nn d/r Re oc ba ull s/F tT1 ri an ind ee rt ,e tc ht ein Ng Lm Li asl pa pb re ol ae cd hs ea sm ap rele is n. - 10 1 20 1 tegratedintothetrainingprocessofthemodel𝑓(𝑥).AsforTracIn, 0 1 6 11 16 21 26 0 0 1 6 11 16 21 26 0 confidentLearningandSimifeat,theNLLapproachesareseparated validation E ap cco c (%h ) train loss validation aE cp co (c %h ) train loss frommodeltraining.Theseapproachesfollowthe“detect-retrain" (a) (b) pipeline.Wefirsttrain/fine-tunethemodel𝑓(𝑥)onthenoisytrain- ing set D𝑡𝑟𝑎𝑖𝑛 (for TracIn and Confident Learning), then apply Figure4:Thetraininglossandvalidationaccuracyduring NLLapproacheson𝑓(𝑥)todetectnoisysamples.Wegeneratea trainingon50%randomlabelnoise.(a):LSTM.(b):CodeBERT. “clean"trainingsetD′ 𝑡𝑟𝑎𝑖𝑛byremovingthedetectedsamples,and re-train/fine-tuneanewmodel𝑓′(𝑥)onD′ 𝑡𝑟𝑎𝑖𝑛forevaluation. TogainaclearunderstandingoftheeffectivenessofNLLap- proachesonprogramclassification,weintroduceasimplebaseline seethatforthesmallmodelLSTM,thetraininglossgraduallydrops approach:treatalldatasampleswiththepredictedlabel𝑦′ that duringthewholetrainingprocess,whilethevalidationaccuracy doesnotmatchthelabelinthedataset𝑦ˆasnoisysamples.After reachesthepeakinaround15epochs,thenstartstodrop.Onthe noisedetection,weremovethesuspectednoisydatasamplesand otherhand,forCodeBERT,itslossdecreasesquicklyinthefirstfew retrainthemodel. epochsanditsvalidationaccuracysimultaneouslyreachesthemax- BeyondevaluatingNLLonnoisytrainingsets,wetakeafur- imum.Then,thedropoftraininglossbecomesmuchslower,and therstepofdetectinglabelnoisesintestsets.Inmanyprogram thevalidationaccuracyremainshighformanyepochs.Thisshows understandingdatasets,training,validation,andtestsetsaresplit thatcomparedtotrained-from-scratchmodels,largepre-trained randomlyorbasedonsimpleruleswithoutfurtherdataprocessing, modelsarelesslikelytooverfitthelabelnoises.Thisismainlybe- sotheymaysharesimilarnoises.Inourexperiment,wemakethe causethatpre-trainedmodelshavegainedstrongergeneralization followingassumption:thetraining,validation,andtestsetshave abilitiesfrompre-trainingonunlabeleddata.Pre-trainedprogram |
thesamenoisedistribution.Intheprogramclassificationdataset understandingmodelsdemonstratesimilarbehaviortopre-trained withsyntheticnoise,thismeansthatallthreesubsetsarecorrupted modelsonnaturallanguageprocessingtasks[39]:themodeltrain- withthesamenoisepatternandrate. inghasalong“settling"phaseinwhichthemodelcontinuesto Results:FromtheresultsinTable5,wecanfindthatafterap- learnoncorrectly-labeledsampleswithoutmemorizingmislabeled plyingnoisylabellearningapproaches,theclassificationaccuracies samples. inmostmodelsandnoisesettingsareimproved.Generally,the improvementsonsmallmodelsaresignificant,especiallyforLSTM. AnswertoRQ1:Inprogramclassification,largepre-trained Forexample,with50%randomnoises,mostNLLapproachescan models achieve significantly higher accuracies than small improve accuracy by approximately 20%. In contrast, large pre- trained-from-scratch models under different training label trainedmodelsonlyachievemarginalimprovementsonmostNLL noises.Label-dependentflipnoiseshavealargerinfluenceon approachesbecausetheyarealreadyrobustagainstlabelnoises. mostprogramunderstandingmodelsthanlabel-independent Whenthenoiserateincreases,mostNLLapproachesachieve randomnoises. greater improvements over no NLL, but they also exhibit some extentofdifferencesintheirperformances.Generally,Confident RQ2:HowdoexistingNLLapproachesperformondifferent LearningandTracInarethebest-performingapproachesinpro- syntheticnoisesinprogramclassification? gramclassification.Especially,TracInperformsmuchbetterthan ExperimentSetup:MostexistingNLLapproachesfocusontwo otherapproacheson40%flipnoises.AlthoughRobustTrainerout- goals:detecttraininglabelnoisesorimprovethemodels’robust- performsitsbaselinemethodCo-teachingonsmallbinaryclassi- nessagainstthem.WewillfirstevaluatethecapabilityofNLLon ficationdatasets[25],itdoesnotshowsuperiorityonthenoisy programclassificationinthesetwoobjectives.Wefollowtheexper- programclassificationtask.Sometimesitevenyieldsnegativeim- imentsettingsinpreviousworks:thetrainingsetiscorruptedwith provementsonlargepre-trainedmodels. labelnoises,andthevalidation/testsetsarenoise-free.Werunthe Asforthesimplebaselineapproach,whichdirectlytreatspre- adoptedNLLapproachesondifferentmodelswiththesamenoise dictedlabel𝑦′ ≠𝑦ˆasnoisylabels,itactuallyperformsquitewell settingsinRQ1.WeevaluatetheeffectivenessofNLLapproachesICSE’24,April14–20,2024,Lisbon,Portugal Table5:Theclassificationaccuracy(%)and(theimprovementafterNLL)onthenoise-freeJava250testsetwithdifferentNLL approaches. Model Approach 10%random 20%random 30%random 50%random 10%flip 20%flip 30%flip 40%flip Co-teaching 90.26(3.58) 88.25(5.37) 83.37(4.68) 77.85(21.28) 87.35(3.71) 84.27(6.68) 76.67(8.45) 68.25(11.93) TracIn 90.17(3.49) 89.46(6.58) 84.05(5.36) 76.81(20.24) 88.81(5.17) 88.62(11.03) 73.30(5.08) 69.26(12.94) LSTM ConfidentLearning 90.59(3.91) 86.96(4.08) 81.72(3.03) 65.12(8.55) 87.49(3.85) 86.41(8.82) 75.26(7.04) 60.28(3.96) RobustTrainer 91.37(4.69) 91.29(8.41) 83.98(5.29) 75.64(19.07) 88.96(5.32) 88.47(10.88) 75.41(7.19) 61.79(5.47) Baseline-class 91.82(5.14) 90.23(7.35) 85.11(6.42) 73.13(16.56) 88.58(4.94) 85.43(7.84) 74.64(6.42) 57.69(1.37) Co-teaching 91.28(2.12) 90.73(4.01) 87.18(3.54) 86.42(7.69) 89.25(4.08) 88.41(6.90) 81.02(7.21) 74.03(12.61) TracIn 90.74(1.58) 90.35(3.63) 87.39(3.75) 83.26(4.53) 89.79(4.62) 88.47(6.96) 78.88(5.07) 75.78(14.36) GIN[42] ConfidentLearning 92.08(2.92) 88.95(2.23) 86.94(3.30) 80.78(2.05) 90.51(5.34) 87.68(6.17) 80.01(6.20) 67.13(5.71) RobustTrainer 89.65(0.49) 90.51(3.79) 84.75(1.11) 82.86(4.13) 89.48(4.31) 85.44(3.93) 76.37(2.56) 59.51(-1.91) Baseline-class 92.21(3.05) 90.95(4.23) 87.02(3.38) 85.63(6.90) 90.55(5.38) 87.48(5.97) 77.00(3.19) 65.23(3.81) Co-teaching 97.58(0.01) 97.40(0.14) 97.05(0.28) 96.43(0.38) 97.52(0.09) 96.95(0.90) 91.29(0.07) 86.28(0.70) TracIn 97.85(0.28) 97.80(0.54) 97.44(0.47) 96.83(0.78) 97.90(0.47) 97.78(1.73) 96.70(5.48) 97.06(11.48) ConfidentLearning 98.05(0.48) 97.81(0.55) 97.47(0.60) 96.69(0.64) 98.02(0.59) 97.71(1.66) 96.79(5.57) 94.27(8.69) CodeBERT[11] Simifeat 97.60(0.03) 96.76(-0.50) 96.66(-0.21) 96.21(0.16) 97.49(0.06) 96.79(0.74) 91.12(-0.10) 89.83(4.25) |
RobustTrainer 97.65(0.08) 97.05(-0.21) 96.92(0.05) 97.01(0.96) 97.71(0.28) 96.61(0.56) 93.19(1.97) 84.87(-0.71) Baseline-class 97.91(0.34) 97.81(0.55) 97.76(0.89) 97.23(1.18) 97.94(0.51) 97.25(1.30) 96.42(3.20) 91.79(6.21) Co-teaching 97.64(0.02) 97.65(0.05) 97.35(0.20) 96.91(0.43) 97.77(0.00) 97.66(1.25) 92.87(0.00) 90.19(2.34) TracIn 98.16(0.54) 98.14(0.54) 97.30(0.15) 97.16(0.68) 98.00(0.23) 97.82(1.41) 97.44(4.57) 97.21(9.36) ConfidentLearning 98.24(0.62) 97.99(0.39) 97.76(0.61) 97.13(0.65) 98.26(0.49) 98.05(1.64) 97.10(4.23) 94.63(6.78) GraphCodeBERT[13] Simifeat 97.67(0.05) 97.22(-0.38) 97.13(-0.02) 96.54(0.06) 97.85(0.08) 97.35(0.94) 94.12(1.25) 90.50(2.65) RobustTrainer 97.96(0.34) 97.59(-0.01) 97.51(0.36) 97.66(1.18) 97.96(0.19) 96.78(0.37) 93.03(0.16) 88.13(0.28) Baseline-class 98.12(0.50) 98.06(0.46) 97.94(0.79) 97.47(0.99) 98.02(0.25) 97.72(1.31) 95.89(3.02) 92.73(4.88) Co-teaching 97.99(0.13) 97.62(0.33) 97.26(0.08) 97.05(0.38) 97.89(0.14) 97.39(0.87) 94.05(0.99) 92.41(2.20) TracIn 98.25(0.39) 98.25(0.96) 97.59(0.33) 97.49(0.82) 98.06(0.31) 98.18(1.66) 97.35(4.29) 97.31(7.10) ConfidentLearning 98.32(0.46) 98.06(0.77) 97.85(0.67) 97.37(0.70) 98.29(0.54) 98.20(1.68) 97.37(4.31) 95.19(4.98) UnixCoder[12] Simifeat 97.86(0.00) 97.25(-0.04) 97.22(0.04) 96.55(-0.12) 97.81(0.06) 97.31(0.79) 93.01(-0.05) 92.69(2.48) RobustTrainer 97.95(0.09) 97.48(0.19) 97.07(-0.11) 97.06(0.39) 97.85(0.10) 97.42(0.90) 94.18(1.12) 91.59(1.38) Baseline-class 98.26(0.40) 98.02(0.73) 97.71(0.53) 97.81(1.14) 98.11(0.36) 98.03(1.51) 95.22(2.16) 93.67(3.46) inourexperiments.Ontherandomnoisesettings,thisbaselineof- NLLapproachesperformsimilarly.largemodelsperformbetter tenoutperformsmostNLLapproaches.However,onflipnoises,its thantrained-from-scratchmodelsinnoisedetection,suggesting performanceislowerthanTracInandConfidentLearning.Theclas- thatprogramunderstandingmodelswithstrongercapabilitiesare sificationaccuraciesonSimifeatwithpre-trainedmodelsarelower alsobetteratdetectingnoisylabels. thanotherapproaches.WebelievethisisbecausethatSimifeatdoes Table7demonstratestheevaluationmetricsindetectingtest notrequiretraining/fine-tuningontheclassificationdataset. datanoisesfortheprogramclassificationdataset.Generally,the Table6showstheprecision,recall,andF1indetectinglabel performances of NLL approaches are similar, but a little lower noises in the Java250 training dataset. We only include the ap- thantheirresultsindetectingtrainingdatanoises.Anunexpected proachesthatseparatemodeltrainingfromnoisedetection(ordo differenceisthatTracInperformsmuchworseontestsetsthanon notinvolvemodeltraining),becauseforapproachesintegratedwith trainingsets,especiallyinlownoiserates.ConfidentLearningis training,their“predictednoisysamples"arecontinuouslychanging thebest-performingNLLapproachinmostnoisesettingsexcept duringdifferenttrainingepochs. for40%flipnoises. Fromtheresults,wecanseethatmostNLLapproachesperform wellindetectingnoisytrainingdataandachieveanF1scoreover Answer to RQ2: Most existing noisy label learning ap- 0.85,exceptforSimifeat.Theresultsinnoisydatadetectionare proachescanmarginallyimproveperformanceoncleantest consistentwiththeaccuraciesontheclassificationtask:NLLap- setsforprogramclassification,buttheydonotshowsignifi- proacheswithhigherclassificationaccuraciestendtohavehigher cantsuperiorityoverasimplebaselineonmanynoisesettings. F1valuesinnoisydatadetection.ConfidentLearningperformsbest TheimprovementsofNLLapproachesonsmalltrained-from- inmostsettingswithlownoiserates,whileTracInexcelsinhigh scratchmodelsarelargerthanonlargepre-trainedmodels. noiserates.Nevertheless,thebaselineachievescomparableresults Largepre-trainedmodelsintegratedwithNLLapproachescan inmostnoisesettings.ComparedtoNLLapproaches,thebaseline’s serveaswell-performinglabelnoisedetectorsfordetecting recallishigher,andprecisionislower,indicatingthatitislikely bothtrainingandtestdatanoiseintheprogramclassification toreportmorefalsepositivenoisesamples.NoticethatTracInhas task,althoughasimplebaselinecanachievesimilarresults. equalprecision/recall/F1ineachexperimentsetting:thisisbecause theassumednoiserateisequaltotheactualnoiserate,resulting inthesamenumberofactualnoisesamplesandsamplesdetected |
RQ3:HowdoNLLapproachesperformonprogramunder- asnoise,whichleadstothesameprecisionandrecall.With most standingtaskswithreal-worldnoises?AnEmpiricalStudyonNoisyLabelLearningforProgramUnderstanding ICSE’24,April14–20,2024,Lisbon,Portugal Table6:Theprecision/recall/F1intrainingdatanoisedetectionwithdifferentnoiserates,models,andnoisylabellearning approachesontheJava250dataset. Model Approach 10%random 20%random 30%random 50%random 10%flip 20%flip 30%flip 40%flip P R F1 P R F1 P R F1 P R F1 P R F1 P R F1 P R F1 P R F1 TracIn 74.17 74.17 74.17 82.51 82.51 82.51 80.05 80.05 80.05 85.70 85.70 85.70 72.96 72.96 72.96 84.27 84.27 84.27 71.82 71.82 71.82 69.11 69.11 69.11 LSTM ConfidentLearning 84.78 79.33 81.96 90.95 84.58 87.65 88.57 76.31 81.99 82.18 82.34 82.26 85.23 72.81 78.53 77.50 87.72 82.30 87.15 68.0 76.39 59.98 65.94 62.82 Baseline-class 76.37 94.11 84.32 72.65 99.96 84.15 71.38 98.53 82.79 74.04 99.83 85.02 64.25 97.72 77.53 60.74 91.43 72.99 65.48 94.74 77.44 56.10 70.55 62.50 TracIn 74.00 74.00 74.00 84.42 84.42 84.42 80.20 80.20 80.20 84.56 84.56 84.56 75.11 75.11 75.11 73.57 73.57 73.57 76.21 76.21 76.21 69.71 69.71 69.71 GIN[42] ConfidentLearning 92.21 80.27 85.83 90.65 85.72 88.12 92.53 81.90 86.89 91.66 84.24 87.10 91.18 78.82 84.55 77.03 89.09 82.62 75.11 85.27 79.87 59.86 65.11 62.38 Baseline-class 82.68 94.16 88.05 75.50 99.98 86.03 76.98 96.67 88.62 85.71 99.94 91.36 78.15 69.47 73.55 62.54 91.58 74.33 66.91 80.91 73.25 56.43 68.41 61.85 TracIn 80.53 80.53 80.53 94.21 94.21 94.21 91.13 91.13 91.13 98.37 98.37 98.37 84.87 84.87 84.87 93.69 93.69 93.69 94.01 94.01 94.01 94.35 94.35 94.35 CodeBERT[11] ConfidentLearning 98.99 95.60 97.26 99.04 93.97 96.43 99.22 94.46 96.78 99.18 94.61 96.84 96.78 96.93 96.85 96.80 96.56 96.68 93.34 93.82 93.58 91.79 89.74 90.75 Simifeat 67.42 61.09 64.10 61.10 78.56 68.74 60.94 68.25 64.39 82.75 60.20 69.70 63.77 55.51 59.35 56.67 70.10 62.67 64.87 73.64 68.98 65.23 51.94 57.83 Baseline-class 88.41 100.0 93.85 92.73 100.00 96.23 95.34 99.99 97.61 96.88 99.99 98.41 88.36 99.73 93.70 89.91 98.57 94.04 83.99 97.88 90.41 82.37 95.30 88.37 TracIn 85.47 85.47 85.47 96.41 96.41 96.41 93.02 93.02 93.02 99.17 99.17 99.17 84.31 84.31 84.31 95.82 95.82 95.82 94.97 94.97 94.97 93.08 93.08 93.08 GraphCodeBERT[13] ConfidentLearning 98.98 94.71 96.79 99.16 95.04 97.06 99.17 94.94 97.01 99.35 93.53 96.36 97.06 97.08 97.07 96.92 97.04 96.98 95.22 92.87 94.03 92.22 89.41 90.79 Simifeat 66.39 59.51 62.76 57.36 85.26 68.58 67.77 60.84 64.12 79.31 73.06 76.06 63.31 69.33 66.18 62.18 59.67 60.90 73.66 61.79 67.21 69.37 61.26 65.06 Baseline-class 87.29 99.98 93.20 94.47 99.98 97.15 95.43 99.99 97.66 97.29 99.99 98.62 89.82 99.82 94.55 90.23 98.57 94.21 87.23 97.98 92.29 84.11 94.49 89.00 TracIn 90.24 90.24 90.24 97.43 97.43 97.43 92.95 92.95 92.95 99.31 99.31 99.31 83.71 83.71 83.71 96.62 96.62 96.62 93.15 93.15 93.15 95.83 95.83 95.83 UnixCoder[12] ConfidentLearning 96.96 92.87 94.87 98.57 89.23 93.67 99.80 92.75 96.15 99.30 92.07 95.55 97.91 94.02 95.93 95.14 93.90 94.51 97.87 91.53 94.59 93.69 92.66 93.17 Simifeat 63.78 70.87 67.14 68.56 81.67 74.54 62.30 66.10 64.14 85.72 65.20 74.06 65.54 46.80 54.61 60.19 72.38 65.72 56.42 61.12 58.67 70.50 47.78 56.96 Baseline-class 93.48 98.13 95.74 94.03 99.98 96.91 92.23 97.87 94.96 96.72 99.99 98.32 92.35 98.93 95.53 87.86 100.00 93.54 90.61 98.16 94.23 91.15 95.98 93.50 Table7:Theprecision/recall/F1intestdatanoisedetectionwithdifferentnoiserates,models,andnoisylabellearningapproaches ontheJava250dataset. Model Approach 10%random 20%random 30%random 50%random 10%flip 20%flip 30%flip 40%flip P R F1 P R F1 P R F1 P R F1 P R F1 P R F1 P R F1 P R F1 TracIn 67.31 67.31 67.31 76.15 76.15 76.15 81.02 81.02 81.02 85.82 85.82 85.82 80.83 80.83 80.83 79.91 79.91 79.91 67.95 67.95 67.95 71.04 71.04 71.04 LSTM ConfidentLearning 81.09 78.33 79.69 80.37 80.67 80.52 78.24 73.84 75.98 73.42 84.48 78.56 74.75 80.51 77.52 62.62 84.00 71.75 75.31 69.4 72.23 55.48 65.17 59.93 Baseline-class 70.42 96.20 81.32 60.54 99.93 75.40 69.99 97.16 81.36 67.38 99.73 80.43 60.33 97.16 74.44 48.77 89.83 63.82 52.62 88.24 65.93 52.35 71.53 60.46 |
TracIn 71.06 71.06 71.06 78.63 78.63 78.63 79.90 79.90 79.90 86.85 86.85 86.85 71.95 71.95 71.95 67.30 67.30 67.30 71.46 71.46 71.46 67.10 67.10 67.10 GIN[42] ConfidentLearning 85.72 78.56 81.98 83.50 83.33 83.42 89.20 74.09 80.95 91.08 83.49 87.12 86.16 81.2 83.61 68.76 86.07 76.45 81.64 73.18 77.18 57.09 65.28 60.91 Baseline-class 80.71 91.93 85.95 65.57 99.93 79.19 79.16 89.20 83.88 83.23 99.92 90.81 78.99 84.98 81.88 54.43 91.03 68.13 71.43 74.61 72.98 54.24 70.27 61.26 TracIn 73.23 73.23 73.23 79.83 79.83 79.83 85.76 85.76 85.76 94.56 94.56 94.56 83.60 83.60 83.60 79.90 79.90 79.90 87.52 87.52 87.52 91.90 91.90 91.90 CodeBERT[11] ConfidentLearning 99.76 91.47 95.43 96.69 92.47 94.53 98.57 91.27 94.78 98.89 92.76 95.73 98.06 85.27 91.22 95.40 96.10 95.75 99.09 81.48 89.43 82.29 79.80 81.03 Simifeat 54.22 58.02 56.05 51.24 76.60 61.40 65.16 61.04 63.04 81.62 55.23 65.88 56.52 73.88 64.04 46.95 69.03 55.89 80.28 57.34 66.9 60.91 53.98 57.24 Baseline-class 89.51 95.80 92.55 89.15 100.00 94.27 88.75 100.0 94.04 95.88 100.00 97.89 79.32 91.89 85.14 88.43 99.90 93.82 82.06 97.87 89.27 73.16 83.18 77.85 TracIn 76.31 76.31 76.31 81.17 81.17 81.17 83.88 83.88 83.88 95.24 95.24 95.24 84.17 84.17 84.17 81.20 81.20 81.20 89.46 89.46 89.46 93.20 93.20 93.20 GraphCodeBERT[13] ConfidentLearning 99.10 88.36 93.42 98.53 91.70 94.99 99.98 90.45 94.98 99.24 92.55 95.77 98.24 80.78 88.66 95.98 95.50 95.74 99.15 84.46 91.22 89.74 87.75 88.73 Simifeat 57.69 64.0 60.68 46.87 68.13 55.53 55.04 67.93 60.81 77.84 47.69 59.14 83.6 59.83 69.74 44.32 64.33 52.48 54.12 82.76 65.44 59.50 51.85 55.41 Baseline-class 89.17 97.33 93.07 91.60 99.97 95.60 93.57 98.67 96.05 96.47 99.99 98.20 90.11 94.11 92.07 89.11 99.03 93.81 88.78 99.31 93.75 82.90 91.87 87.15 TracIn 82.97 82.97 82.97 90.00 90.00 90.00 87.77 87.77 87.77 97.39 97.39 97.39 80.06 80.06 80.06 89.80 89.80 89.80 92.37 92.37 92.37 96.03 96.03 96.03 UnixCoder[12] ConfidentLearning 96.78 91.6 94.12 98.13 90.97 94.41 98.21 91.9 94.95 98.67 90.81 94.58 93.98 91.89 92.92 95.79 94.57 95.17 97.56 88.16 92.62 92.83 92.17 92.50 Simifeat 49.88 64.78 56.36 58.50 84.30 69.07 52.88 64.75 58.21 88.85 65.81 75.61 55.56 72.16 62.78 52.74 74.27 61.68 67.15 57.36 61.87 52.67 55.85 54.21 Baseline-class 88.95 96.04 92.36 92.45 99.97 96.06 94.83 99.3 97.01 95.45 100.00 97.58 88.41 96.27 92.17 90.10 100.00 94.79 88.75 97.96 93.13 91.42 97.98 94.59 Table8:Theprecision/recall/F1indetectingnoisy-labeled samples in the human-verified subset within the Devign trainingset. Model Approach P R F1 TracIn20% 33.33 36.36 34.78 LSTM TracIn50% 26.67 72.73 39.02 ConfidentLearning 75.0 54.55 63.16 Baseline-class 53.85 63.64 58.33 TracIn20% 50.00 54.55 52.17 (a)Losses (b)TracInscores CodeBERT[11] TracIn50% 30.00 81.82 43.90 ConfidentLearning 88.89 72.73 80.00 Baseline-class 69.23 81.82 75.00 TracIn20% 66.67 72.73 69.57 Figure5:AcomparisonbetweenNLLapproaches(TracInand GraphCodeBERT[13] TracIn50% 36.67 100.0 53.66 loss)andhumanevaluationontheTLCcodesummarization ConfidentLearning 87.5 63.64 73.68 Baseline-class 75.0 81.82 78.26 testsubset.(a):Losses.(b):TracInscores. TracIn20% 66.67 72.73 69.57 UnixCoder[12] TracIn50% 36.67 100.0 53.66 ConfidentLearning 69.23 81.82 75.00 Baseline-class 66.67 90.91 76.92 etal.[8]createdasubsetwith70vulnerable-labeledsamples,in which20%ofthemaremislabeled.Amongthese70examples,60of ToanswerthisRQ,weadopttwotaskswithreal-worldnoises themareinthetrainingsetofDevign,andweusethemtomeasure intheirdatasets:vulnerabilitydetectionandcodesummarization. thecapabilityofNLLapproachestodetectnoisy-labeledsamples. ExperimentSetup:Forvulnerabilitydetection,weinvestigate AsourpriorknowledgeofDevignnoiseratemaynotbeaccurate, theperformancesofTranIn,ConfidentLearning,andSimifeatin weadopttwodifferentsuspectednoiserates:20%and50%when detectingnoisysamples,similartoourexperimentinRQ2.Croft evaluatingTracIn.ICSE’24,April14–20,2024,Lisbon,Portugal NearlyalloftheexistingNLLapproachesarebuiltforclassifica- Code: public void or(Criteria criteria){ tiontasks,somostofthemcannotbeappliedtocodesummarization. }oredCriteria.add(criteria); WeonlyinspectTracIninthisexperimentbecauseTracInonlyre- (a) Summary: This method was generated by MyBatisGenerator. This method liesondatagradientswithoutpriorassumptionsonthetasktype. corresponds to the database table company_application Human eval: 0 |
W tere mco inm ep thar ee liT kr ea lc ihIn oow dit oh fa nosi im syp sle amba ps le el si .n Se a: mus pe let she wl io thss hv igal hu ee rs lt oo ssd ee s- G t ch oe i rsn r ee m sra e pt t oe h nd o d do s u w tot ap s tu h gt e: e n de atr aa bte ad s eb y ta m bly eb ua st eis rgenerator . this method T Lora sc sI :n 0: .0 4. 80 20 92 4 RaR na kn : k 1: 3 17 Code: aremorelikelytobenoisyorlow-qualitysummarizationdata.We public boolean initStream(ReadStream readStream,ReadStream rawStream) throws IOException { usethesubsetwith100samplesandtheirhumanevaluationscores r re ea td uS rt nr e ta rm u. ei ;nit(_inStream); } inSection3.2.3forourexperiment.Thehumanevaluationscores (b) Summary: arecomputedbyaveragingthescoresofthesixannotatorsranging Initialize the read stream from the raw stream. Human eval: 2 TracIn: 0.0027 Rank: 20 from0to2. G ine itn iae lr ia zete td h eo u retp au dt s: tream . Loss: 0.8441 Rank: 21 Forthecodesummarizationtask,thereisnoclearboundary Code: between“noisy"and“clean"samples,sowecannotperformquan- public void endElement(String qName) throws SAXException { if (!namespaces) { titativeanalysislikedetectingnoisysamplesforcodeclassifica- i f c( oc no tn et ne tn Ht aH na dn ld el re .r e n! d= E ln eu ml el n) t ({ "","",qName.intern()); } tion.Instead,weanalyzethedistributionofscoresgivenbyNLL return; } approachesandcheckwhethertheyareconsistentwiththedistri- String names[]=processName(qName,false,false); if (contentHandler != null) { butionofhumanevaluationscores. contentHandler.endElement(names[0],names[1],names[2]); Enumeration prefixes=nsSupport.getDeclaredPrefixes(); Results:Table8exhibitstheresultsofnoisylabeldetectionin (c) while (prefixes.hasMoreElements()) { String prefix=(String)prefixes.nextElement(); thehuman-verifiedDevignsubset[8].WedonotevaluateSimifeat } contentHandler.endPrefixMapping(prefix); } becausethesubsetistoosmalltoperformclusteringalgorithms. nsSupport.popContext(); } We find that the performances of NLL approaches in detecting Summary: noisesaremuchlowerthaninprogramclassificationdatasetswith A evd ea np tt .er implementation method; do not call. Adapt a SAX1 end element Human eval: 0.5 syntheticnoises.Meanwhile,TracIn,whichperformedverywell Generated output: T Lora sc sI :n 3: .0 2. 80 01 15 1 R aR na kn :k 9: 592 onsyntheticnoises,fallsbehindotherapproachesandperforms receive notification of the end of an element . muchworsethanournaivebaseline.Ontheotherhand,Confident Figure6:CasesfromTLC’ssubsetwithhumanevaluation Learning performs better and achieved F1 scores similar to the scoresandTracIn/lossrankings.TheTracIninfluencesand baseline. lossesarerankedfromlowtohighwithinthe100samples. Fig.5showsthedistributionofTracInscoresandlossesacross TheTracIninfluence,loss,andgeneratedsummaryarepro- differenthumanevaluationscores.WefurtheradoptSpearman’s ducedfromPLBART. rankcorrelationcoefficienttomeasuretherelevancebetweenhu- manevaluationandlosses/TracInscores.Ifloss/TracInareeffective AnswertoRQ3:ExistingNLLapproachesstillhavemuch fordetectingnoisesincodesummarization,theyshouldhaveneg- roomforimprovementwhendealingwithreal-worldlabel ativecorrelationswithhumanevaluationscores.Wefindthatfor noisesinprogramunderstanding,especiallyingeneration- bothmodels,theirlossesnegativelycorrelatewithhumanevalua- styletasks. tionscores(correlationsarenegative,and𝑝 < 0.05).Thismeans thatcodesummarizationsampleswithhighqualitytendtohave 5 THREATSTOVALIDITY lowerlosses.However,thereisnosignificantcorrelationbetween theTracIninfluencescoresandhumanevaluation(𝑝 > 0.05),in- Usageofsyntheticlabelnoises.Fortheprogramclassification dicatingthatTracInisineffectivefordetectingnoisysamplesfor task,weonlyusesyntheticlabelnoisebecausetheoriginaldataset codesummarizationdatasets,andisaworsenoisedetectorthan is clean, and we are able to investigate the impact of different simplyusinglosses. noiseratesandpatternswithsyntheticnoises.Tomitigatethis TobetterunderstandNLL’sabilitytoidentifynoisycodesum- threat, we use multiple noise patterns to mimic different cases marizationsamples,weuseseveralexamplestodemonstratethe of noises in different program understanding datasets. We also similaritiesanddifferencesbetweenNLLapproachesandhuman conductexperimentsontwodifferenttaskswithreal-worldnoises: evaluation.Fig.6showsthreeexamplesinour100-samplecode vulnerabilitydetectionandcodesummarization. summarizationsubset.Wecanobservethatforexamples(b)and(c), Humanannotationofdatasets.Inourcodesummarization thehumanevaluationscoresareconsistentwithTracIninfluence experiments,weusehumanannotationstojudgethequalityof andloss.Sampleswithhighhumanevaluationscoreshavelow code-summarypairs,thescoresgivenbyhumanannotatorsmay TracIninfluence/lossandviceversa.However,forexample(a),NLL notaccuratelyreflecttherelatednessbetweenthecodeandsum- |
approachesgivewrongpredictions.Itssummarydoesnotdescribe mary. To alleviate this threat, we choose six annotators whose thecode,buttheTracIninfluenceandlossarerelativelylow.We expertiseisinsoftwareengineeringandusetheiraveragescoresas assumethisisbecausethissummarypatternfrequentlyoccursin thefinalhumanevaluationscore.Inthefuture,wehopetolever- thetrainingset,whichmakesthemodelgenerateanoutputsimilar agetheabilityoflargedataannotationteamstobuildhigh-quality, tothelow-qualitysummaryinthissample.Thiswillresultinalow noise-freecodesummarizationdatasetsonlargerscalesforaccurate lossandgradient,thusleadingtoalowTracInscore. evaluation. LimitationinthechoiceofNLLapproaches.IntheAIcom- munity,thereexistsalargenumberofNLLapproaches,someofAnEmpiricalStudyonNoisyLabelLearningforProgramUnderstanding ICSE’24,April14–20,2024,Lisbon,Portugal whicharenotdiscussedandevaluatedinourstudy.Tomakeour [8] RolandCroft,MAliBabar,andMMehdiKholoosi.2023.Dataqualityforsoftware studyrepresentativeofmostNLLapproaches,wemakeataxonomy vulnerabilitydatasets.In2023IEEE/ACM45thInternationalConferenceonSoftware Engineering(ICSE).IEEE,121–133. ofexistingNLLapproachesbasedontheirmachinelearningtech- [9] RolandCroft,YongzhengXie,andMuhammadAliBabar.2022. Dataprepara- niques,andpickrepresentativeapproacheswithineachcategory tionforsoftwarevulnerabilityprediction:Asystematicliteraturereview.IEEE suitableforprogramunderstandingtasks. TransactionsonSoftwareEngineering49,3(2022),1044–1063. [10] AnhTVDau,NghiDQBui,ThangNguyen-Duc,andHoangThanh-Tung.2022. TowardsUsingData-InfluenceMethodstoDetectNoisySamplesinSourceCode Corpora.In37thIEEE/ACMInternationalConferenceonAutomatedSoftware 6 CONCLUSION Engineering.1–3. [11] ZhangyinFeng,DayaGuo,DuyuTang,NanDuan,XiaochengFeng,MingGong, Inthispaper,weconductthefirstempiricalstudyonnoisylabel LinjunShou,BingQin,TingLiu,DaxinJiang,etal.2020. CodeBERT:APre- learningforprogramunderstanding.Inparticular,wearethefirst TrainedModelforProgrammingandNaturalLanguages.InFindingsoftheAsso- toinvestigateNLLforgenerationtasksinprogramunderstanding, ciationforComputationalLinguistics:EMNLP2020.1536–1547. [12] DayaGuo,ShuaiLu,NanDuan,YanlinWang,MingZhou,andJianYin.2022. whichhasnotbeenexploredbefore.Ourevaluationresultsshow UniXcoder:UnifiedCross-ModalPre-trainingforCodeRepresentation.InPro- thatNLLapproachesaremorehelpfultosmalltrained-from-scratch ceedingsofthe60thAnnualMeetingoftheAssociationforComputationalLinguistics modelsthanlargepre-trainedmodels.Althoughsomeapproaches (Volume1:LongPapers).7212–7225. [13] DayaGuo,ShuoRen,ShuaiLu,ZhangyinFeng,DuyuTang,LIUShujie,Long achievesatisfactoryresultsonsyntheticnoises,theystillstruggle Zhou,NanDuan,AlexeySvyatkovskiy,ShengyuFu,etal.2021.GraphCodeBERT: indetectingreal-worldnoisesinprogramunderstandingdatasets. Pre-trainingCodeRepresentationswithDataFlow.InInternationalConference onLearningRepresentations. Inthefuture,themaintrendindeeplearningforprogramunder- [14] BoHan,QuanmingYao,XingruiYu,GangNiu,MiaoXu,WeihuaHu,IvorTsang, standingistheincreasingpopularityoflargepre-trainedmodels, andMasashiSugiyama.2018.Co-teaching:Robusttrainingofdeepneuralnet- andpromptlearningwithGPT-basedmodelsislikelytosurpass workswithextremelynoisylabels.Advancesinneuralinformationprocessing systems31(2018). traditionalsupervisedlearninginmanytasks.Therefore,rather [15] KimHerzig,SaschaJust,andAndreasZeller.2013.It’snotabug,it’safeature: thanusingNLLtoenhancemodelrobustnessagainsttraininglabel howmisclassificationimpactsbugprediction.In201335thinternationalconference noises,webelieveitismoremeaningfultoutilizeNLLtoassist onsoftwareengineering(ICSE).IEEE,392–401. [16] SeppHochreiterandJürgenSchmidhuber.1997.Longshort-termmemory.Neural humanexpertsinconstructinghigher-qualityprogramunderstand- computation9,8(1997),1735–1780. ingdatasetsforevaluationandpre-training.Anotherdirectionis [17] XingHu,GeLi,XinXia,DavidLo,andZhiJin.2018. Deepcodecomment generation.InProceedingsofthe26thconferenceonprogramcomprehension.200– toexplorethepossibilityofNLLinsoftwareengineeringbeyond 210. thescopeofprogramunderstanding,suchascodegenerationand [18] XingHu,GeLi,XinXia,DavidLo,ShuaiLu,andZhiJin.2018. Summarizing programrepair. sourcecodewithtransferredapiknowledge.(2018). [19] HudaKhayrallahandPhilippKoehn.2018.Ontheimpactofvarioustypesof noiseonneuralmachinetranslation.arXivpreprintarXiv:1805.12282(2018). [20] PangWeiKohandPercyLiang.2017. Understandingblack-boxpredictions ACKNOWLEDGEMENT viainfluencefunctions.InInternationalconferenceonmachinelearning.PMLR, 1885–1894. ThisresearchissupportedbytheNationalResearchFoundation, [21] AnranLi,YueCao,JiabaoGuo,HongyiPeng,QingGuo,andHanYu.2023. Singapore,andtheCyberSecurityAgencyunderitsNationalCy- FedCSS:JointClient-and-SampleSelectionforHardSample-AwareNoise-Robust |
bersecurityR&DProgramme(NCRP25-P04-TAICeN),andNRFIn- FederatedLearning.ProceedingsoftheACMonManagementofData1,3(2023), 1–24. vestigatorshipNRF-NRFI06-2020-0001.Anyopinions,findingsand [22] AnranLi,LanZhang,JuntaoTan,YaxuanQin,JunhaoWang,andXiang-Yang conclusions or recommendations expressed in this material are Li.2021.Sample-leveldataselectionforfederatedlearning.InIEEEINFOCOM those of the author(s) and do not reflect the views of National 2021-IEEEConferenceonComputerCommunications.IEEE,1–10. [23] AnranLi,LanZhang,JunhaoWang,FengHan,andXiang-YangLi.2021.Privacy- Research Foundation, Singapore and Cyber Security Agency of preservingefficientfederated-learningmodeldebugging.IEEETransactionson Singapore. ParallelandDistributedSystems33,10(2021),2291–2303. [24] AnranLi,LanZhang,JunhaoWang,JuntaoTan,FengHan,YaxuanQin,Niko- laosMFreris,andXiang-YangLi.2021.Efficientfederated-learningmodelde- REFERENCES bugging.In2021IEEE37thInternationalConferenceonDataEngineering(ICDE). IEEE,372–383. [1] WasiAhmad,SaikatChakraborty,BaishakhiRay,andKai-WeiChang.2020.A [25] ZhongLi,MinxuePan,YuPei,TianZhang,LinzhangWang,andXuandongLi. Transformer-basedApproachforSourceCodeSummarization.InProceedingsof 2022.RobustLearningofDeepPredictiveModelsfromNoisyandImbalanced the58thAnnualMeetingoftheAssociationforComputationalLinguistics.4998– SoftwareEngineeringDatasets.In37thIEEE/ACMInternationalConferenceon 5007. AutomatedSoftwareEngineering.1–13. [2] WasiAhmad,SaikatChakraborty,BaishakhiRay,andKai-WeiChang.2021.Uni- [26] YinhanLiu,MyleOtt,NamanGoyal,JingfeiDu,MandarJoshi,DanqiChen,Omer fiedPre-trainingforProgramUnderstandingandGeneration.InProceedingsof Levy,MikeLewis,LukeZettlemoyer,andVeselinStoyanov.2019. Roberta:A the2021ConferenceoftheNorthAmericanChapteroftheAssociationforCompu- robustlyoptimizedbertpretrainingapproach.arXivpreprintarXiv:1907.11692 tationalLinguistics:HumanLanguageTechnologies.2655–2668. (2019). [3] MiltiadisAllamanis,EarlTBarr,PremkumarDevanbu,andCharlesSutton.2018. [27] ShuaiLu,DayaGuo,ShuoRen,JunjieHuang,AlexeySvyatkovskiy,Ambro- Asurveyofmachinelearningforbigcodeandnaturalness. ACMComputing sioBlanco,ColinClement,DawnDrain,DaxinJiang,DuyuTang,etal.2021. Surveys(CSUR)51,4(2018),1–37. Codexglue:Amachinelearningbenchmarkdatasetforcodeunderstandingand [4] MiltiadisAllamanis,MarcBrockschmidt,andMahmoudKhademi.2018.Learning generation.arXivpreprintarXiv:2102.04664(2021). toRepresentProgramswithGraphs.InInternationalConferenceonLearning [28] LiliMou,GeLi,LuZhang,TaoWang,andZhiJin.2016.Convolutionalneuralnet- Representations. worksovertreestructuresforprogramminglanguageprocessing.InProceedings [5] DanaAngluinandPhilipLaird.1988.Learningfromnoisyexamples.Machine oftheAAAIconferenceonartificialintelligence,Vol.30. Learning2(1988),343–370. [29] XuNie,NingkeLi,KailongWang,ShangguangWang,XiapuLuo,andHaoyu [6] MarkChen,JerryTworek,HeewooJun,QimingYuan,HenriquePondedeOliveira Wang.2023.UnderstandingandTacklingLabelErrorsinDeepLearning-Based Pinto,JaredKaplan,HarriEdwards,YuriBurda,NicholasJoseph,GregBrockman, VulnerabilityDetection(ExperiencePaper).InProceedingsofthe32ndACM etal.2021. Evaluatinglargelanguagemodelstrainedoncode. arXivpreprint SIGSOFTInternationalSymposiumonSoftwareTestingandAnalysis.52–63. arXiv:2107.03374(2021). [30] CurtisNorthcutt,LuJiang,andIsaacChuang.2021. Confidentlearning:Esti- [7] RolandCroft,MAliBabar,andHuamingChen.2022.Noisylabellearningfor matinguncertaintyindatasetlabels.JournalofArtificialIntelligenceResearch70 securitydefects.InProceedingsofthe19thInternationalConferenceonMining (2021),1373–1411. SoftwareRepositories.435–447. [31] OpenAI.2023.GPT-4TechnicalReport. arXiv:2303.08774[cs.CL]ICSE’24,April14–20,2024,Lisbon,Portugal [32] GarimaPruthi,FrederickLiu,SatyenKale,andMukundSundararajan.2020. [41] WenhanWang,GeLi,BoMa,XinXia,andZhiJin.2020.Detectingcodeclones Estimatingtrainingdatainfluencebytracinggradientdescent. Advancesin withgraphneuralnetworkandflow-augmentedabstractsyntaxtree.In2020IEEE NeuralInformationProcessingSystems33(2020),19920–19930. 27thInternationalConferenceonSoftwareAnalysis,EvolutionandReengineering [33] RuchirPuri,DavidSKung,GeertJanssen,WeiZhang,GiacomoDomeniconi, (SANER).IEEE,261–271. VladimirZolotov,JulianDolby,JieChen,MihirChoudhury,LindseyDecker,etal. [42] KeyuluXu,WeihuaHu,JureLeskovec,andStefanieJegelka.2019.HowPowerful 2021.CodeNet:ALarge-ScaleAIforCodeDatasetforLearningaDiversityof areGraphNeuralNetworks?.InInternationalConferenceonLearningRepresenta- CodingTasks.InThirty-fifthConferenceonNeuralInformationProcessingSystems tions. DatasetsandBenchmarksTrack(Round2). [43] SurajYatish,JirayusJiarpakdee,PatanamonThongtanunam,andChakkritTan- |
[34] LinShi,FangwenMu,XiaoChen,SongWang,JunjieWang,YeYang,GeLi,Xin tithamthavorn.2019. Miningsoftwaredefects:Shouldweconsideraffected Xia,andQingWang.2022.Arewebuildingontherock?ontheimportanceof releases?.In2019IEEE/ACM41stInternationalConferenceonSoftwareEngineering datapreprocessingforcodesummarization.InProceedingsofthe30thACMJoint (ICSE).IEEE,654–665. EuropeanSoftwareEngineeringConferenceandSymposiumontheFoundationsof [44] XingruiYu,BoHan,JiangchaoYao,GangNiu,IvorTsang,andMasashiSugiyama. SoftwareEngineering.107–119. 2019.Howdoesdisagreementhelpgeneralizationagainstlabelcorruption?.In [35] JunShu,QiXie,LixuanYi,QianZhao,SanpingZhou,ZongbenXu,andDeyu InternationalConferenceonMachineLearning.PMLR,7164–7173. Meng.2019.Meta-weight-net:Learninganexplicitmappingforsampleweighting. [45] ZhiqiangYuan,JunweiLiu,QianchengZi,MingweiLiu,XinPeng,andYiling Advancesinneuralinformationprocessingsystems32(2019). Lou.2023.Evaluatinginstruction-tunedlargelanguagemodelsoncodecompre- [36] HwanjunSong,MinseokKim,DongminPark,YoojuShin,andJae-GilLee.2022. hensionandgeneration.arXivpreprintarXiv:2308.01240(2023). Learningfromnoisylabelswithdeepneuralnetworks:Asurvey.IEEETransac- [46] JianZhang,XuWang,HongyuZhang,HailongSun,KaixuanWang,andXudong tionsonNeuralNetworksandLearningSystems(2022). Liu.2019.Anovelneuralsourcecoderepresentationbasedonabstractsyntax [37] WeisongSun,ChunrongFang,YuduYou,YunMiao,YiLiu,YuekangLi,Gelei tree.In2019IEEE/ACM41stInternationalConferenceonSoftwareEngineering Deng,ShenghanHuang,YuchenChen,QuanjunZhang,etal.2023. Auto- (ICSE).IEEE,783–794. maticCodeSummarizationviaChatGPT:HowFarAreWe? arXivpreprint [47] KechiZhang,WenhanWang,HuangzhaoZhang,GeLi,andZhiJin.2022.Learn- arXiv:2305.12865(2023). ingtorepresentprogramswithheterogeneousgraphs.InProceedingsofthe30th [38] ZhensuSun,LiLi,YanLiu,XiaoningDu,andLiLi.2022.Ontheimportanceof IEEE/ACMInternationalConferenceonProgramComprehension.378–389. buildinghigh-qualitytrainingdatasetsforneuralcodesearch.InProceedingsof [48] GuoqingZheng,AhmedHassanAwadallah,andSusanDumais.2021.Metalabel the44thInternationalConferenceonSoftwareEngineering.1609–1620. correctionfornoisylabellearning.InProceedingsoftheAAAIConferenceon [39] MichaelTänzer,SebastianRuder,andMarekRei.2022. Memorisationversus ArtificialIntelligence,Vol.35.11053–11061. GeneralisationinPre-trainedLanguageModels.InProceedingsofthe60thAnnual [49] YaqinZhou,ShangqingLiu,JingkaiSiow,XiaoningDu,andYangLiu.2019. MeetingoftheAssociationforComputationalLinguistics(Volume1:LongPapers). Devign:Effectivevulnerabilityidentificationbylearningcomprehensiveprogram 7564–7578. semanticsviagraphneuralnetworks.Advancesinneuralinformationprocessing [40] AshishVaswani,NoamShazeer,NikiParmar,JakobUszkoreit,LlionJones, systems32(2019). AidanNGomez,ŁukaszKaiser,andIlliaPolosukhin.2017. Attentionisall [50] ZhaoweiZhu,ZihaoDong,andYangLiu.2022. Detectingcorruptedlabels youneed.Advancesinneuralinformationprocessingsystems30(2017). withouttrainingamodeltopredict.InInternationalConferenceonMachine Learning.PMLR,27412–27427. |
2307.11454 Structure-Aware Code Vulnerability Analysis With Graph Neural Networks RavilMussabayev ravmus@gmail.com MoscowSoftwareDevelopmentToolsCouldTechnologyLab, HuaweiRussianResearchInstitute Moscow,Russia Abstract 1 Introduction This study explores the effectiveness of graph neural net- Codevulnerabilitydetectionisacriticalchallengeinsoft- works(GNNs)forvulnerabilitydetectioninsoftwarecode, waresecuritythathassignificantimplicationsforbothindi- utilizing a real-world dataset of Java vulnerability-fixing vidualsandorganizations[2].Assoftwaresystemsgrowin- commits.Thedataset’sstructure,basedonthenumberof creasinglycomplexandinterconnected,thepresenceofvul- modified methods in each commit, offers a natural parti- nerabilitiesposesseriousthreats,includingpotentialbreaches, tionthatfacilitatesdiverseinvestigativescenarios.Thepri- dataleaks,andcompromiseduserprivacy.Detectingcode maryfocusistoevaluatethegeneralapplicabilityofGNNs vulnerabilitiesisessentialtoproactivelyidentifyandreme- in identifying vulnerable code segments and distinguish- diate security flaws before they can be exploited by mali- ingthesefromtheirfixedversions,aswellasfromrandom ciousactors.However,manualinspectionofcodeforvul- non-vulnerablecode.Throughaseriesofexperiments,the nerabilitiesistime-consuming,error-prone,andimpractical researchaddresseskeyquestionsaboutthesuitabilityofdif- forlarge-scalecodebases.Therefore,developingautomated ferentconfigurationsandsubsetsofdatainenhancingthe methods,suchasmachinelearningmodels,foraccurately predictionaccuracyofGNNmodels.Experimentsindicate and efficiently identifying code vulnerabilities is of para- that certain model configurations, such as the pruning of mountimportancetoenhancesoftwaresecurityandprotect specificgraphelementsandtheexclusionofcertaintypesof againstpotentialrisks. coderepresentation,significantlyimproveperformance.Ad- Oneofthestate-of-the-artmodelsforvulnerabilitydetec- ditionally,thestudyhighlightstheimportanceofincluding tionisReVeal[1].Itconsistsofthreemainmodules:agated randomdataintrainingtooptimizethedetectioncapabilities graphneuralnetwork(GGNN),aSMOTEresampling,and ofGNNs. arepresentationlearningblock.Forapictorialrepresenta- tionofthearchitecture,seeFigure1.Theauthorscollected Keywords: vulnerabilitydetection,cybersecurity,graphneu- anewdatasetofC++vulnerabilitiesfromtheLinuxDebian ralnetworks KernelandtheChromiumprojects.Ineachofthesecurity patches,theyannotatedthepreviousversionsofallchanged functions(i.e.,theversionspriortothepatch)as“vulnerable” ACMReferenceFormat: andthefixedversionofallchangedfunctions(i.e.,thever- RavilMussabayev.2024.Structure-AwareCodeVulnerabilityAnal- sionafterthepatch)as“clean”.Additionally,otherfunctions ysis With Graph Neural Networks. In Proceedings of ACM Con- thatwerenotinvolvedinthepatch(i.e.,thosethatremained ference(Conference’17).ACM,NewYork,NY,USA,6pages.https: unchanged)areallannotatedas“clean”.Fromnowon,this //doi.org/10.1145/nnnnnnn.nnnnnnn datasetwillbereferredtoasthe“ReVeal”dataset. In[1],extensiveexperimentswithothervulnerabilityde- tectionmodelspresentintheliteratureshowedtheiracute inadequacywhentestedontheReVealdataset.ReVealdataset standsoutfromothervulnerabilitydetectionbenchmarks Permissiontomakedigitalorhardcopiesofallorpartofthisworkfor personalorclassroomuseisgrantedwithoutfeeprovidedthatcopiesarenot availableintheliterature.Itconsistsofrealimbalanceddata madeordistributedforprofitorcommercialadvantageandthatcopiesbear annotatedbyhumandevelopers.Otherdatasetsweremainly thisnoticeandthefullcitationonthefirstpage.Copyrightsforcomponents synthetic or semi-synthetic annotated by static analysers ofthisworkownedbyothersthanACMmustbehonored.Abstractingwith or unsupervised techniques. A misleadingly high scores creditispermitted.Tocopyotherwise,orrepublish,topostonserversorto achieved by other models could be explained by the low redistributetolists,requirespriorspecificpermissionand/orafee.Request permissionsfrompermissions@acm.org. qualityoftheirtestdatasets.Moreconcretely,theauthors Conference’17,July2017,Washington,DC,USA of [1] point at the following limitations of other existing ©2024AssociationforComputingMachinery. ACMISBN978-x-xxxx-xxxx-x/YY/MM...$15.00 https://doi.org/10.1145/nnnnnnn.nnnnnnn 4202 nuJ 81 ]RC.sc[ 2v45411.7032:viXraConference’17,July2017,Washington,DC,USA RavilMussabayev Figure1.ArchitectureoftheReVealmodel approaches:(a)dataduplication,(b)nothandlingdataim- 𝐷 𝑘 =𝑃 1∪𝑃 2∪𝑃 3 (1) balance,(c)notlearningsemanticinformation,(d)lacking ={(𝑓,𝑓′) ∈𝐶 |𝐶 isstrict}∪ classseparability. {(𝑓,𝑓′) ∈𝐶 |𝐶 is𝑘-strict}∪ Inthisstudy,wewouldliketoreproducetheresultsof[1] andanswerthefollowingresearchquestion: {𝑓 | 𝑓 israndom&safe} ResearchQuestion1.Howwouldoneoptimizethepa- where𝐶isavulnerability-fixingcommit,and(𝑓,𝑓′)denotes rameters in the following dimensions to achieve the best thepairofanoriginalfunction𝑓 withitschangedversion possible performance of the ReVeal model on the ReVeal 𝑓′.Wesaythatavulnerabilityfixingcommit𝐶 is𝑘-strictif dataset? itcontainsexactly𝑘 changedpairsoffunctions. |
Wealsodecomposetheoriginalproblemintotwoinde- pendenttasks: 1. IncludetheSMOTEandrepresentationlearningmod- ulesoronlyuseasingleGGNNblock; • Task𝑇 :dividinginthesetofpotentiallyvulnerable 1 2. IncludeinformationaboutASTedgesintotheinput methods,i.e.,vulnerablemethods(activevulnerable) graphsoronlyuseDDGandCFGedges; againsttheirfixedversions(passivevulnerable); 3. Include the full graph, which can be too large and • Task𝑇 :dividinginthesetofallmethods,i.e.,poten- 2 detailed,oruseitsprunedversionatoperatornodes tiallyvulnerablemethodsagainstrandomsafecode. instead; Then,thezero-dayvulnerabilitydetectiontaskisacomposi- 4. Balancethetrainingdatabydownsamplingthemajor- tionofthesetwotasks ityclassorkeeptheoriginalclassratio. 𝑇 =𝑇 ◦𝑇 0 1 2 Ourhypothesisisthattask𝑇 ismuchmoredifficultthan WealsoinvestigatetheperformanceoftheReVealmodel 1 task𝑇 for the state-of-the-art models. If we answer this ontheJavavulnerabilitydetectiondata.Wecollectedalarge 2 question in the positive, then task𝑇 is a bottleneck and dataset of 865 Java vulnerability-fixing commits across a 1 thereisaneedtodevelopbettermodelsthatarespecifically widevarietyofCWEvulnerabilitytypes.Inthiswork,we tailoredtotackle𝑇 . restrictourselvestotheproblemofmethod-levelvulnerabil- 1 Thus,wehavethefollowinglistofresearchquestions: itydetection.Eachcommitcaninvolveadifferentnumber ofchangedmethods.Thisinducesanaturalpartitionofthe ResearchQuestion2.Is𝑃 𝑖 useful?(𝑖 =1,2,3) ResearchQuestion3.Howdifficultistask𝑇 ? datasetwithrespecttothenumberofchangedfunctionsin 1 ResearchQuestion4.Howdifficultistask𝑇 ? acommit. 2 ResearchQuestion5.Doesrandomcodeappearin𝑃 Statistically,therearemanymorecommitswheremore 2 as𝑘 increases? thanonefunctionhaschanged.Thus,acrucialproblemarises ResearchQuestion6.Howdoesthesizeof𝑃 affectthe inthissetting.Inavulnerability-fixingcommitwheremore 3 overallperformance? thanonefunctionhaschanged,wecannotensurethatallthe changesarerelatedtofixingtheunderlyingvulnerability. 2 Experimentalsetup Thus,notallmatchedpairsoffunctionsinvolvedinsucha commitcanbelabelledasfixingthevulnerability. WeadaptedthesourcecodefromGitHubprovidedbytheau- Toaddresstheabove-mentionedissue,wecompileand thorsof[1]:https://github.com/VulDetProject/ReVeal.The answeralistofresearchquestions.Toformulatetheseques- experiments were conducted on a computer with the fol- tions,weintroduceanewnotation.Wecreateasequenceof lowing configuration: Intel(R) Xeon(R) Gold 6151 CPU @ setswiththefollowingstructure: 3.00GHzwith32cores,NVIDIATeslaV100PCIeGPUwithStructure-AwareCodeVulnerabilityAnalysisWithGraphNeuralNetworks Conference’17,July2017,Washington,DC,USA 16GB,and126GBRAM.Thecomputingplatformhadthe 4 ExperimentswithJavadata followingspecifications:Python3.10.7,NumPy1.23.3,DGL To answer the rest of research questions, we trained and 1.0.1+cu117. Joern of version 1.1.1495 was used to parse testedthemodelondifferentpartsoftheJavadataset(1):𝑃 , 1 sourcecodeintoagraphrepresentation. 𝑃 ,and𝑃 .Inparticular,wevaried𝑘 intherangefrom1to 2 3 Throughouttheexperiments,weusedthedefaultchoice 14.Then,weplottedtheresultingROCAUCscoresagainst ofhyperparameters:learningrate0.0001,weightdecay0.001, 𝑘,anddrawconclusionsbasedontheobserveddynamics. graphembeddingsize200,batchsize128,maximumnumber To make set 𝑃 to be independent of 𝑘, we fixed it to be 3 ofbatches10000,numberofgradientaccumulationsteps8, the complement of 𝑃 . That is, 𝑃 consisted of functions 1 3 maximumpatienceof50forC++dataand20forJavadata. thatremainedunchangedinthecommitswhereonlyone function was changed. Also, in order to balance different 3 ExperimentswithC++data partsinvolvedintrainingandtesting,werestrictedthesize Toanswerthefirstresearchquestion,weusedtheoriginal of𝑃 : 3 C++method-levelvulnerabilitydatasetfrom[1].Afterpars- |𝑃 | = |𝑃 |+|𝑃 | 3 1 2 ing,weobtainedthefollowingstatisticsoftheinputgraphs: Duringthedatacleaningphase,weensuredthatineach 11788traingraphs(956vulnerable),1667validationgraphs experiment,𝑃 didnotcontainfunctionsthatarecontainedin (133vulnerable),3385testgraphs(286vulnerable) 3 𝑃 ∪𝑃 .Also,weremovedanyduplicatefunctionsfromeach 1 2 TotesteachdimensionofRQ1,weperformed10trials oftheparts𝑃 ,𝑃 ,and𝑃 ,andremovedmethodscontained 1 2 3 of training the model. In each trial, the dataset was split inthetrainingdatafromthetestdata. intotrain,validation,andtestpartsanew.Theresultscanbe Table2showsthedistributionofthecollectedJavameth- foundinTable1. odsafterstratificationby𝑘 andcleaningthedata: Configuration MedianF1 MedianROCAUC Baseline 27.29 0.696 P1 P2 WithoutSMOTE&RL 21.45 0.730 k train test train test WithoutASTedges 27.65 0.706 1 410(205) 135(68) 0(0) 0(0) Withpruning 30.83 0.724 2 399(200) 145(73) 343(171) 122(61) Majoritydownsampling 26.61 0.678 3 416(208) 132(66) 696(347) 228(113) Table1.Resultsofexperimentsforresearchquestion1 4 414(207) 128(65) 960(479) 346(172) 5 415(210) 129(64) 1159(575) 433(217) 6 414(208) 131(65) 1393(692) 506(254) 7 421(212) 120(60) 1583(789) 596(296) 8 394(197) 151(75) 1870(938) 572(284) 3.1 ExcludingSMOTEandRL 9 410(207) 135(67) 2027(1012) 664(330) |
ThemodelwithoutSMOTEandRLachievestheworstperfor- 10 411(206) 131(66) 2195(1089) 632(314) mancewithrespecttotheF1scoreandthebestperformance 11 399(199) 150(75) 2439(1215) 708(353) withrespecttheROCAUCmeasure. 12 400(202) 144(72) 2545(1270) 769(383) 13 397(200) 143(72) 2619(1303) 872(434) 3.2 ASTedges 14 409(204) 136(68) 2853(1421) 845(419) ThemodelperformsslightlybetterwithoutincludingAST Table 2. Statistics of collected Java methods after stratifi- edges.Thisislikelyduetoincludingtoomuchoffine-grained cationby𝑘 andcleaning.Eachcellhastheformat𝑁 (𝑁 ), informationortoomanynodes.Themodelbecomesmore 1 2 where𝑁 isthetotalnumberofmethodsand𝑁 isthenum- likelytooverfittoirrelevantfeaturesintheinputandfailto 1 2 berofvulnerableones. generalize. 3.3 Pruning Theexperimentsalsoshowedthatthemodelperformsbetter with pruning at operator nodes. Pruning makes a graph 4.1 Researchquestion2 simplerandlessentangledforthemodeltounderstand. Inthisresearchquestion,weinvestigatetrainingondifferent combinationsofsets𝑃 ,𝑃 ,and𝑃 ,andtestingon𝑃 ∪𝑃 ∪𝑃 1 2 3 1 2 3 3.4 Downsampling or𝑃 ∪𝑃 ,whichisastrictertest.Theresultscanbefound 1 3 Table1showsthatthemodelperformsworsewithbalancing inFigures2and3. thetrainsetbydownsamplingnon-vulnerablemethods.We Figures2and3allowustoconcludethatifthetestset thinkthataroughbalancingofthetrainpartimpactsthe includespart𝑃 ,thentheinclusionofpart𝑃 intotraining 3 3 scorenegativelysinceitturnsoffSMOTE. iscriticaltoachievingahighperformance.Overall,parts𝑃 2Conference’17,July2017,Washington,DC,USA RavilMussabayev Figure2.ReVealmodeltrainedonparts,testedon𝑃 ∪𝑃 ∪𝑃 . Figure4.ReVealmodeltrainedonparts,testedon𝑃 .This 1 2 3 1 isastricttestfortask𝑇 . 1 smalldifferencesbetweenverysimilarcode.Theresulting plotcanbefoundinFigure4. Asyoucaninferfromthisfigure,theReVealmodelisun- abletoperformmuchbetterthanrandomguessingonthis testdatairrespectiveofthetrainingconfiguration.However, aslightlybetterresultisachievedbythetrainingdatacon- sisting of the set𝑃 ∪𝑃 . Also, training on sets𝑃 and𝑃 1 2 1 2 separatelyshowsaperformancebetterthanrandomstrategy formostvaluesof𝑘.Includingdatafrom𝑃 intotrainingmis- 3 leadsthemodelsincethetestdatadoesnothaveinstances fromthedistributionof𝑃 . 3 This experiment shows that the ReVeal model heavily underperformsontask𝑇 . 1 4.3 Researchquestion4 Inthisexperiment,thetrainingdataconsistedofinstances fromset𝑃 ∪𝑃 markedasapositiveclass,andinstancesfrom Figure3.ReVealmodeltrainedonparts,testedon𝑃 1∪𝑃 3. part𝑃 m1 arke2 dasanegativeclass.Likewise,thetestdata Thisisastrictertestfortask𝑇 2thantheoneonFigure2). wasco3 mprisedofinstancesfrompart𝑃 markedasapositive 1 class,andinstancesfrompart𝑃 markedasanegativeclass. 3 and𝑃 contributethemosttotheprediction,asseenbythe The results of this setting reflect the ability of the model 3 redandbluelinesonFigures2and3. todifferentiateclose-to-vulnerablecodefromrandomsafe Also,onFigure3,weseeaslightdegradationofperfor- code.TheresultingROCAUCvaluesforthisexperimentcan mance corresponding to training on 𝑃 ∪𝑃 (red line) as befoundinFigure5. 2 3 𝑘 increases.Thismightindicatetheincreasingamountof FromFigure5,weseethatthemodelperformsfairlywell randomnoisein𝑃 2as𝑘 increases,partiallyansweringRQ5 ontask𝑇 2,achievingthebestresultsinthetrainingregime inthepositive. involving𝑃 1∪𝑃 3. 4.2 Researchquestion3 4.4 Researchquestion5 Toassessthequalityofthemodelontask𝑇 ,wechangethe Toanswerthisresearchquestion,wetrainonallpossible 1 combinationofthetestsetto𝑃 .Thisisthestrictestpossible combinationsofpartsinvolving𝑃 .Then,wetestthetrained 1 2 testsetthatreflectstheabilityofthemodeltodistinguish modelson𝑃 ∪𝑃 .TheresultscanbeseeninFigure6. 1 2Structure-AwareCodeVulnerabilityAnalysisWithGraphNeuralNetworks Conference’17,July2017,Washington,DC,USA Figure5.ReVealmodeltrainedonparts,testedon𝑃 (all Figure7.ReVealmodeltrainedon𝑃 ∪𝑃 ∪𝑃 ,testedon 1 1 2 3 markedpositive)∪𝑃 (allmarkednegative).Thisisastrict 𝑃 ∪𝑃 ∪𝑃 withvaryingsizeof𝑃 inthetraindata. 3 1 2 3 3 testfortask𝑇 . 2 different sizes of𝑃 in the training data. The test set was 3 fixed.TheresultsaredisplayedonFigure7. ItisclearfromFigure7thatthesizeof𝑃 inthetraining 3 datadoesnotaffecttheperformanceofthemodel. 5 Threatstovalidity Therearesomethreatstothevalidityofthecurrentstudy: 1. Insufficientnumberoftrialsmadeforeachchoiceof𝑘 (forRQs2–5)and |𝑃 | (forRQ6).Onlyonetrialwas 3 performedinourstudy.Thismightnotbeenoughto accountforvariousrandomphenomenapresentinthe trainingofagraphneuralnetworkandinthesplitof dataintotrain,validation,andtestsubsets; 2. The available training data might be insufficient to make solid conclusions. In particular, we only had around3148trainingexamplesfor𝑘 =5intheregime 𝑃 ∪𝑃 ∪𝑃 .Thisnumbermightnotsufficetotraina 1 2 3 largegraphneuralnetwork. Figure6.ReVealmodeltrainedonparts,testedon𝑃 ∪𝑃 . 1 2 6 Conclusion Thisplotdoesnotallowustodefinitivelyconcludeany- Inthisstudy,wehaveinvestigatedtheperformanceofthe thingaboutRQ5.Themodeldoesnotperformadequately ReVealmodelondifferentdatasetsandconfigurations,fo- foranytrainingregime,anddoesnotexhibitanytrendsthat cusingontheidentificationofvulnerablecodeinC++and canbedetectedacrossdifferentvaluesof𝑘. Java.Weusedagraph-basedapproach,representingcodeas graphs,andemployedamachinelearningmodeltopredict 4.5 Researchquestion6 vulnerabilities. RQ2concludedthatincluding𝑃 intothetrainingdatais Ourinvestigationfocusedonsixresearchquestions(RQs), 3 crucialforachievinggoodperformanceontask𝑇.Now,we eachexploringdifferentaspectsoftheproblem.RQ1showed investigate how the size of 𝑃 in the training data affects thatthemodelperformsbetterwithpruningandwithout 3 the final performance. For that, we pick the best training includingASTedges,whiletheabsenceofSMOTE,RL,and |
configurationfromRQ2andplotitsperformanceagainst downsamplingtechniquesledtoadecreaseinperformance.Conference’17,July2017,Washington,DC,USA RavilMussabayev TheanalysisofRQ2andRQ3indicatedthattheinclusion Inconclusion,ourresearchprovidesvaluableinsightsinto ofpart𝑃 inthetrainingsetiscriticalforachievinghighper- theperformanceandsuitabilityofgraphneuralnetworks 3 formance,especiallywhenthetestsetalsoincludespart𝑃 . for identifying vulnerable code. However, more research 3 However,themodelunderperformedontask𝑇 ,suggesting isrequiredtofurtherrefinethesemodelsandaddressthe 1 thatdistinguishingsmalldifferencesbetweenverysimilar identified challenges, particularly in distinguishing small coderemainschallenging. differencesincodeandhandlingimbalanceddatasets.Future OurfindingsfromRQ4andRQ5providedinsightsonthe work could involve investigating other machine learning model’s outstanding performance in differentiating close- models,aswellasimprovingdataaugmentationtechniques to-vulnerablecodefromrandomsafecodeandthepossible toenhancethemodel’sperformance. effectofrandomnoisein𝑃 as𝑘increases.InRQ6,wefound 2 thatthesizeof𝑃 inthetrainingdatadidnotsignificantly References 3 affectthemodel’sperformance. [1] S.Chakraborty,R.Krishna,Y.Ding,andB.Ray.2022.DeepLearning Whileourresearchofferssubstantialinsights,therearea BasedVulnerabilityDetection:AreWeThereYet?IEEETransactionson fewthreatstoitsvalidity.Theseincludethelimitednumber SoftwareEngineering48,09(sep2022),3280–3296. https://doi.org/10. oftrialsforeachchoiceof𝑘 and|𝑃 |,andthepossibilitythat 1109/TSE.2021.3087402 3 [2] Michael Fu and Chakkrit Tantithamthavorn. 2022. LineVul: A theavailabletrainingdatamaybeinsufficienttomakesolid Transformer-based Line-Level Vulnerability Prediction. In 2022 conclusions. IEEE/ACM19thInternationalConferenceonMiningSoftwareRepositories (MSR).608–620. https://doi.org/10.1145/3524842.3528452 |
2307.11853 Exploring Security Commits in Python Shiyu Sun∗, Shu Wang∗, Xinda Wang∗, Yunlong Xing∗, Elisa Zhang†, Kun Sun∗ ∗George Mason University, †Dougherty Valley High School {ssun20, swang47, xwang44, yxing4, ksun3}@gmu.edu, elisaz.ca@gmail.com Abstract—Python has become the most popular program- and evolution since the downstream developers may not be ming language as it is friendly to work with for beginners. aware of the criticality of these security commits. Therefore, However, a recent study has found that most security issues it is vital to identify the hidden security commits among all in Python have not been indexed by CVE and may only be Python commits. fixed by “silent” security commits, which pose a threat to software security and hinder the security fixes to downstream The existing datasets and methods are insufficient for software. It is critical to identify the hidden security commits; security commit detection in Python. To identify security however, the existing datasets and methods are insufficient for commits, researchers first build commit datasets [5], [6] and security commit detection in Python, due to the limited data then either extract features manually from commit messages/- variety, non-comprehensive code semantics, and uninterpretable code changes [5], [7], [8] or learn features automatically learned features. In this paper, we construct the first security commit dataset in Python, namely PySecDB, which consists via deep learning models, e.g., recurrent neural networks of three subsets including a base dataset, a pilot dataset, and (RNN) [9], [10], Transformers [11], [12], and graph neural an augmented dataset. The base dataset contains the security networks (GNN) [13], [14]. However, these solutions have commits associated with CVE records provided by MITRE. To three main constraints, namely, limited data variety, non- increase the variety of security commits, we build the pilot comprehensive code semantics, and uninterpretable learned dataset from GitHub by filtering keywords within the commit messages. Since not all commits provide commit messages, we features. First, existing works [5], [6], [15] only construct further construct the augmented dataset by understanding the security commit datasets in C/C++ or Java, and there is no semantics of code changes. To build the augmented dataset, we availablePythondatasetforsecuritycommitresearch.Second, propose a new graph representation named CommitCPG and a the existing feature extraction methods cannot be directly multi-attributedgraphlearningmodelnamedSCOPYtoidentify applied to Python security commit detection. The manually the security commit candidates through both sequential and structural code semantics. The evaluation shows our proposed extracted features [5], [7] are language-dependent and cannot algorithms can improve the data collection efficiency by up to bedirectlymigratedtothePythonlanguage.Also,theexisting 40percentagepoints.Aftermanualverificationbythreesecurity deep learning features [9], [12], [13], [15] are incapable of experts, PySecDB consists of 1,258 security commits and 2,791 integrating both the sequential and structural semantics of non-security commits. Furthermore, we conduct an extensive code since the RNN and Transformer-based models simply case study on PySecDB and discover four common security fix patterns that cover over 85% of security commits in Python, treat code as a natural language [16], [17] and the GNN- providinginsightintosecuresoftwaremaintenance,vulnerability based models only focus on the code dependencies [13], [14]. detection, and automated program repair. Third, though manually extracted features are interpretable, IndexTerms—SecurityCommit,Python,DatasetConstruction, feature extraction methods can only provide limited accuracy. Code Property Graph, Graph Learning, Vulnerability Fixes In contrast, deep learning based methods may yield better accuracy, but their learned features are uninterpretable. I. INTRODUCTION To tackle the above challenges, we construct the first secu- According to the TIOBE index [1], Python overtakes Java ritycommitdatasetinPython,namedPySecDB,1bycollecting and C as the most popular programming language as of April the samples from CVE records and filtering the commits 2023. However, a recent study [2] reveals that among 749K from GitHub. It consists of three subsets: a base dataset, a security issues of 197K Python packages in PyPI [3], only pilot dataset, and an augmented dataset. We first build a base 1,232 vulnerabilities are reported to CVE [4] and only 556 dataset by collecting the security commits associated with of them have public fixes. Thus, most security issues are not CVE IDs [4]. Since the CVE records on Python programs indexed and may only be resolved by “silent” fixes, without are limited, we observe that only 46% of them provide the explicit log messages indicating the vulnerabilities. corresponding security commits and more security commits The hidden security fixes pose a threat to the security and fall in the wild silently, without being indexed by CVE. To privacy of users, since attackers may exploit the undisclosed enrichsecuritycommitsforcoveringmorevulnerabilitytypes, vulnerabilities to comprise the unpatched software systems. weconstructapilotdatasetbyfilteringGitHubcommits.Since Particularly, Python is friendly to beginners; however, with only6-10%ofGitHubcommitsarerelatedtosecurityfixes[5], limited security knowledge, learners may be unable to de- filtering commit messages using relevant keywords can effi- termine if an upstream commit is intended to address a ciently narrow down the list of security commit candidates. vulnerability and hence neglect a critical security fix. The implicit security commits can impair software maintenance 1Thisdatasetisreleasedinhttps://github.com/SunLab-GMU/PySecDB. 1 3202 luJ 12 ]RC.sc[ 1v35811.7032:viXraThe security keywords are automatically extracted from the |
1 commit dbeb87afefdb63de2f4cff69b6f10c5965d14b54 commitsinthebasedatasetbytheLatentDirichletAllocation 2 Subject: [PATCH] Fixed code execution bug using (LDA) method [18]. Then, three security experts manually SafeLoader() 3 diff --git a/pystemon/config.py b/pystemon/config.py verifythecandidatecommitsandbuildthepilotdataset.Well- 4 @@ -315,7 +315,7 @@ def _load_yamlconfig(self documentedcommitmessagesarerequiredforthepilotdataset 5 yamlconfig = None 6 ... construction, but not all commits provide commit messages. 7 for includes in yamlconfig.get("includes", []): To include more diverse security commits that do not 8 try: 9 logger.debug("... ’{0}’".format(includes)) provide sufficient commit messages, we extend the base and 10 - yamlconfig.update(yaml.load(open(includes))) pilot datasets with an augmented dataset by considering the 11 + yamlconfig.update(yaml.safe_load(open(includes) )) semantics of code revisions. We develop a new commit graph 12 except Exception as e: representationnamedCommitCPGandagraphlearningmodel 13 raise PystemonConfigException("failed to load ’{0}’: {1}".format(includes, e)) named SCOPY to capture the semantics of code changes. 14 return yamlconfig Inspired by [19], our CommitCPG is constructed by merg- Listing1:Anexampleofsecuritycommit(CVE-2021-27213). ing the code property graphs of the previous and current versions. In CommitCPG, each node presents a statement 1 commit 4cd1067faf3df14dbbe7eb6de2bd7693d5cd829a withitsversioninformation;eachedgepreservesthesemantic 2 diff --git a/IPython/lib/security.py b/IPython/lib/ security.py level dependency between two statements. To reduce analysis 3 @@ -109,7 +109,7 @@ def passwd_check(hashed_passphrase overhead,weperformprogramslicing[20]overCommitCPGs , passphrase): 4 except ValueError: to remove the nodes/edges irrelevant to the commits. Given 5 return False a CommitCPG, SCOPY embeds the node statements using 6 - if len(pw_digest) == 0 or len(salt) != salt_len: 7 + if len(pw_digest) == 0: CodeBERT [17] and embeds the edge attributes as one-hot 8 return False vectorstocontaintheedgeversionsandthesyntax/dependency Listing 2: An example of non-security commit. relationships.Then,agraphconvolutionalnetworkwithmulti- head attention is trained over the base and pilot datasets. andsecuritydecorators)toensuretheeffectivenessofsecurity Finally, we apply SCOPY to identify the security commit mechanisms or policies. These fix patterns can be generalized candidatesfromthewildandbuildtheaugmenteddatasetafter and formulated into intermediate representations to facilitate manual verification. secure software development and automated program repair. Toenhancethevarietyofcommitsbeyondthebasedataset, In summary, our paper makes the following contributions: we construct the pilot and augmented datasets over popular repositories. We evaluate the efficiency of data collection • We construct the first security commit dataset in Python by screening CVE records and GitHub commits. using the ratio of security commits to the total number of candidates. Compared with random selection, the keyword • We design a keyword filtering method to identify the po- tential security commits based on the commit messages. filtering method and SCOPY can improve the efficiency by 30 and 40 percentage points when constructing the pilot and • Basedoncodechanges,weproposeanewcommitgraph representation CommitCPG and a graph learning model augmented datasets, respectively. In total, PySecDB contains SCOPY to locate the security commit candidates. 1,258 security commits associated with 119 distinctive CWEs across 351 repositories, providing sufficient diversity in vul- • To facilitate software maintenance, we discover four common security fix patterns, which provide insights in nerability types and application scenarios. We also find that vulnerability detection and program repair in Python. unique patterns exist in the pilot and augmented datasets, respectively, since these two datasets are built from different II. BACKGROUNDANDRELATEDWORK perspectives, i.e., commit messages and code changes. A. Security and Non-security Commits To facilitate software maintenance, we conduct an exten- sive case study on the security commits in PySecDB and On the version control platforms such as GitHub, a commit discoverfourcommonsecurityfixpatterns,i.e.,addorupdate is mainly composed of two parts: a set of code changes sanity checks, update API usage, update regular expressions, between two versions and a descriptive message including the and restrict security properties. First, security commits often subjectlineandbody(ifany).InListing1,Lines5-14arethe include sanity checks (i.e., verify if certain conditions are source code changes and Line 2 presents a commit message true) to secure critical operations, especially in the authen- with only one subject line. tication and authorization scenarios. Second, since Python A security commit includes code changes made to a soft- provides multiple pre-built packages, security commits can ware codebase, addressing a security vulnerability defined by address vulnerabilities by replacing APIs, e.g., APIs related an individual Common Weakness Enumeration (CWE) Spec- to strings, paths, and commands. Third, security commits can ification [21]. Security commits are typically critical updates handle secure escapes by updating regular expressions, which that need to be applied as soon as possible to prevent attack- protectsoftwarefrombeinginjectedbyshellcommands,SQL ers from exploiting vulnerabilities. List 1 shows a security |
queries, and web scripts. Fourth, security commits can update commit example fixing the vulnerability CVE-2021-27213 by security properties (e.g., security flags, restriction arguments, replacingyaml.load()withyaml.safe_load()toloadthe 2content in a safer way. Non-security commits are the changes made to the software codebase that do not relate to security Content from hyperlinks issues.Thesechangesincludefixingnon-security-relatedbugs, associated with CVE adding new features, improving performance, and updating √ documentation. Typically, non-security commits are not as CVE Reports Keywords Topic Modeling Base Dataset urgent as security commits and can be applied later without affecting software security. In List 2, a non-security commit commit commit removes the unnecessary check on password salt length. Wild Keyword Manual Commits ? √ B. Security Commit Datasets Filtering Verification Candidates Pilot Dataset Security commits provide plentiful information on both the existing vulnerabilities and the corresponding fixes. Thus, re- commit commit searchersconstructsuchdatasetsforsecuritycommitdetection Prediction and automated program repair [5], [6], [22]–[25]. However, Manual ? √ existing datasets only focus on specific projects [6], [15] or Verification SCOPY Candidates Augmented contain limited security commits associated with CVEs [22], Dataset [24]. Although some researchers also consider both commits Fig. 1: Overview of collecting three datasets. indexed by NVD and silent fixes [5], [23], [25], they solely investigatethecommitsinC/C++andJava,neglectingthepop- Commit Representation. To better represent the commits, ularityofPython.Besides,theexistingworksadoptlanguage- we preserve the code structure via the graph representation dependent security-related features, which cannot be directly CommitCPG and also consider the sequential information via migrated for collecting security commits in Python. CodeBERT [17]. However, the existing works either consider C. Security Commit Detection the sequential information [9], [11], [12], [27] or keep the structural semantics [13]. Numerous commits are submitted to GitHub every day, Commit Understanding. We conduct a comprehensive study while 6-10% of them are silent security fixes [7], [26]. To on understanding how the security commits fix Python vul- identify security commits automatically and effectively, [27] nerabilities. The commit patterns can be used to generalize analyzesthenaturallanguagedescriptionofcommitmessages vulnerability fix schemes, which may enhance software main- and bug reports. However, this approach only relies on well- tenance and provide insight into automated program repair. maintained documentation, which is impractical for detecting silent security patches. Thus, some researchers detect security III. DATACOLLECTION commitsbyextractingcodefeaturesmanually[5],[28].Wang et al. [9] ensemble two BiLSTM models to learn not only Our dataset consists of three sections: a) base dataset, b) the commit message but also the code changes. Similarly, pilotdataset,andc)augmenteddataset.Figure1illustratesthe SPI [15] adopts LSTM to learn the representation of commit compositionandconstructionprocedureofPySecDB.Wefirst message and utilizes CNN to learn the representation of code form the base dataset by collecting the commits associated revision. As the prevalence of applying large language model with CVE records indexed by MITRE. Yet, less than 50% on code analysis, CodeBERT [17] is fine-tuned to learn the of CVE records have published their security commits. To semantics of code changes [12]. Zhou et al. [11] increase the introduce more code semantics, we further build the pilot fix data at the function level and then generalize the code dataset by filtering the wild GitHub commits that have pre- change semantic with contrasting learning. definedsecuritykeywordsintheircommitmessages.However, To preserve the inherent structural semantics of code, CLo- notallcommitscontainwell-maintainedcommitmessagesthat zoya et al. [29] and Wu et al. [14] employ BiLSTM to learn precisely describe the rationales of changed code. Thus, we the representation of commits from their AST paths. Wang et consider directly mining the most critical part of commits, al. [13] propose GraphSPD to represent C/C++ commits with i.e., the source code changes. To the end, we propose an code property graphs and learn the representation with GNN. intermediate commit representation (i.e., CommitCPG) and design a dependency-aggregation graph neural network (i.e., D. Novelty of Our Study SCOPY) to capture the inherent sequential and structural Dataset. We build the first security commit dataset in Python, semantics of code changes. Trained with the base and pilot whichcontains1,258securitycommitsand2,791non-security datasets,SCOPYisabletofurtherbuildtheaugmenteddataset commits extracted from over 351 popular GitHub projects, by pinpointing the silent security commits from the wild. covering 119 more CWEs. Different from the SPI [15] based A. Base Dataset Collection onkeywordfilteringandPatchDB[5]basedoncodesimilarity, we consider both commit message and code changes so that WebuildthebasedatasetaccordingtotheCVErecords[4]. thedatasetcancovermorediversesecuritycommits,especially Thefirststepistoretrievethevulnerabilitiesthathavealready for the commits without any clear commit message. been indexed with CVE IDs. Then, we parse the vulnerability 3TABLE I: Security-related keywords for commit filtering. data quality and minimize false positives, the experts are required to follow our two-step labeling procedure strictly. #Tokens Keywords First, each expert tags the commits independently with the attack, bypass, CVE, DoS, exploit, injection, labels: security, non-security, or unsure. Then, they gather |
1-gram leakage, malicious, overflow, smuggling, together to discuss each disagreement and reach a consensus spoofing, unauthorized, underflow, vulnerability on each uncertain candidate. Only the security commits with 2-gram access control, open redirect, race condition 100% agreement will be included in the pilot dataset. In total, it takes 48 man-hours to finish the labeling work. 3-gram denial of service, out of bound, dot dot slash The proposed keyword filtering mechanism reduces the workload and time for manual verification; meanwhile, the reports and crawl the corresponding commits via the pro- human-in-the-loop ensures the quality of the pilot dataset. vided reference hyperlinks. It comes to our attention that the More details on labeling efficiency are shown in Section V-A. collected commits may contain some noise, e.g., changelog, C. Augmented Dataset Construction test case, refactoring, and renaming. After excluding these unrelateddocuments,weobtain729securitycommitstoform The pilot dataset overlooks the commits that lack security the base dataset;meanwhile, we collect theexcluded commits keywords in the commit messages, while these commits may as the non-security subset in the base dataset and expand it provideadditionalvariantsinsyntaxandsemantics.Therefore, by manually identifying the commits that add new features or we propose to further augment our dataset. While the pilot perform refactoring, linting, and version updates. dataset is collected based on commit messages, we build the augmenteddatasetbyonlyanalyzingthesourcecodechanges. B. Pilot Dataset Collection Different from existing works that simply regard source code as sequential data [9], [15], we present a commit graph After examining all the indexed CVE records (as of representationnamedCommitCPGandagraphlearning-based 01/27/2023), only 46% of them contain the corresponding model SCOPY to capture the inherent structural information. security fixes. Therefore, the limited samples in the base dataset may not provide adequate syntactic and semantic 1) CommitCPG: Graph Representation for Commits information. That means, only with the base dataset, we are To preserve the inherent structure of source code and the unable to train a robust model for capturing a wide variety modified content between two versions, we propose a graph- of security commits in the real world. Given the fact that a basedcommitrepresentationcalledCommitCPG,whichoffers majority number of security patches are silently committed essential syntactic and semantic information for comprehen- without reporting to the MITRE [15], [26], we propose to sive commit understanding. Code property graph (CPG) [19] enrich the security commits with the pilot dataset collected is a program representation that contains abstract syntax trees from GitHub, i.e., the most common OSS hosting platform. (AST), control-flow graphs (CFG), and program dependence The pilot dataset is constructed by keyword filtering with graphs (PDG), providing a more comprehensive view for humans in the loop. The list of security-related keywords is code static analysis, compared with traditional sequential built automatically by analyzing the CVE descriptions, CWE structure adopted by NLP-based works [30]. In Figure 2, we types (if exist), and commit messages. We determine the final first preprocess the raw commits by excluding the irrelevant keywords by calculating the word frequency and evaluating functions. Inspired by [13], we then merge the CPGs [19] the correlation between the keywords and security commits. constructedfromthepreviousandcurrentversionsbyaligning Toobtainthesecuritysubsetofthepilotdataset,welocateand the unchanged statements. Next, we adopt a code slicing manually verify the security commit candidates that contain method to retain the crucial context-related code snippets, thepre-definedsecuritykeywordsinthecommitmessages;the which are not changed directly by commits but can assist us excluded commits are collected as the non-security subset. to understand the reason and the effects of code changes. Security Keyword Extraction. For each security commit Commit Preprocessing. To generate the CPG for each code collected from the CVE records, we generate its security version, we need to retrieve the source code of the previous impactsummarybycombiningthecommitmessage,theCWE version and the current version, respectively. To reduce the information (if exists), and the CVE report. After generating overhead of CPG generation, we only focus on the modified the summary, we conduct 1-gram, 2-gram, and 3-gram tok- files instead of the whole project. Then, we extract the enization. Then, we consider the frequency of each token and functions with code revisions as well as the modified global the correlation of each token with security and non-security statements. To achieve this goal, Joern parser [19] is applied commits. We set the frequency threshold and derive the list todetectallrelevantfunctionsandtheircorrespondingscopes. of security-related keywords, as shown in Table I. Then, we We only retain the functions whose scope overlaps with the determine the security commit candidates by checking if the modifiedlinesinthecommits.Forexample,inList1,wewill wild GitHub commits contain any security keywords in their only keep the content of function _load_yamlconfig(). commitmessages.Thesecandidateswillbemanuallyverified. CPG Generation for Previous and Current Versions. Manual Verification. We hire three security experts to man- With the extracted source code of two versions, we em- ually verify the security commit candidates. To guarantee the ploy Joern [19] to generate the CPGs for both versions. 4Locate Function Generate Graph Retrive Previous-Version Previous-Version Previous-Version Merge Slice Source Code Modified Function CPG Commit Locate Function Generate Graph Merged CPG CommitCPG Current-Version Current-Version Current-Version Source Code Modified Function CPG (a) Commit Preprocessing (b) CPG Generation (c) CommitCPG Generation |
Fig. 2: The generation process of CommitCPGs from commits. A CPG can be described as (V,E), where V is the node Python. SCOPY contains two steps: (i) node embedding with set and E is the edge set. V is comprised of multiple CodeBERTandedgeembeddingwithdependency-aggregation 5-tuples (id,func name,file name,version,code), which mechanism, (ii) graph convolution with multi-head attention. contain the information of each node. The node version, CommitCPG Embedding. To feed the CommitCPG to our represented by version ∈ {previous,current}, reflects if SCOPY,weencodethenodeandedgeattributesintonumeric the code line belongs to the previous version or current vectors. Each node represents a code statement; hence, the version. The directed edge set E is made up of 4-tuples node embedding should capture the semantics within the (id 1,id 2,type,version), where id 1 and id 2 denote the start statement. Thus, we first utilize CodeBERT [17] to generate andendnodeIDs,respectively.Theedgetype,representedby token embeddings and grasp the sequential-based semantics. type∈{AST,CDG,DDG}, specifies if the edge belongs to Then,weobtainthenodeembeddingbyaggregatingthetoken theASTorcontrol/datadependencygraphs.Theedgeversion embeddings. In addition, each edge presents the dependency is consistent with the node’s version. between two nodes; thus edge embedding preserves crucial CPG Merging and CommitCPG Slicing.Wefirstgeneratea structural and attribute information. We generate edge em- unified commit graph by fusing the CPGs of two versions beddings with 5-dimensional one-hot vectors. The first two according to each node pair. Then, we update the repre- dimensions are used to embed the structural information and sentation of the merged CPG by two sets: (V′,E′). The present which code version the edge belongs to. The last node set V′ is comprised of 5-tuples, which are denoted as three dimensions are used to embed the attribute information, (id,func name,file name,version,code). id is updated which indicates if the edge presents control dependency, data so that each node has a unique identifier and the node version dependency, or syntax relationship. is changed to version ∈ {current,previous,unchanged}, Graph Convolution with Multi-Head Attention. After em- representing if the code in this node belongs to the current, bedding the CommitCPG with a sequential model, we adopt previous, or both commits. The directed edge set E′ is made a graph convolutional network with multi-head attention to up of 4-tuples (id ,id ,type,version), where id , id , and 1 2 1 2 learn the structural representation of commits. To avoid over- type stay the same as E. The edge version will be updated smoothing, the number of convolutional layers is limited to as unchanged if both connected nodes are unchanged nodes. 3. We feed the embedded CommitCPG into 3 multi-attributed To reduce the noise introduced by irrelevant nodes and graph convolutional layers. The node embeddings of Com- emphasize the semantics of code changes, we generate the mitCPG are updated with the neighborhood information from CommitCPGbyabi-directionalprogramslicing[20],i.e.,for- differentsubgraphs.Then,thegraphembeddings,i.e.,aunified ward and backward slicing. Backward slicing is to reason the vector representation transformed from all the nodes, edges, codechanges,whileforwardslicingistolocatethestatements andfeatures,canbeobtainedthroughgraphpoolingandvector affected by the commit. For example, in List 1, if we set the concatenation. The graph embeddings learned by the SCOPY deletedstatement(Line10)asabackwardslicingcriterion,the are finally fed into a multi-layer perceptron to determine the slicing results include Lines 5, 7, and 8; if we set the added likelihood that a commit fixes a security vulnerability, i.e., statement (Line 11) as a forward slicing criterion, the slicing whether the given commit is a security commit. results contain Line 14. After we conduct code slicing over To demonstrate the generalization ability of SCOPY, we control/data dependency, we can obtain CommitCPG by only utilize the trained SCOPY to discover more security commits retaining all the nodes of modified and sliced statements (i.e., inthewild.WedirectlysendtheCommitCPGofwildcommits Line 7, 8, 10, 11, and 14) along with the traced edges. into SCOPY. For the commits labeled as security commits, 2) SCOPY: Graph Learning for Commits weadoptasimilarprocess(asdescribedinIII-B)tomanually Figure 3 illustrates the workflow of SCOPY, our pro- verifyiftheyarerealsecuritycommits.Theexcludedcommits posed graph-based network to identify security commits in composite the non-security subset of the augmented dataset. 5Node Embedding [0.123, 0.23, 1.34 ...,0.05] Node Embedding √ Security Commit with CodeBERT Edge Embedding Edge Embedding X Non-Security Commit with Multi-relation[0, 1, 0] Embedded Graph Graph Multi-layer CommitCPG Prediction CommitCPG Convolution Embedding Perceptron Fig. 3: The workflow of SCOPY that identifies security commits via CommitCPGs. IV. IMPLEMENTATION multiple-layerperceptron(MLP)isusedasabinarypredictor, whichconvertsthegraphembeddingsintopredictedlabels.We A. Base Dataset Construction train CommitCPG with the base and pilot datasets. Then, we The base dataset consists of the commits linked with CVE feed the wild unlabeled commits into the trained SCOPY and records,whichhavebeenindexedbyMITRE[4].MITREpro- apply manual verification to generate our augmented dataset. videshyperlinksofvulnerabilityfixesfor46%ofCVEentries. We focus on the hyperlinks from GitHub, where each commit V. ANALYSISRESULTS is identified with a unique hash value and the hyperlink is in |
the form: https://github.com/{owner}/{repo}/commit/{hash}. Afterconstructingourdatasets,weframeourevaluationinto We build the base dataset by downloading the vulnerability four research questions, as outlined below. fixingcommitsandremovingthecommitsthatarenotwritten • RQ1: Can the graph learning-based method help improve in Python or only focus on security-unrelated modifications the data collection efficiency? (e.g., renaming and refactoring). • RQ2: How various and representative are the collected security commits? B. Pilot Dataset Construction • RQ3: What are the unique patterns of security commits in We adopt Latent Dirichlet Allocation (LDA) [18], a topic Python? modeling method, to extract the essential security-related • RQ4: How do the wild commit samples help improve tokens from the commit messages. Then, a keyword filtering SCOPY model for downstream security commit detection? algorithm is applied to exclude non-security commits. We download popular open-source repositories in Python and A. Dataset Construction (RQ1) retrieve their commit histories till Jan 27, 2023. For each After keyword filtering and graph-based identification with commit,ifitcontainsatleastoneproposedkeyword,weregard humansintheloop,wecollect1,258securitycommitsintotal. it as a security commit candidate. Later, we manually check Specifically, asshown in Table II,there are 729, 400,and 129 these security commit candidates and finalize the dataset. security commits in the base, pilot, and augmented datasets, To facilitate the verification process, we use PyQt [31] to respectively. Also, 2,791 non-security commits are manually develop a graphical user interface (GUI) that visualizes the labeled during the collection process. codechangesofeachindividualcommitandstorestheverified security commits according to verification results. TABLE II: The composition of PySecDB. C. Augmented Dataset Construction Dataset Base Pilot Augmented Total Commit To build SCOPY for further dataset augmentation, we first generate the corresponding CommitCPG for each commit in Security 729 400 129 1258 thebaseandpilotdatasets.Specifically,weadoptJoern[19]to Non-Security 2134 535 122 2791 generateCPGsforthecodeversionsbeforeandafterapplying the commit, respectively. Then, we parse the generated graph Table III lists the augmentation efficiency of random se- files and merge the graphs to build CommitCPG. To achieve lection, keyword filtering, and SCOPY. Compared with iden- the program slicing, we develop a Python script to analyze tifying security commits from scratch, the keyword filtering the control/data dependency and AST information and output mechanism improves the collecting efficiency by over 30 a sliced CommitCPG ready to be embedded. percentage points and SCOPY improves the efficiency by 40 To prepare an embedded graph for SCOPY, we embed the percentage points. nodes and edges respectively. We fine-tune CodeBERT [17] TABLE III: Efficiency of keyword filtering and SCOPY. to generate the node embedding dedicated to Python. For the edge embeddings, we apply the one-hot encoding to represent Method #Candidates #VerifiedSC∗ Ratio the attributes on each edge. We build the SCOPY on the Random[5] - - 6-10% deep learning library PyTorch 1.6, which is optimized for Keywords 935 400 42.70% tensor computing. We develop and optimize our graph model based on the PyTorch-geometric 1.6 library, which supports SCOPY 251 129 51.39% deep learning on graphs and other structured data. Finally, a ∗ SC=SecurityCommits. 6TABLEIV:Top5repositoriesbynumberofsecuritycommits. Repository #SecurityCommits Proportion django 166 13.20% twisted 87 6.91% glance 54 4.29% pillow 41 3.26% numpy 39 3.10% TotalofTop5 387 30.76% B. Security Commits Categorization and Distribution (RQ2) NVD CWE slice [21] associated classification taxonomy serves to identify and describe security vulnerabilities. To understand the purpose of these commits, we investigate the CWE types associated with the CVE reports and plot the distribution of the CWE types that have been explicitly documented. Among the 729 security commits linked to 556 CVEs, due to the limited number of MITRE human analysts, only 312 (56.1%) CVEs have been assigned CWEs. Even so, there are already 119 distinct CWEs associated with our security commits in the base dataset, which means our PySecDB contains at least 119 types of security commits in terms of corresponding vulnerabilities. Figure 4 enumerates themostcommonCWEs,includingfrequentsecurityproblems such as cross-site scripting (CWE-79), path traversal (CWE- 22), etc. Note that we do not directly assign CWE type to security samples in the remaining base, pilot, and augmented dataset since the MITRE CWE team has its own internal process. However, based on our observation and our data collection approaches that are able to introduce wild security commits with more variance (as discussed in V-D), PySecDB canencompassabroadrangeofsecurityconcernswithvarious kinds of security commits, including but not limited to above 119 CWEs. 12 10 8 6 4 2 0 CWE-79 CWE-22 CWE-20 CWE-20 C0 WE-40 C0 WE-60 C1 WE-89 CWE-352 )%(noitroporP TABLEV:ThepatterntypesofsecuritycommitsinPySecDB. Pattern #Commits Proportion 1)AddorUpdateSanityChecks 416 37.12% 2)UpdateAPIUsage 241 19.16% 3)UpdateRegularExpressions 189 15.02% 4)RestrictSecurityProperties 183 14.55% 5)Others 178 14.15% Total 1258 100% of all security commit samples) that may benefit software maintenance, i.e., adding or updating sanity checks, updating APIs, updating regular expressions, and updating security properties, as listed in Table V. 1) Add or Update Sanity Checks: A sanity check is a basic method to quickly evaluate if a claim or a calculation result can be true, which has been extensively applied to |
multiple scenarios, e.g., authentication property verification, access control, HTTP request checking [37]. We summarize three representative patterns that fix the vulnerabilities via adding or updating sanity checks, which are presented by 37.12% of security commits in PySecDB. Authentication. Authentication is the act of proving an asser- tion, e.g., we need to compare the identity with the system data to verify a system user. The authentication-related vul- nerabilities provide attackers the opportunities to masquerade as legitimate users. To defend them, an effective solution is to perform the additional authentication by adding more check requirements or making existing conditions more restrictive. List 3 presents an example of fixing an authentication vulner- ability by narrowing down an existing restriction from True (i.e., all possible return values except False) to "on" only. 1 commit 0c0313f375bed7b035c8c0482bbb09599e16bfcf 2 diff --git a/cps/shelf.py b/cps/shelf.py 3 @@ -248,7 +248,7 @@ def create_edit_shelf(shelf, 4 ... 5 return redirect(url_for(’web.index’)) 6 - is_public = 1 if to_save.get("is_public") else 0 7 + is_public = 1 if to_save.get("is_public") == "on" else 0 8 if config.config_kobo_sync: 9 ... Listing3:Anexampleofsecuritycommittofixauthentication vulnerability (CVE-2022-0273). Fig. 4: The top 8 CWE types in PySecDB. Authorization.Authorizationreferstotheprocessofgranting Our collectedsecurity commitsdistribute among351 popu- or denying access to certain data or actions within a system. larGitHubrepositoriesunevenly.Amongthem,69repositories Authorization comes after authentication and is achieved by provide more than two security commits, bringing a certain an access control list (ACL). The ACL is used to check the amount of variety. In Table IV, the top five repositories that useridentitywithalistofauthorizedoperationsanddetermine have the most occurrence in our dataset are django [32], which actions a user is allowed to take, e.g., file and data twisted [33], glance [34], pillow [35], and numpy [36], im- permission. Unrestricted authorization may lead to improper plying that the samples in PySecDB align with the popularity resourceconsumptionsinceattackerscouldbypassthesystem trend of security issue in practice. to access high-security level data. List 4 is an example that fixes an authorization bypass exploit by requiring the value of C. Patch Patterns (RQ3) os.environ.get(’GITHUB_ACTIONS’) to be true. We manually go through the whole PySecDB dataset, and HTTPRequest.IftheinterpretationofContent-Lengthand/or discoverfourcommonsecurityfixpatterns(takingup85.85% Transfer-Encoding headers between HTTP servers are incon- 71 commit c658b4f3e57258acf5f6207a90c2f2169698ae22 Web Applications. To properly process the inputs of 2 diff --git a/core.py b/core.py web applications, security commits can adopt APIs in 3 @@ -112,7 +112,7 @@ def actualsys() : 4 if attemps == 6: third-party packages for Python (e.g., parser.quote, 5 ## Brute force protection request.server.escape, django.utils.html.escape, 6 raise Exception("Too many password attempts.") 7 - if os.environ.get(’GITHUB_ACTIONS’) != "": and html.unescape) to escape ampersands, brackets, and 8 + if os.environ.get(’GITHUB_ACTIONS’) == "true": quotes to the HTML/XML entities or HTTP requests for 9 logging.warning("Running on Github Actions") 10 actualsys() defeating cross-site scripting (XSS) and HTTP Smuggling. 11 elif uname == cred.name and pwdhash == cred.pass: List 7 is an example that fixes an XSS vulnerability by using Listing 4: An example of security commit that fixes an the API django.utils.html.escape. authorization bypass exploit vulnerability (CVE-2022-46179). 1 commit f6753a1a1c63fade6ad418fbda827c6750ab0bda sistent,theattackersmaytakeadvantageofthisissueandsend 2 diff --git a/weblate/trans/forms.py b/weblate/trans/ forms.py malicious requests to the servers, i.e., HTTP request smug- 3 @@ -37,6 +37,7 @@ gling. A good solution is to maintain the same interpretation 4 ... 5 +from django.utils.html import escape methods in both front-end and back-end servers. In this way, 6 ... an effective coding practice is to add consistent sanity checks 7 - label = str(unit.translation.language) 8 + label = escape(unit.translation.language) on request interpretation for both servers. List 5 adds such a 9 ... sanity check on data to determine if all characters are digits. Listing 7: An example of security commit that fixes an XSS vulnerability (CVE-2022-24710). 1 commit 8ebfa8f6577431226e109ff98ba48f5152a2c416 2 diff --git a/src/twisted/web/http.py b/src/twisted/web /http.py Shell Commands. To handle the shell commands securely, 3 @@ -2274,6 +2274,8 @@ def fail(): security fixes can adopt shlex.quote and subprocess to 4 if header == b"content-length": 5 + if not data.isdigit(): load or execute the commands. With the shlex.quote API, 6 + return fail() we can have an escaped version of shell inputs, which can 7 try: 8 length = int(data) be safely used as tokens in a command line to avoid shell 9 except ValueError: commandinjection.List8isanexamplethatshowstheusage Listing 5: An example of security commit that fixes an HTTP of shlex.quote to fix a shell injection vulnerability. |
request smuggling vulnerability (CVE-2022-24801). 1 commit 2817869f98c54975f31e2dd674c1aefa70749cca 2 diff --git a/canto_curses/guibase.py b/canto_curses/ 2) Update API Usage: Compared with implementing the guibase.py fixes from scratch, there are abundant well-formulated pack- 3 @@ -156,6 +156,11 @@ def _fork(self, path, href, text, fetch=False): agesthatcanbeadoptedtorealizetheintendedfunctionalities 4 ... and help enforce security restrictions. We notice that a large 5 + href = shlex.quote(href) 6 ... number (19.16%) of Python security commits fix vulnerabil- ities by imposing or substituting APIs. We further categorize Listing 8: An example of security commit that fixes a shell such security fixes according to their application scenarios. injection vulnerability (CVE-2013-7416). General Purpose. There is a set of security-related modifica- Path Name. If a path name is improperly neutralized, at- tions on built-in packages shared by applications for various tackers may access the files and directories outside of the purposes. For instance, re.escape is an API to escape non- restricted location. This vulnerability can occur by using alphanumerics that are not part of regular expression syntax, absolute file paths or manipulating the path variables where to avoid OS command injection, code injection, and regular the reference files contain “dot-dot-slash (../)” sequences expressioninjection.List6isacommitexampletofixregular or variations. To effectively escape such unsafe sequences, expression injection vulnerability, which demonstrates the Python security commits usually adopt the secure APIs, application of re.escape on user and collection_url. e.g., werkzeug.utils.safe_join, yaml.safe_load, and werkzeug.utils.secure_filename,topreventthefilesor 1 commit 4bfe7c9f7991d534c8b9fbe153af9d341f925f98 2 diff --git a/radicale/rights/regex.py b/radicale/ directoriesfrombeingaccessedbymalicioususers.List9isa rights/regex.py commit example that fixes a path traversal via using the API 3 @@ -65,7 +65,10 @@ def _read_from_sections(user, collection_url, permission): werkzeug.utils.secure_filename. 4 ... 3) Update Regular Expressions: Python has become a 5 - regex = ConfigParser({"login": user, "path": collection_url}) popularchoiceforback-endwebdevelopment,anditisusually 6 + # Prevent "regex injection" combined with some other front-end languages [38]. For 7 + user_escaped = re.escape(user) 8 + collection_url_escaped = re.escape(collection_url) this reason, we observe there are 15.02% fixes that modify 9 + regex = ConfigParser({"login": user_escaped, "path the regular expressions to avoid XSS, SQL injection, and ": collection_url_escaped}) 10 ... open redirect vulnerabilities. The regular expression patterns are tailored to match specific strings within the given text, Listing 6: An example of security commit that fixes a regular including SQL commands, URLs, and other scripts. expression injection vulnerability (CVE-2015-8748). 81 commit 1eb1e5428f0926b2829a0bbbb65b0d946e608593 1 commit a22eb0673fe0b7784f99c6b5fd343b64a6700f06 2 diff --git a/upload/server.py b/upload/server.py 2 diff --git a/helpdesk/models.py b/helpdesk/models.py 3 @@ -5,7 +5,7 @@ 3 @@ -238 +238 @@ def cvesForCPE(cpe, 4 - 4 if not text: 5 +import werkzeug.utils 5 return "" 6 @@ -189,7 +189,7 @@ def uploadimage(): 6 - pattern = fr’([\[\s\S\]]*?)\(([\s\S]*?):([\[\s\S 7 filename = all_files[0][1] + all_files[0][2] \]]*?)\)’ 8 - remove(filename) 7 + pattern = fr’([\[\s\S\]]*?)\(([\s\S]*?):([\s\S]*?) 9 + remove(werkzeug.utils.secure_filename(filename)) \)’ 10 del all_files[0] 8 # Regex check 11 length = len(all_files) 9 if re.match(pattern, text): 10 # get get value of group regex Listing 9: An example of security commit that fixes a path Listing 12: An example of security commit that fixes an XSS traversal vulnerability (CVE-2022-23609). vulnerability (CVE-2021-3994). SQL Commands. The improper neutralization of SQL com- Update Security Flags. Security flags perform restrictions mands may lead to SQL injection vulnerabilities, which allow on the methods that may have access to sensitive objects. attackers to manipulate the backend database and access the Improper restrictions on such flags may expose users to a information not intended to be displayed. The corresponding riskyenvironmentand/orleadtosensitiveinformationleakage. fixes need to escape the unsafe characters. List 10 is a fixed List 13 changes the flag from False to True to fix a vulner- example of SQL injection vulnerability, which substitutes the ability, where a sensitive cookie does not have a ‘HttpOnly’ matched single and double quote characters (i.e., ’ and ") in flag. the string self.queueid. 1 commit 60a3fe559c453bc36b0ec3e5dd39c1303640a59a 1 commit fc2c1ea1b8d795094abb15ac73cab90830534e04 2 diff --git a/src/nsupdate/settings/base.py b/src/ 2 diff --git a/.../model.py b/.../model.py nsupdate/settings/base.py 3 @@ -772,13 +772,13 @@ def _get_filter(self): 3 @@ -283,7 +283,7 @@ |
4 if self.queueid: 4 ... 5 - ... = ’%s’" % (self.queueid) 5 -CSRF_COOKIE_HTTPONLY = False 6 + ... = ’%s’" % (re.sub("[\"’]", "", self.queueid)) 6 +CSRF_COOKIE_HTTPONLY = True 7 ... Listing 10: An example of security commit that fixes a SQL injection vulnerability (CVE-2014-125082). Listing 13: An example of security commit that fixes a vulnerability where the sensitive cookie does not have a URLs.TheimproperneutralizationofURLsmayleadtoopen ‘HttpOnly’ flag (CVE-2019-25091). redirect vulnerability, which redirects an unsuspecting victim from a legitimate domain to an attacker’s phishing site. Effec- Add Restriction Arguments. Some restriction arguments tive mitigation is to replace the dangerous special characters will be passed to the functions during execution. Improper withtrustedsymbols.List11isanexampleofanopenredirect argument settings may lead to a variety of mishandling. As vulnerability, which replaces the explicit backslash with an shown in List 14, the formaction is added to restrict the encoded backslash to circumvent the dangerous redirect. attributes of a variable to avoid XSS vulnerability. 1 commit 08c4c898182edbe97aadef1815cce50448f975cb 1 commit 10ec1b4e9f93713513a3264ed6158af22492f270 2 diff --git a/auth/login.py b/auth/login.py 2 diff --git a/src/lxml/html/defs.py b/src/lxml/html/ defs.py 3 @@ -39,6 +39,10 @@ def _redirect_safe(self, url, ...): 4 + url = url.replace("\\", "%5C") 3 @@ -23,6 +23,8 @@ 5 parsed = urlparse(url) 4 ... 6 if parsed.netloc or not (parsed.path + ’/’). 5 + # HTML5 formaction startswith(self.base_url): 6 + ’formaction’ 7 ]) Listing 11: An example of security commit that fixes an open 8 ... redirect vulnerability (CVE-2019-10255). Listing 14: An example of security commit that fixes a cross- site-scripting (XSS) vulnerability (CVE-2021-28957). Scripts. The improper input validation and encoding during webpagegenerationmayleadtoXSS,whichisabletoreveal AddSecurityDecorators.Adecoratorisafunctionthattakes the cookies, session tokens, or other sensitive information anotherfunctionandextendsthebehaviorofthefunctionwith- retained by the browser to the attackers. A straightforward out explicit modification. This mechanism has been widely solution is to validate the matched characters of a pre-defined adopted by security commits to add more detailed security pattern. List 12 is an example to fix the XSS vulnerability by restrictionsonexistingmethods.List15showsasecuritycom- re-matching the characters between parentheses instead of the mit that fixes an access control vulnerability by adding deco- charactersbetweensquarebracketsandvalidatingthematched rator security.private to function enumerateRoles. pattern one by one. D. Unique Patterns Captured from the Wild (RQ4) 4) Restrict Security Properties: The exploits often result from improper settings of security properties. 14.55% secu- Recall that we construct pilot and augmented datasets rity commits in PySecDB fix improper settings by updating because the base dataset provides a limited number of se- booleanflagsfromTruetoFalseorviceversa,addingmore curity commits samples. Here, we further show the examples arguments to methods, or adding security decorators. captured by our security commit collection approaches that 91 commit 2dad81128250cb2e5d950cddc9d3c0314a80b4bb add vulnerability fix labels to their commits, streamlining 2 diff --git a/src/Products/plugins/ZODBRoleManager.py b the code auditing process and reducing the workload on /src/Products/plugins/ZODBRoleManager.py 3 @@ -112,6 +112,7 @@ def getRolesForPrincipal(self, developers.Inaddition,downstreamdevelopersanduserswho principal, request=None): usethird-partylibrariescanbenefitfromtheSCOPYbybeing 4 # IRoleEnumerationPlugin implementation 5 + @security.private reminded to make necessary security fixes on time. Finally, 6 def enumerateRoles(self, id=None, exact_match= researchers can obtain labeled commits without requiring False, sort_by=None, max_results=None, **kw): 7 """ See IRoleEnumerationPlugin. extensivemanuallaborforfuturedata-drivenvulnerabilityand patch-related research. Listing15:Anexampleofsecuritycommitthatfixesanaccess Ethical Consideration. The SCOPY has the potential to control vulnerability (CVE-2021-21336). identify undisclosed vulnerability fixes, but this presents a introduce more variety in syntax and semantics of security- mixed blessing as attackers could exploit this information to relatedcodechanges,enablingwiderapplicationsofPySecDB target unpatched systems. Our objective in this paper is to in solving real-world Python-related security issues. prioritize the security of the users’ systems; that is why we 1) Data Variety Introduced by Pilot Dataset: We study only share detailed information on the security fixes, rather the contribution of involving the pilot dataset for SCOPY by than the vulnerabilities. By taking this approach, attackers comparing the model trained only on the base dataset and cannot leverage the SCOPY to gain additional details on the model trained on the combination of the base and pilot the vulnerabilities. However, with the SCOPY, open-source datasets. We find that the pilot dataset helps the latter model softwaremaintainerscanquicklyrevealvulnerabilitiesassoon tobeabletoidentifymorewildsecuritycommits.Forinstance, assecurityfixesbecomepublic,improvingtheoverallsecurity |
the latter SCOPY can detect more subtle changes. In List 16, of their software systems. the ’%s’ has been changed to ? in a SQL query, protecting the database from being injected. The capability of detecting VII. THREATSTOVALIDITY such minor changes is enabled by similar samples in the pilot Threats to internal validity. Internal bias and errors pose a dataset but not existed in the base dataset. significant risk in the dataset construction phase. The most essential threat is the exclusion of critical keywords or tokens 1 commit 9d8adbc07c384ba51c2583ce0819c9abb77dc648 2 diff --git .../__init__.py .../__init__.py that are important for identifying security-related commits. 3 @@ -71,7 +71,7 @@ def klauen(self, To address this issue, we propose an automated approach for 4 - a = u"name == ’%s’ AND item ==’%s’" % (name, item) 5 + a = u"name == ? AND item ==?", (name, item) learning security-related keywords. However, the current ap- Listing 16: An example of security commit detected by proachoftopicmodelsprioritizestheoccurrenceprobabilities SCOPY trained on the base and pilot datasets. of words, which may lead to ignoring infrequent but essential words or tokens. Additionally, commits lacking proper docu- 2) Variance Introduced by Augmented Dataset: We further mentation or commit messages are often overlooked, leading evaluate to show that our augmented dataset can help train a to further bias in the dataset. model that is able to identify more various security commits Threats to external validity. Our experiment and dataset from the wild. For example, after introducing augmented are focused on Python commits, which may limit the gen- datasetintothetrainingphase,themodeldetectsanewescape eralizability of the SCOPY to other programming languages. pattern. As shown in List 17, the characters <, >, and & have Also, since our dataset derives from open-source software, beenescapedbybeingtranslatedintoUnicode,whichprevents the data may not be applicable for identifying security-related cross-site-scripting crafted with a partial JSON-serializable commitsinclosed-sourcesystems.However,weaimtoexpand object. Compared with the escape expressions in Section V-C the scope of our research in the future by incorporating thatonlyincludeASCIIcharacters,theaugmenteddatasethelp more programming languages and diversifying our dataset to SCOPY generalize the escapes to Unicode. enhance the applicability of the SCOPY. 1 commit d3e428a6f7bc4c04d100b06e663c071fdc1717d9 Threats to construct validity. SCOPY is built on top of 2 diff --git a/.../djblets_js.py b/.../djblets_js.py Joern [39] to construct the code property graphs for the pro- 3 @@ -28,11 +28,18 @@ 4 +_safe_js_escapes = { grams of previous and current versions; thus, SCOPY inherits 5 + ord(’&’): u’\\u0026’, the limitations of Joern. Since Joern disregards the calling 6 + ord(’<’): u’\\u003C’, 7 + ord(’>’): u’\\u003E’, relations among multiple functions, SCOPY cannot handle 8 +} the commits that only change the function calls. Besides, Listing 17: A security commit example detected by the Joern cannot identify the import and use operations of Python SCOPY trained on the base, pilot, and augmented datasets. packages; thus, SCOPY discards these edges in CommitCPG when the commits only operate packages. VI. DISCUSSION VIII. CONCLUSIONANDFUTUREWORK Usability.TheSCOPYisversatileandnottiedtoanyspecific platform or commit format, making it compatible with a wide By fully leveraging the commit message and the code range of version control systems like GitHub and GitLab. By change semantics, we construct a large-scale Python security integratingtheSCOPYasanextension,contributorscaneasily commit dataset named PySecDB that consists of three parts: 10base,pilot,andaugmenteddatasets.Toenrichthebasedataset [15] Y. Zhou, J. K. Siow, C. Wang, S. Liu, and Y. Liu, “SPI: Automated extracted from CVE reports, the pilot dataset collects the identification of security patches via commits,” ACM Transactions on SoftwareEngineeringandMethodology(TOSEM),vol.31,no.1,pp.1– commits that contain the pre-defined security keywords in 27,2021. their commit messages. Given the diversified data samples, [16] S. Hochreiter and J. Schmidhuber, “Long short-term memory,” Neural we further train SCOPY to learn the security semantics in computation,vol.9,no.8,pp.1735–1780,1997. [17] Z. Feng, D. Guo, D. Tang, N. Duan, X. Feng, M. Gong, L. Shou, the code changes to compensate for the poorly documented B. Qin, T. Liu, D. Jiang, et al., “CodeBERT: A pre-trained model for commits.Weconductalarge-scaleempiricalstudyofsecurity programmingandnaturallanguages,”arXivpreprintarXiv:2002.08155, commitsbyanalyzingPySecDBof119CWEcategoriesacross 2020. [18] D. M. Blei, A. Y. Ng, and M. I. Jordan, “Latent dirichlet allocation,” 351 repositories. The summarized patterns can assist further Journal of machine Learning research, vol. 3, no. Jan, pp. 993–1022, software maintenance, e.g., auto program repair. In the future, 2003. we will adopt large language models to expand the dataset [19] F. Yamaguchi, N. Golde, D. Arp, and K. Rieck, “Modeling and Dis- covering Vulnerabilities with Code Property Graphs,” in 2014 IEEE and apply the summarized patterns to fix the vulnerabilities SymposiumonSecurityandPrivacy,pp.590–604,2014. automatically. [20] M.Weiser,“Programslicing,”IEEETransactionsonsoftwareengineer- ing,no.4,pp.352–357,1984. |
ACKNOWLEDGMENTS [21] NIST,“NVDCWESlice.”https://nvd.nist.gov/vuln/categories. [22] J.Fan,Y.Li,S.Wang,andT.N.Nguyen,“AC/C++codevulnerability We would like to thank our anonymous reviewers for their dataset with code changes and CVE summaries,” in Proceedings of valuable comments and suggestions. This work was partially the 17th International Conference on Mining Software Repositories, pp.508–512,2020. supportedbytheUSOfficeofNavalResearchgrantsN00014- [23] G.Nikitopoulos,K.Dritsa,P.Louridas,andD.Mitropoulos,“CrossVul: 23-1-2122. across-languagevulnerabilitydatasetwithcommitdata,”inProceedings of the 29th ACM Joint Meeting on European Software Engineering REFERENCES ConferenceandSymposiumontheFoundationsofSoftwareEngineering, pp.1565–1569,2021. [1] “TIOBEIndexforApril2023.”https://www.tiobe.com/tiobe-index/. [24] G. Bhandari, A. Naseer, and L. Moonen, “CVEfixes: automated col- [2] J. Ruohonen, K. Hjerppe, and K. Rindell, “A Large-Scale Security- lectionofvulnerabilitiesandtheirfixesfromopen-sourcesoftware,”in Oriented Static Analysis of Python Packages in PyPI,” 2021 18th Proceedingsofthe17thInternationalConferenceonPredictiveModels InternationalConferenceonPrivacy,SecurityandTrust(PST),p.1–10, andDataAnalyticsinSoftwareEngineering,pp.30–39,2021. Dec2021. [25] Y. Chen, Z. Ding, X. Chen, and D. Wagner, “DiverseVul: A New [3] PyPI.https://pypi.org/,2023. VulnerableSourceCodeDatasetforDeepLearningBasedVulnerability [4] CommonVulnerabilitiesandExposures(CVE).https://cve.mitre.org/. Detection,”arXivpreprintarXiv:2304.00409,2023. [5] X. Wang, S. Wang, P. Feng, K. Sun, and S. Jajodia, “PatchDB: A [26] X. Wang, K. Sun, A. Batcheller, and S. Jajodia, “Detecting” 0-day” large-scale security patch dataset,” in 2021 51st Annual IEEE/IFIP vulnerability: An empirical study of secret security patch in OSS,” in InternationalConferenceonDependableSystemsandNetworks(DSN), 201949thAnnualIEEE/IFIPInternationalConferenceonDependable pp.149–160,IEEE,2021. SystemsandNetworks(DSN),pp.485–492,IEEE,2019. [6] S. E. Ponta, H. Plate, A. Sabetta, M. Bezzi, and C. Dangremont, [27] Y. Zhou and A. Sharma, “Automated identification of security issues “A manually-curated dataset of fixes to vulnerabilities of open-source from commit messages and bug reports,” in Proceedings of the 2017 software,”in2019IEEE/ACM16thInternationalConferenceonMining 11thjointmeetingonfoundationsofsoftwareengineering,pp.914–919, SoftwareRepositories(MSR),pp.383–387,IEEE,2019. 2017. [7] F.LiandV.Paxson,“Alarge-scaleempiricalstudyofsecuritypatches,” [28] A. D. Sawadogo, T. F. Bissyande´, N. Moha, K. Allix, J. Klein, L. Li, inProceedingsofthe2017ACMSIGSACConferenceonComputerand and Y. L. Traon, “Learning to catch security patches,” arXiv preprint CommunicationsSecurity,pp.2201–2215,2017. arXiv:2001.09148,2020. [8] S.Kim,S.Woo,H.Lee,andH.Oh,“VUDDY:Ascalableapproachfor [29] R. Cabrera Lozoya, A. Baumann, A. Sabetta, and M. Bezzi, “Com- vulnerablecodeclonediscovery,”in2017IEEESymposiumonSecurity mit2Vec: Learning distributed representations of code changes,” SN andPrivacy(SP),pp.595–614,IEEE,2017. ComputerScience,vol.2,pp.1–16,2021. [9] X. Wang, S. Wang, P. Feng, K. Sun, S. Jajodia, S. Benchaaboun, and [30] D. Guo, S. Ren, S. Lu, Z. Feng, D. Tang, S. Liu, L. Zhou, N. Duan, F.Geck,“PatchRNN:Adeeplearning-basedsystemforsecuritypatch A. Svyatkovskiy, S. Fu, et al., “GraphCodeBERT: Pre-training code identification,”inMILCOM2021-2021IEEEMilitaryCommunications representationswithdataflow,”arXivpreprintarXiv:2009.08366,2020. Conference(MILCOM),pp.595–600,IEEE,2021. [31] PyQt.https://wiki.python.org/moin/PyQt. [10] Z. Li, D. Zou, S. Xu, H. Jin, H. Qi, and J. Hu, “VulPecker: an auto- [32] django: The Web framework for perfectionists with deadlines. matedvulnerabilitydetectionsystembasedoncodesimilarityanalysis,” https://github.com/django/django. in Proceedings of the 32nd annual conference on computer security [33] twisted: Event-driven networking engine written in Python. applications,pp.201–213,2016. https://github.com/twisted/twisted. [11] J.Zhou,M.Pacheco,J.Chen,X.Hu,X.Xia,D.Lo,andA.E.Hassan, [34] OpenStackImageManagement.https://github.com/openstack/glance. “CoLeFunDa:ExplainableSilentVulnerabilityFixIdentification,” [35] python-pillow/Pillow: Python Imaging Library. [12] J. Zhou, M. Pacheco, Z. Wan, X. Xia, D. Lo, Y. Wang, and A. E. https://github.com/python-pillow/Pillow. Hassan, “Finding a needle in a haystack: Automated mining of silent [36] numpy:ThefundamentalpackageforscientificcomputingwithPython. vulnerability fixes,” in 2021 36th IEEE/ACM International Conference https://github.com/numpy/numpy. onAutomatedSoftwareEngineering(ASE),pp.705–716,IEEE,2021. [37] X.Wang,S.Wang,K.Sun,A.Batcheller,andS.Jajodia,“Amachine |
[13] S.Wang,X.Wang,K.Sun,S.Jajodia,H.Wang,andQ.Li,“GraphSPD: learningapproachtoclassifysecuritypatchesintovulnerabilitytypes,” Graph-BasedSecurityPatchDetectionwithEnrichedCodeSemantics,” in 2020 IEEE Conference on Communications and Network Security in 2023 IEEE Symposium on Security and Privacy (SP), pp. 604–621, (CNS),pp.1–9,IEEE,2020. IEEEComputerSociety,2022. [38] Why Use Python for Web Development? [14] B. Wu, S. Liu, R. Feng, X. Xie, J. Siow, and S.-W. Lin, “Enhancing https://www.imaginarycloud.com/blog/why-use-python-for-web- securitypatchidentificationbycapturingstructuresincommits,”IEEE development/,Dec2020. TransactionsonDependableandSecureComputing,2022. [39] Joern:TheBugHunter’sWorkbench.https://joern.io/. 11 |
2307.11917 Vulnerability Detection Through an Adversarial Fuzzing Algorithm Michael Wang Michael Robinson Montgomery Blair High School Department of Mathematics & Statistics Silver Spring, MD American University mxw206@gmail.com Washington, DC michaelr@american.edu Abstract—Fuzzingisapopularvulnerabilityautomatedtesting propose the augmentation of an adversarial method on top of method utilized by professionals and broader community alike. apopular,existingevolutionaryfuzzer,AFL(AmericanFuzzy However, despite its abilities, fuzzing is a time-consuming, com- Lop) [5]. We assert that our augmented method is extendable putationally expensive process. This is problematic for the open (with proper interfacing) to other software fuzzing programs source community and smaller developers, as most people will not have dedicated security professionals and/or knowledge to and targets with slight modifications to existing code. In perform extensive testing on their own. The goal of this project Section II, we discuss the implementation and methodology istoincreasetheefficiencyofexistingfuzzersbyallowingfuzzers behind our approach. In Section III, we reveal the results of to explore more paths and find more bugs in shorter amounts ourmethodcomparedtotheoriginalfuzzer.Finally,inSection of time, while still remaining operable on a personal device. To IV, we conclude with a summary of our findings and avenues accomplish this, adversarial methods are built on top of current evolutionary algorithms to generate test cases for further and for further research. more efficient fuzzing. The results of this show that adversarial II. BACKGROUND attacks do in fact increase outpaces existing fuzzers significantly and, consequently, crashes found. A. Neural Smoothing and Approximation Index Terms—Fuzzing, Adversarial Samples, Vulnerabilities The universal approximation theorem tells us neural net- works are able to approximate any continuous function [13]. I. INTRODUCTION This is important as, while typical smoothing masks are built Fuzzersareinwidespreadusefortestingsoftware.Usedby upon integrals and computed analytically [6], it is infeasi- hackers, cybersecurity professionals, software developers, and ble to create a closed form of or analytically compute a more, fuzzing is a valuable technique that discovers bugs and computer program. As such, the use of a neural network implementation flaws through immense swaths of malformed couldpotentiallybevaluableinmodelingprogrambehaviorby payloads. learning smooth approximations of their complex behaviors. Fuzzing has been met with a lot of success in years past; This idea is demonstrated in several studies. While traditional the OSS-FUZZ [1] project revealed over 30,000 bugs in 500 softwaremodelshaveexperiencedsuccessintheirapplications open-source projects. Despite this, there remain many areas [14] [15], they fall short on real-world programs with far uponwhichexistingfuzzerscanbeimproved.Inparticular,the more complicated behaviors. On the other hand, models that currentstate-of-the-artforsoftwarefuzzinghasshiftedtowards utilize similar machine learning methods prove to have far anemphasisonmaximizingcodecoverage.Morerecently,the more success [6] [16] [17]. This is important in the context application of machine learning has appeared in the field as of our design because fuzzing requires the program to be well. Some notable examples of this include the use of RNNs able to explore, make sense of, and debug large, complicated in input generation [2], the use of genetic algorithms to guide programs. mutation strategies [3] [4] [5], and the use of neural networks Neural networks also are very relevant in the area of to model code coverage [6]. adversarial learning. The current most effective adversarial In this article, an approach that combines fuzzing with methods rely on the computation of gradients to search for adversarialattacksisexplored.Whiletraditionallyatechnique adversarial samples. As such, adversarial methods have been heavily employed in the machine learning fields of computer almost exclusively reserved for deep learning models due to vision and image recognition, adversarial attacks find applica- theeaseofgradientcomputationandthelackofdiscontinuities tions in many AI-gated systems [7] [8] [9] [10]. In this case, in the generated approximation. A neural network therefore adversarial attacks could potentially position themselves well has the potential to prove itself as a strong choice in enabling toassistfuzzingsoftwareduetoitsabilitytocarryouttargeted the use of adversarial methods. It is not only capable of attacks and transfer them to other systems [11] [12]. As such, accuratelycapturingprogrambehavior,butitattemptstocreate we develop the application of machine learning in fuzzing a smooth approximation of the behavior in the process. These programs to improve the efficiency of existing fuzzing meth- properties enable the use of gradient-based attacks, which in ods, even on low-performance devices. More specifically, we turn could transfer to the program. 3202 luJ 12 ]ES.sc[ 1v71911.7032:viXraB. Adversarial Attacks Adversarial methods have grown immensely due to the rising prevalence of deep learning. Adversaries can now ma- nipulate and perturb DNNs to force instances of misclassi- fication. But while this effect is well-studied in computer vision, this method draws a parallel to computer programs. By accurately representing a target program with a neural network, adversarial samples targeting the neural network can Fig.1. Summaryofthepiecesinthemodifiedfuzzingalgorithm. be crafted and by extension, samples that target the program itself. One particular method is chosen in the construction of A. Preprocessing the modified fuzzing algorithm within this paper, namely, the Thefuzzerstartsfromasetofprogramdata,whichinvolves |
Jacobian Saliency Map Attack (JSMA) [18]. an initial exploratory phase without a neural network in order togatherenoughdata.Thedataisthenpreprocessed,carefully C. Fuzzing with AFL tracking the number of times each edge appears across each To understand the goal of the various methods presented in test case. In order to encode the structured data in a way that this fuzzer, it is important to understand how AFL maintains is recognizable by both the fuzzer and the neural network, itsprocess.OfthemanycomponentstoAFL,itisparticularly several additional steps are taken. Each input is converted to important to understand how inputs are mutated and then a series of Unicode bytes before being turned to a series of evaluated by the fuzzer. integer values and normalized. This process is summarized in For each input generated by AFL, there is a associated Figure 2, where an example is given of the procedure. bitmap that stores the hits of each set of inputs encountered throughthefuzzingprocess.Thistraceiscomparedtoaglobal map updated throughout the entire fuzzing process to help AFL determine if any new behavior was found in the fuzzing process. Through this mechanism, AFL is able to track the branch (edge) coverage of the program, storing successful inputs as seeds to use as a starting point for future rounds of fuzzing. This will serve as the basis for our augmented method to find new areas in the program. For the actual fuzzing, AFL’s mutation algorithm can be split into two primary parts: deterministic and non- deterministic fuzzing. In the deterministic stage, the fuzzer iterates through the inputs and sequentially navigates through Fig.2. Walkthroughoftheinputencodingprocess. a series of preprogrammed mutations. These include bit flips, adding constant values, setting bytes to known-to-be- Due to the limitations of a neural network, inputs into the troublesome values, and more. As a consequence, whenever network must always be set to a particular size. As such, the an input is fuzzed, AFL guarantees that the fuzzer searches neural network is trained to accommodate the largest-sized withinacertainareaaroundtheinput.Fromthere,AFLmoves input in the corpus, and all other entries are padded with null intoitsnon-deterministic,alsoreferredtoas”havoc”,stage.At bytes. This helps to meet the size limitation without altering thispoint,thefuzzerappliesrandomtrickstomutatetheinput the input itself. even further. These include operations such as input splicing, Thepreprocessingoftheoutputisrelativelysimpleaswell. insertions,deletions,andmore.Asusefulasthismightbewith In the execution of each test case, AFL returns a list of the some good luck, this also leads to many wasted mutations, edges encountered and assigns each one a unique ID label. inspiring the use of new methods to help the fuzzer land at With this, we compile each list together and return a one-hot- more effective inputs more frequently. encoded vector, representing which edges a particular input encounters.Therearealsoseveraladditionalstepstakenduring III. METHODOLOGY this stage to reduce the size of the output. Edges that are always activated together are condensed into one node to The key idea behind the fuzzing scheme lies in the gener- reduce the amount of information. Furthermore, only edges ation of adversarial samples to expedite the fuzzing process. that have been activated at least once are included within the Targetinginactivatededges,eachtestcaseismutatedfollowing output vector to prevent overly sparse bitmaps. the computed gradient for the targeted edge. When combined B. Neural Network with the blanket, deterministic fuzzing and random havoc stages performed by AFL, there is a higher chance of finding In designing the neural network, a simple, feed-forwand inputs that uncover rare edges. denseneuralnetworkwasusedtoincreasetheeaseofgradientcomputation. As such, the network was kept relatively simple Underthenativeimplementation,JSMAisconfiguredtoin- with only two hidden, fully connected layers of 256 neurons terferewiththefinalprobabilitiesinamulti-classclassification each. The network was also trained with binary cross-entropy problem.However,computersoftwareendsupasacompletely as our primary mechanism to compute the distance between different class of problem as each input has a set of edges it the predicted and true coverage of the outputted bitmap. covers, making it difficult to set a constant adversarial target Design-wise, because linear behavior in higher dimensions for each test case. While multi-label classification describes has been shown to increase the speed and effectiveness of this situation, the fuzzer only cares about the probability of adversarial attacks [19], the rectified linear activation unit the target edge, meaning that the other labels only serve as (ReLU) is used in the hidden layers. On the outside, the extraneousinformationthatmayhindertheconvergenceofthe network takes a fixed size program input in the form of a attack.Toaddressthis,inthismethod,theprobabilityreturned byte sequence. For its output, the network outputs an edge throughthenetworkispreservedthroughouttheattack.Given bitmap, essentially a one-hot encoded vector of all the unique that only one class is attacked at a time, this limitation can be paths discovered through AFL’s fuzzing process. The output worked around by ignoring the probabilities from non-target layer resolves to a sigmoid function because multiple edges classes.Specifically,wefirstuseasigmoidfunctiontoevaluate can be traversed through one input. thelogitsreturnedfromtheinput.Asinsuchasituation,each probability acts independently of the other, the success of the bitmap can be broken down and verified instead by separately checking each edge individually. As a consequence of this change, we preserve only the logits to the classes we are interested in targeting. In doing this, we remove any assigned importanceonotheredges,notonlyremovingtheneedtoread |
overextraneousedges,butalsoallowingtheadversarialmodel tofocusonourtargetclasses,withoutthepressuretomaintain or deactivate any activated paths from the initial input. This allows the attacks to converge more often onto target classes Fig. 3. General architecture of the trained neural network. Consists of two with higher confidence. hiddenlayersandtrainstoroughly94%accuracyeachcycle. Another important alteration from the original JSMA is that the saliency computation doesn’t rank inputs past the The neural network is retrained and updated with new length of the input. While unlikely that these values are sample cases if any of the following three conditions are met. considered to be substantially salient by the algorithm, to be (1) A certain number of new cases have been found. (2) A safe, we discount these values completely by removing them newcaseisfoundthateitherdiscoversanewedgeorislarger from the calculation. Instead, we substitute their values on than any previous case. (3) The fuzzer has arrived at the end the map with 0, giving the minimum possible saliency value of a fuzzing cycle (All queue cases have been handled). and removing any possibility of them being considered. The actual manipulation of the sizes of each input are handled C. Adversarial Method by random insertions, deletions, splicing, and other strategies The method computes the signed gradient of the neural invoked through AFL. network with respect to the input in order to generate an D. Parallelization adversarial saliency map. This method can find and leverage high-saliency features with an input, which are then mutated Both the neural network and adversarial method are run in by the parameter that controls the magnitude of perturbation. parallel to the actual fuzzing process. As interesting test cases These mutations are repeated up to a certain number of are passed into the fuzzing cycle, they are also passed into iterations with accordance to the JSMA attack. Note that a separate process that crafts targets with adversarial samples although the JSMA attack is modified to meet the needs of targetingthenleastfrequentedgesdependingontheprogram program-based fuzzing, the essense of the algorithm remains size. This operation is facilitated by splitting the fuzzer into the same. The attack constructs an adversarial saliency map - two main processes. One process is the actual fuzzer, being a input (in this case a vector) that ranks all the original input AFL in this case. The other process manages the components features chosen from how influential they are in leading the ofouraugmentedmethod,suchasinputprocessing,theneural modeltopredictacertainclass.Inshort,thealgorithmconsists network, and the use of adversarial attacks. Because our of iterating the three following steps until either the target augmented method requires these the components to work is reached or a certain number of iterations is reached. (1) closely together, we split the second process into two threads. Assuming F(X) to be the vector-valued function that maps to One acts as a control tower for the functioning of the fuzzer, theoutputYascomputedbytheneuralnetwork,compute∇F. whiletheotherremainsopentologeverysignalitencounters. (2) Construct an adversarial saliency map computed from the Combined,thetwothreadsaresettolistenandrecordallthe derivatives with respect to the input. (3) Modify the identified communication done in a queue, which distributes commands input features. to each of the two processes. Loading these commands into aFig.4. Diagramdetailinghowtheparallelprocessesinteractwithoneanother. queue is a relatively important part of this process because it oughlyevaluatetheperformanceofthefuzzers.Theprograms ensures that instructions are sent in order, preventing the pos- are Fuzzgoat [20], libxml2, libpng, openssl x509 and mupdf. sibilityoflosingsignalsamidstthevastamountofinformation While the other four are popular real world programs, thus being communicated. making them valauble to test, Fuzzgoat was chosen for a Between the fuzzer and these various components, sockets different reason. Fuzzgoat is a deliberately flawed C program connections and file writing act as the primary forms of com- of decent length made to test fuzzers. This choice was made munication. Updated inputs discovered through the fuzzing totestthemechanisminanenvironmentwherevulnerabilities processed are logged as text files in a folder which are then were already marked in the code for analysis. Additionally, read by the preprocessing code. Likewise, mutated inputs are Fuzzgoat could execute relatively quickly, meaning that dif- passed back into the fuzzing cycle for further mutation, either ferences in computational efficiency are more transparent, as directly being sent via the socket, or stored as a file in the differencesinruntimewouldnotberelatedtotheloadincurred queue folder if deemed too large. Otherwise, various signals from the program. are sent via the socket throughout the fuzzing process. These A total of four fuzzers, the modified algorithm, AFL [5], often indicate key milestones such as new cycles, new paths FairFuzz[21],andAFL++[22],aretestedandcomparedwith discovered, and priority inputs to attack. one another to evaluate how this fuzzing method shapes up to IV. EVALUATION the industry standard. AFL serves as a base comparison for thefuzzerastheaugmentedmethodisbuiltontopoftheAFL In this section, we discuss how the adversarial method was algorithm.FairFuzzwasalsoidentifiedasavaluablefuzzerfor tested and how well the fuzzer performed. comparisonbecauseliketheadversarialmethod,itattemptsto A. Target target rarer branches while adopting a far different approach. This fuzzer was tested across a variety of open source Finally,AFL++wasincludedasawaytocomparethismethod |
programs of different sizes and input formats in order to thor- to what is widely regarded as the industry standard. Each testTABLEI SUMMARYSTATISTICSOFTHEFOURTESTEDFUZZERSONFUZZGOAT(5X30MINUTETRIALS) Evaluated Metrics Fuzzers AverageExecutionsPerSecond TotalExecutions(Millions) LevelsofMutation PathsFound UniqueCrashesFound Adversarial 5078.26 7.73 21 699 46 AFL 5522.47 8.48 26 618 31 AFL++ 6004.86 9.07 31 646 40 FairFuzz 4749.93 7.51 25 673 38 TABLEII EDGECOVERAGEOFTHEFOURTESTEDFUZZERSONOTHERPROGRAMS(3X24HOURTRIALS) Evaluated Targets Fuzzers libxml2-v2.9.2 libpng-1.2.56 openssl x509 mupdf Adversarial 5154 1713 1255 417 AFL 5002 1690 1144 360 AFL++ 5441 1727 1298 388 FairFuzz 4688 1750 1287 355 was an average of five runs on Fuzzgoat for 30 minutes each, able to consistently maintain its performance, indicating its which proves to be enough time to explore the majority of performanceiscomparabletosimplergeneticfuzzersthatlack the program, regardless of which method we employ. For the complicated machine learning architecture. other programs, the results are taken from 3 runs of 24 hours each. The fuzzers are run on a machine with an AMD Ryzen 7 5700U processor, 12 GB memory, 64-bit Microsoft Windows 11 Home Operating System, and x64-based processor. Each process is hosted on Ubuntu 20.04.4 LTS with 5888 MB of memory each. B. Results We present three primary differences in the performance of the modified fuzzing algorithm: 1) Runtime: For this section we look exclusively at Fuz- Fig.5. Comparisonovertimebetweenthepathcoverageoftheadversarial zgoat as is a much more controlled environment. Any differ- fuzzer,AFL,AFL++,andFairFuzzwhentestedonFuzzgoat. encesinruntime/computationalefficiencyaremorenoticeable because we reduce the effect of any load brought by the 2) Path Coverage: The results in Figure 5 indicate that program itself. Notice in Figure I that the execution speed of the adversarial fuzzer accomplishes its task when compared theoriginalAFLisnotablyhigherthantheexecutionspeedof to AFL. Looking only at Fuzzgoat, despite running slower the adversarial fuzzing algorithm. Specifically, the execution than the other algorithms, the coverage exhibited by the speed experienced by AFL is on average, 5522 executions algorithm still finds far more paths in the same amount of per second, whereas the execution speed of the adversarial time. Furthermore, the adversarial fuzzer also leads the other fuzzing algorithm falls to about 5078 executions per second; fuzzerswhilefuzzingFuzzgoat,showinghowitcanfindthese Anear10%differenceinexecutionspeed.Thisisexplainable paths sooner than other methods. Notably, FairFuzz, AFL++, as the revised fuzzing algorithm is more computationally and AFL dig significantly deeper into their test cases to find intensive and contains many more parts. Hardware aside, the thesameresults.Onaverage,in30minutesFairFuzz,AFL++, adversarial algorithm relies on thousands of rapid gradient and AFL explore 25, 31, and 26 levels, respectively, while computations to arriveat a new test case,something that AFL the adversarial algorithm searches only 21. This difference does not have to do. The added workload likely inhibited the suggests that adversarial methods could successfully inject fuzzer, especially since the processes were run in the same much more valuable test cases to fuzz, skipping over extra instance on the same machine. Despite this, the adversarial levels of mutation spent searching for critical inputs. fuzzing algorithm can keep up with the other two fuzzers That said, when we compare the performance of of each in terms of speed, even beating FairFuzz. This is reflected fuzzer across our various real world targets, these results be- in Table I, where AFL++ ran the most executions, followed come slightly different (see Figure 6). Over longer periods of by AFL, then the adversarial method, and finally FairFuzz, time,theedgecoveragewithrespecttotimetendstoevenout, at 9.07, 8.48, 7.73, and 7.51 million executions respectively. While AFL++ boasts the highest edge coverage overall, the Throughout the fuzzing process, the adversarial fuzzing is adversarial method seems to follow behind, outforming bothability to discover new areas sooner than AFL. 3) Crashes: Crashes found are an interesting metric be- cause detecting bugs in the ultimate goal in softare fuzzing. That said, with the exception of Fuzzgoat, crashes found is a poor metric to evaluate with because bugs are typically very sparse in real world programs. As such, this section will primarily focus on the fuzzing results from Fuzzgoat in order to provide evidence that edge coverage is a valid proxy for bugsdiscovered.ItcanbeobservedinFigureIthatcrashesare foundmuchsoonerandfasterintheadversarialschemethanin theotherthreefuzzers.Theadversarialalgorithmuncovers46 instances of unique crashes while FairFuzz, AFL++, and AFL find 37, 40, and 31, respectively. This aligns with the findings forpathcoverage.Itisreasonabletolinkcoverageandcrashes together as with more paths discovered, the bugs within those paths are discovered as well. While not trained to look for harmful inputs, the results show that by increasing path coverage, vulnerability detection also increases. We suspect thattheadversarialmethodcandothisbecausetheadversarial methodactivatesafargreaterareaintheinputspace.Thisisin accordancewithpreviousstudiesthatfindintheirapplications that path coverage increases bug detection [6] [23] [24]. V. DISCUSSION The results of our method show that this technique is a promising way to increase fuzzing efficiency. With a neural network, we can effectively identify points of attack and |
engineer specific edges to appear by conducting a saliency map attack. However, along with this, there are a few things to note. 1) Model Performance: Model performance has proved to greatly affect the fuzzer. As the algorithm is based on a gradient-guidedoptimizationmethod,thereturngradientsmay not be accurate, which is a problem only exacerbated when the neural network itself is not accurate. Thus, we see a fall in performance when we train the network inadequately. 2) Hardware: Whilethe resultsof thisstudy showpromis- ingresultsinovercomingchallengesincomputationefficiency, the more powerful, the better. This experiment was not run Fig.6. Comparisonovertimebetweentheedgecoverageoftheadversarial fuzzer, AFL, AFL++, and FairFuzz when tested on various real world on an optimal configuration, and because of that, the model programs. may have suffered in several ways. Notably, the speed at which adversarial inputs can be generated and inserted into the fuzzing queue slows significantly. AFL and FairFuzz. This indicates the adversarial methods are This has several important ramifications. The current attack successful in deriving cases that produce extra edge coverage is configured to search for the first 50 uncommon edges, when compared to its original algorihtm (AFL). Notably, the primarily because each attack takes time, and many seeds performance of our adversarial method seems to excel in need to be mutated. In addition, the amount of iterations the medium to smaller sized programs like mupdf and Fuzzgoat, attack takes has been reduced from 2000 to 200. This change while AFL++ is able to experience more success with larger isalsotospeedupeachcaseandisjustanotherinstancewhere programs like libxml2 and opennssl. When compared directly we sacrifice some adversarial samples so that the attacks can to AFL, we can see that the adversarial fuzzer is able to keep up with the fuzzer. Given this, it is reasonable to believe consistently find more paths and in shorter aounts of time that the results of this fuzzing scheme would only be better as well. For instance, while AFL struggled with openssl, the with different equipment. This difference would allow for an adversarial algorithm was able to overcome this issue and increase in not just the quantity of samples generated, but remain on par with the other two fuzzers. Furthermore, in the quality of each one as well. Attacks could search more mupdf and libxml2, the adversarial algorithm showed the rigorously and identify potential samples that exist furtherFig.7. ExamplesofaJSMAandFSGMattackrunonanexampleinputdiscoveredduringtheinitialdiscoveryphaseofthefuzzer.Notably,theJSMAonly mutatesafewselectfeatures(boxedinred),whileFSGMaffectsalmosttheentirefeaturespacetoachievethesameresult. away from the seeded input. Similarly, the reduced execution variation, which allows the algorithm to set bounds on how speed on our adversarial method could be mitigated if run much an input changes and how much to modify each input on separate instances. Despite this, this fuzzing scheme still feature. showsimpressiveadaptability,especiallywhencomparedwith 3) Guided Mutation: The use of a saliency map is par- other state-of-the-art fuzzers in Tables I and II. ticularly beneficial in mutation-based fuzzing algorithms. In identifying groups of important features, the algorithm can A. Adversarial Method focus on mutating only high-impact bytes, which is apparent When comparing this attack to others, we find that this in Figure 7. Furthermore, because the algorithm iterates over mechanism fits a few important criteria which makes it su- thesegradientsmanytimes,wecanarriveatinputsthatwould perior to other forms of gradient-based attacks. take multiple rounds of fuzzing to reach. These two factors 1) NullByteSpillover: OneoftheuniquefeaturesofJSMA greatlydecreasetheamountofpotentiallywastefulmutations. is its adversarial saliency map. The map identifies a set of inputs most important in mutating the output in its desired VI. CONCLUSION direction. Using this mechanism, we can specifically craft saliency maps that focus only on features that already exist This report presents a new fuzzing scheme that combines within the current input. This identification helps prevent any the concept of adversarial attacks with the fuzzing of a target spillover into null bytes. We can observe this difference when program. Unlike current GAN-related approaches with fixed- comparing JSMA with other methods. Although methods like sized outputs generated between fuzzing cycles, this fuzzer the Fast Gradient Sign Method (FGSM) [19] and Projected implements a version of the Jacobian Saliency Map Attack Gradient Descent [25] create small perturbations, the noise to craft samples to preserve the length of original inputs gets distributed across the entire input, often activating many and run parallel to the fuzzing process. Generated cases are null bytes by accident. This is demonstrated in Figure 7. As inserted into the fuzzing queue to be fuzzed live and new such, inputs are generated using a saliency map to avoid this interesting cases are sent back to the network to refine the issue. model. An evaluation of the setup indicates that this method 2) Perturbation Magnitude: As research into adversarial increases the coverage of AFL and by extension, the bugs attacks continues, there is a continued emphasis on the foundwithintargetprograms.Thismethodwasalsocompared imperceptibility of attacks. While useful in the context of to other common fuzzers on real world programs and showed image classification and the like, that is less of a concern in comparableperformance.Thefindingsfurthersuggestthatthis fuzzing. Popular attacks like the Carlini and Wagner attack method could be even more powerful if done with improved |
[26], optimize to minimize distance metrics, which is not hardware setups, more efficient fuzzing/coding practices, and particularly important in this context. On the flip side, JSMA optimized parameter configurations. canbeconfiguredtomakelarger,moremeaningfulmutations, Asresearchintoadversarialtechniquesandneuralnetworks whichusuallygetsplitintonumerous,smallerperturbationsin progress,wecanexpecttoseeamoremathematicallyconcrete otherattacks(seeFigure7).Furthermore,saliencymapattacks version to optimize the susceptibility of the network while have a great degree of freedom for distortion and feature minimizing the impact on accuracy. The closer we get to asolution, the easier it is to find adversarial examples in space, [21] C. Lemieux and K. Sen, “FairFuzz: A targeted mutation strategy greatly enhancing the potential of this methodology. for increasing greybox fuzz testing coverage,” in Proceedings of the 33rd ACM/IEEE International Conference on Automated Software Engineering. ACM, sep 2018. [Online]. Available: https: ACKNOWLEDGMENT //doi.org/10.1145%2F3238147.3238176 We acknowledge the The Blair Jones Fund from the Amer- [22] A.Fioraldi,D.Maier,H.Eißfeldt,andM.Heuse,“AFL++:Combining incremental steps of fuzzing research,” in 14th USENIX Workshop on ican University Mathematics and Statistics Department for OffensiveTechnologies(WOOT20). USENIXAssociation,Aug.2020. hosting this project and making it possible. [23] G. Yi, X. Yang, P. Huang, and Y. Wang, “A coverage-guided fuzzing frameworkbasedongeneticalgorithmforneuralnetworks,”in20218th REFERENCES InternationalConferenceonDependableSystemsandTheirApplications (DSA),2021,pp.352–358. [1] K. Serebryany, “OSS-Fuzz - Google’s continuous fuzzing service for [24] X. Zhao, H. Qu, W. Lv, S. Li, and J. Xu, “MooFuzz: Many-objective open source software.” Vancouver, BC: USENIX Association, Aug. optimization seed schedule for fuzzer,” Mathematics, vol. 9, no. 3, 2017. 2021.[Online].Available:https://www.mdpi.com/2227-7390/9/3/205 [2] P.Godefroid,H.Peleg,andR.Singh,“Learn&Fuzz:Machinelearning [25] A.Kurakin,I.Goodfellow,andS.Bengio,“Adversarialmachinelearning forinputfuzzing,”201732ndIEEE/ACMInternationalConferenceon atscale,”2017. AutomatedSoftwareEngineering(ASE),Oct2017.[Online].Available: [26] N.CarliniandD.Wagner,“Towardsevaluatingtherobustnessofneural http://dx.doi.org/10.1109/ASE.2017.8115618 networks,”2017. [3] G. Yi, X. Yang, P. Huang, and Y. Wang, “A coverage-guided fuzzing frameworkbasedongeneticalgorithmforneuralnetworks,”in20218th InternationalConferenceonDependableSystemsandTheirApplications (DSA),2021,pp.352–358. [4] D. Ray and S. Seshan, “CC-fuzz,” Proceedings of the 21st ACM Workshop on Hot Topics in Networks, Nov 2022. [Online]. Available: http://dx.doi.org/10.1145/3563766.3564088 [5] “American Fuzzy Lop (AFL),” Tech. Rep. [Online]. Available: https://lcamtuf.coredump.cx/afl/technical details.txt [6] D. She, K. Pei, D. Epstein, J. Yang, B. Ray, and S. Jana, “NEUZZ: Efficient fuzzing with neural program smoothing,” 2019 IEEE Symposium on Security and Privacy (SP), May 2019. [Online]. Available:http://dx.doi.org/10.1109/SP.2019.00052 [7] F.Cartella,O.Anunciacao,Y.Funabiki,D.Yamaguchi,T.Akishita,and O.Elshocht,“Adversarialattacksfortabulardata:Applicationtofraud detectionandimbalanceddata,”2021. [8] M.M.Irfan,S.Ali,I.Yaqoob,andN.Zafar,“Towardsdeeplearning: A review on adversarial attacks,” in 2021 International Conference on ArtificialIntelligence(ICAI),2021,pp.91–96. [9] K.Ren,T.Zheng,Z.Qin,andX.Liu,“Adversarialattacksanddefenses in deep learning,” Engineering, vol. 6, no. 3, pp. 346–360, 2020. [Online]. Available: https://www.sciencedirect.com/science/article/pii/ S209580991930503X [10] A.Chakraborty,M.Alam,V.Dey,A.Chattopadhyay,andD.Mukhopad- hyay, “Adversarial attacks and defences: A survey,” ArXiv, vol. abs/1810.00069,2018. [11] F.Trame`r,N.Papernot,I.Goodfellow,D.Boneh,andP.McDaniel,“The spaceoftransferableadversarialexamples,”2017. [12] C.Szegedy,W.Zaremba,I.Sutskever,J.Bruna,D.Erhan,I.Goodfellow, andR.Fergus,“Intriguingpropertiesofneuralnetworks,”2013. [13] K.-I. Funahashi, “On the approximate realization of continuous mappings by neural networks,” Neural Networks, vol. 2, no. 3, pp.183–192,1989.[Online].Available:https://www.sciencedirect.com/ science/article/pii/0893608089900038 [14] M.J.D.Powell,“UOBYQA:Unconstrainedoptimizationbyquadratic approximation,” Mathematical Programming, vol. 92, pp. 555–582, 2002. [15] A. R. Conn, K. Scheinberg, and P. L. Toint, “Recent progress in unconstrainednonlinearoptimizationwithoutderivatives,”Mathematical Programming,vol.79,pp.397–414,1997. [16] G.J.Saavedra,K.N.Rodhouse,D.M.Dunlavy,andP.W.Kegelmeyer, “Areviewofmachinelearningapplicationsinfuzzing,”2019. [17] Y. Wang, P. Jia, L. Liu, C. Huang, and Z. Liu, “A systematic review of fuzzing based on machine learning techniques,” PLOS |
ONE, vol. 15, no. 8, pp. 1–37, 08 2020. [Online]. Available: https://doi.org/10.1371/journal.pone.0237749 [18] N. Papernot, P. McDaniel, S. Jha, M. Fredrikson, Z. B. Celik, and A. Swami, “The limitations of deep learning in adversarial settings,” 2016IEEEEuropeanSymposiumonSecurityandPrivacy(EuroS&P), Mar 2016. [Online]. Available: http://dx.doi.org/10.1109/EuroSP.2016. 36 [19] I. J. Goodfellow, J. Shlens, and C. Szegedy, “Explaining and harnessing adversarial examples,” 2014. [Online]. Available: https: //arxiv.org/abs/1412.6572 [20] J.Carlos,“Fuzzgoat,”https://github.com/fuzzstati0n/fuzzgoat,2017. |
2307.14480 PSOFuzz: Fuzzing Processors with Particle Swarm Optimization Chen Chen∗,†, Vasudev Gohil∗,†, Rahul Kande†, Ahmad-Reza Sadeghi‡, and Jeyavijayan (JV) Rajendran† †Texas A&M University, USA, ‡Technische Universita¨t Darmstadt, Germany †{chenc, gohil.vasudev, rahulkande, jv.rajendran}@tamu.edu, ‡{ahmad.sadeghi}@trust.tu-darmstadt.de Abstract—Hardwaresecurityvulnerabilitiesincomputingsys- privilege escalations, etc., in hardware designs. Due to their temscompromisethesecuritydefensesofnotonlythehardware promising potential, semiconductor giants such as Intel and but also the software running on it. Recent research has shown Google are actively developing new and efficient hardware that hardware fuzzing is a promising technique to efficiently fuzzers for vulnerability detection [10], [14]. detect such vulnerabilities in large-scale designs such as modern processors. However, the current fuzzing techniques do not Though hardware fuzzing is promising, its coverage incre- adjust their strategies dynamically toward faster and higher ment usually stagnates quickly, leaving design spaces unex- designspaceexploration,resultinginslowvulnerabilitydetection, ploredandvulnerabilitiesundetected.Oneofthemainreasons evident through their low design coverage. is that all the existing hardware fuzzers schedule the mutation To address this problem, we propose PSOFuzz, which uses operators and generate seeds using static schemes, and lack particle swarm optimization (PSO) to schedule the mutation operators and to generate initial input programs dynamically feedback-guided dynamic updates via interaction with the with the objective of detecting vulnerabilities quickly. Unlike coverage achieved and the complexity of the hardware (more traditional PSO, which finds a single optimal solution, we use details in Sec. V) [6]–[13]. For example, [9] generates input a modified PSO that dynamically computes the optimal solution instructions with the same operands to verify the renaming for selecting mutation operators required to explore new design strategies in out-of-order processors. However, this strategy is regionsinhardware.Wealsoaddressthechallengeofinefficient initialseedgenerationbyemployingPSO-basedseedgeneration. not optimal for processors without renaming strategies. While Includingtheseoptimizations,ourfinalformulationoutperforms [11] uses profiling to analyze the correlation between the mu- fuzzers without PSO. Experiments show that PSOFuzz achieves tation operators and the processor instructions, the scheduling up to 15.25× speedup for vulnerability detection and up to is static throughout fuzzing and does not update with cover- 2.22× speedup for coverage compared to the state-of-the-art age achieved. Therefore, to dynamically adjust the schedule simulation-based hardware fuzzer. of mutation operators and seed generation, we develop an Index Terms—Hardware Security, Security Vulnerabilities, Fuzzing, Particle Swarm Optimization approach to equip any hardware fuzzer with particle swarm optimization(PSO)targetingfastervulnerabilitydetectionand I. INTRODUCTION coverage achievement. PSOisabio-inspiredalgorithmthatusesaswarmconsisting Hardware designs are becoming increasingly complex to of multiple particles to find the optimal solution in a high- meettherisingneedforcustomhardwareandincreasedperfor- dimensional space [15]. Since fuzzers usually run multiple mance. However, as the design complexity grows, verification threads in parallel to accelerate the design space exploration, dominates the development lifecycle—over 70% of resources we model the scheduler of each thread’s mutation operations are spent to verify the security of a hardware design [1]. as a particle. The probability distribution of each mutation Therefore, a verification technique that can expose design operator being selected composes the position of a particle. flaws/vulnerabilities as early as possible is critical [2]–[5]. Each particle updates its position based on the highest cover- Recent research has shown that coverage feedback-based age achieved by itself and the highest coverage achieved by fuzzers can effectively detect security vulnerabilities in mod- the swarm in the current iteration. ern processors and achieve coverage faster than traditional Researchers have used PSO in software fuzzing to find the hardware verification techniques such as random regression optimal probability distribution of mutation operators [16]. [6]–[13]. Fuzzers start with seed inputs and apply prede- Results show a significant improvement over the fuzzers fined mutation operators on current inputs to generate new without PSO. However, one cannot simply use their tech- inputs. Fuzzers utilize one or several coverage metrics to nique for hardware fuzzing for the following reasons: (i) track the activity caused by the inputs in the hardware They assume a static optimal probability distribution of the and guide themselves to generate inputs that explore new mutation operators, which is not true for hardware fuzzing. hardwareregions,therebyacceleratingvulnerabilitydetection. Our experiments show that if a static distribution is used, two These fuzzers successfully found vulnerabilities that execute critical vulnerabilities are not detected even after using PSO undefined behaviors, compromise memory isolation, lead to (more details in Sec. III-B and IV). (ii) They use randomly ∗Theseauthorscontributedequallytothiswork. generated programs as seeds, which is not ideal for hardware 3202 guA 81 ]RC.sc[ 2v08441.7032:viXraListing1: Code snippetfrom CVA6 [20]processor (simplified fuzzing(moredetailsinSec.III-C).TosuccessfullyapplyPSO to improve readability) to hardware fuzzing, we must address two critical challenges: 1 unique case (instr.opcode) • Challenge 1: Saturation of Particles’ Performance. 2 ... |
Naively applying PSO to hardware fuzzing results in the 3 CSRRS: begin particles converging to a fixed position leading to a lack of 4 if (instr.rs1 == 5'b0) coverage improvement and vulnerabilities undetected. 5 instruction_o.op = CSR_READ;// c1 • Challenge2:IneffectiveSeedGeneration.Theseedsfrom 6 else 7 instruction_o.op = CSR_SET; // c2 which the fuzzing loop starts strongly affect the coverage achieved. Traditional fuzzers use either statically or ran- B. PSO Algorithm domly generated seeds, which results in slower coverage PSO is a bio-inspired algorithm that allocates multiple increments. Moreover, the performance of applying PSO to particlestoiterativelysearchforanoptimalsolution[15].The hardware fuzzing is also subject to the seed: poor quality position of a particle is a candidate solution and is updated seeds result in poor coverage. based on its velocity. The velocity is determined by the best We address these challenges by designing specific solutions position the particle ever achieved and the best position the (in Sec. III-B and III-C) that result in faster vulnerability entire swarm ever achieved. A particle’s velocity, v , and detectionandcoverageachievement.Inparticular,weaugment i position, p , are updated as PSO with a reset strategy to schedule mutation operators i dynamically.Moreover,weemployPSOtoselecthigh-quality v (t+1)=k×v (t)+r ×(lbest(t)−p (t)) i i 1 i i (1) seed inputs resulting in faster coverage. Overall, the main +r ×(gbest(t)−p (t)) 2 i contributions of this work are as follows: 1) To the best of our knowledge, we develop the first tech- p i(t+1)=p i(t)+v i(t+1) (2) niquethatusesthePSOalgorithmtoschedulethemutation Here, lbest(t) represents the best position the particle i i operators and generate seed inputs in hardware fuzzing. ever achieved since the beginning (i.e., t = 0), and gbest(t) 2) We overcome challenges in adapting PSO to hardware represents the best position ever achieved by any particle in fuzzers. In particular, we develop optimizations to reset the swarm. k is a pre-defined constant, and r and r are two 1 2 the particles for selecting mutation operators and a novel randomdisplacementweightsthatdecidehowfasttheparticle PSO-basedseedgenerationalgorithmforhardwarefuzzers. i will move toward lbest(t) and gbest(t), respectively. i 3) We evaluate PSOFuzz on three widely-used open-source PSO has been widely applied to optimize the performance RISC-V processors and achieve up to 15.25× speedup of applications due to its searching efficiency and conver- in detecting vulnerabilities and up to 2.22× speedup gence speed [18]. Though the solutions found by PSO are in achieving coverage compared to the state-of-the-art heuristic results, they are usually close to the real global simulation-based fuzzer without PSO. optimum [19]. The software community has also leveraged II. BACKGROUND PSO(e.g., MOPT [16])todetectvulnerabilities(e.g.,memory crashes)inprograms.However,forhardwarefuzzing,theopti- A. Hardware Processor Fuzzers mal probability distribution of the mutation operators changes Hardware processor fuzzers iteratively generate testing withcoverageachievedsofar,andthequalityofseedsgreatly inputs (i.e., inputs or tests) such as binary executables to affects the performance of the fuzzer. Hence, MOPT cannot detect vulnerabilities in target hardware (i.e., design-under- be applied for hardware fuzzing directly. test(DUT)).Thesefuzzersmainlyconsistofaseedgenerator, mutation engine, feedback engine, and vulnerability detec- III. PSOFuzz:FUZZINGPROCESSORSWITHPSO tor [9], [11]–[13]. The seed generator generates an initial set In this section, we first formulate the problem of selecting oftestscalledseeds.Fuzzersimulatesthehardwarewiththese optimal mutation operators as a PSO problem. However, the seeds to generate feedback and output. The feedback engine formulationhascriticallimitations,suchassaturationofparti- capturestheactivityinhardware,suchastogglingofthevalue cles’ performance and inefficient seed generation. We analyze of flip-flops [11], as coverage data during simulation. The these limitations and devise appropriate solutions, resulting in mutation engine modifies the tests that achieve new coverage a final formulation that outperforms fuzzers without PSO. (i.e., interesting tests) to create new tests. For example, the A. Selecting Mutation Operators Using PSO Bitflip mutation operator flips one random bit in the test [17]. The vulnerability detector detects vulnerabilities in hardware Most existing hardware fuzzers select mutation operators bycomparingitsoutputwiththeoutputofagolden-reference uniformly at random, i.e., they have an equal probability of model (GRM) [9], [11], [13]. selecting from all possible mutation operators [6]–[13]. This Existing hardware fuzzers use static mutation operator is not ideal as mutation operators have varying impacts on scheduling and seed generation schemes which cannot dy- covering new points in hardware. The following example namically adjust based on the complexity of hardware and demonstrates this. the coverage achieved, slowing down vulnerability detection Motivational Example. Consider a component from the and design space exploration (more details in Sec. III and V). decoder module in the CVA6 [20] processor as shown inListing 1. When decoding the CSRRS rd, csrReg, rs1 Seeds Tests PM Mutation instruction, the processor performs CSR_READ (line 5) or CSR_SET (line 7) operation on the control and status regis- Simulation Coverage Update PSO |
ter (CSR), csrReg, based on the register operand rs1 (line BBrraanncchh 5566%% Lbest,M Vt+1 = k*Vt+r1… 4). Assume the coverage points c 1 and c 2 in the if-else block DDUUTT TTooggggllee 8800%% gbest,M + ... as shown in line 5 and line 7. Suppose the instruction in the FFSSMM 3322%% Pt+1 = Pt+Vt+1 current input is CSRRS x16, stvec, x0. The value of rs1 for this instruction is 0. Hence the if condition evaluates Fig. 1: Flow for integrating PSO in TheHuzz. to True, and the CSR_READ operation is performed on the CSR,stvec,coveringthepointc .Now,ourobjective,when 1 mutatingthisinput,istocoverc 2.Also,supposewehaveonly and the cycle continues. After several iterations, the particles twomutationoperatorsinthistoyexample:Bitflip,whichflips are expected to converge to the optimal solution. one bit of the operand, rs1, and OpcodeMut, which mutates This preliminary solution provides a way to find a weight the opcode to another opcode. If both mutation operators are distribution of the mutation operators. However, it has two equally likely to be selected, the probability of covering c 2 critical limitations, as explained below. after mutation is (0.5×0)+(0.5×1) = 0.5. On the other hand, if we assign a higher weight to Bitflip, say 0.9, the B. Reset Particles and Seeds probability of covering c is (0.1 × 0) + (0.9 × 1) = 0.9. 2 Challenge 1: Saturation of Particles’ Performance. Tra- So, selecting mutation operators with equal probability is not ditional PSO is designed so that the particles converge to an ideal. To address this problem, we formulate the problem of optimum (ideally the global optimum) in the solution space. finding the optimal weights for the mutation operators as a However, for fuzzing hardware, one must find new coverage PSO problem, as explained next. points in each iteration that have not been covered. In other Notation. Let M be an ordered list of all mutation op- words, the optimal solution (i.e., the weights of the mutation erators (i.e., M[j] is the jth mutation operator). Let WM = operators) changes based on the coverage achieved so far, as [w 1M,w 2M,...,w |M M|]beaweightvectorforthe|M|operators. explained in the following example. So, wM is the weight of the jth mutation operator M[j]. Motivational Example.RefertoListing.1withtwocover- j Note that since we interpret the weights as the probabilities age points, c and c . Without loss of generality, assume two 1 2 of selecting the mutation operators, we normalize the weights mutation operators m and m with the following property: 1 2 so that (cid:80)|M|wM =1 and wM ≥0,∀wM ∈WM. P(c |m ) = 0.9 and P(c |m ) = 0.2, where P(c |m ) j=1 j 1 1 1 2 i j Particles. We associate a particle with one thread of the denotes the probability of covering c i conditioned on the fuzzer. Since fuzzers run multiple, say |N|, threads simulta- event that mutation operator m j is used.1 Suppose during neously,wehaveaswarmof|N|particlesassociatedwiththe the first iteration (t = 1), the weights for the two mutation fuzzer.Eachofthese|N|threadshasadifferentweightvector operatorsareequal,i.e.,0.5.Then,theprobabilityofcovering W iM for mutating the inputs in its thread. Each such W iM is c 1, P(c 1)t=1 = (0.5 × 0.9) + (0.5 × 0.2) = 0.55, and assigned as the position pM i of the corresponding particle iM P(c 2)t=1 = (0.5 × 0.1) + (0.5 × 0.8) = 0.45. Now, if c 1 (M indicates that the particle refers to mutation operators). is covered in the first iteration, then, for the second iteration Mathematically, WM =pM. (t = 2), having equal weights for both operators results in i i Local Best Position. Following PSO, we assign the local P(c 2)t=2 = P(c 2)t=1 = 0.45. On the other hand, if we best position, lbest,M, of a particle as the best position of that have a larger weight for m 2, say 0.9, then P(c 2)t=2 = i particle so far. In our case, we define a position at iteration (0.1×0.1)+(0.9×0.8) = 0.73. In fact, to maximize the t 2, pM i (t 2), as better than the position at iteration t 1, pM i (t 1), likelihood of covering c 2 in the second iteration, the weight if and only if pM i (t 2) results in higher coverage than pM i (t 1). for m 2 should be 1. This simple example shows that to maximize the likelihood Global Best Position. Likewise, following PSO, we assign a single global best position, gbest,M, as the best position of of covering the maximal number of points with the minimal number of iterations (i.e., input tests), the weights of the all particles in the swarm. mutation operators should be decided dynamically based on Fig.1illustratesthehigh-levelflowofthisformulation.Like thecoverageachievedsofar.However,duringourexperiments other hardware fuzzers, we generate a set of seeds, which withthepreliminaryPSOformulation,weobservethatthepo- are simulated to obtain their coverage information. Then, sitions of the particles (pM) saturate after a few iterations be- we use this coverage information to update the Lbest,M = i cause their velocities (vM) become zero according to Eq. (1). [lbest,M,lbest,M,...,lbest,M] and the gbest,M. Then, we up- i 1 2 |N| Inotherwords,theweightsofselectingthemutationoperators date the velocities (vM) and positions (pM) of all particles i i (WM) stagnate very quickly. Fig. 2 (a) demonstrates this according to Eqs. (1) and (2). We sample the mutation oper- i phenomenon for the CVA6 processor. The particles saturate |
ators according to the updated positions (pM), i.e., mutation i operatorweights(WM),andperformthemutationstogenerate i 1Note that since the coverage points belong to two different mutually new tests. These new tests are simulated to obtain coverage, exclusiveandexhaustivebranches,P(c2|m1)=0.1andP(c2|m2)=0.8.0.5 Bitflip 1 Bitflip 2 Bitflip 4 0.0 0.5 Arith 8 Arith 16 Random 8 0.0 0.5 Byteflip Byteflip 16 Random 8 any 0.0 0.5 Delete Clone Opcode 0.0 0 1000 2000 0 1000 2000 0 1000 2000 ytilibaborp noitceleS Particle 1 Particle 3 Particle 5 Particle 7 Particle 9 Particle 2 Particle 4 Particle 6 Particle 8 Particle 10 0.5 0.0 0.5 0.0 0.5 0.0 0.5 0.0 0 1000 2000 0 1000 2000 0 1000 2000 # iterations # iterations (a) (b) Fig. 2: Selection probability trend for all mutation operators for CVA6 [20] (a) without and (b) with reset within 50 iterations. Due to this, the preliminary formulation Algorithm 1: RstMon: Reset monitor fails todetect criticalvulnerabilities (moredetails in Sec.IV). Input: P,Lbest,β,Ct,F Solution 1. To address challenge 1, we reset the position Output: Lbest,gbest,Ct,rst P (pM) and velocity (vM) of the particles that saturate, i.e., i i 1 rst P ←ϕ that do not yield new coverage. Resetting removes saturating 2 for i∈P do particles and replaces them with new particles, leading to new weights for the mutation operators (WM). Along with 3 if F(p i)>F(Lbest[i]) then i 4 Lbest[i]←p i resetting the position and velocity of the saturated particle, 5 Ct[i]←0 we also reset the associated seed because the position and velocity of a particle are a function of the seed it started from 6 else (as seen in Fig. 1). Using the same seed when resetting the 7 Ct[i]←Ct[i]+1 particlewilllikelyleadtotheexplorationofdesignspacethat // add particle to the reset set has already been explored by that particle. This is suboptimal 8 if Ct[i]>β then since our objective is to cover new regions in the design. 9 rst P ←rst P ∪{i} The condition for resetting the particles and their seeds is decided based on the coverage trend in recent iterations. 10 gbest ←particle with highest Lbest We reset when there is no improvement in coverage for 11 return Lbest,gbest,rst P,Ct βM consecutive iterations. Here, βM controls the trade-off betweenruntimeandexploitationoflearnedknowledgebythe particles.LargervaluesofβM canleadtoadeeperexploration counter (Ct) is reset (lines 4 and 5). Otherwise, the counter of design but will incur runtime overhead since the particles is incremented, indicating no improvement in coverage for are not reset quickly after they saturate. On the other hand, one more consecutive iteration for that particle (line 7). If smaller values of βM can reduce runtime but will make the thecounterexceedsthethresholdβ foraparticle,thatparticle algorithm similar to random exploration, which will not cover is added to the set of particles to be reset, rst P (lines 8 and deeper regions of the design. 9). Finally, the algorithm updates the global best (gbest) using Fig. 2 (b) shows the positions of the particles for different all particles’ local bests (line 10). mutationoperatorsafterimplementingthissolutionforCVA6. When the particles saturate, they are reset (along with the C. Seed Generation Using PSO associated seeds), resulting in higher coverage speedup (as Challenge 2: Ineffective Seed Generation. A drawback seen in Table II). Algorithm 1 details how this solution of existing hardware fuzzers (as well as our preliminary is incorporated using a reset monitor, RstMon. It takes as formulation)isthattheyuseastaticprobabilitydistributionof input a set of particles, their Lbest, resetting threshold (β), a instructionstogeneratetheseeds[6]–[8],[11]–[13].However, variableto countthe numberof consecutiveiterations withno the optimal set of instructions required by the seeds to trigger improvement (Ct), and a function F that returns the fitness newcoveragepointschangeswithtimeduringfuzzing.2More- (i.e., coverage) of a particle. The algorithm iterates over all over, the performance of each particle for mutation operators particles and compares the coverage with the particle’s local best coverage (lines 2 and 3). If a particle’s coverage is more 2An example similar to the one described in Sec. III-B can demonstrate than its local best coverage, the local best is updated, and the this,butweomititintheinterestofspace.rst_PT gbest,M,T PPSSOO:: SSeeeedd ggeenneerraattiioonn PPSSOO:: MMuuttaattiioonn Reset monitor Lbest,M,T iinnsstt11::((RR--ttyyppee,,00..33)),,((II--ttyyppee,,00..22)),,…… ooppeerraattoorrss rst_PM iinnsstt22::((RR--ttyyppee,,00..66)),,((II--ttyyppee,,00..22)),,…… BBBiiitttfffllliiippp 111///111 000...222 ...... MMuuttaattiioonn eennggiinnee Coverage BBBiiitttfffllliiippp 222///111 000...333 1111001100 1100000011 BBrraanncchh 5566%% IISSAA ppooooll SSeeeedd ggeenneerraattoorr BBBiiitttfffllliiippp 444///111 000...111555 1111110000 0011000000 RRRaaannndddooommm 888 000...000222 0000111111 1111111111 TTooggggllee 8800%% RR--ttyyppee:: mmaaiinn:: FFSSMM 3322%% AADDDD,,SSUUBB,,SSLLLL AADDDD,,xx11,,zz00,,xx33 ......... ......... AANNDD,,DDIIVV,,RREEMM OORR ,,xx22,,xx11,,xx33 |
AAArrriiittthhh 888///888 000...000777 Input test ...... ...... II--ttyyppee::...... RREETT CCClllooonnneee 000...111444 database Tests DDUUTT Seeds Fig. 3: PSOFuzz framework. (iM),i.e.,thenumberofiterationsitsurvives,ishighlyrelated a single global best position, gbest,T, as the best position of to the quality of its seed. all particles in the swarm. Solution 2.Toaddressthisproblemofstaticdistributionof The high-level flow of this PSO for seed generation is very instructions for seed generation, we devise a dynamic seed similar to that of the PSO for selecting mutation operators. generation algorithm using PSO. The idea is to map the We start with randomly initialized particles and update their problemofidentifyingoptimalprobabilitiesoftheinstructions velocities and positions according to Eqs. (1) and (2), respec- forseedsasaPSOproblem.Next,wediscussthisformulation. tively.Moreover,learningfromthepriorpitfallofsaturationof Notation.LetT beanorderedlistofinstructiontypes,such particles’ performance (Sec. III-B), we also reset the particles as R-type and I-type [21]. Let WT = [wT,wT,...,wT ] be for this PSO-based seed generation when they saturate. Since 1 2 |T| the weight vector for the |T| instruction types. So, wT is the the quality of a particle for selecting instruction types (iT) is j weightofthejth instructiontypeT[j],and(cid:80)|T| wT =1and measuredbythenumberofiterationsitscorrespondingparticle j=1 j for selecting mutation operators (iM) survives, we reset i wT ≥0,∀wT ∈WT. T when its corresponding iM is reset βT consecutive times. Particles. Similar to the PSO formulation for selecting SimilartoβM,βT controlsthetrade-offbetweenruntimeand mutation operators (Sec. III-A), we associate a particle with exploitation of learned knowledge by iTs. onethreadofthefuzzer.So,thereareatotalof|N|particlesin theswarm,where|N|isthenumberoffuzzerthreads.Suppose D. Putting it All Together thateachseedconsistsofasequenceof|O|instructions.Then, Fig. 3 shows the PSOFuzz framework, which includes PSO foreachofthe|N|threadsbeingrunsimultaneously,wehave formulation along with the resetting of seeds and particles for adifferentweightvectorW iT (whichcontains|O|×|T|entries, selecting mutation operators as well as the PSO formulation one for each of the |T| instruction types for each of the |O| for seed generation. The PSO formulation of seed generation instructions in the seed). guides the seed generator by selecting the instruction type Each weight vector W iT is assigned as the position pT i of from the instruction set architecture (ISA) pool. Once the the corresponding particle iT. Here, the T in the superscript instruction type is sampled, the seed generator randomly indicates that the particle is for the instruction types, as selectsanopcodeofthatinstructiontypeandthentheoperands opposed to the M in the particles for selecting mutation to create the instruction. These instructions are then used to operators in Sec. III-A. Mathematically, W iT =pT i . create the seeds, which are added to the input test database. Local Best Position. Following PSO, we assign the local The DUT is simulated with the tests to obtain coverage. This best position, lbest,T, of a particle as the best position (i.e., coverage data is used to update the particles’ velocities and i the probabilities of the instruction types) of that particle so positions through their local and global bests and the reset far. Since this PSO is for seed generation, the objective it monitor.Theupdatedpositionsareusedtogenerateseedsand aims to maximize is the quality of the generated seed. We mutate tests in the subsequent iterations. measurethequalityofaparticleforselectinginstructiontypes Algorithm 2 details the steps of PSOFuzz. It takes the (iT) as the number of iterations the associated particles for DUT, a user-defined time limit, t , a user-defined target limit selecting mutation operators (iM) survive. For instance, for coverage, tc, the thresholds for resetting the PSOs for a given particle, iT, if at iteration t 1 and t 2, its associated mutation operators and seed generation, βM and βT, and particleforselectingmutationoperators(iM)survivedfor150 the constant, k, used to update the velocities of the particles and 200 iterations, respectively (as explained in Sec. III-B), (Eq. (1)). We fuzz the DUT and return the coverage achieved, then pT i (t 2) is better than pT i (t 1). cov. First, we initialize all required variables for PSO Global Best Position. Likewise, following PSO, we assign (PM,VM,PT,VT,Lbest,M,gbest,M,Lbest,T,gbest,T). WeAlgorithm 2: PSOFuzz of the particles for seed generation are updated. Input: DUT,t ,tc,βM,βT,k limit Output: cov: total coverage achieved IV. EVALUATION // initialization In this section, we evaluate the speed of PSOFuzz in de- 1 t←0, cov ←0, tests←ϕ tectingvulnerabilitiesandachievingcoverageonthreepopular 2 Initialize PM,VM,PT,VT open-sourced RISC-V [21] processors. 3 Initialize Lbest,M to PM and gbest,M to pM 0 4 Initialize Lbest,T to PT and gbest,T to pT 0 5 CtM ←0, CtT ←0 A. Evaluation Setup 6 rst PM ←ϕ, rst PT ←ϕ We use the state-of-the-art simulation-based processor 7 tests←GenSeed(PT,tests,rst PM) fuzzer, TheHuzz [11] as a baseline for all evaluations.3 To 8 while (cov <tc) and (t<t limit) do // main loop ensure that the enhancements in results exclusively stem from |
9 FM,cov ←Simulate(DUT,tests) PSO adaptation, we integrate PSO schemes into TheHuzz’s 10 Lbest,,gbest,M,rst PM,CtM ← mutation engine and seed generator. In addition to reporting RstMon(PM,Lbest,M,βM,CtM,FM) the results for our final formulation, PSOFuzz, which is also 11 if rst PM ̸=ϕ then // update PSO seed denotedasPSO+Reset+Seed,wealsoreporttheresultsfor(i) 12 FT ←CalcFitness(rst PM,PT) the preliminary formulation, PSO, which includes the PSO- 13 Lbest,T,gbest,T,rst PT,CtT ← based mutation operator selection, but neither the resetting RstMon(PT,Lbest,T,βT,CtT,FT) solution (Solution 1), nor the PSO-based seed generation 14 PT,VT ← technique (Solution 2), and (ii) the intermediate formulation, UpdatePV(PT,VT,Lbest,T,gbest,T,rst PT,k) PSO+Reset,whichincludesthePSO-basedmutationoperator 15 PM,VM ← selection with reset, but not PSO-based seed generation. UpdatePV(PM,VM,Lbest,M,gbest,M,rst PM,k) Following [11], we set the number of simultaneous threads // gen. seeds for reset particles and hence the number of particles, |N|, as 10 and the number 16 tests←GenSeed(PT,tests,rst PM) ofinstructionsineachprogram,|O|,as20.Tohaveabalanced // mutate tests for other particles impact of exploration (due to velocity) and exploitation (due 17 tests←Mut(PM,tests,{iM|iM ∈/ rst PM}) to local and global bests), we set k (Eq. (1)) as 0.5. Based 18 return cov on empirical observations, we set βM = βT = 3, as a larger β will cause runtime overhead, while a smaller β will make PSOFuzzgeneratetestcasessimilartorandomexploration,as discussed in Sec. III-B. also initialize the saturation counters (CtM,CtT) along with Since most commercial processors are close-sourced, we the sets indicating particles that need to be reset because of evaluate PSOFuzz using three widely-used open-sourced pro- saturation (rst PM,rst PT). Next, on line 7, we use the cessors from RISC-V [21] ISA: CVA6 [20], BOOM [23], and positions PT to generate the initial set of seed tests. Then, Rocket Core [22]. Existing hardware processor fuzzers the main fuzzing loop starts on line 8, which iterates until use similar open-sourced processors for their evaluation [9], either the target coverage (tc) is achieved or the runtime [11],[13].CVA6supportsout-of-orderexecution(OoO)anda exceeds the time limit, t . In each iteration of the fuzzing custom single instruction-multiple data (SIMD) floating point limit loop, we first simulate the DUT with the generated tests to unit. Rocket Core is an in-order processor. BOOM is a obtain the function FM (which calculates the fitness of the superscalar processor built using the components of Rocket particles)andthecoverageachievedsofar,cov (line9).Next, Core.Moreover,alloftheseprocessorsarecapableofbooting on line 10, this FM is used to calculate the local and global Linux operating system while CVA6 is commercially used to bests for the particles for mutation operators and to decide buildprocessorsforhigh-securityapplications[24].Therefore, which particles need to be reset according to βM following these processors with different complexity form a diverse Algorithm 1. Then, skipping ahead on line 15, the velocities benchmark set to evaluate PSOFuzz. and the positions of the particles for mutation operators are We use Synopsys VCS [25] as the simulation tool and updated, and on lines 16 and 17, the new tests are generated Chipyard [26] as the system-on-chip (SoC) simulation envi- for both particles that are reset and not reset, respectively. ronment. To ensure a fair comparison, we ran experiments Additionally,online11,wecheckifanyoftheparticlesfor on each benchmark for 24 hours and repeated them thrice. the mutation operators needs to be reset, i.e., rst PM ̸= ϕ, We demonstrate our results using the branch coverage metric, and calculate the number of iterations those particles survived whichishighlyrelatedtovulnerabilitydetection[27].Weuse (i.e., fitness) and return FT on line 12. This FT is used to a Linux-based CPU running at 2.6GHz, with 64 threads and calculate the local and global bests for the particles for seed 512GB of RAM for our experiments. generation and to decide which ones to reset according to βT on line 13. Finally, on line 14, the velocities and the positions 3Following[11],weimplementedTheHuzzinPython.TABLE I: Vulnerability detection speedup compared to TheHuzz [11]. N.D. denotes “not detected.” TheHuzz[11] PSO PSO+Reset PSO+Reset+Seed(PSOFuzz) Processor Vulnerability CWE #Tests #Tests Speedup #Tests Speedup #Tests Speedup V1:Accessinvalidaddresses CWE-1252 3.52×102 1.38×102 2.55× 5.71×102 0.62× 2.32×102 1.52× withoutthrowingexceptions. V2:Decodemultiplication CWE-440 2.71×103 5.09×103 0.53× 1.80×103 1.50× 4.51×102 6.01× instructionsincorrectly. CVA6[20] V3:Accessunimplemented CWE-1281 4.75×103 N.D. N.D. 8.56×102 5.54× 5.70×103 0.83× CSRsandreturnX-values. V4:Cachecoherency CWE-1202 1.83×102 1.23×104 0.01× 1.70×101 10.76× 1.20×101 15.25× violationundetected. V5:DecodetheFENCE.I CWE-440 6.80×101 4.50×102 0.15× 1.80×101 3.78× 1.35×102 0.50× instructionincorrectly. V6:Incorrectexceptiontype CWE-1202 5.55×103 1.94×104 0.29× 5.39×102 10.30× 1.26×103 4.40× |
ininstructionqueue. V7:Someillegalinstructions CWE-1242 9.30×101 N.D. N.D. 2.54×102 0.37× 7.40×101 1.26× withoutthrowingexceptions. Rocket Core[22] V8:EBREAKdoesnot CWE-1201 1.67×103 6.67×103 0.25× 1.07×103 1.56× 4.10×102 4.07× increaseinstructioncount. B. Vulnerability Detection Fig. 4 shows the mean and standard deviation of coverage The vulnerability detection strategy used by our techniques achieved with respect to the number of input tests. (PSO, PSO+Reset, PSO+Reset+Seed) compares the proces- PSOFuzz outperforms PSO+Reset on Rocket Core and sor’s outputs with that of a GRM. Many existing fuzzers BOOM because the PSO-based seed generation dynamically use a similar detection strategy [9], [11]–[13]. The strategy adjusts the optimal set of instructions required to cover new compares the architectural states of the processor and the points. While PSOFuzz is slower than PSO+Reset on CVA6, GRM for each executed instruction. The architectural states it still outperforms TheHuzz and PSO techniques. include the instructions committed; any exceptions triggered; Among the three processors, PSOFuzz achieves the fastest the general purpose registers (GPRs) modified; the CSRs speedup (2.22×) and highest coverage increment (1.00%) modified;theprivilegeleveloftheprocessor;andthememory on CVA6, which is the complex processor with OoO and address and data accesses. A mismatch in architectural states SMID features. This is because the PSO optimizations aid indicates a potential vulnerability in the processor. Similar to in covering the hard-to-reach coverage points in the custom [9], [11]–[13], we use Spike [28], the RISC-V ISA emulator, floating point unit of CVA6, which are difficult to cover with as the GRM. static mutation operator scheduling schemes. Even on the Comparison with TheHuzz. Table I shows the number of remaining processors, BOOM and Rocket Core, PSOFuzz testsandthespeedupofourtechniquescomparedtoTheHuzz. achieves faster coverage (up to 1.72×) compared to TheHuzz PSOFuzz detects all the vulnerabilities detected by TheHuzz and covers more points than TheHuzz. The speedup on these up to 15.25× faster. The results also show the necessity of processors is less than that of CVA6 because Rocket Core using the reset strategy for PSO. Na¨ıve PSO is slower than is a simple processor compared to CVA6 while BOOM is TheHuzz in detecting vulnerabilities because its particles are built by duplicating most of the components of Rocket likely exploring the design spaces that have already been Core.Hence,TheHuzzcoversmorethan87%oftheirpoints, explored, as mentioned in Sec. III-B. PSO+Reset performs resulting in less scope for improvement for PSOFuzz. better than PSO due to resetting the particles, allowing it In summary, PSOFuzz detects vulnerabilities and achieves to dynamically select the optimal mutation operators. It also coverage faster than TheHuzz on all three processors, demon- outperforms PSO+Reset+Seed (PSOFuzz) in detecting some strating the necessity of dynamic scheduling of mutation vulnerabilities, such as V3, because PSOFuzz initially spends operators and seed generation. time exploring the optimal probabilities for seed generation. However, PSOFuzz achieves the highest speedup compared to V. RELATEDWORK TheHuzz and other PSO techniques for most vulnerabilities This section describes the existing hardware fuzzers, their because it uses the optimal probabilities for both seed gener- limitations, and how PSOFuzz addresses those limitations. ation and instruction mutation, efficiently exploring different RFUZZ [6] uses mux-toggle coverage to capture the ac- regions of the design space. tivity in the select signals of MUXes. It schedules mutation C. Coverage Achievement operators statically, similar to AFL fuzzer [17]. Also, mux- Wenowcomparethecapabilityofourtechniquesinachiev- toggle coverage is not scalable to large designs such as ing coverage against TheHuzz, as coverage achieved is a BOOM [9]. HyperFuzzing [7] is an SoC fuzzer that defines proxy metric to the extent of design verified and determines security properties and uses AFL fuzzer’s static mutation its readiness to tape out [29]. Across the three processors, operator scheduling and random seed generation to detect PSO optimizations achieve up to 6.39× speedup compared to vulnerabilities. DirectFuzz [8] modifies RFUZZ to perform TheHuzzwhileobtainingupto2%morecoverageafterfuzzing directed fuzzing on specific modules of the target hardware. for 24 hours with more than 20K tests, as shown in Table II. However, it uses similar static schemes as RFUZZ.TABLE II: Coverage improvement compared to TheHuzz [11]. TheHuzz[11] PSO PSO+Reset PSO+Reset+Seed(PSOFuzz) Core Total Total Increment Speedup Total Increment Speedup Total Increment Speedup CVA6[20] 6214 6074 −2.25% 0.25× 6334 2.00% 6.39× 6277 1.00% 2.22× BOOM[23] 23086 23052 −0.15% 0.73× 23088 0.01% 1.11× 23092 0.01% 1.25× Rocket Core[22] 11947 11846 −0.85% 0.10× 11864 −0.06% 0.23× 11958 0.09% 1.72× 6.5 6.0 5.5 5.0 0 1 2 3 4 (a) stniop hcnarB # )K1×(derevoc TheHuzz PSO PSO+Reset PSO+Reset+Seed (PSOFuzz) 23.3 12.0 23.0 11.8 22.7 11.6 22.4 11.4 0 1 2 3 4 0 1 2 3 4 # Tests (×5K) (b) (c) Fig. 4: Coverage achieved compared to TheHuzz [11] for (a) CVA6 [20], (b) BOOM [23], and (c) Rocket Core [22]. |
Processor fuzzer DIFUZZRTL [9] uses activity in the of other meta-heuristic algorithms, such as simulated anneal- controlregistersascoveragetoaddressthescalabilityissuesof ing [30] and differential evolution [31], and identify the ideal RFUZZ.Itusesgrammar-basedmutationoperatorsinspiredby one for hardware fuzzing. AFL.But,itgeneratesseedsrandomlyandusesstaticmutation Leveraging Prior Knowledge for Initialization. One key operatorschedulingschemes.BugsBunny[12]fuzzesspecific way to improve its performance is by initializing with a good target signals in the hardware using DIFUZZRTL as the base starting point [32]. PSOFuzz initializes particles’ positions fuzzer. Hence, its mutation operator scheduling and seed randomly. However, we can use the static schemes of existing generation schemes are static. Trippel et al. [10] convert fuzzers to initialize the particles. For example, the static hardwaretoasoftwaremodelandfuzzusingAFLfuzzerwith probabilitiesfromtheprofilingstateofTheHuzzcanbeusedas staticmutationscheduling.TheHuzz[11]isanotherprocessor theinitialpositionofparticlestoselectthemutationoperators. fuzzer that uses different types of code coverage metrics to capture activity in the combinational and sequential logic of VII. CONCLUSION the hardware. It also uses a profiler to optimize the mutation Processorfuzzers,whichrelyonthemutationofinputtests, scheduling. However, this optimization is static for a given have shown promise in detecting vulnerabilities. However, processor and does not change with the coverage achieved. they use static scheduling strategies for mutation and seed ArecenthardwarefuzzerHyPFuzz[13]attemptstoaddress generation, which is not ideal. To overcome this limitation, the slower coverage speeds of hardware fuzzers by combing wedevelopanovelPSO-basedframework,PSOFuzz,thatcan formal tools with fuzzing. This optimization to fuzzing is beintegratedwithanyfuzzertofindoptimalschedulingstrate- orthogonal to PSOFuzz as HyPFuzz also uses static mutation gies. To ensure better vulnerability detection performance, we operator scheduling and seed generation schemes which can augment na¨ıve PSO with (i) a reset strategy that allows it be optimized through our PSO techniques. to find dynamic selection probabilities for mutation operators In summary, all of the existing hardware fuzzers use static and (ii) a PSO-based seed generation algorithm. Experimental mutation operator scheduling and seed generation schemes results with the state-of-the-art simulation-based hardware and cannot dynamically adjust their strategies for the target fuzzer demonstrate that PSOFuzz can speed up vulnerability hardware and coverage achieved. In contrast, we propose detectionbyupto15.25×andcoverageachievementbyupto PSOFuzz, a PSO-guided fuzzer, to demonstrate how hardware 2.22×. In conclusion, PSOFuzz addresses a critical limitation fuzzers can be equipped with PSO optimizations to improve of existing processor fuzzers and significantly improves the theirvulnerabilitydetectionandcoverageachievementspeeds. effectiveness and efficiency of processor verification. VI. DISCUSSION VIII. ACKNOWLEDGEMENT In this section, we discuss possible extensions to improve OurresearchworkwaspartiallyfundedbytheUSOfficeof PSOFuzz and hardware fuzzing in general. Naval Research (ONR Award #N00014-22-1-2279), by Intel’s Dynamically Identifying Optimal Solutions. Though the Scalable Assurance Program, and by the European Union reset strategy works well in practice, it is a heuristic that (ERC, HYDRANOS, 101055025). Any opinions, findings, modifies the PSO algorithm. In the future, we plan to model conclusions, or recommendations expressed herein are those and analyze the impact of resetting threshold (β) on the capa- of the authors and do not necessarily reflect those of the US bility of vulnerability detection and design space exploration Government, the European Union, or the European Research ofPSOFuzz.Moreover,wewillalsoevaluatetheperformance Council.REFERENCES [28] RISC-V, “SPIKE Source Code,” https://github.com/riscv/riscv-isa-sim, 2023,lastaccessedon05/21/2023. [1] S.FineandA.Ziv,“CoverageDirectedTestGenerationforFunctional [29] Synopsys, “Accelerating Verification Shift Left with Intelligent Cover- VerificationusingBayesianNetworks,”DesignAutomationConference, ageOptimization,”https://www.synopsys.com/cgi-bin/verification/dsdla/ 2003. pdfr1.cgi?file=ico-wp.pdf,2022,Lastaccessedon05/21/2023. [2] J.Rajendran,V.Vedula,andR.Karri,“DetectingMaliciousModifica- [30] D. Bertsimas and J. Tsitsiklis, “Simulated Annealing,” Statistical sci- tionsofDatainThird-partyIntellectualPropertyCores,”2015. ence,1993. [3] G. Dessouky et al., “HardFails: Insights into Software-Exploitable [31] K.V.Price,“DifferentialEvolution,”HandbookofOptimization:From HardwareBugs,”28thUSENIXSecuritySymposium,2019. ClassicaltoModernApproach,pp.187–214,2013. [4] A.-R. Sadeghi, J. Rajendran, and R. Kande, “Organizing The World’s [32] D.Simpsonetal.,“Penalisingmodelcomponentcomplexity:Aprinci- LargestHardwareSecurityCompetition:Challenges,Opportunities,and pled,practicalapproachtoconstructingpriors,”2017. LessonsLearned,”2021. [5] C. Chen et al., “Trusting the Trust Anchor: Towards Detecting Cross- LayerVulnerabilitieswithHardwareFuzzing,”2022. [6] K. Laeufer et al., “RFUZZ: Coverage-Directed Fuzz Testing of RTL |
on FPGAs,” IEEE/ACM International Conference on Computer-Aided Design,pp.1–8,2018. [7] S.K.Muduli,G.Takhar,andP.Subramanyan,“HyperFuzzingforSoC SecurityValidation,”ACM/IEEEInternationalConferenceonComputer- AidedDesign,pp.1–9,2020. [8] S.Canakcietal.,“Directfuzz:AutomatedTestGenerationforRTLDe- signsusingDirectedGrayboxFuzzing,”ACM/IEEEDesignAutomation Conference,pp.529–534,2021. [9] J. Hur et al., “DIFUZZRTL: Differential Fuzz Testing to Find CPU Bugs,”IEEESymposiumonSecurityandPrivacy,pp.1286–1303,2021. [10] T.Trippeletal.,“FuzzingHardwareLikeSoftware,”USENIXSecurity Symposium,2022. [11] R. Kande et al., “TheHuzz: Instruction Fuzzing of Processors Using Golden-ReferenceModelsforFindingSoftware-ExploitableVulnerabil- ities,”USENIXSecuritySymposium,pp.3219–3236,2022. [12] H.Ragabetal.,“BugsBunny:HoppingtoRTLTargetswithaDirected Hardware-Design Fuzzer,” SILM, Jun. 2022. [Online]. Available: https://download.vusec.net/papers/bugsbunny silm22.pdf [13] C. Chen et al., “HyPFuzz: Formal-Assisted Processor Fuzzing,” arXiv preprintarXiv:2304.02485,2023. [14] IntelLabs, “Pre-Silicon Hardware Fuzzing Toolkit,” https://github.com/ IntelLabs/PreSiFuzz,2023,lastaccessedon05/21/2023. [15] J. Kennedy and R. Eberhart, “Particle swarm optimization,” IEEE internationalconferenceonneuralnetworks,1995. [16] C. Lyu et al., “MOPT: Optimized Mutation Scheduling for Fuzzers.” USENIXSecuritySymposium,pp.1949–1966,2019. [17] lcamtuf, “American Fuzzy Lop (AFL) Fuzzer.” 2014, Last accessed on 05/21/2023. [Online]. Available: http://lcamtuf.coredump.cx/afl/ technical details.txt [18] Z.-H. Zhan et al., “Adaptive Particle Swarm Optimization,” IEEE Transactions on Systems, Man, and Cybernetics, Part B (Cybernetics), 2009. [19] Y.ShiandR.Eberhart,“AModifiedParticleSwarmOptimizer,”IEEE international conference on evolutionary computation proceedings., 1998. [20] F. Zaruba and L. Benini, “The Cost of Application-Class Processing: Energy and Performance Analysis of a Linux-Ready 1.7-GHz 64-Bit RISC-VCorein22-nmFDSOITechnology,”IEEETransactionsonVery Large Scale Integration Systems, vol. 27, no. 11, pp. 2629–2640, Nov 2019. [21] RISC-V,“RISC-VWebpage,”https://riscv.org/,2021,Lastaccessedon 05/21/2023. [22] K. Asanovic´ et al., “The Rocket Chip Generator,” no. UCB/EECS- 2016-17,Apr2016.[Online].Available:http://www2.eecs.berkeley.edu/ Pubs/TechRpts/2016/EECS-2016-17.html [23] J.Zhaoetal.,“SonicBOOM:The3rdGenerationBerkeleyOut-of-Order Machine,” Fourth Workshop on Computer Architecture Research with RISC-V,May2020. [24] H. C. GmbH, “MiG-V – Made in Germany RISC-V,” 2022, Last accessed on 05/21/2023. [Online]. Available: https://hensoldt-cyber. com/mig-v/ [25] “VCS,” https://www.synopsys.com/verification/simulation/vcs.html, 2023,Lastaccessedon05/21/2023. [26] A. Amid et al., “Chipyard: Integrated Design, Simulation, and Imple- mentation Framework for Custom SoCs,” IEEE Micro, vol. 40, no. 4, pp.10–21,2020. [27] A. Mockus, N. Nagappan, and T. T. Dinh-Trong, “Test Coverage and Post-VerificationDefects:AMultipleCaseStudy,”pp.291–301,2009. |
2307.16064 Education E xcellence and Innovation Management: A 2025 Vision to Sustain Economic Development during Global Challenges Vulnerability Detection Approaches on Application Behaviors in Mobile Environment Abdellah OUAGUID RITM Laboratory, ESTC, Hassan II University, Casablanca, Morocco ouaguid@gmail.com Mohamed OUZZIF RITM Laboratory, ESTC, Hassan II University, Casablanca, Morocco ouzzif@gmail.com Noreddine ABGHOUR LIMSAD, FSAC, Hassan II University, Casablanca, Morocco nabghour@gmail.com Abstract Several solutions ensuring the dynamic detection of malicious activities on Android ecosystem have been proposed. These are represented by generic rules and models that identify any purported malicious behavior. However, the approaches adopted are far from being effective in detecting malware (listed or not) and whose form and behavior are likely to be different depending on the execution environment or the design of the malware itself (polymorphic for example). An additional difficulty is added when these approaches are unable to capture, analyze, and classify all the execution paths incorporated in the analyzed application earlier. This suggests that the functionality of the analyzed application can constitute a potential risk but never explored or revealed. We have studied some malware detection techniques based on behavioral analysis of applications. The description, characteristics, and results obtained from each technique are presented in this article wherein we have also highlighted some open problems, challenges as well as the different possible future directions of research concerning behavioral analysis of malware. Keywords: Android Security, Malware detection approaches, Behavior Detection, Dynamic analysis, Malware classification. Introduction The year 2019 has witnesses yet again Android dominance by 72.2% (StatCounter Global Stats 2020) of smart-phones worldwide market share. The large adoption of Android sets it as the preferred target of mobile cybercrime (Figure 1). 16830 Electronic copy available at: https://ssrn.com/abstract=4102022Education E xcellence and Innovation Management: A 2025 Vision to Sustain Economic Development during Global Challenges Fig. 1: Mobile Operating System Market Share Worldwide (2020) Victim of its popularity, Android is an opportunity for hackers to get their hands on a large amount of victim data (SMS, GPS location, etc.) with less effort by taking advantage of free access to the source code of Android (known under the name AOSP). This makes installing and spreading malware easier compared to a closed operating system (iOS, BlackBerry, etc.). The Android ecosystem also plays a role in the emergence of new vulnerabilities and the spread of hacker attack vectors. Indeed, several mobile manufacturers (Smartphone or Tablet) manage to design and market several products adapted to the needs and financial capacity of the consumer. These products do not host Android as published by Google but adopt a modified version including new proprietary components essential for its proper functioning (device driver for example) or presentation layers to stand out from the competition. Specific and personalized developments made by manufacturers, and which are subsequently integrated into Android OS, may also contain vulnerabilities whose impact is of serious comparable to those found in applications installed by the user (Wu et al. 2013) or even in AOSP. The detected vulnerabilities affect the preinstalled components of specific manufacturers or specific ranges for a given manufacturer (Farhang, Kirdan, et al. 2020) (Elsabagh et al. 2020). This makes the Android ecosystem and its security segmented more and more (within the same manufacturers), and it only increases the risks associated with any equipment running Android such as Farhang, Laszka, and Grossklags (2018) shown in their study. With the evolution of mobile attacks, which have become increasingly stealthy (McAfee 2020), any flaws introduced by the manufacturer or developers of third-party applications can constitute a gateway for hackers to gain access to sensitive resources and data of hardware and the user by acquiring system privileges and permissions in an illegal manner, and without the consent of the end-user. To address the various threats, in particular those caused by malware or those intentionally introduced into applications installed by the manufacturers or by the user, several analysis methods and approaches have been proposed by Kouliaridis et al. (2020) and others. In this work, we will focus on existing detection approaches based on malware behavioral analysis and the potential they have for identifying and detecting malicious behaviors that malicious applications may carry once installed in an adequate environment to start their malicious mission. The rest of this article is organized as follows: Part 2 presents the different techniques for detecting vulnerabilities. Part 3 describes in detail the approach to behavioral malware analysis and the various solutions proposed. Part 4 presents possible future research prospects regarding the behavioral analysis of malware. Finally, Part 5 concludes the article. 16831 Electronic copy available at: https://ssrn.com/abstract=4102022Education E xcellence and Innovation Management: A 2025 Vision to Sustain Economic Development during Global Challenges Vulnerability Detection Techniques Several detection approaches and techniques have been proposed to ensure efficiency in the various phases of the analysis and the detection process to decide whether the application analyzed is malicious or not. To identify the functionality and how the malware activates, executes, and manipulates its data or stolen data, two main analysis techniques are used: static and dynamic analysis. Static Code Analysis Static analysis of an application consists of reconstructing, scanning, and analyzing the code of the application without executing it. Its advantage is that it tries to cover and explore all possible paths of control and execution and examine the functionalities programmed without invoking them in order to |
extract, identify and analyze any malicious or legitimate action but which could be used maliciously by malware (system and API call (Aafer, Du, and Yin 2013), permission (Saracino et al. 2016), etc.). All these processing can consume a lot of time and require resources in terms of calculation and storage without forgetting that the executable of the application must first undergo a treatment of “Reverse Engineering (RE)” (Eilam 2011), the latter is essential to have exploitable source code. However, RE is becoming increasingly unreliable (easily bypassed) and expensive because of the obfuscation techniques (Dalla Preda and Maggi 2017) (Suarez-Tangil et al. 2017) that the creator of malware adopts when compiling its source code. In several studies (those based on Machine Learning, such as Xi et al. (2019)), the static characteristics extracted from the analyzed applications which will be normalized, processed are used as input data to machine learning algorithms to decide whether the application is malicious or benign. Dynamic Behavior Analysis Unlike static analysis, dynamic analysis of an application consists of observing and studying the behavior and actions taken by this application during its execution. It consists of listing and examining all activities related to the file system as Cabau, Buhu, and Oprisa (2016) proposed, to the network (Nari and Ghorbani 2013), to the sequences of API and system calls (functions, parameters, instructions, associated data flows) (Martinelli, Marulli, and Mercaldo 2017) (Egele et al. 2008), etc. Dynamic analysis is generally carried out in a controlled and virtual test environment where several monitoring software components are installed. This customization of the test environment can influence the normal and natural execution of malicious applications because it can generate a completely different behavior compared to a similar execution in a real environment. This will weaken the effectiveness of dynamic analysis in reducing the probability of the malware detection since the verification of rules and models already classified will be based on system calls and data generated by artificial behaviors that do not reflect the reality. Dynamic analysis requires continuous monitoring, adaptation, and updating for effective automation in the analysis or classification of malicious behaviors to follow the continuous evolution of the techniques used in malware. The complexity and the transformation capacity of a certain type of these malware (Polymorphic and Metamorphic malware) allow it to escape from the various traditional detection methods, thanks to the self-adaptation of malware functionalities according to the environment in which they are executed. There are also hybrid detection techniques that try to merge the strengths of static and dynamic analysis (Anderson, Storlie, and Lane 2012) to improve the assessment and classification of the applications analyzed based on the collection and analysis of the functionalities detected via machine learning. Other approaches monitor the application during its execution to report any malicious behavior that may occur in the Smartphone (Faiella et al. 2017). 16832 Electronic copy available at: https://ssrn.com/abstract=4102022Education E xcellence and Innovation Management: A 2025 Vision to Sustain Economic Development during Global Challenges Analysis of Behavior Detection Techniques Because of the integration of advanced techniques in the design and development of malwares (Wazid, Zeadally, and Das 2019), the detection of the latter is now more and more difficult despite the various works done in this direction. Its algorithms can be effective in specific cases for a context Well-defined. However, analyzing the behavior of malware in a real execution environment can be an important factor in identifying and detecting the impacts associated with the malicious behavior of malware and its future targets. For an effective analysis of the integrated vulnerabilities in the applications or in AOSP itself, implicitly or explicitly (security flaws in the code), the behavioral analysis of the launched processes must be implemented and remain in active listening in order to control the various flows and interactions between its processes and the resources (of which they have access or not) from Smartphones. The data provided by these can contain information on behaviors that can be considered inappropriate or malicious, even if the resources used can already be made available to the applications, the source of their behaviors, thanks to the permissions granted upon installation or they are, in one way or another, put within its reach because of a security breach (following an elevation of privileges for example). Techniques for Detecting and Analyzing Malware To minimize human intervention in understanding and analyzing new malware, it is essential to automate its tasks in order to “robotize” their detections so that the potential risks associated with their malicious behavior can easily be identified. Despite the increase, diversification, and complication of the technics of malicious applications, the analysis, extraction, and sample classification processes of these applications must be capable of extracting models or images representing the identity of its malware. Its representations can then be used for the classification of any new application whose behavior is likely to harm the security and normal functioning of the end user’s devices. 16833 Electronic copy available at: https://ssrn.com/abstract=4102022Education E xcellence and Innovation Management: A 2025 Vision to Sustain Economic Development during Global Challenges Fig. 2: Malware detection schema The detection of a malicious application is mainly based on four steps (Figure 2): • Analysis of the application: after receiving the executable of the application to be analyzed, the system begins the analysis step, which can be dynamic, static, or both: o Dynamic analysis: consists of the execution and monitoring of the application in a real or virtual machine. The observation of the activities of the application can relate to the launched processes, the network requests, the modifications made on the system files, the registry, etc. |
o Static analysis: consists of applying “Reverse-engineering” to the application to be able to decompile the executable and reconstruct its source code so that it can be used in the following steps. • Data Extraction and Transformation: data mining techniques (Graph model, n-tuple, n-gram, etc.) can be used in this step to extract data that may contain characteristics, specifications, and functionalities (unitary or combined). This is geared towards determining the benign behaviors (representing the normal functioning of applications) or malicious behavior which could constitute a potential risk for the security of system resources and the integrity of sensitive user data. The extracted data can undergo transformations in order to eliminate unnecessary data (noise-tolerant) and then generate signatures, behavioral models, graphs representing the image of the extracted functionalities. • Feature Classification: uses the Machine Learning to classify the characteristics of the analyzed application by referring to the generic rules and models previously built based on the characteristics already extracted from the application samples (benign and malicious) during the training phase of the system. • Evaluation/Decision: in this step, the characteristics extracted from the analyzed application are compared with the signatures or behavioral model previously-stored the system database, and following this comparison, the system can deduce whether the analyzed application is malicious or not. 16834 Electronic copy available at: https://ssrn.com/abstract=4102022Education E xcellence and Innovation Management: A 2025 Vision to Sustain Economic Development during Global Challenges Malware Behavior Detection Approach Several studies have been elaborated to describe the different malware detection approaches based on their behavioral imprint extracted during their interaction with the environment on which they are hosted. The nature of the latter, which can be a real environment, Sandbox, or a virtual machine, and its architecture play a decisive role in identifying the different application execution paths (malicious or not). 1) MADAM: Saracino et al. (2016) proposed Madam, which is an Android malware detection system based on behavior monitoring at the level of the user (their activity/inactivity), the application (critical APIs), the package (permissions requested), and the kernel (system calls, etc.). After having classified most of the behavioral characteristics of real and known malware in misbehavior classes, the system ensures the extraction, analysis, and correlation of the functionalities of installed applications with behavioral models, previously generated, in order to be able to effectively detect and block any malicious activity. This system has shown its effectiveness in detecting more than 96% of malicious applications with a low rate of false alarms. 2) M0droid: This technique about detecting Android malware had been proposed by Damshenas et al. (2015). It consists of two elements: a light client agent and an analyzer server. The client agent is installed in mobile devices that communicate with an analysis server, the latter analyzes the behavior of Android applications (invoked system calls) and creates signatures representing the malicious activities that malware can carry out; its signatures are used by client agents to identify and detect any vulnerability threatening users. The client-server architecture of this framework allows the end-user to minimize the consumption of resources and phone energy. The latter runs the client agent in the background and transmits to the analyzer server the various data collected regarding the installed applications. The analyzer server takes care of the analysis of the applications in an emulator by injecting it with random events both to invoke the system calls corresponding to the processing, and to cover the maximum of the possible paths of execution of the analyzed application. The behavior of the latter is captured and then used to create a standardized signature that will then be classified and compared with the blacklist of signatures that are previously constructed by this framework. Outsourcing the detection functionality to the cloud overcomes the limitations related to the performance of the end user’s mobile device. 60.16% is the malware detection rate with 0.4% false negatives and 39.43% as a false positive rate. 3) DroidDetector: The functionalities of dynamic and static analysis of Android applications have been combined in Droiddetector (Yuan, Lu, and Xue 2016), this hybrid solution is based on a Deep Learning method based on the Deep Belief Network (DBN) to extract, investigate and classify static characteristics (calls system, permissions, ...) and dynamics (behavior categories) of benign and malicious applications analyzed. The result of these treatments is used to feed the DBN network so that it can be used afterward by the DroidDetector mobile application previously installed on the end user’s device. With a sample of 1,760 malicious applications, 192 static and dynamic characteristics were extracted, which allowed the level of detection accuracy to reach 96.76%. 4) Andromaly: Andromaly (Shabtai et al. 2012) is a Host-based malware detection system that continuously monitors and classifies the various events dynamically generated by the mobile device while applications are running. Other features (related to network traffic, battery level, number of running processes, etc.) are also monitored by this system. Using Machine Learning algorithms, the behavioral characteristics collected are classified according to their nature (malicious or not), and then used to assess the level of infection of the mobile device. The alert history is also used and combined with the results obtained to reduce the rate of the false positives that are obtained. Even if the experiments are not done on samples of real malicious applications, the obtained results confirm that their solution is effective on the applications analyzed. 16835 Electronic copy available at: https://ssrn.com/abstract=4102022Education E xcellence and Innovation Management: A 2025 Vision to Sustain Economic Development during Global Challenges 5) ServiceMonitor: With the system proposed by Salehi, Amini, and Crispo (2019), malicious behaviors are identified using Machine Learning algorithms. Indeed, ServiceMonitor consists of generating a precise |
representation of the behavior of applications based on its different interactions with the service and system resources. The use of these resources is classified and represented by a statistical model (in the form of Markov chains) making it possible to monitor their exploitation by the various running applications. With a sample of 18,058 applications processed (10,024 benign and 8,034 malicious), ServiceMonitor was efficient and precise in detecting malicious behavior with an accuracy rate of 96.7%. 6) HIDROID: Ribeiro et al. (2020) developed a novel Host-based IDPS for Android (HIDROID), which is a standalone Intrusion Detection and Prevention Systems that runs entirely on a mobile device without the need for a remote server. The behavior of applications with the device’s resources (battery, CPU, memory, etc.) is monitored using a detection engine, which collects data in real-time and builds up a model representing benign behaviors by using a combination of statistics and Machine Learning algorithms that will help detect vulnerabilities (known or not). Any suspicious behavior is communicated to the user in the form of an alert, and countermeasures are taken to reduce the risk of an attack or intrusion. HIDROID has the ability to analyze, learn, and classify behaviors without the need for any malware data. The summary of behavioral malware detection techniques described in this section is presented in Table 1. Table 1: Comparative behaviors analysis of existing techniques Techniques Features Accuracy of detection Behavior monitoring is carried out at the The detection accuracy is 96.9% on a Madam user, application, package, and kernel sample of 2,784 malicious applications, level. with a low false-positive rate. The Framework is composed of an analyzer server and a lightweight client. 60.16% is the malware detection rate M0droid The analysis and detection are based on with 0.4% false negatives and 39.43% the system call invoked by the analyzed as a false positive rate. application. This hybrid solution is based on a Deep Learning method (Deep Belief Network - With a sample of 1,760 malicious DBN-) to extract, investigate, and DroidDetector applications, the detection accuracy classify the static and dynamic reached 96.76% characteristics of the analyzed application. For better efficiency, the alert history is combined with the analysis results made Achieve accuracy in between 87% and Andromaly on the dynamic characteristics of the 99% monitored applications Static models representing the use of resources, and call systems are made Malicious applications are detected ServiceMonitor based on the behavior of applications with an accuracy rate of 96.7% with the different used resources. Learning and classifying behaviors are Detection accuracy reached 0.91 with a HIDROID performed without the use of any false positive rate limited to 0.03. malware data. Despite the multitude of methods for observing, analyzing, and investigating the applications analyzed, some malicious behaviors can remain undetectable. This can be due to: (1) non-satisfaction of the conditions required for its triggering (Smartphone brand or a specific version of Android for 16836 Electronic copy available at: https://ssrn.com/abstract=4102022Education E xcellence and Innovation Management: A 2025 Vision to Sustain Economic Development during Global Challenges example). (2) the difficulty of identifying similarities between the characteristics previously extracted with those detected during the analysis of a behavior; this is due to the complexity linked to determining clearly and exhaustively the different functionalities of behavior and its associated characteristics. (3) or it is because of the nature of the runtime environment. Indeed, the use of a virtual environment (emulator) can be easily detectable thanks to the methods already implemented in malware. This will give malware the opportunity to mask their malicious behavior and remain undetectable. Possible Future Research Prospects Cybersecurity researchers have the interest of improving the effectiveness of current approaches to detecting malicious applications and especially those interested in behavioral analysis of malware. This type of analysis has shown its effectiveness in several studies; hence the need to concentrate efforts in improving the capacities of this component. The use of a few features by benign and malicious applications creates some confusion in the classification of these features and increases the false positive rate. To overcome this malfunction and improve detection performance, it is necessary or even essential to add other layers of analysis using other detection techniques (static or heuristic for example) in order to confirm or reverse a decision before communicating it. These layers will have the mission of verifying the suspect functionalities and characteristics, and not redoing a new independent analysis as suggested by some hybrid approaches. This will also help to ensure an adaptation to the different reactions and transformation that malware (normal, polymorphic or other) can undergo depending on the deployment environment (real, virtual device, etc.), the version of Android or even according to the nature of overlay added by the manufacturer. The approaches based on Deep Learning have given satisfactory results and may also be an area of research that can be explored by experimenting all the algorithms proposed by this method in order to improve the classification of the characteristics and functionalities processed and, thus, improve the performance of the decisions taken. Having complete coverage of the execution and control paths of an application is considered a major challenge to reveal and block any activity likely to harm the security of devices; and this requires the adoption of a new distributed architecture allowing a better inventory of the different behaviors of the analyzed application. The launching of several simultaneous dynamic analyzes of the latter in different environments will allow the identification and capture of new behaviors (data flow, system |
calls, etc.). Ouaguid, Abghour, and Ouzzif (2018) had already proposed a similar architecture based on the Blockchain (ANDROSCANREG) but intended only for the static analysis of Android applications. Adopting such an architecture in the dynamic analysis will help improve the detection of malicious behavior which activates if specific conditions are satisfied. Conclusion In this article, we have presented some techniques for detecting malicious applications and we have specifically examined some dynamic approaches based on malware behavioral analysis. These malware are increasingly sophisticated and difficult to detect in the real world despite the integration of Machine Learning and Deep Learning methods in the classification of generic characteristics, rules, and models identifying the behaviors captured. We believe that the solution to these limits is to have a hybrid method based on a hierarchical combination of different analysis techniques in a distributed environment (based on Blockchain technology for example). Such solution will allow better accuracy in the classification of functionalities extracted during the dynamic analysis of an application or from application samples (benign and malicious) that are analyzed during the training phase of the system. This direction deserves an in-depth study and could open up other opportunities to improve the detection of 16837 Electronic copy available at: https://ssrn.com/abstract=4102022Education E xcellence and Innovation Management: A 2025 Vision to Sustain Economic Development during Global Challenges malicious behavior from more sophisticated malware (polymorphic for example) which changes its representations, its behavior and it is triggered if specific conditions are satisfied. References Aafer, Yousra, Wenliang Du, and Heng Yin (2013). "Droidapiminer: Mining api-level features for robust malware detection in android". In: International conference on security and privacy in communication systems. Springer, pp. 86-103. Anderson, Blake, Curtis Storlie, and Terran Lane (2012). "Improving malware classification: bridging the static/dynamic gap". In: Proceedings of the 5th ACM workshop on Security and artificial intelligence, pp. 3-14. Cabau, George, Magda Buhu, and Ciprian Pavel Oprisa (2016). "Malware classification based on dynamic behavior". In: 2016 18th International Symposium on Symbolic and Numeric Algorithms for Scientific Computing (SYNASC).IEEE, pp. 315-318. Dalla Preda, Mila and Federico Maggi (2017). "Testing android malware detectors against code obfuscation: a systematization of knowledge and unified methodology". In: Journal of Computer Virology and Hacking Techniques 13.3, pp. 209-232. Damshenas, Mohsen et al. (2015). "M0droid: An android behavioral-based malware detection model". In: Journal of Information Privacy and Security 11.3, pp. 141-157. Egele, Manuel et al. (2008). "A survey on automated dynamic malware-analysis techniques and tools". In: ACM computing surveys (CSUR) 44.2, pp. 1-42. Eilam, Eldad (2011). Reversing: secrets of reverse engineering. John Wiley & Sons. Elsabagh, Mohamed et al. (2020). " {FIRMSCOPE}: Automatic Uncovering of Privilege-Escalation Vulnerabilities in Pre-Installed Apps in Android Firmware". In: 29th {USENIX} Security Symposium ({USENIX}Security 20). Faiella, Mario et al. (2017). "A distributed framework for collaborative and dynamic analysis of android malware". In: 2017 25th Euromicro International Conference on Parallel, Distributed and Network-Based Processing (PDP). IEEE, pp. 321-328. Farhang, Sadegh, Mehmet Bahadir Kirdan, et al. (2020). "An Empirical Study of Android Security Bulletins in Different Vendors". In: Proceedings of The Web Conference 2020, pp. 3063-3069. Farhang, Sadegh, Aron Laszka, and Jens Grossklags (2018). "An economic study of the effect of android platform fragmentation on security updates". In: International Conference on Financial Cryptography and Data Security. Springer, pp. 119-137. Kouliaridis, Vasileios et al. (2020). "A Survey on Mobile Malware Detection Techniques". In: IEICE Transactions on Information and Systems 103.2, pp. 204-211. Martinelli, Fabio, Fiammetta Marulli, and Francesco Mercaldo (2017). "Evaluating convolutional neural network for effective mobile malware detection". In: Procedia Computer Science 112, pp. 2372-2381. McAfee (2020) ''McAfee Mobile Threat Report''. [Online], [Retrieved April 23, 2020], https://www.mcafee.com/content/dam/consumer/en-us/docs/2020-Mobile-Threat-Report.pdf Nari, Saeed and Ali A Ghorbani (2013). "Automated malware classification based on network 16838 Electronic copy available at: https://ssrn.com/abstract=4102022Education E xcellence and Innovation Management: A 2025 Vision to Sustain Economic Development during Global Challenges behavior". In: 2013 International Conference on Computing, Networking and Communications (ICNC). IEEE, pp. 642-647. Ouaguid, Abdellah, Noreddine Abghour, and Mohammed Ouzzif (2018). "A novel security framework for managing android permissions using blockchain technology". In: International Journal of Cloud Applications and Computing (IJCAC) 8.1, pp. 55-79. Ribeiro, Jos´e et al. (2020). "HIDROID: Prototyping a Behavioral Host-Based Intrusion Detection and Prevention System for Android". In: IEEE Access 8, pp. 23154-23168. Salehi, Majid, Morteza Amini, and Bruno Crispo (2019). "Detecting malicious applications using system services request behavior". In: Proceedings of the 16th EAI International Conference on Mobile and Ubiquitous Systems: Computing, Networking and Services, pp. 200-209. Saracino, Andrea et al. (2016). "Madam: Effective and efficient behavior-based android malware detection and prevention". In: IEEE Transactions on Dependable and Secure Computing 15.1, pp. 83-97. |
Shabtai, Asaf et al. (2012). " "Andromaly": a behavioral malware detection framework for android devices". In: Journal of Intelligent Information Systems 38.1, pp. 161-190. StatCounter Global Stats (2020) ''Mobile Operating System Market Share Worldwid''.[Online] , [Retrieved April 23, 2020], https://gs.statcounter. com/os-market-share/mobile/worldwide Suarez-Tangil, Guillermo et al. (2017). "Droidsieve: Fast and accurate classification of obfuscated android malware". In: Proceedings of the Seventh ACM on Conference on Data and Application Security and Privacy, pp. 309-320. Wazid, Mohammad, Sherali Zeadally, and Ashok Kumar Das (2019). "Mobile banking: evolution and threats: malware threats and security solutions". In: IEEE Consumer Electronics Magazine 8.2, pp. 56-60. Wu, Lei et al. (2013). "The impact of vendor customizations on android security". In: Proceedings of the 2013 ACM SIGSAC conference on Computer & communications security, pp. 623-634. Xi, Shengqu et al. (2019). "DeepIntent: Deep Icon-Behavior Learning for Detecting Intention- Behavior Discrepancy in Mobile Apps". In: Proceedings of the 2019 ACM SIGSAC Conference on Computer and Communications Security, pp. 2421-2436. Yuan, Zhenlong, Yongqiang Lu, and Yibo Xue (2016). "Droiddetector: android malware characterization and detection using deep learning". In: Tsinghua Science and Technology 21.1, pp. 114-123. 16839 Electronic copy available at: https://ssrn.com/abstract=4102022 |
2308.00288 1 VulMatch: Binary-level Vulnerability Detection Through Signature Zian Liu∗§, Lei Pan†, Chao Chen‡, Ejaz Ahmed§, Shigang Liu∗, Jun Zhang∗, Dongxi Liu§ ∗Swinburne University of Technology {zianliu, shigangliu, junzhang}@swin.edu.com †Deakin University {l.pan}@deakin.edu.au ‡Royal Melbourne Institute of Technology {chao.chen}@rmit.edu.au §Data61, CSIRO {ejaz.ahmed, dongxi.liu}@data61.csiro.au Abstract—Similar vulnerability repeats in real-world software real-world scenarios. This paper’s research question is how to productsbecauseofcodereuse,especiallyinwildlyreusedthird- effectively and efficiently find similar vulnerabilities or bugs party code and libraries. Detecting repeating vulnerabilities like from existing ones. 1-day and N-day vulnerabilities is an important cyber security task.Unfortunately,thestate-of-the-artmethodssufferfrompoor Automated detection methods have great advantages over performance because they detect patch existence instead of vul- manual analysis because binary code is notoriously difficult nerabilityexistenceandinferthevulnerabilitysignaturedirectly for humans to read and understand. Mainstream research frombinarycode.Inthispaper,weproposeVulMatchtoextract consistsofthreegenres:binarycodesimilaritydetection,patch precise vulnerability-related binary instructions to generate the existence detection, and vulnerability signature detection. vulnerability-related signature. VulMatch detects vulnerability existencebasedonbinarysignatures.Unlikepreviousapproaches, VulMatchaccuratelylocatesvulnerability-relatedinstructionsby • Binary Code Similarity Detection. Given a set of utilizing source and binary codes. Our experiments were con- query binary samples, code similarity detection tools ducted using over 1000 vulnerable instances across seven open- [4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, sourceprojects.VulMatchsignificantlyoutperformedthebaseline 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, toolsAsm2vecandPalmtree.Besidestheperformanceadvantages 34, 35, 36, 37, 38, 39] identify the best matching code over the baseline tools, VulMatch offers a better feature by providingexplainablereasonsduringvulnerabilitydetection.Our snippets stored in the database with known vulnerable empiricalstudiesdemonstratethatVulMatchdetectsfine-grained binary codes. Code similarity-based vulnerability detec- vulnerability that the state-of-the-art tools struggle with. Our tionfindsvulnerablebinarycodebutintroducesexcessive experiment on commercial firmware demonstrates VulMatch is falsepositivesbecausepatchedbinarycodesusuallyhave able to find vulnerabilities in real-world scenario. high similarity scores. Furthermore, the similarity-based Index Terms—vulnerability detection, software patch, source methodiscoarse-grained.Theyonlyoutputsimilarbinary code, binary code, code signature snippets at a large scale (e.g., function level). Since the functionlevelbinarycodeisusuallylargeinscaleandthe I. INTRODUCTION vulnerability commonly only relates to several instruc- Finding vulnerabilities or bugs in software is vital to im- tions, they can not explain specifically what instructions prove its quality. Vulnerabilities and bugs tend to inherit in indicate the vulnerability. new software products due to the sluggishness of making up- • Patch Existence Detection. This genre of work [4, 40, to-datepatches.Avulnerabilitydetectionparadigmislearning 41, 42] determines whether a patch exists in a query from existing vulnerable codes to find similar vulnerabilities binary function. This genre of work extracts patch code and bugs. Human security analysts can learn from hundreds signatures and detects the existence of patch signatures orthousandsofexistingvulnerabilitiestogainexperienceand in the query function. However, it usually targets kernel improvesecurityawarenesstomanuallyfindvulnerabilitiesor binaries with debugging symbols like function names bugs by reviewing the code [1]. However, with an extremely that are used to filter the query function and detect large number of codes to review, there is an urgent call for patch signatures. Moreover, this genre of work fails to automated methods to identify vulnerability codes directly or address the existence of vulnerability because the lack filter out potentially vulnerable codes for human experts to of patches does not equal the vulnerability’s existence. review later. Moreover, automatic vulnerability detection is in In the National Vulnerability Database (NVD), some high demand due to replicated vulnerabilities spread by code Common Vulnerabilities and Exposures (CVEs) are vul- reuse as a common practice in the software industry [2, 3]. nerable from some versions in a series, suggesting that Detecting the 1-day or N-day vulnerabilities in binary code theversionsbeforetheconsecutivevulnerableversionsdo is vital because of the unavailability of source code in many notcontainpatchedcode.Forinstance,aprojectcontains 4202 naJ 81 ]RC.sc[ 2v88200.8032:viXra2 ten versions, but the versions between the third and the information. The local control-flow information refers to the sixth are vulnerable, so its first two versions are not context instructions. It enriches the signature with unique considered vulnerable because of the absence of patches. features.Toassisthumansinunderstandingthedecisionmade • Vulnerability Signature Detection. This genre of work by VulMatch, a user interface interpreting the matched binary [43, 44, 45] detects fine-grained vulnerability-related signatures shows the matched signatures and the match score signatures in the binary code. Existing works extract in the binary. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.