-
Notifications
You must be signed in to change notification settings - Fork 16
feat(semgrep): Add Semgrep backend for KNighter CSA generation & fix some issues found by recent reviews #15
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Conversation
Kenaz123
commented
Aug 28, 2025
- Adding Semgrep backend using the structure of ClangBackend
- Adding Semgrep examples under manual check
- Implemented semgrep_gen.py and semgrep_repair.py (Here repair might be of little use) with corresponding prompts
- (new) Merge into the newest commits in the upstream KNighter repo
- (new) Reuse the checker_code to represent the Semgrep rule (checker_data.py)
- (new) Delete src/commands.txt and example prompt in get_semgrep_example_text (agent.py)
- (new) Add patch.md in semgrep examples(out-of-bound & integer-overflow)
- (new) Replace all the 'semgrep_dir' with result_dir in agent.py
There was a problem hiding this 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
SemgrepBackendclass 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, andmodel.pyhave 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
-
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. ↩
There was a problem hiding this 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()) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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.
| 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', '') |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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.
| base_path = obj.replace('.o', '') | |
| base_path = obj[:-2] if obj.endswith('.o') else obj |
| 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 | ||
|
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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.