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]

Different GtC setup with planning stage

Kilian Lieret074baefa2e7d
diff --git a/config/default_ctf_retry_5_gtc.yaml b/config/default_ctf_retry_5_gtc.yaml
index 783ca5ba..8f7c5a39 100644
--- a/config/default_ctf_retry_5_gtc.yaml
+++ b/config/default_ctf_retry_5_gtc.yaml
@@ -143,8 +143,8 @@ review_loop_config:
- `open {file}`: This action opens the file {file}. The output of the command shows part of the content of the file.
- `edit {from}:{to}`, followed by the content to replace lines {from} to {to}. This action always affects the currently
opened file. The output of the command is the content of the file after the edit.
- - `python {file}`: This action executes the Python script {file}. The output of the command is the output of the script.
- `submit`: This action submits a flag for checking.
+ - any normal bash command, like `curl`
RESPONSE FORMAT:
@@ -158,26 +158,30 @@ review_loop_config:
The challenge is guaranteed to be solvable. You cannot contact the organizers or ask for help/hints.
Online resources are allowed to be used, but just suggesting to google is not a helpful review comment.
instance_template: |
- ==========================
- INPUT 1: Problem statement
- ==========================
+ ==================
+ INPUT 1: Challenge
+ ==================
{issue}
- ======================
- INPUT 2: Investigation
- ======================
+ =============================
+ INPUT 2: Failed Investigation
+ =============================
{traj}
+ traj_item_template: |
+ Step {i_step}: {response}
max_samples: 5
gtc_classname: CTFGTC
gtc_config:
prologue: |
- Here is a summary of previous failed attempts to solve the challenge:
+ Here is a summary of previous FAILED attempts to solve the challenge:
epilogue: |
HOW TO USE THE REVIEWS OF PREVIOUS ATTEMPTS:
+
Your first step should be to develop a plan on how to tackle the challenge.
For that, look at the previous solution attempts. Are there any completely new ideas that have not been tried?
If yes, you should do that rather than trying to improve a previous attempt.
If not, try picking the attempt that has the most potential to be successful.
- If a strategy has been tried multiple times already, it's better to pick a different strategy.
\ No newline at end of file
+ If a strategy has been tried multiple times already, it's better to pick a different strategy.
+ All previous attempts have FAILED, so trying to run the same commands again is not going to help you.
\ No newline at end of file
diff --git a/config/default_ctf_retry_5_gtc_planning.yaml b/config/default_ctf_retry_5_gtc_planning.yaml
new file mode 100644
index 00000000..37991ba8
--- /dev/null
+++ b/config/default_ctf_retry_5_gtc_planning.yaml
@@ -0,0 +1,202 @@
+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!
+
+ {gtc}
+
+ (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
+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: CTFSummarizingReviewer
+ reviewer_config:
+ system_template: |
+ SETTING: You are a skilled cybersecurity professional and top CTF player.
+ Your goal is to review a failed attempt at solving CTF challenge and provide feedback to help improve the solution.
+
+ INPUTS
+
+ **INPUT 1**: Problem statement/challenge
+ **INPUT 2**: Investigation: History of how the first developer tried to fix the problem
+
+ The investigation is structured as a series of actions ("Step {i} action: "), where each action is a thought followed by a command in triple-backticks.
+ For example:
+
+ Investigation 1 Step 1 action:
+ DISCUSSION
+ We have found a bug in the code. Let's try to reproduce it.
+ ```
+ create reproduce.py
+ ```
+
+ Investigation 1 Step 1 output:
+ reproduce.py created.
+
+ After the command, there is a description of the output of the command ("Step {i} output: ").
+ The most important actions are
+
+ - `open {file}`: This action opens the file {file}. The output of the command shows part of the content of the file.
+ - `edit {from}:{to}`, followed by the content to replace lines {from} to {to}. This action always affects the currently
+ opened file. The output of the command is the content of the file after the edit.
+ - `submit`: This action submits a flag for checking.
+ - any normal bash command, like `curl`
+
+ RESPONSE FORMAT:
+
+ Your answer must contain the following sections:
+
+ 1. SUMMARY: Summarize the attempted solution. Mention any specific commands or code that was used. Also mention any important files that were found.
+ 2. CRITIQUE: What could we do to improve the solution? What went wrong? What was missed? What could have been done more thoroughly?
+
+ IMPORTANT TIPS:
+
+ The challenge is guaranteed to be solvable. You cannot contact the organizers or ask for help/hints.
+ Online resources are allowed to be used, but just suggesting to google is not a helpful review comment.
+ instance_template: |
+ ==================
+ INPUT 1: Challenge
+ ==================
+
+ {issue}
+
+ =============================
+ INPUT 2: Failed Investigation
+ =============================
+
+ {traj}
+ traj_item_template: |
+ Step {i_step}: {response}
+ max_samples: 5
+ gtc_classname: CTFPlanningGTC
+ gtc_config:
+ system_template: |
+ Setting: You are an expert at CTF challenges.
+ Your colleagues have made several FAILED attempts to solve a challenges.
+ You will be presented with individual reviews of all these attempts.
+
+ BASED ON THEM, COME UP WITH A NEW PLAN FOR AN ATTEMPT.
+
+ For that, look at the previous solution attempts. Are there any completely new strategies that have not been tried?
+ If there are unexplored strategies, suggest ONE such strategy. Do not try to list all possible new strategies.
+ Instead focus on ONE strategy that hasn't been tried and outline how to proceed.
+
+ If there are no completely new strategies, try picking the strategy that has the most potential to be successful.
+ If a strategy has been tried multiple times already, it's better to pick a different strategy.
+ Suggest a new plan based on this strategy and provide detailed hints on how to make it succeed.
+ instance_template: |
+ ==================
+ INPUT 1: Challenge
+ ==================
+
+ {issue}
+
+ ===================================
+ INPUT 2: Reviews of failed attempts
+ ===================================
+
+ {reviews}
+ answer_template: |
+ PLEASE FOLLOW THE FOLLOWING PLAN AND HINTS FROM AN EXPORT CTF PLAYER WHO REVIEWED PREVIOUS FAILED ATTEMPTS:
+
+ {answer}
\ No newline at end of file
diff --git a/sweagent/agent/reviewer.py b/sweagent/agent/reviewer.py
index e4302db9..acb1ad2e 100644
--- a/sweagent/agent/reviewer.py
+++ b/sweagent/agent/reviewer.py
@@ -54,11 +54,13 @@ class AbstractBinaryReviewer(ABC):
class AbstractGraveToCradle(ABC):
+ LOG_PREFIX = "️👶 Grave to cradle: "
"""Forward messages from past attempts to the next one"""
@abstractmethod
def get_forwarded_vars(
self,
+ instance: INSTANCE_TYPE,
submissions: list[ReviewSubmission],
reviews: list[ReviewerResult],
breviews: list[tuple[int, int, BinaryReviewerResult]],
@@ -173,6 +175,15 @@ class CTFGTCConfig(FrozenSerializable):
epilogue: str = ""
+@dataclass(frozen=True)
+class CTFPlanningGTCConfig(FrozenSerializable):
+ """The configuration for the GraveToCradle"""
+
+ system_template: str
+ instance_template: str
+ answer_template: str = "{answer}"
+
+
@dataclass(frozen=True)
class ReviewLoopConfig(FrozenSerializable):
"""The configuration for the review loop"""
@@ -180,7 +191,7 @@ class ReviewLoopConfig(FrozenSerializable):
review_loop_classname: str
reviewer_config: ReviewerConfig | CTFSummarizingReviewerConfig | None = None
binary_reviewer_config: BinaryReviewerConfig | None = None
- gtc_config: CTFGTCConfig | GTCConfig | None = None
+ gtc_config: dict | None = None
reviewer_classname: str | None = None
binary_reviewer_classname: str | None = None
gtc_classname: str = ""
@@ -211,9 +222,6 @@ class ReviewLoopConfig(FrozenSerializable):
msg = "`max_accepted_draws` must be less than or equal to `min_draws`, else it has no effect"
raise ValueError(msg)
- def __post_init__(self):
- self.validate()
-
# --- IMPLEMENTATIONS ---
@@ -455,12 +463,15 @@ class BinaryReviewer(AbstractBinaryReviewer):
class GraveToCradle(AbstractGraveToCradle):
- def __init__(self, config: GTCConfig, model: BaseModel):
- self._config = config
+ def __init__(self, config: GTCConfig | dict, model: BaseModel):
+ if isinstance(config, dict):
+ config = GTCConfig(**config)
+ self._config: GTCConfig = config
self._model = model
def get_forwarded_vars(
self,
+ instance: INSTANCE_TYPE,
submissions: list[ReviewSubmission],
reviews: list[ReviewerResult],
breviews: list[tuple[int, int, BinaryReviewerResult]],
@@ -482,13 +493,16 @@ class GraveToCradle(AbstractGraveToCradle):
class CTFGTC(AbstractGraveToCradle):
- def __init__(self, config: CTFGTCConfig, model: BaseModel):
- assert isinstance(config, CTFGTCConfig)
- self._config = config
+ def __init__(self, config: CTFGTCConfig | dict, model: BaseModel):
+ """GTC for CTF challenges that simply concatenates all of the reviews"""
+ if isinstance(config, dict):
+ config = CTFGTCConfig(**config)
+ self._config: CTFGTCConfig = config
self._model = model
def get_forwarded_vars(
self,
+ instance: INSTANCE_TYPE,
submissions: list[ReviewSubmission],
reviews: list[ReviewerResult],
breviews: list[tuple[int, int, BinaryReviewerResult]],
@@ -498,7 +512,7 @@ class CTFGTC(AbstractGraveToCradle):
return {"gtc_prologue": "", "failed_attempts_summary": "", "gtc_epilogue": ""}
msg_lines = []
for i, review in enumerate(reviews):
- msg_lines.append(f"Review of attempt {i+1}:\n\n{review.output}")
+ msg_lines.append(f"Review of FAILED attempt {i+1}:\n\n{review.output}")
msg = "\n\n".join(msg_lines)
return {
"gtc_prologue": self._config.prologue,
@@ -507,6 +521,44 @@ class CTFGTC(AbstractGraveToCradle):
}
+class CTFPlanningGTC(AbstractGraveToCradle):
+ def __init__(self, config: CTFPlanningGTCConfig, model: BaseModel):
+ """GTC for CTF challenges that summarizes previous attempts and creates a new plan"""
+ if isinstance(config, dict):
+ config = CTFPlanningGTCConfig(**config)
+ self._config: CTFPlanningGTCConfig = config
+ self._model = model
+
+ def format_messages(self, instance: INSTANCE_TYPE, reviews: list[ReviewerResult]):
+ system_message = self._config.system_template
+ logger.debug(f"{self.LOG_PREFIX}MODEL INPUT (system)\n{system_message}")
+ msg_lines = []
+ for i, review in enumerate(reviews):
+ msg_lines.append(f"Review of FAILED attempt {i+1}:\n\n{review.output}")
+ user_message = self._config.instance_template.format(reviews="\n\n".join(msg_lines), **instance)
+ logger.debug(f"{self.LOG_PREFIX}MODEL INPUT (user)\n{user_message}")
+ return [
+ {"role": "system", "content": system_message},
+ {"role": "user", "content": user_message},
+ ]
+
+ def get_forwarded_vars(
+ self,
+ instance: INSTANCE_TYPE,
+ submissions: list[ReviewSubmission],
+ reviews: list[ReviewerResult],
+ breviews: list[tuple[int, int, BinaryReviewerResult]],
+ ) -> dict[str, Any]:
+ assert len(submissions) == len(reviews)
+ if not reviews:
+ return {"gtc": ""}
+ msgs = self.format_messages(instance, reviews)
+ answer = self._config.answer_template.format(answer=self._model.query(msgs))
+ return {
+ "gtc": answer,
+ }
+
+
class ReviewLoop(AbstractReviewLoop):
LOG_PREFIX = "🔄 Review Loop: "
@@ -640,7 +692,7 @@ class ReviewLoop(AbstractReviewLoop):
def get_forwarded_vars(self) -> dict[str, Any]:
if self._gtc is None:
return {}
- return self._gtc.get_forwarded_vars(self._submissions, self._reviews, self._comparisons)
+ return self._gtc.get_forwarded_vars(self._instance, self._submissions, self._reviews, self._comparisons)
def get_review_loop_from_config(