<?xml-model href='http://www.tei-c.org/release/xml/tei/custom/schema/relaxng/tei_all.rng' schematypens='http://relaxng.org/ns/structure/1.0'?><TEI xmlns="http://www.tei-c.org/ns/1.0">
	<teiHeader>
		<fileDesc>
			<titleStmt><title level='a'>Ad hoc Test Generation Through Binary Rewriting</title></titleStmt>
			<publicationStmt>
				<publisher></publisher>
				<date>09/01/2020</date>
			</publicationStmt>
			<sourceDesc>
				<bibl> 
					<idno type="par_id">10192348</idno>
					<idno type="doi"></idno>
					<title level='j'>IEEE 20th International Working Conference on Source Code Analysis and Manipulation (SCAM)</title>
<idno></idno>
<biblScope unit="volume"></biblScope>
<biblScope unit="issue"></biblScope>					

					<author>Anthony Saieva</author><author>Shirish Singh</author><author>Gail Kaiser</author>
				</bibl>
			</sourceDesc>
		</fileDesc>
		<profileDesc>
			<abstract><ab><![CDATA[When a security vulnerability or other critical bug is not detected by the developers' test suite, and is discovered post-deployment, developers must quickly devise a new test that reproduces the buggy behavior. Then the developers need to test whether their candidate patch indeed fixes the bug, without breaking other functionality, while racing to deploy before attackers pounce on exposed user installations. This can be challenging when factors in a specific user environment triggered the bug. If enabled, however, record-replay technology faithfully replays the execution in the developer environment as if the program were executing in that user environment under the same conditions as the bug manifested. This includes intermediate program states dependent on system calls, memory layout, etc. as well as any externally-visible behavior. Many modern record-replay tools integrate interactive debuggers, to help locate the root cause, but don't help the developers test whether their patch indeed eliminates the bug under those same conditions. In particular, modern record-replay tools that reproduce intermediate program state cannot replay recordings made with one version of a program using a different version of the program where the differences affect program state. This work builds on record-replay and binary rewriting to automatically generate and run targeted tests for candidate patches significantly faster and more efficiently than traditional test suite generation techniques like symbolic execution. These tests reflect the arbitrary (ad hoc) user and system circumstances that uncovered the bug, enabling developers to check whether a patch indeed fixes that bug. The tests essentially replay recordings made with one version of a program using a different version of the program, even when the the differences impact program state, by manipulating both the binary executable and the recorded log to result in an execution consistent with what would have happened had the the patched version executed in the user environment under the same conditions where the bug manifested with the original version. Our approach also enables users to make new recordings of their own workloads with the original version of the program, and automatically generate and run the corresponding ad hoc tests on the patched version, to validate that the patch does not break functionality they rely on.]]></ab></abstract>
		</profileDesc>
	</teiHeader>
	<text><body xmlns="http://www.tei-c.org/ns/1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xlink="http://www.w3.org/1999/xlink">
