Skip to content

Conversation

@Kenaz123
Copy link
Contributor

  1. Adding Semgrep backend using the structure of ClangBackend
  2. Adding Semgrep examples under manual check
  3. Implemented semgrep_gen.py and semgrep_repair.py (Here repair might be of little use) with corresponding prompts
  4. (new) Merge into the newest commits in the upstream KNighter repo
  5. (new) Reuse the checker_code to represent the Semgrep rule (checker_data.py)
  6. (new) Delete src/commands.txt and example prompt in get_semgrep_example_text (agent.py)
  7. (new) Add patch.md in semgrep examples(out-of-bound & integer-overflow)
  8. (new) Replace all the 'semgrep_dir' with result_dir in agent.py

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Summary of Changes

Hello @Kenaz123, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request significantly enhances the KNighter CSA generation system by integrating a new Semgrep backend. This integration allows the system to not only generate, but also validate and automatically repair Semgrep rules, mirroring the existing capabilities for Clang Static Analyzer checkers. The changes encompass the addition of new modules for Semgrep rule generation and repair, the incorporation of Semgrep into the backend factory, and the provision of extensive example vulnerability patterns and their corresponding Semgrep rules. This feature aims to broaden the static analysis capabilities of the KNighter system.

Highlights

  • Semgrep Backend Integration: A new SemgrepBackend class has been introduced, enabling the system to generate, validate, and run static analysis checks using Semgrep rules, expanding beyond the existing Clang Static Analyzer integration.
  • Automated Semgrep Rule Generation and Repair: New modules (semgrep_gen.py, semgrep_repair.py) and corresponding prompt templates have been added to automate the entire lifecycle of Semgrep rule creation, from extracting bug patterns from patches to generating and repairing the final YAML rules.
  • Expanded Vulnerability Knowledge Base: The system now includes a comprehensive set of example vulnerability patterns (e.g., double-free, integer overflow, null pointer dereference, out-of-bounds) with their associated patches, plans, and ready-to-use Semgrep rules, serving as a knowledge base for rule generation.
  • System-wide Refactoring and Enhancements: Core components like agent.py, checker_data.py, global_config.py, and model.py have been updated to seamlessly support the new Semgrep workflow, including handling YAML rule content and specialized LLM interactions for Semgrep rule generation.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point in your pull request via creating an issue comment (i.e. comment on the pull request page) using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in issue comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces a significant new feature: a Semgrep backend for generating and validating static analysis rules. This includes new prompt templates, example rules, and the core logic for generation and repair, integrated into the existing workflow. The changes are well-structured and comprehensive. I've identified a few areas for improvement, including a potential security risk with eval(), some code duplication, and minor code quality issues. Overall, this is a great addition to the project.


ranking_file = semgrep_dir / id / "ranking.txt"
if ranking_file.exists():
semgrep_id = eval(ranking_file.read_text())
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

Using eval() on data read from a file can be a security risk if the file's content can be manipulated. Although in this case the file is written by the application itself, it's a best practice to use a safer alternative like ast.literal_eval for evaluating literal structures from strings. For even better safety and interoperability, consider using a standard data serialization format like JSON.

Suggested change
semgrep_id = eval(ranking_file.read_text())
import ast
semgrep_id = ast.literal_eval(ranking_file.read_text())

list: List of source file paths
"""
# Remove .o extension and add common source extensions
base_path = obj.replace('.o', '')
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Using obj.replace('.o', '') to get the base path might be unreliable if the object file path contains .o in a directory name (e.g., path/to/foo.o/bar.o). A safer way to remove the extension is to check if the string ends with .o and then slice it.

Suggested change
base_path = obj.replace('.o', '')
base_path = obj[:-2] if obj.endswith('.o') else obj

Comment on lines +211 to 313
def invoke_llm_semgrep(
prompt,
temperature=model_config["temperature"],
model=model_config["model"],
max_tokens=model_config["max_tokens"],
) -> str:
"""Invoke the LLM model with the given prompt for Semgrep rule generation."""

logger.info(f"start LLM process: {model}")
num_tokens = num_tokens_from_string(prompt)
logger.info("Token counts: {}".format(num_tokens))
if num_tokens > 100000:
logger.warning("Token counts exceed the limit. Skip.")
return None

failed_count = 0
while True:
try:
# Get the appropriate client and model
client, actual_model = get_client_and_model(model)

# Handle different client types for Semgrep generation
if isinstance(
client, anthropic.Anthropic if ANTHROPIC_AVAILABLE else type(None)
):
# Claude API
system_prompt = """You generate Semgrep rules in YAML format.
Return only the raw YAML content without any markdown formatting or additional text.
Always include these required fields: id, pattern, message, severity, languages.
Focus on detecting security vulnerabilities and coding issues."""

response = client.messages.create(
model=actual_model,
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": prompt}
],
max_tokens=max_tokens,
temperature=temperature,
)
answer = response.content[0].text

elif isinstance(client, genai.Client):
# Google API
system_prompt = """You generate Semgrep rules in YAML format.
Return only the raw YAML content without any markdown formatting or additional text.
Always include these required fields: id, pattern, message, severity, languages.
Focus on detecting security vulnerabilities and coding issues."""

full_prompt = f"{system_prompt}\n\n{prompt}"
response = client.models.generate_content(
model=actual_model,
contents=full_prompt,
)
answer = response.text

else: # OpenAI or compatible
system_content = """You generate Semgrep rules in YAML format.
Return only the raw YAML content without any markdown formatting or additional text.
Always include these required fields: id, pattern, message, severity, languages.
Focus on detecting security vulnerabilities and coding issues."""

kwargs = {
"model": actual_model,
"messages": [
{"role": "system", "content": system_content},
{"role": "user", "content": prompt}
],
"max_completion_tokens": max_tokens,
}

# Only add temperature for models that support it
no_temp_models = ["o1", "o3-mini", "o4-mini", "o1-preview", "gpt-5"]
if not any(m in actual_model for m in no_temp_models):
kwargs["temperature"] = temperature

response = client.chat.completions.create(**kwargs)
answer = response.choices[0].message.content

except Exception as e:
logger.error("Error: {}".format(e))
failed_count += 1
if failed_count > 5:
logger.error("Failed too many times. Skip.")
raise e
time.sleep(2)
else:
logger.info("finish LLM process")

if isinstance(answer, str):
# Remove think tags if present
if "<think>" in answer or "</think>" in answer:
answer = answer.split("</think>")[-1].strip()
return answer
else:
logger.warning("Response is not a string")
failed_count += 1
if failed_count > 5:
logger.error("Failed too many times. Skip.")
return None
time.sleep(2)
continue

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The functions invoke_llm and invoke_llm_semgrep share a lot of common logic, such as client selection, the retry mechanism, and response parsing. This code duplication can make maintenance harder in the long run. Consider refactoring this into a shared private helper function to reduce duplication. The helper function could take an optional system_prompt argument to handle the difference between the two functions.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant