SWE-agent takes a GitHub issue and tries to automatically fix it, using your LM of choice. It can also be employed for offensive cybersecurity or competitive coding challenges. [NeurIPS 2024]
added decompilation command
Talor Abramovich1924d10a946e
diff --git a/config/commands/decompile.py b/config/commands/decompile.pynew file mode 100644index 00000000..c4978605--- /dev/null+++ b/config/commands/decompile.py@@ -0,0 +1,96 @@+#!/root/miniconda3/bin/python++# @yaml+# signature: decompile <binary_path> <function_name>+# docstring: Decompile a binary and prints the decompilation of a given function name+# arguments:+# binary_path:+# type: file path+# description: The path to the binary to be decompiled+# required: true+# function_name:+# type: string+# description: The function name to be decompiled, or main by default+# required: false++import argparse+import subprocess+import re+import json+import tempfile+from typing import Annotated+from pathlib import Path++GHIDRA_BINARY = "analyzeHeadless"++class Decompile:+ def __init__(self):+ self._decomp_cache = {}++ def __call__(self,+ path: Annotated[str,"path to the binary to decompile"],+ function: Annotated[str,"the function to decompile"] = 'main'):+ """Decompile a function from a binary using Ghidra."""+ if path is None or not Path(path).is_file():+ return f"Error: Binary {path} does not exist! Please try again with a real binary file."+ if function is None:+ function = "main"+ return self.decompile(path, function)++ def find_function(self, dis, function):+ if function in dis["functions"]:+ return dis["functions"][function]+ # Looking for main entry point, so try other names also+ if function == "main":+ if "_start" in dis["functions"]:+ return dis["functions"]["_start"]+ if "invoke_main" in dis["functions"]:+ return dis["functions"]["invoke_main"]+ # Check if requesting radare2 unnamed function with address+ if re.match(r"fcn\.[0-9a-f]+$", function):+ addr = function[4:]+ if addr in dis["addresses"]:+ return dis["functions"][dis["addresses"][addr]]+ # Nothing found+ return None++ def decompile(self, binary, function):+ # Look for the decompilation output in "decomp"+ basename = Path(binary).name+ if basename not in self._decomp_cache:+ decomp_output = Path(f"decomp/{basename}.decomp.json")+ if decomp_output.exists():+ self._decomp_cache[basename] = json.loads(decomp_output.read_text())+ else:+ if not self.run_ghidra(basename, decomp_output):+ return f"Error: Decompilation for {binary} not available"+ self._decomp_cache[basename] = json.loads(decomp_output.read_text())++ if found := self.find_function(self._decomp_cache[basename], function):+ return f"Decompilation Found!\n{found}"+ else:+ return f"Error: Function {function} not found in {binary}.\nThese are the available functions found: {", ".join(self._decomp_cache[basename]['functions'].keys())}"++ def run_ghidra(self, binary, output):+ real_binary = Path(binary)+ if not real_binary or not real_binary.exists():+ return False+ output.parent.mkdir(parents=True, exist_ok=True)+ with tempfile.TemporaryDirectory() as tmpdir:+ tmpdir = Path(tmpdir)+ subprocess.run(+ [GHIDRA_BINARY, tmpdir, "DummyProj", "-scriptpath", '/ghidra_scripts',+ "-import", real_binary, "-postscript", "DecompileToJson.java", output],+ check=False, capture_output=True,+ )+ return output.exists()+++if __name__ == "__main__":+ parser = argparse.ArgumentParser(+ description="Print the contents of a Python file, skipping lengthy function and method definitions."+ )+ parser.add_argument("file_path", type=str, help="The path to the binary to be decompiled")+ parser.add_argument("--function_name", type=str, help="The function name to be decompiled", required=False, default="main")+ args = parser.parse_args()+ print(Decompile()(args.file_path, args.function_name))diff --git a/config/default_ctf.yaml b/config/default_ctf.yamlindex 913c0aab..ed8c5640 100644--- a/config/default_ctf.yaml+++ b/config/default_ctf.yaml@@ -99,5 +99,6 @@ command_files:- config/commands/edit_linting.sh- config/commands/_split_string.py- config/commands/submit_ctf.sh+- config/commands/decompile.pyparse_command: ParseCommandDetailedhistory_processor: Last5Observationsdiff --git a/docker/ghidra_scripts/Decompile.java b/docker/ghidra_scripts/Decompile.javanew file mode 100644index 00000000..a4b4258c--- /dev/null+++ b/docker/ghidra_scripts/Decompile.java@@ -0,0 +1,58 @@+import java.io.File;+import java.io.IOException;+import java.util.ArrayList;+import java.util.List;++import org.apache.logging.log4j.LogManager;+import org.apache.logging.log4j.Logger;++import ghidra.app.script.GhidraScript;+import ghidra.app.util.Option;+import ghidra.app.util.OptionException;+import ghidra.app.util.exporter.CppExporter;+import ghidra.app.util.exporter.ExporterException;++public class Decompile extends GhidraScript {+ private static Logger log;++ public Decompile() {+ log = LogManager.getLogger(Decompile.class);+ }++ public void export(String filename) {+ File outputFile = new File(filename);+ CppExporter cppExporter = new CppExporter();+ cppExporter.setExporterServiceProvider(state.getTool());++ List<Option> options = new ArrayList<Option>();+ Option cppExportHeaderOption =+ new Option(CppExporter.CREATE_HEADER_FILE, Boolean.FALSE);+ options.add(cppExportHeaderOption);+ try {+ cppExporter.setOptions(options);+ } catch (OptionException e) {+ log.error("Unable to set cppExporter options", e);+ return;+ }++ try {+ cppExporter.export(outputFile, currentProgram, null, monitor);+ } catch (IOException e) {+ log.error("Failed writing decompiled code as output", e);+ } catch (ExporterException e) {+ log.error("Failed to export with cppExporter", e);+ }+ }++ @Override+ public void run() throws Exception {+ // IngredientDescription[] ingredients = getIngredientDescriptions();+ // for (IngredientDescription ingredient : ingredients) {+ // state.addParameter(ingredient.getID(), ingredient.getLabel(),+ // ingredient.getType(), ingredient.getDefaultValue());+ // }++ String[] args = getScriptArgs();+ export(args[0]);+ }+}\ No newline at end of filediff --git a/docker/ghidra_scripts/DecompileToJson.java b/docker/ghidra_scripts/DecompileToJson.javanew file mode 100644index 00000000..60b8b709--- /dev/null+++ b/docker/ghidra_scripts/DecompileToJson.java@@ -0,0 +1,61 @@+import java.io.File;+import java.io.FileWriter;+import java.io.IOException;+import java.util.HashMap;++import org.apache.logging.log4j.LogManager;+import org.apache.logging.log4j.Logger;++import ghidra.app.script.GhidraScript;+import ghidra.app.decompiler.DecompInterface;+import ghidra.app.decompiler.DecompileResults;++import com.google.gson.*;++public class DecompileToJson extends GhidraScript {+ private static Logger log;++ public DecompileToJson() {+ log = LogManager.getLogger(DecompileToJson.class);+ }++ public void export(String filename) {+ Gson gson = new GsonBuilder().setPrettyPrinting().create();+ File outputFile = new File(filename);+ HashMap<String, String> function_map = new HashMap<String, String>();+ HashMap<String, String> address_map = new HashMap<String, String>();+ DecompInterface ifc = new DecompInterface();+ ifc.openProgram(currentProgram);++ for (var func : currentProgram.getListing().getFunctions(Boolean.TRUE)) {+ DecompileResults res = ifc.decompileFunction(func,0,monitor);+ if (!res.decompileCompleted()) {+ System.err.println(res.getErrorMessage());+ continue;+ }+ String code = res.getDecompiledFunction().getC();+ function_map.put(func.getName(), code);+ address_map.put(func.getEntryPoint().toString(), func.getName());+ System.out.println(func.getName());+ }++ HashMap<String, HashMap<String, String>> json_data = new HashMap<String, HashMap<String, String>>();+ json_data.put("functions", function_map);+ json_data.put("addresses", address_map);+ // Convert the HashMap to JSON+ String json = gson.toJson(json_data);++ // Write JSON to file+ try (FileWriter writer = new FileWriter(outputFile)) {+ writer.write(json);+ } catch (IOException e) {+ e.printStackTrace();+ }+ }++ @Override+ public void run() throws Exception {+ String[] args = getScriptArgs();+ export(args[0]);+ }+}\ No newline at end of filediff --git a/docker/ghidra_scripts/Disassemble.java b/docker/ghidra_scripts/Disassemble.javanew file mode 100644index 00000000..4988a1c9--- /dev/null+++ b/docker/ghidra_scripts/Disassemble.java@@ -0,0 +1,34 @@+import java.io.File;+import java.io.IOException;++import org.apache.logging.log4j.LogManager;+import org.apache.logging.log4j.Logger;++import ghidra.app.script.GhidraScript;+import ghidra.app.util.exporter.AsciiExporter;++public class Disassemble extends GhidraScript {+ private static Logger log;++ public Disassemble() {+ log = LogManager.getLogger(Disassemble.class);+ }++ public void export(String filename) {+ File outputFile = new File(filename);+ AsciiExporter asciiExporter = new AsciiExporter();+ asciiExporter.setExporterServiceProvider(state.getTool());++ try {+ asciiExporter.export(outputFile, currentProgram, null, monitor);+ } catch (IOException e) {+ log.error("Failed writing disassembled code as output", e);+ }+ }++ @Override+ public void run() throws Exception {+ String[] args = getScriptArgs();+ export(args[0]);+ }+}\ No newline at end of filediff --git a/docker/ghidra_scripts/DisassembleToJson.java b/docker/ghidra_scripts/DisassembleToJson.javanew file mode 100644index 00000000..80dbd24a--- /dev/null+++ b/docker/ghidra_scripts/DisassembleToJson.java@@ -0,0 +1,263 @@+import java.io.File;+import java.io.FileWriter;+import java.io.IOException;+import java.util.List;+import java.util.HashMap;++import org.apache.logging.log4j.LogManager;+import org.apache.logging.log4j.Logger;++import ghidra.app.script.GhidraScript;+import ghidra.app.util.EolComments;+import ghidra.program.model.listing.CodeUnit;+import ghidra.program.model.listing.CodeUnitFormat;+import ghidra.program.model.listing.CodeUnitFormatOptions;+import ghidra.program.model.listing.CodeUnitIterator;+import ghidra.program.model.listing.Data;+import ghidra.program.model.listing.Instruction;+import ghidra.program.model.listing.Listing;+import ghidra.program.model.listing.Variable;+import ghidra.program.model.mem.MemoryAccessException;+import ghidra.program.model.symbol.Symbol;+import ghidra.app.util.template.TemplateSimplifier;+import ghidra.app.util.viewer.field.EolExtraCommentsOption;++import com.google.gson.*;++public class DisassembleToJson extends GhidraScript {+ private static Logger log;++ public DisassembleToJson() {+ log = LogManager.getLogger(DisassembleToJson.class);+ }++ private String getBytes(CodeUnit cu) {+ StringBuffer bytesbuf = new StringBuffer();+ try {+ byte[] bytes;+ if (cu instanceof Instruction instr) {+ bytes = instr.getParsedBytes();+ }+ else {+ bytes = cu.getBytes();+ }+ for (int i = 0; i < bytes.length; ++i) {+ if (bytes[i] >= 0x00 && bytes[i] <= 0x0F) {+ bytesbuf.append("0");+ }+ bytesbuf.append(Integer.toHexString(bytes[i] & 0xff));+ }+ }+ catch (MemoryAccessException e) {+ return "";+ }+ return bytesbuf.toString();+ }++ private String getOperands(CodeUnit cu, CodeUnitFormat cuFormat) {+ StringBuffer buffy = new StringBuffer();+ if (cu instanceof Instruction) {++ Instruction inst = (Instruction) cu;++ int opCnt = inst.getNumOperands();+ String firstSeparator = ((Instruction) cu).getSeparator(0);++ String[] opSeparators = new String[opCnt];+ String[] opReps = new String[opCnt];+ for (int i = 0; i < opCnt; ++i) {+ opReps[i] = cuFormat.getOperandRepresentationString(cu, i);+ opSeparators[i] = ((Instruction) cu).getSeparator(i + 1);+ if (opSeparators[i] == null) {+ opSeparators[i] = "";+ }+ }++ if (firstSeparator != null) {+ buffy.append(firstSeparator);+ }+ for (int i = 0; i < opCnt; ++i) {+ buffy.append(opReps[i]);+ buffy.append(opSeparators[i]);+ }+ }+ else if (cu instanceof Data) {+ Data data = (Data) cu;+ String opRep = cuFormat.getDataValueRepresentationString(data);+ buffy.append(opRep);+ }+ return buffy.toString();+ }++ private String getVariableSorageString(Variable var) {+ String offsetStr;+ if (var.isStackVariable()) {+ int offset = var.getStackOffset();+ offsetStr =+ (offset >= 0 ? " 0x" + Integer.toHexString(offset) : "-0x" + Integer.toHexString(-offset));+ }+ else if (var.isRegisterVariable()) {+ offsetStr = var.getRegister().getName();+ }+ else {+ offsetStr = var.getVariableStorage().toString();+ }+ return offsetStr;+ }++ public void export(String filename) {+ Gson gson = new GsonBuilder().setPrettyPrinting().create();+ File outputFile = new File(filename);+ HashMap<String, String> function_map = new HashMap<String, String>();+ HashMap<String, String> address_map = new HashMap<String, String>();++ // Formatter for disassembled code+ TemplateSimplifier simplifier = new TemplateSimplifier();+ simplifier.setEnabled(false);+ CodeUnitFormatOptions formatOptions = new CodeUnitFormatOptions(+ CodeUnitFormatOptions.ShowBlockName.NEVER,+ CodeUnitFormatOptions.ShowNamespace.NON_LOCAL,+ null,+ true, // doRegVariableMarkup+ true, // doStackVariableMarkup+ true, // includeInferredVariableMarkup+ true, // alwaysShowPrimaryReference+ true, // includeScalarReferenceAdjustment+ true, // showLibraryInNamespace+ true, // followReferencedPointers+ simplifier+ );+ var cuf = new CodeUnitFormat(formatOptions);++ // Annoying thing: for some reason catch blocks are not considered part of+ // a function (listing.getFunctionContaining() returns null), so we'll just+ // keep track of the last function we saw and assume that the next code unit+ // belongs to the same function if it's not in a function.++ ghidra.program.model.listing.Function lastFunc = null;+ CodeUnitIterator cuIterator = currentProgram.getListing().getCodeUnits(true);+ Listing listing = currentProgram.getListing();+ for (var cu : cuIterator) {+ var currentAddress = cu.getMinAddress();+ var func = listing.getFunctionContaining(currentAddress);+ if (func == null) {+ if (cu instanceof Instruction && lastFunc != null) {+ log.warn(String.format(+ "Instruction at [%s] not in a function; assuming it's part of %s",+ currentAddress, lastFunc+ ));+ func = lastFunc;+ }+ else {+ // System.err.printf(+ // "[%s] Note: skipping CU of type %s\n",+ // currentAddress, cu.getClass().getName()+ // );+ continue;+ }+ }+ lastFunc = func;+ boolean isFunctionEntryPoint = func.getEntryPoint().equals(currentAddress);+ // Get the code for this function so far, or create a new one+ String code = function_map.getOrDefault(func.getName(), "");++ // If this is the first code unit in the function, add preamble+ if (isFunctionEntryPoint) {++ log.info(String.format(+ "Processing: %s [%s,%s]",+ func.getName(),+ func.getBody().getMinAddress(),+ func.getBody().getMaxAddress()+ ));+ // Add comment with function signature+ code += String.format("; %s\n", func.getPrototypeString(true, true));+ // Add comment with parameters+ code += "; Parameters:\n";+ for (var v : func.getParameters()) {+ code += String.format("; %-14s %-14s %s\n",+ v.getName(), v.getDataType().getDisplayName(), getVariableSorageString(v)+ );+ }+ // Add comment with local variables on the stack+ code += "; Stack variables:\n";+ for (var v : func.getLocalVariables()) {+ code += String.format("; %-14s %-14s %s\n",+ v.getName(), v.getDataType().getDisplayName(), getVariableSorageString(v)+ );+ }+ }+ String addrString = cu.getAddressString(true, false);+ // Any pre-comment+ String preComment = cu.getComment(CodeUnit.PRE_COMMENT);+ if (preComment != null) {+ code += String.format("%-16s %-16s ; %s\n",+ "",+ "",+ preComment+ );+ }++ // Primary symbol name (either function name or label)+ Symbol primarySymbol = cu.getPrimarySymbol();+ if (primarySymbol != null) {+ code += String.format("%-16s %-16s %s:\n", "", "", primarySymbol.getName());+ }++ // Disassembly+ code += String.format("%-16s %-16s %-11s %-40s",+ addrString,+ getBytes(cu),+ cu.getMnemonicString(),+ getOperands(cu, cuf),+ cuf.getRepresentationString(cu, true)+ );++ // EOL comments+ EolExtraCommentsOption eolOption = new EolExtraCommentsOption();+ EolComments eolComments = new EolComments(cu, true, 6 /* arbitrary */, eolOption);+ List<String> comments = eolComments.getComments();+ if (comments.size() > 0) {+ code += " ; " + String.join(", ", comments);+ }++ // Trim trailing whitespace+ code = code.stripTrailing();+ code += "\n";++ // Any post-comment+ String postComment = cu.getComment(CodeUnit.POST_COMMENT);+ if (postComment != null) {+ code += String.format("%-16s %-16s ; %s\n",+ "",+ "",+ postComment+ );+ }++ // Update the code for this function+ function_map.put(func.getName(), code);+ // Add the address to map+ address_map.put(func.getEntryPoint().toString(), func.getName());+ }++ HashMap<String, HashMap<String, String>> json_data = new HashMap<String, HashMap<String, String>>();+ json_data.put("functions", function_map);+ json_data.put("addresses", address_map);+ // Convert the HashMap to JSON+ String json = gson.toJson(json_data);++ // Write JSON to file+ try (FileWriter writer = new FileWriter(outputFile)) {+ writer.write(json);+ } catch (IOException e) {+ e.printStackTrace();+ }+ }++ @Override+ public void run() throws Exception {+ String[] args = getScriptArgs();+ export(args[0]);+ }+}\ No newline at end of filediff --git a/docker/swe-ctf.Dockerfile b/docker/swe-ctf.Dockerfileindex 07d60475..c6971d39 100644--- a/docker/swe-ctf.Dockerfile+++ b/docker/swe-ctf.Dockerfile@@ -29,9 +29,7 @@ RUN apt-get update && apt-get install -y \# Install radare2WORKDIR /tmpRUN apt-get update && apt-get install -y curl netcat qemu-user qemu-user-static-RUN wget https://github.com/radareorg/radare2/releases/download/5.8.8/radare2_5.8.8_${TARGETARCH}.deb && \- apt-get install -y ./radare2_5.8.8_${TARGETARCH}.deb && \- rm -rf ./radare2_5.8.8_${TARGETARCH}.deb+RUN curl -Ls https://github.com/radareorg/radare2/releases/download/5.8.8/radare2-5.8.8.tar.xz | tar xJv radare2-5.8.8/sys/install.sh# SagemathRUN apt-get install -y sagemath@@ -54,6 +52,7 @@ RUN cd /opt \&& unzip ghidra.zip \&& rm -f ghidra.zipENV PATH=$PATH:/opt/ghidra_11.0.1_PUBLIC/support:/opt/ghidra_11.0.1_PUBLIC/Ghidra+COPY docker/ghidra_scripts /ghidra_scripts# Install python requirementsENV PIP_NO_CACHE_DIR=1