<div xmlns="http://www.tei-c.org/ns/1.0"><head>I. INTRODUCTION</head><p>Developer testing may not be representative of how software is used in the field <ref type="bibr">[1]</ref>. User bug reports <ref type="bibr">[2]</ref>, <ref type="bibr">[3]</ref> and vulnerability reports <ref type="bibr">[4]</ref>, <ref type="bibr">[5]</ref> are populated primarily with bugs that were not discovered by developer tests. But reproduction steps included in bug reports are often insufficient to reproduce the The Programming Systems Laboratory is supported in part by NSF CNS-1563555, CCF-1815494 and CNS-1842456. bug <ref type="bibr">[6]</ref>. Thus when a security vulnerability or other critical bug is not detected by developer testing prior to deployment, but reported by users, developers need to construct a new test that both reproduces the bug in the original version of the code and verifies the absence of the bug in the patched code.</p><p>This paper presents a novel approach for rapidly generating tests that reproduce post-deployment bugs, support debugging, and verify that candidate patches do not exhibit the buggy behavior. We build on state-of-the-art record-replay technology that records execution traces in the user environment, reproduces post-deployment bugs, and supports debugging, but state-of-the-art record-replay tools do not support testing candidate patches. Since bug-fix patches may introduce other errors not detected by developer tests, breaking users' missioncritical functionality <ref type="bibr">[7]</ref>, our approach also supports user validation of released patches.</p><p>The gist of our patch-testing solution is illustrated abstractly in Figure <ref type="figure">1</ref>. Production applications are recorded by some always-on lightweight recording mechanism. When a bug is discovered, the lightweight recording is replayed and rerecorded offline to augment with additional context necessary for replaying in a different environment. The verbose log is shipped to the developer, who writes and verifies prospective patches. Finally, the new release is accompanied by patchspecific metadata enabling users to validate the patch.</p><p>We refer to this concept as ad hoc test generation because the generated test emulates whatever user context manifested the bug. We emphasize that ad hoc test generation is intended only for urgent time-crunch situations, when there are no existing developer tests that detect the bug and careful planning and design of new developer tests would take too long. Ad hoc test generation is feasible when execution trace divergence is small, analogous to Tucek et al's "delta execution" <ref type="bibr">[8]</ref>, whose large-scale study of patch size found that security and other patches solely to fix bugs tend to be modest in size and scope, rarely changing core program semantics, shared memory layout or process/thread layout.</p><p>The premise of record-replay technology is that there are behaviors that manifest in the user environment that cannot be reproduced by simply running the program with known inputs in the developer environment. If there are such known inputs, ad hoc testing is easy -just run the program with those inputs. This paper addresses more complicated scenarios.</p><p>We have developed a novel ad hoc test generation tool, ATTUNE (Ad hoc Test generation ThroUgh biNary rEwriting). Instead of requiring developers to build doubles, mocks or other test scaffolding to fake the user environment for its tests, ATTUNE builds on existing record-replay tools: It emulates the original execution context, including external inputs, environment variables, the results of system calls, network connections, and the accessed portions of the file system, databases and other local resources as they were at the time the exploit or bug manifestation. Unlike existing record-replay tools, ATTUNE leverages binary rewriting <ref type="bibr">[9]</ref> to modify the original executable at load-time to insert the patched functions from the modified executable, and then interprets the recorded log to manipulate the test emulation as it executes the patched functions. Inserting the patched functions into the original binary results in an execution that perfectly matches the recorded log until divergence when the first patched function is reached. Continuing the execution beyond this point enables the developer to assess whether a candidate patch indeed fixes the bug.</p><p>ATTUNE is based on two key insights: The first is that the symbol tables in Linux ELF files provide points of reference between original and patched versions. Thus each patched function can replace the corresponding original function and access the same global variables and strings. Our second key insight is the recorded log of the original execution trace does not need to be replayed verbatim in order. Instead, events in the log can be skipped or swapped, and new events can be derived on the fly from those in the log, to match the patch.</p><p>ATTUNE follows the workflow illustrated in Figure <ref type="figure">1</ref> to generate an ad hoc test for candidate patches faithful to the execution trace recorded in the user environment. Since ATTUNE requires detailed traces that would impose too much time and space overhead for always-on recording in user environments, we envision that always-on recording is performed by a lightweight record-replay mechanism like Castor <ref type="bibr">[10]</ref>. Then when user observation, analysis, monitoring, etc. determines that a lightweight trace manifests a security vulnerability or other bug, then that trace is augmented offline by ATTUNE's verbose recorder.</p><p>Our ATTUNE prototype builds on Mozilla's rr open-source record-replay tool <ref type="bibr">[11]</ref>- <ref type="bibr">[13]</ref> as the verbose recorder. ATTUNE like rr runs without privileges in user-space, with conventional hardware, operating system, compiler, libraries, build pro-Fig. <ref type="figure">2</ref>. Recording and Preparation for Ad Hoc Test Generation cesses etc. and no changes to the application. This represents a stark contrast to other test generation techniques like symbolic or concolic execution. ATTUNE's binary rewriting modifies the application executable only at load-time, i.e., in memory, not the executable file(s). While the technical details of our binary rewriting mechanisms are specific to our modification of rr's replayer, ad hoc test generation is not, and in principle ATTUNE prototypes could be built on any record-replay technology that supports sufficiently detailed execution traces.</p><p>We explain our requirements for verbose execution traces and the technical details of our binary rewriting techniques in Section II. Our evaluation in Section III describes how a developer would use ATTUNE to test candidate patches for a variety of bugs from well-known open-source projects. Section III also gives an example where the user records their own workload with the original program and replays with the modified program to convince themselves that the bug has been fixed and the patch does not break other behavior. Finally, our evaluation compares to the time and space costs of using KLEE <ref type="bibr">[14]</ref> to generate a test that covers the patched part of the code, given that the bug has already been found and its location known. Section IV discusses related work.</p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head>The contributions of this paper are:</head><p>&#8226; An approach to leveraging record-replay technology and binary rewriting to generate ad hoc test cases to exercise candidate patches as if they had been executing in the user context, instead of the previous buggy version, when the bad behavior was originally recorded.</p><p>&#8226; A technique for adding developer environment metadata to patch releases, enabling users to validate patched versions with their own workloads by (re-)recording with the old version and replaying with the new version.</p><p>&#8226; An open-source prototype implementation, portable across Linux distributions running on x86-64, available at <ref type="url">https://github.com/Programming-Systems-Lab/ATTUNE</ref>.</p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head>II. ARCHITECTURE AND DESIGN</head><p>Our ad hoc test generation workflow has four main components: recording, static preprocessing, loadtime quilting and ---a/pngrutil.c // file info +++ b/pngrutil.c @@ -3167,10 +3167,13 @@ png_check_chunk_length(... </p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head>A. Recording</head><p>We assume production recording with the user's choice of lightweight tool and, when warranted by some external mechanism that detects an error or exploit, offline replaying that tool's recording while re-recording with rr's recorder as in Figure <ref type="figure">1</ref>. Instead of rr, any other recording engine that constructs sufficiently verbose traces would suffice, but we do not know of any actively-supported open-source alternatives. Specifically, the trace must provide the details needed for ATTUNE to recreate the successive register contents and memory layouts leading up to when the bug manifested. Thus the recorded sequence of events must include register values before and after system calls, files that are mmapped into memory, and points at which thread interleaving and signal delivery occur during execution.</p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head>B. Static Preprocessing</head><p>Source Code and Binary Preprocessing. Figure <ref type="figure">3</ref> shows an abbreviated example patchfile from a libpng bug-fix <ref type="bibr">[16]</ref>. Patchfiles document which files changed, which function in the file changed, and which lines within that function were inserted and deleted. Patchfiles are created with a standard format so we are not limited to a single diff implementation.</p><p>Dwarf Information &amp; Symbol Table . Patch files don't provide any information about the resulting binary. Since the recorded trace relies on binary/OS level information (register values, pointers, file descriptors, thread ids, etc.), we need to translate from changes in the source to changes in the binary.  Two mechanisms enable this translation: The first is the symbol table standard in all ELF files and the 2nd is DWARF information. The key insight is that the symbols act as a point of reference between the old and the modified binaries. They remain unchanged even if their addresses and references change. After processing the patchfile we use the symbol tables to find the locations of functions and global variables, and we use DWARF information for finding changed lines and identifying source files. These two sources combined contain all the information in the source level diff at the binary level. Refer to Figures <ref type="figure">4</ref> and<ref type="figure">5</ref> for concrete examples.</p><p>Most real-world builds create multiple binaries and associated libraries, so it may be unclear which binary contains the associated change. In order to generalize to sophisticated build processes ATTUNE uses DWARF information to search through all re-compiled binaries to find the modified file. </p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head>C. Load Time Quilting</head><p>Pre-Load Steps for Quilting. Once the function and line addresses have been resolved, and a prospective patched binary has been compiled, we can generate our test code. In order for the newly compiled patched code to remain a viable test case, it must maintain the binary context of the original code. While most of the binary context remains unchanged, code pointers and data pointers that point somewhere inside the modified functions or that point from the modified functions to any location outside of the modified binary must be updated accordingly. To create the most accurate test we point to the original binary context wherever possible. In order to fully integrate the patched code with the recording, references to shared libraries must point to where the shared libraries were loaded in the recording, references to places in the modified section of the code must point to the appropriate place in the patched code, and references to unmodified contents of the patched binary must point to the appropriate place in the original binary as in Figure <ref type="figure">6</ref>.</p><p>In order to prepare for load time quilting resolution (explained shortly), static reference identification needs to occur for bookkeeping purposes. The patched function is scanned for all symbol references that need to be resolved to integrate with the recorded context. Some references like references to locations within the modified function (e.g.jump and conditional jump instructions) can remain unaltered in position Fig. <ref type="figure">7</ref>. Pointer Translation Procedure independent code. So after all references are accounted for, they are trimmed to the subset of references that need to be changed during the quilting procedure. This includes references to strings, shared library functions, functions that only exist in either the original or the modified binary, functions that exist in both, procedure linkage table (PLT) entries, and global variables. Since symbols are the points of reference between original and patched binaries because recompilation renders addresses meaningless, references to be resolved are defined as a symbol and an offset from that symbol.</p><p>Loading Replication &amp; Custom Loading. In modern Linux systems the system loader is responsible for parsing the executable's header, loading it into memory, and dynamic linking. Since shared libraries are not always loaded at the same positions, references related to the global offset table (GOT), and procedure linkage table (PLT) are resolved after loading completes. So even though ATTUNE knows pre-load which references need resolution, it can't actually resolve those references until load time. In order to preserve the integrity of the replay, all required shared libraries, executables, and system libraries must be loaded into the recorded memory locations. Shared libraries and executables required for replay are included in the trace, and non-recorded libraries loaded during replay are limited to the system loader, which is required at the start of any process.</p><p>In order to replicate the recorded loading activity, ATTUNE begins by loading a small entry point program (replay hook) which hijacks execution from the system loader and begins the replay process. As mentioned earlier, some references in the patched code can't be resolved until the original code is loaded into memory, so initially loading replicates exactly what was recorded. Once the original segments are loaded into memory and GOT/PLT relocations are completed, ATTUNE resolves remaining references in the patched code (described below).</p><p>Finally, ATTUNE's loader loads the quilted code after finding an appropriate place to put it. Note quilting has to be repeated on every replay, and the files containing the original and patched executables are not modified. The loader searches the address space for the lowest slot large enough to accommodate all of the patched code, then loads the patch following the Linux loading conventions. Figure <ref type="figure">6</ref> depicts the address space when loading has completed, and Algorithm 1 outlines the loading procedure.</p><p>Address Translation Procedure. A summary of the procedure to translate pointers from the context of the modified binary to the context of the original binary is given in Figure <ref type="figure">7</ref>, for "chunk data is too large" //identified string in original binary Found string: "chunk data is too large" at 0x320e ... module pngutil code found at 0x000000 ... module pngutil data found at 0x200000 ... generating quilted code Fig. <ref type="figure">8</ref>. libpng-1 abbreviated linking example and consists of both pre-load and load-time actions. The process starts from the address of the modified function as determined from the patchfile and DWARF processing. The modified function is scanned for references. When a reference is identified, if the pointer is affected by the quilting process then ATTUNE's translation procedure corrects the pointer.</p><p>The log messages in Figure <ref type="figure">8</ref> explain the process in detail: An instruction in the patched binary at 0x1b214 points to 0xaa60. In order to update the instruction to point to the same position in the original binary we need to identify the correct symbol and offset in the original. First we convert the target address 0xaa60 into a symbol and offset in the patched binary. Since this instruction is just calling a function, the target symbol is the function name and the target offset is 0. Then ATTUNE searches the original binary for the same symbol and offset, and in this case the function was generated at the same address in original binary. Resolving string refer- Position independent code compilation has become the standard for security and efficiency reasons, so modern binaries can be loaded anywhere in the address space. As a result the locations of external functions and symbols are not known until those symbols actually exist in the address space. Since most library functions aren't called, they aren't all resolved at load time and instead are resolved only after they are called. The procedure linkage table (PLT) acts as a table of tiny functions that perform a function lookup and trampoline to where the code for external functions are defined.</p><p>Unfortunately we can't rely on a PLT because the system loader that performs the runtime function resolution doesn't know about ATTUNE's special memory configuration. Two key differences let us implement static trampolines instead of relying on the traditional PLT mechanism. 1) We only need to resolve the PLT entries that are referenced by the modified code, which comprise a small fraction of the overall PLT, and 2) we can resolve these beforehand without relying on the PLT's lazy loading mechanism because the shared libraries have already been loaded by the time this code is injected. The x86 64 architecture only allows call instructions with a 32-bit offset, but we need to call functions across the 64-bit address space to reference shared library functions. To accomplish this we transform calls to PLT entries into a move instruction that loads an address into a register, and then a call instruction to the address in the register, as shown in Figure <ref type="figure">9</ref>.</p><p>Resolving String &amp; Data Sections. The patched code may also reference data section variables like global data and strings. The patched code must reference the old code where possible and the patched code where required. Identical symbols and strings function act as points of reference between the modified and the original binary.</p><p>These translations are similar to Figure <ref type="figure">7</ref>, with a few minor differences: String tables don't have an associated symbol table. The modified code references the string directly, but to lookup the location of a specific string in the original, we have to iterate through all of the read-only data. If the string exists in the original binary, then we point at it, otherwise ATTUNE points to the appropriate location in the new data section. Note the binary normally accesses data through a global offset table entry, but cannot use it here because the global offset table was compiled for the modified code. Instead, ATTUNE transforms the binary to point to the data directly, since it knows where the data has been loaded. </p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head>D. Runtime Replay Decisions</head><p>The runtime architecture is shown in Figure <ref type="figure">10</ref>. At runtime we continue to leverage developer environment information to aid ATTUNE's decision making, e.g., we know exactly which functions have been modified and perform a strict replay until a modified function is called. We break at that point and move to the patched code, where we use information about added or deleted lines to inform decision making.</p><p>For any non-deterministic event that takes place during replay, we must decide whether to use a corresponding event recorded in the log or to actually submit the event for operation by the kernel, i.e., execute live as would be required if the inserted code makes a new system call. We emulate kernel state and kernel events whenever possible, and only ask the kernel to perform the replaying action when necessary, following the greedy approach shown by the pseudocode in Algorithm 2. It should be noted that system calls which depend on process state, like malloc, and mmap, don't require emulation since this state is actually recreated during replay. All file operations performed during replay are based on information available from the recorded trace, essentially recreating how the program would have acted at the time of the bug except now (for successful patches) without the bug. If there is no further information available, the emulation ends.</p><p>System Calls. The simplest event types to replay are system calls that don't involve file IO. We can reuse results from the log if the parameters for the syscall match what is in the log. It won't match the log exactly since the log contains checks for all registers including the instruction pointer which is obviously different, but we relax these checks once replay has diverged to only check registers containing syscall parameters.</p><p>File IO. System calls involving file, network or device IO are harder to replay since they require a specific kernel state. We have to recreate the file state so we track open, close, stat, read, write, and seek operations for all file descriptors during replay. At the point the replay diverges we have a partial view of the file system. Of course we can't recreate any data that doesn't exist, but if a file operation can't be satisfied during replay we can look forward in the recorded trace to see if we have enough information to satisfy the operation. If we do then we emulate it, and unfortunately if we don't we have to die. Another approach would be to supply random bytes, but we feel this wouldn't accurately reflect a realistic state if the full file system were available.</p><p>Signal Delivery. If a signal is intercepted by the emulation engine, we need to decide if that signal should be delivered to the replaying process. Our normal replay mechanism based on rr's replay mechanism determines when to deliver signals based on the value of the retired conditional branches (RCB) performance counter standard in Intel chips. For signals that have been recorded based on signal type, we check if we are in an inserted line. If we are then we deliver the signal and assume it's created by the patch (e.g.a segfault from an incorrect memory reference in the patch). However if a recorded signal is delivered and we are not currently in the inserted section of the code we can do our best to estimate at what RCB count it should be delivered by taking the target RCB count and adding the number of RCB's caused by inserted lines. While this isn't perfect it does allow for a rough idea as to when the signal should be delivered. In the event an unrecorded signal fires we allow that signal to be delivered without interference since there is no recorded timing information to guide delivery.</p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head>Algorithm 2: Runtime Replay Algorithm</head><p>Input : e: an event that stops replay Output:  <ref type="bibr">[37]</ref>, we used KLEE version 2.1 <ref type="bibr">[38]</ref> (the most recent version as of this writing) compiled with LLVM 9.0.1.</p><p>Since we want to evaluate ATTUNE on an unbiased selection of patches for both security vulnerabilities (CVEs) and other kinds of bugs, and know of no benchmark that provides user environment execution traces or scripts to set up the user context for recording traces, we recruited (for one semester of academic credit) an independent challenge team of three graduate students who were not involved in developing ATTUNE nor versed in how it works. They were tasked to identify a diverse collection of around 20 bugs in widely used C/Linux programs. The bugs had to have been patched during 2016-2019 and the students had to construct user contexts that demonstrated the buggy behavior. For example, in order to recreate the circumstances leading up to the redis-1 bug, first one needs to run the server with a specific configuration, connect to the server in MONITOR mode, and then send a specific byte stream to the server. Note the team could script creation of such contexts given the bug and its root cause is already known; record/replay is for capturing and reproducing the contexts of previously unknown bugs. The team identified the 21 bugs listed in Table <ref type="table">11</ref>.</p><p>We empirically compared ATTUNE with KLEE <ref type="bibr">[14]</ref>, a state of the art test suite generation tool. We limited our comparison to bugs in Table <ref type="table">11</ref> that are part of the coreutils project since KLEE supports coreutils easily. Our other studied bugs have more external libraries, aside of libc, so require additional engineering for KLEE to accommodate. KLEE was given 60 minutes before a timeout ended the test generation, as in <ref type="bibr">[37]</ref>.</p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head>A. ATTUNE successfully validates a wide range of patches provided that corresponding metadata is available</head><p>ATTUNE successfully validated the real developer patches for 19 and failed for 2 of the bugs the challenge team collected, marked with and &#10007; in Table <ref type="table">11</ref>, resp. We organize the 19 bugs successfully handled into several different types and describe how the developer employs ATTUNE in each case, then explain the 2 failures.</p><p>String Parsing bugs are fairly common as there are often many corner cases, which can have significant security implications since input strings may act as attack vectors. Figure <ref type="figure">12</ref> [17] adjusts Curl's treatment of URLs that end in a single colon. In the buggy version, Curl incorrectly throws an error and never initiates a valid http request. The patch modifies one file. Since ATTUNE replaces the entire modified function instead of individual lines of code, it needs to resolve all references in the new version.</p><p>ATTUNE uses the recorded execution to recreate the context that triggered the bug, and then jumps to the patched code upon entering the modified function. Since the only change was adding an if statement that doesn't trigger a recorded event, the ad hoc test continues past the point where the bug occurred, without divergence other than instruction pointer and base pointer. The developer can set a breakpoint at the patched section, watch the if statement process the input correctly and verify the string in *portptr. The test then ends since the log has no information regarding how the network would have responded to the http request had it been sent.</p><p>Figure <ref type="figure">13</ref> [25] deals with mishandling URL strings crafted with special characters, e.g., the "#@" in <ref type="url">http://example.com#@evil.com</ref> caused Curl to erroneously send a request to a malicious URL. The patch calls sscanf Bug Success or Failure Patching Effort Files Modified LOC Changed curl-1 <ref type="bibr">[17]</ref> Changes how a string is parsed 1 16+, 16curl-2 <ref type="bibr">[18]</ref> Changes functions arguments and call. 4 9+, 9curl-5 <ref type="bibr">[19]</ref> Modified if statement for buffer overflow 1 4+, 1curl-6 <ref type="bibr">[20]</ref> Added new function and inserted call 1 55+, 8curl-8 <ref type="bibr">[21]</ref> &#10007; Changes multiple functions calling a write function 4 17+, 17curl-9 <ref type="bibr">[22]</ref> Change parameters to a function call 1 2+,1curl-10 <ref type="bibr">[23]</ref> Adds a condition check 1 6+, 2curl-11 <ref type="bibr">[24]</ref> Off by 1 correction 1 1+, 1curl-12 <ref type="bibr">[25]</ref> Changes libc calls to add extra parsing 1 5+, 5libpng-1 <ref type="bibr">[16]</ref> Calculation modification for divide by 0 error 1 6+, 3libpng-2 <ref type="bibr">[26]</ref> Adjust calculation for idat chunk max 3 13+, 13wc-1 <ref type="bibr">[27]</ref> Added new function and condition check 1 23+, 2wc-2 <ref type="bibr">[28]</ref> Added error condition check 1 3+, 0yes-1 <ref type="bibr">[29]</ref> Substantial changes in option parsing 15 40+, 141shred-1 <ref type="bibr">[30]</ref> &#10007; Removed a break statement 1 1+, 1ls-1 <ref type="bibr">[31]</ref> Added condition for change in option parsing 1 1+, 2mv-1 <ref type="bibr">[32]</ref> Adding a conditional check before operation 2 6+, 0df-1 <ref type="bibr">[33]</ref> Replacing open calls with stat calls 2 12+,8bs-1 <ref type="bibr">[34]</ref> Changing a loop condition 1 2+, 1wget-1 <ref type="bibr">[35]</ref> Adding conditional check for log 1 1-, 2+ redis-1 <ref type="bibr">[36]</ref> Adding conditional check 1 1+, 1-   with a different filter string. Since the surrounding function handles all the URL parsing for the application, it is rather large with lots of references. Unlike the above bug, which only requires resolving pointers to old strings, the new filter string needs to be loaded into a new data section and referenced appropriately. ATTUNE recreates the state that caused the initial behavior and then jumps to the modified code. There the developer can verify the patch by checking the values in protobuf and slashbuf.</p><p>Mathematical Errors can have security implications when related to pointer errors or integer overflows. For example, a malicious PNG image triggers a bad calculation of row factor in Figure <ref type="figure">14</ref>  <ref type="bibr">[16]</ref>, causing a divide-by-zero error and Denialof-Service (DoS). With traditional bug reports, the user would need to send the image as an attachment, but a legitimate user affected by the DoS is unlikely to be aware of the carefully crafted malicious image uploaded by an attacker. ATTUNE does not require attachments besides the execution trace, since create a challenge from ATTUNE's perspective. Since both the function that has been refactored or inserted and the functions that call the new/refactored function need to be modified, ATTUNE must replace all these functions in the executable and properly link them.</p><p>A patch for the wc file processing utility adds special character parsing functions as shown in Figure <ref type="figure">15</ref>  <ref type="bibr">[27]</ref>. ATTUNE loads patched versions of the new function and those functions that call the new function into the address space. The new function is loaded to point towards the original libraries and executables where appropriate, and the modified calling functions point to the new function. There is no need to send a file with the problematic non-standard characters in the bug report to the developer, since it is included in the recorded log. These types of bugs can be difficult for conventional bug reports as files in transit may arrive with modified encoding types and changed contents.</p><p>ATTUNE provides the input from the recorded file and successfully returns from the modified functions displaying the patched output. Testing the modified wc code doesn't diverge drastically from the original execution trace. The developer can verify the patch by letting the program run to termination and inspecting the calculated value.</p><p>Adding Conditionals. Perhaps the most common patch we saw involved adding conditionals. Many security-critical patches make one-line changes to correct conditional checks. We examined one such example in redis. Such services are particularly hard to test and debug using conventional mocks, as complex network inputs can be difficult to recreate in mocking frameworks. Redis allows monitor connections to send logging and status checking commands. The buggy version in Figure <ref type="figure">16</ref> [36] didn't check the client flags for the monitor, which resulted in a kernel panic. While this was one of the smaller patches, the validation process varied substantially from the log. ATTUNE enables the developer to step through the program and watch progress through the modified control flow past the point of the crash.</p><p>New or Changing Loop Conditions. Bad loop conditionals are also common. Reference resolution is performed as before, but these patches vary greatly from an ad hoc testing perspective because loop conditionals do not necessarily exhibit the bug on the loop's first iteration. One such example from the wget utility demonstrates how ATTUNE handles this sort of change in a security-critical situation. The bug allowed attackers to inject arbitrary HTTP headers via CRLF sequences into the URL's host subcomponent. Attackers could insert arbitrary cookies and other header info, perhaps granting access to unauthorized resources. The developer modified the url parse functions in Figure 17 <ref type="bibr">[39]</ref> to check each character in the host name and throw an appropriate error. During ad hoc testing the developer verifies the patch works by watching the program check each character, and upon entering the if statement freeing the URL pointer and proceeding correctly to the error handling code. Swapped Code: ATTUNE successfully constructed test cases in scenarios that swapped library function calls yes-1 <ref type="bibr">[29]</ref> and swapped control flow blocks df-1 <ref type="bibr">[33]</ref>. The yes-1 patch makes far-reaching changes across the code base to address the same bug in multiple places (15 files). Assuming the recorded log only manifests one instance of the bug, then the generated ad hoc test case can only check for that instance, not changes elsewhere in the code base.</p><p>Failures: ATTUNE successfully generated ad hoc test cases for those challenge patches where the compiled binaries included complete metadata. However, it failed on functions with no ELF symbol table entry: We were initially surprised that a removed break statement in shred-1 <ref type="bibr">[30]</ref> caused an error, since the change is so small. Upon investigation, we found this behavior should be expected, since the function (used only in one place) was inlined by the compiler -thus no symbol table entry for cross-referencing the function. ATTUNE also failed due to DWARF omissions: Applying ATTUNE to parameter changes in curl-8 <ref type="bibr">[21]</ref> was unsuccessful. We expected to be able to locate the modified function in the loaded binaries to link the patch, but the DWARF metadata generated by the compiler did not include the filename for the file containing that function. ATTUNE depends on the compiler's compliance with the DWARF specification.</p><p>As Table <ref type="table">18</ref> shows, ATTUNE created tests for 7 of the 8 studied coreutils bugs, while KLEE created tests for 5 and timed out on 2 that were handled by ATTUNE (wc-2, bs-1). Neither was able to generate tests for the shred-1 bug.</p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head>B. ATTUNE's wait time and memory overhead is small</head><p>Ad Hoc Test Construction Time ATTUNE's quilting occurs at load time so runs when each candidate patch is tested. However, since recording allows for targeted test construction, almost all the overhead introduced by searching the program space is removed. Table <ref type="table">18</ref> shows our measurements of quilting overhead relative to KLEE. In all but one case our speedup was well over 90% and could reduce generation time by as much as 99.6%. In absolute time measurements our worst case was just under 4 seconds.</p><p>Memory Footprint: ATTUNE inserts patched code during testing so it incurs some memory overhead at test time.  However, thanks again to targeted testing this is a one time operation. Symbolic execution on the other hand requires significant resources to maintain the intermediate program states required to develop test cases. We found on the studied bugs that ATTUNE reduced memory overhead over 90% in all cases and could reduce memory usage by as much as 97%.</p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head>C. Users validate released patches with their own workloads</head><p>In the last (optional) stage of the patching workflow, the user validates the patch in their own environment to verify no needed functionality has broken. This stage would be particularly useful if combined with our separate static quilting tool <ref type="bibr">[40]</ref>, which enables users to select individual bug-fix patches from new releases containing other unrelated changes. Because ATTUNE operates entirely in user-space, without hardware, operating system, etc. support, it can run in both developer and user environments. ATTUNE summarizes the "diffs" in source and binary code, and exports metadata along with the released binary patch allowing for user validation.</p><p>For sample user environment workloads, we used the redis benchmark <ref type="bibr">[41]</ref>, which simulates thousands of different requests to the server, and the httperf benchmarking tool <ref type="bibr">[42]</ref> making thousands of connections. The validation procedure for the redis patch <ref type="bibr">[41]</ref> is similar to the redis discussion above, but ATTUNE utilizes only the metadata it added to the released patch, shown in Figure <ref type="figure">19</ref>.</p><p>ATTUNE needs inserted and deleted line addresses for its runtime decision algorithm. The metadata's "inserted line addresses" and "deleted line addresses" are offsets into the relevant files while deleted lines from the original binary are offsets into the original executable. Inserted lines only appear in the patch release so their addresses are offsets into the patched codefile that gets mapped into memory.</p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head>D. Threats to Validity</head><p>Internal. As far as we know, no execution traces were recorded when any of the studied bugs were discovered. Some of our scripts for recording the buggy version run bug reproduction tests included in the real bug reports, but others were contrived. This threat is partially mitigated since the contrived scenarios were developed by three grad students who were not ATTUNE developers. We describe how we imagine a developer would verify patches using ATTUNE, but we are not developers on these projects and lack the developers' knowledge. This is mitigated to some extent since ATTUNE generated ad hoc tests for the real developer patches. Lastly, since do not have execution traces for any real users using the programs in our dataset, we simulated workloads with benchmarks that may not be representative of how real users would validate these programs.</p><p>External. We demonstrate that ATTUNE supports a wide variety of single-line and multi-line patches for security vulnerabilities and other bugs in real programs. ATTUNE resolved references between modified and original executables and program state with binary transformations, but we cannot claim that ATTUNE's set of transformations will resolve all types of references supported by the expansive x86-64 instruction set. We have not yet studied C++ or other non-C programs and we have not yet investigated ARM or other architectures. The bugs we studied may not be representative of real-world bugs; notably we have not yet studied GUI bugs.</p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head>E. Limitations</head><p>Our ATTUNE prototype extending rr inherits rr's design decision to replay multi-threaded recordings on a single thread and simulate thread interleaving by interrupting that single thread's execution <ref type="bibr">[11]</ref>, <ref type="bibr">[12]</ref>. Although ATTUNE accommodates thread synchronization and faithfully emulates the error state, rr's approach makes it impossible for ATTUNE to accurately verify patches for concurrency bugs that manifest due to the true parallelism of multi-core execution. There is nothing in ATTUNE itself that inherently prevents it from addressing concurrency bugs, but we would need to find a faithfully multi-threading replacement for rr, ATTUNE also relies on rr to re-record the execution trace in the user environment and to replay that recording in the developer environment with the original version of the program <ref type="bibr">[11]</ref>- <ref type="bibr">[13]</ref>. Since rr was designed to be used during developer testing, with too high overhead for production <ref type="bibr">[11]</ref>, we adopt the re-recording model shown in Figure <ref type="figure">2</ref>. In theory, lightweight production recorders could fail to capture sufficient detail to faithfully replay some behaviors even in the same user environment, in which case the re-recording might not manifest the bug, but Mashtizadeh et al <ref type="bibr">[10]</ref> explain this limitation is generally unimportant in practice.</p><p>A few ATTUNE limitations are orthogonal to the recorder. ATTUNE does not currently verify patches to preprocessor macros, since it compares the source file versions rather than the results of preprocessing the source files. ATTUNE also does not currently support generating tests for patches that change the size of a data structure on the stack or in the heap. We allow new values to be put on the stack and heap, but don't adjust memory allocation when replaying logged values.</p><p>IV. RELATED WORK iFixR <ref type="bibr">[2]</ref> automatically generates candidate patches from bug reports, but relies on conventional regression testing even though those tests initially failed to detect the bug. In future work, we plan to investigate integrating ATTUNE with automatic program repair (APR) technology. Differential unit tests <ref type="bibr">[43]</ref> construct unit tests using in-memory program state immediately prior to invoking the target method, but cannot reproduce bugs not detected by the original developer tests. <ref type="bibr">[44]</ref> similarly extracts unit tests from developer execution traces. In future work, we will investigate constructing unit tests from the ad hoc tests generated by ATTUNE.</p><p>KATCH <ref type="bibr">[45]</ref> combines symbolic execution with heuristics to generate test cases that cover the patched part of the code, while shadow symbol execution <ref type="bibr">[46]</ref> symbolically explores divergences between original and patched versions. Neither leverages execution traces recorded in the user environment, nor fully models system calls, so the generated test cases may not reflect the bug-triggering circumstances. However, symbolic execution enables reaching parts of the program not exercised by the recording, complementing ATTUNE.</p><p>Parallel retro-logging <ref type="bibr">[47]</ref> allows developers to change their logging instrumentation so previous executions produce augmented logs, but the program is not modified. Parikshan <ref type="bibr">[48]</ref> feeds cloned network traffic to a sandboxed component of a service-oriented architecture, for debugging or testing patches of that component, but the sandboxed execution is not faithful for non-network sources of non-determinism.</p><p>Kravets and Tsafrir <ref type="bibr">[49]</ref> proposed "mutable replay", a hypothetical design to execute a patched program reusing the system calls and other non-deterministic events from a recorded execution trace, as in ATTUNE. Mutable replay was later implemented in Dora <ref type="bibr">[50]</ref>, building on the Scribe recordreplay system <ref type="bibr">[51]</ref>. Dora leveraged checkpoint/restart <ref type="bibr">[52]</ref> in a backtracking search to minimize adds/deletes to the recorded execution trace. Although successful on many bugfix examples in the sense that execution continued through the patched part of the code, the minimal-distance execution is not necessarily the same as would have occurred had the patched code been running in the user environment, as ATTUNE aims. Dora and Scribe relied on a 2.6.x kernel module that intercepted and controlled system calls and other events within both user and developer environments. This module will not operate in modern Linux kernels. In contrast, ATTUNE runs without privileges in user-space with no special OS support.</p><p>There are numerous other record-replay tools in the literature, e.g., <ref type="bibr">[53]</ref>- <ref type="bibr">[59]</ref>. These tools reproduce executions, but none tests patched versions. Much research focuses on reducing recording overhead, e.g., <ref type="bibr">[60]</ref>- <ref type="bibr">[62]</ref>. Cui et al <ref type="bibr">[63]</ref> combines hardware tracing and binary analysis to reconstruct execution traces, which can then be replayed with the same program version. Castor <ref type="bibr">[10]</ref> records multi-core applications by leveraging hardware-optimized logging, transactional memory, and a custom compiler. It can replay slightly modified binaries that do not impact program state.</p><p>Multi-Version Execution (MVE) provides an alternative approach to user validation. We envision that the user records production workloads with the old version and re-records offline as in Figure <ref type="figure">1</ref>, but skips the developer stage and uses ATTUNE locally to generate ad hoc tests that replay the workloads with the patch. If all is satisfactory, production switches to the new version via some mechanism outside ATTUNE, e.g., mutable checkpoint-restart <ref type="bibr">[64]</ref>. In MVE, the patched and original versions run simultaneously on production user workloads, adding runtime overhead but enabling immediate detection of undesirable divergences <ref type="bibr">[65]</ref>, <ref type="bibr">[66]</ref>.</p><p>V. CONCLUSION ATTUNE (Ad hoc Test generation ThroUgh biNary rEwriting) leverages record-replay and binary rewriting technologies to automate test generation for security vulnerabilities and other critical bugs discovered post-deployment, when there are no existing tests for testing candidate patches, and little time for constructing and vetting new tests. ATTUNE first quilts the modified functions (the patch) into the original binary and then interprets the recorded execution trace from the original binary, as it executed in the user environment, to "replay" on the patched binary in the developer environment. The developer monitors the progress of the ad hoc test to check that the bug no longer manifests, but does not intervene in test generation and does not need to build test scaffolding. ATTUNE also produces metadata that the developer can deploy with the patched program, which enables users to validate the patch by using ATTUNE to create additional ad hoc tests from their own workloads. We showed that ATTUNE successfully generates tests for a wide range of known security vulnerabilities and other bugs in recent versions of opensource software, with minimal developer effort, both quickly and efficiently. Our open-source implementation is available at <ref type="url">https://github.com/Programming-Systems-Lab/ATTUNE</ref>.</p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head>VI. ACKNOWLEDGMENT</head></div></body>
		</text>
</TEI>
