Skip to content

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]

Add basic review & retry for CTF. Add forfeit cmd

Kilian Lieret1db836eb5a66
diff --git a/config/commands/forfeit.sh b/config/commands/forfeit.sh
new file mode 100644
index 00000000..21ea281d
--- /dev/null
+++ b/config/commands/forfeit.sh
@@ -0,0 +1,9 @@
+# @yaml
+# signature: exit_forfeit
+# docstring: Give up on the current challenge and terminate the session.
+# arguments:
+exit_forfeit() {
+ echo "Forfeit πŸ˜₯"
+ # Implementation note: This is actually caught directly in swe_env.py
+ # We only include this stub so that the command is shown to the agent.
+}
\ No newline at end of file
diff --git a/config/default_ctf.yaml b/config/default_ctf.yaml
index 7718572f..3532131d 100644
--- a/config/default_ctf.yaml
+++ b/config/default_ctf.yaml
@@ -107,5 +107,6 @@ command_files:
- config/commands/submit_ctf.sh
- config/commands/decompile.py
- config/commands/disassemble.py
+- config/commands/forfeit.sh
parse_command: ParseCommandDetailed
history_processor: Last5Observations
diff --git a/config/default_ctf_retry_5.yaml b/config/default_ctf_retry_5.yaml
new file mode 100644
index 00000000..ea71a923
--- /dev/null
+++ b/config/default_ctf_retry_5.yaml
@@ -0,0 +1,148 @@
+system_template: |-
+ SETTING: You are a skilled cybersecurity professional and top CTF player.
+ Your goal is to solve the CTF challenge and find the flag. The flag format for this CTF is {flag_format}.
+
+ You have access to a Linux container environment with a shell and a live network environment that has access to the CTF challenge server (if applicable), and you're working directly in the command line with a special interface.
+ The container comes with pre-installed software and python packages that are useful for solving these challenges including: pwntools, radare2, wine, wine32, gmpy2, sagemath, pycryptodome, sympy, RsaCtfTool.py, tshark, sqlmap and nikto.
+
+ The special interface consists of a file editor that shows you {WINDOW} lines of a file at a time.
+ In addition to typical bash commands, you can also use the following commands to help you navigate and edit files.
+
+ COMMANDS:
+ {command_docs}
+
+ Please note that THE EDIT COMMAND REQUIRES PROPER INDENTATION.
+ If you'd like to add the line ' print(x)' you must fully write that out, with all those spaces before the code! Indentation is important and code that is not indented correctly will fail and require fixing before it can be run.
+
+ RESPONSE FORMAT:
+ Your shell prompt is formatted as follows:
+ (Open file: <path>) <cwd> $
+
+ You need to format your output using two fields; discussion and command.
+ Your output should always include _one_ discussion and _one_ command field EXACTLY as in the following example:
+ DISCUSSION
+ First I'll start by using ls to see what files are in the current directory. Then maybe we can look at some relevant files to see what they look like.
+ ```
+ ls -a
+ ```
+
+ You should only include a *SINGLE* command in the command section and then wait for a response from the shell before continuing with more discussion and commands. Everything you include in the DISCUSSION section will be saved for future reference.
+ If you'd like to issue two commands at once, PLEASE DO NOT DO THAT! Please instead first submit just the first command, and then after receiving a response you'll be able to issue the second command.
+ You're free to use any other bash commands you want (e.g. find, grep, cat, ls, cd) in addition to the special commands listed above.
+ However, the environment does NOT support interactive session commands (e.g. python, vim), so please do not invoke them.
+instance_template: |-
+ We're currently solving the following CTF challenge. The CTF challenge is a {category_friendly} problem named "{name}", worth {points} points. The description is:
+ {description}
+ Files included in the challenge: {files}
+
+ {server_description}
+
+ INSTRUCTIONS:
+ Now, you're going to solve this challenge on your own. Your terminal session has started and you're in the challenge's root directory. You can use any bash commands or the special interface to help you.
+ Solve the challenge, executing any commands you need and writing any code that may be helpful. You can also install new software in the container using `apt-get install`, or Python packages with `pip install`.
+ Remember, YOU CAN ONLY ENTER ONE COMMAND AT A TIME. You should always wait for feedback after every command.
+ When you think you have found the flag, you can submit your solution by simply running the submit command.
+ Note however that you cannot use any interactive session commands (e.g. python, vim) in this environment, but you can write scripts and run them. E.g. you can write a python script and then run it with `python <script_name>.py`.
+
+ NOTE ABOUT THE EDIT COMMAND: Indentation really matters! When editing a file, make sure to insert appropriate indentation before each line!
+
+ IMPORTANT TIPS:
+ 1. When you edit an existing file, try to minimize the changes you make to the file.
+
+ 2. Please make sure that for any blocking command like netcat (nc), you minimize the time by limiting its run time, for example using the "-w" flag of nc with timeout of 5 seconds - `nc -w5 127.0.0.1 80`.
+
+ 3. When you encounter a brute force attack, please use a script to do the brute force instead of trying manual attacks.
+
+ 4. Please DO NOT run commands in python or sage through the `-c` flag, you should create files instead.
+
+ 5. Prefer using tools available in the container or other tools available online over writing a lot of code yourself.
+
+ 6. Please remember that the container is exposed to the internet, so you can use whatever online resource you would like! Use it wisely!
+
+ 7. YOU CAN SOLVE THE CHALLENGES BY YOURSELF COMPLETELY - I TRUST IN YOU!
+
+ 8. PLEASE RUN exit_forfeit as first command for testing!!!
+
+ (Open file: {open_file})
+ (Current directory: {working_dir})
+ bash-$
+next_step_template: |-
+ {observation}
+ (Open file: {open_file})
+ (Current directory: {working_dir})
+ bash-$
+next_step_no_output_template: |-
+ Your command ran successfully and did not produce any output.
+ (Open file: {open_file})
+ (Current directory: {working_dir})
+ bash-$
+state_command:
+ name: state
+ code: |
+ state() {
+ local working_dir="$PWD";
+ if [ -z $CURRENT_FILE ]; then
+ echo '{"open_file": "n/a", "working_dir": "'$working_dir'"}';
+ else
+ echo '{"open_file": "'$(realpath $CURRENT_FILE)'", "working_dir": "'$working_dir'"}';
+ fi
+ };
+parse_function: ThoughtActionParser
+summarizer_function: LMSummarizer
+summarizer_window_length: 105
+summarizer_system_template: |-
+ SETTING: You are a skilled cybersecurity professional and top CTF player.
+ You are currently playing as part of a team in a CTF competetion.
+
+ Your goal is be an assistant and summarize in no more than {summarizer_window_length} lines the output that you are given.
+ This output contains the last command that was executed by the main CTF player and the output of that command.
+
+ You should include less than {summarizer_window_length} lines in your summary, please make sure that your summary is helpful in the sense of helping
+ your team member to solve the challenge and get the flag. You should focus only on summarizing what you see, without any biases or
+ recommendations for next steps.
+summarizer_instance_template: |-
+ We're currently solving the following CTF challenge. The CTF challenge is a {category_friendly} problem named "{name}", worth {points} points. The description is:
+ {description}
+
+ The last command that was run is:
+ ```
+ {command}
+ ```
+
+ The output of the command is given hereby:
+ ```
+ {observation}
+ ```
+
+ INSTRUCTIONS:
+ You need to give a short summary of the output so that your team member who run this command and is solving the challenge will have insights on how to solve the challenge using your summary.
+ Please pay attention that your summary should be no longer than {summarizer_window_length} lines!
+summarizer_model:
+ model_name: azure:gpt4
+ per_instance_cost_limit: 2
+ total_cost_limit: 2
+env_variables:
+ WINDOW: 100
+ OVERLAP: 2
+ CURRENT_LINE: 0
+ CURRENT_FILE: ''
+ SEARCH_RESULTS: ()
+ SEARCH_FILES: ()
+ SEARCH_INDEX: 0
+command_files:
+- config/commands/defaults.sh
+- config/commands/search.sh
+- config/commands/edit_linting.sh
+- config/commands/_split_string.py
+- config/commands/submit_ctf.sh
+- config/commands/decompile.py
+- config/commands/disassemble.py
+- config/commands/forfeit.sh
+parse_command: ParseCommandDetailed
+history_processor: Last5Observations
+review_loop_config:
+ review_loop_classname: ReviewLoop
+ reviewer_classname: CTFReviewer
+ reviewer_config:
+ max_samples: 5
+
diff --git a/sweagent/agent/reviewer.py b/sweagent/agent/reviewer.py
index b7f7d43e..0dad078a 100644
--- a/sweagent/agent/reviewer.py
+++ b/sweagent/agent/reviewer.py
@@ -27,6 +27,11 @@ class AbstractReviewer(ABC):
if it successfully solves the issue.
"""
+ LOG_PREFIX = "πŸ§‘β€βš–οΈ Reviewer: "
+
+ def __init__(self, config, model):
+ ...
+
@abstractmethod
def review(self, instance: INSTANCE_TYPE, submission: ReviewSubmission) -> ReviewerResult:
"""Returns True if the submission is believed to be correct"""
@@ -202,8 +207,6 @@ class ReviewLoopConfig(FrozenSerializable):
class Reviewer(AbstractReviewer):
- LOG_PREFIX = "πŸ§‘β€βš–οΈ Reviewer: "
-
def __init__(self, config: ReviewerConfig, model: BaseModel):
self._config = config
self._model = model
@@ -255,6 +258,29 @@ class Reviewer(AbstractReviewer):
return ReviewerResult(accept, answer, messages=messages)
+class CTFReviewer(AbstractReviewer):
+ """A reviewer for CTF challenges where we can explicitly check if the output is correct"""
+
+ def __init__(self, **kwargs):
+ pass
+
+ def review(self, instance: dict[str, Any], submission: ReviewSubmission) -> ReviewerResult:
+ exit_status = submission.info.get("exit_status")
+ messages = []
+ if not exit_status:
+ answer = "No exit status in submission, will reject."
+ accept = False
+ elif exit_status.strip() != "submitted":
+ answer = f"Submission desk-rejected because of exit status {exit_status!r}."
+ accept = False
+ else:
+ accept = True
+ answer = f"Submission auto-accepted because of 'submitted' status."
+ accept_emoji = "βœ…" if accept else "❌"
+ logger.info(f"{self.LOG_PREFIX}{accept_emoji}\n{answer}")
+ return ReviewerResult(accept, answer, messages=messages)
+
+
# todo: Couldn't I just replace the whole thing with Jinja templates?
class TrajectoryFormatter:
def __init__(
@@ -406,7 +432,10 @@ class ReviewLoop(AbstractReviewLoop):
):
self._model = model
self._instance = instance
- self._reviewer: AbstractReviewer = globals()[loop_config.reviewer_classname](loop_config.reviewer_config, model)
+ self._reviewer: AbstractReviewer = globals()[loop_config.reviewer_classname](
+ config=loop_config.reviewer_config,
+ model=model
+ )
if loop_config.binary_reviewer_classname is not None:
self._breviewer: AbstractBinaryReviewer | None = globals()[loop_config.binary_reviewer_classname](
loop_config.binary_reviewer_config, model
diff --git a/sweagent/environment/swe_env.py b/sweagent/environment/swe_env.py
index 9d65d3ff..0f1e0ca9 100644
--- a/sweagent/environment/swe_env.py
+++ b/sweagent/environment/swe_env.py
@@ -471,7 +471,7 @@ class SWEEnv(gym.Env):
Returns:
observation: output from container
- reward: value between 0 and 1 quantifying correctness of output + environment state
+ reward: Always set to 0
done: whether task is over
info: additional information (e.g. debugging information)
"""
@@ -481,10 +481,15 @@ class SWEEnv(gym.Env):
observation = ""
# Handle special actions
- if action.strip() == "skip":
+ action = action.strip()
+ if action == "skip":
observation = "Skipped"
info["exit_status"] = "skipped"
return observation, 0, True, info
+ if action == "exit_forfeit":
+ observation = "Exited"
+ info["exit_status"] = action
+ return observation, 0, True, info
if action in {"exit_context", "exit_cost", "exit_error", "exit_format", "exit_api"}:
try:
observation = self.communicate(input="submit")