Back to skill

Security audit

code-risk-agent

Security checks for vulnerabilities and agentic risk

Overview

This appears to be a real code-security scanner, but it needs review because it can send full source files to LLM services and silently save scan memory that affects future scans.

Review before installing, especially for private repositories. Keep enable_ai=false unless you are comfortable sending full source files to the configured LLM provider, use a local backend for sensitive code, and inspect or clear ~/.coderisk/memory because saved findings can influence later scans.

Vulnerability Patterns
  • Skill Instruction HijackingAlters the agent's session goals or safety constraints when the skill loads
  • Agent Memory PoisoningWrites attacker-controlled rules into memory that affect later sessions
  • Remote Payload Retrieval and ExecutionFetches external code whose behavior can change after review
  • Embedded Malicious CodeShips malicious scripts inside the skill and executes them locally
  • Unauthorized Access and Privilege EscalationObtains permissions beyond the task's legitimate needs
Findings (2)

T01 · Skill Instruction Hijacking

Error
Location
mcp-server/server.py:145
Finding

<![CDATA[ChatML Prompt-Boundary Injection Through Scanned Source Code]]>

Content
View full analysis
dict: prompt = f"<|im_start|>system\n{system}\n<|im_end|>\n<|im_start|>user\n{user}\n<|im_end|>\n<|im_start|>assistant\n" result = self._local_llm(prompt, max_tokens=max_tokens, temperature=0.1, stop=["<|im_end|>"]) raw = result["choices"][0]["text"] return self._extract_json(raw) ``` The `user` value contains source code read from the scan target: ```python user_prompt = f"""## Source File: {code_file.path} Language: {code_file.language.value} ```{code_file.language.value} {code_file.content} ``` ## Risks Found by Static Analysis {chr(10).join(risk_summaries) if risk_summaries else "No risks found by static analysis."} Please validate each risk and identify any missed vulnerabilities.""" response = _llm.chat_json(SEMANTIC_SYSTEM, user_prompt, max_tokens=4096) ``` The reflection phase repeats the same unsafe construction: ```python user_prompt = f"""## Source File: {f.path} Language: {f.language.value} ```{f.language.value} {f.content} ``` ## Current Risks {risk_text} Verify these risks and find any missed vulnerabilities.""" try: response = _llm.chat_json(VERIFY_SYSTEM, user_prompt, max_tokens=4096) except Exception: break ``` ### Technical Analysis The local LLM client manually constructs a ChatML prompt and interpolates the entire scanned file into the `user` segment without escaping model control tokens such as `<|im_start|>` and `<|im_end|>`. A repository-controlled source file can therefore contain sequences that terminate the intended user message and introduce forged `system`, `assistant`, or additional `user` messages. The model may interpret the injected co ...[truncated 2268 chars]
Remediation
View remediation

T02 · Agent Memory Poisoning

Warning
Location
mcp-server/server.py:530
Finding

<![CDATA[Cross-Session Security Analysis Memory Poisoning]]>

Content
View full analysis
= 2: suppressed += 1 continue elif mtype == "correct" and risk.confidence != Confidence.HIGH: risk = risk.model_copy(update={"confidence": Confidence.HIGH}) ``` The state is stored across sessions in the user's home directory: ```python MEMORY_DIR = os.path.expanduser("~/.coderisk/memory") CORRECT_MEMORY_FILE = os.path.join(MEMORY_DIR, "correct_memory.json") ERROR_MEMORY_FILE = os.path.join(MEMORY_DIR, "error_memory.json") ``` The memory entry is accepted without human confirmation: ```python def store_correct(self, risk: Risk) -> None: """Store a confirmed vulnerability pattern in correct memory.""" pattern_hash = self._hash_risk_pattern(risk) if pattern_hash in self._correct_memory: entry = self._correct_memory[pattern_hash] entry.source_count += 1 entry.last_seen = time.time() if entry.source_count >= 3 and entry.confidence != "high": entry.confidence = "high" else: self._correct_memory[pattern_hash] = MemoryEntry( pattern_hash=pattern_hash, cwe_id=risk.cwe_id or "", severity=risk.severity.value, title=risk.title, description=risk.description, suggestion=risk.sug ...[truncated 3400 chars]
Remediation
View remediation
Vulnerability Patterns
  • Data ExfiltrationExternal Transmission, Env Variable Harvesting, File System Enumeration
  • Supply ChainUnpinned Dependencies, External Script Fetching, Obfuscated Code
  • Excessive AgencyUnrestricted Tool Access, Autonomous Decision Making, Scope Creep
  • Output HandlingUnvalidated Output Injection, Cross-Context Output, Unbounded Output
  • Behavioral ASTexec() Call, eval() Call, Dynamic Import
Findings (55)

Tp4

High
Category
MCP Tool Poisoning
Confidence
95% confidence
Finding

If the real function is a generic retry/backoff utility rather than code-security analysis, the discrepancy is severe because the skill may be selected for sensitive workflows under false pretenses. In a security-assurance context, such mismatches are dangerous even without malicious code because they create silent failure modes and false confidence.

Content

No source excerpt is available for this finding.

Tp4

High
Category
MCP Tool Poisoning
Confidence
95% confidence
Finding

If the real function is a generic retry/backoff utility rather than code-security analysis, the discrepancy is severe because the skill may be selected for sensitive workflows under false pretenses. In a security-assurance context, such mismatches are dangerous even without malicious code because they create silent failure modes and false confidence.

Content

No source excerpt is available for this finding.

Tp4

High
Category
MCP Tool Poisoning
Confidence
95% confidence
Finding

If the real function is a generic retry/backoff utility rather than code-security analysis, the discrepancy is severe because the skill may be selected for sensitive workflows under false pretenses. In a security-assurance context, such mismatches are dangerous even without malicious code because they create silent failure modes and false confidence.

Content

No source excerpt is available for this finding.

Tp4

High
Category
MCP Tool Poisoning
Confidence
95% confidence
Finding

If the real function is a generic retry/backoff utility rather than code-security analysis, the discrepancy is severe because the skill may be selected for sensitive workflows under false pretenses. In a security-assurance context, such mismatches are dangerous even without malicious code because they create silent failure modes and false confidence.

Content

No source excerpt is available for this finding.

Tp4

High
Category
MCP Tool Poisoning
Confidence
90% confidence
Finding

If the real function is a generic retry/backoff utility rather than code-security analysis, the discrepancy is severe because the skill may be selected for sensitive workflows under false pretenses. In a security-assurance context, such mismatches are dangerous even without malicious code because they create silent failure modes and false confidence.

Content

No source excerpt is available for this finding.

Tp4

High
Category
MCP Tool Poisoning
Confidence
98% confidence
Finding

If the real function is a generic retry/backoff utility rather than code-security analysis, the discrepancy is severe because the skill may be selected for sensitive workflows under false pretenses. In a security-assurance context, such mismatches are dangerous even without malicious code because they create silent failure modes and false confidence.

Content

No source excerpt is available for this finding.

Ae1

High
Category
analysis-evasion
Confidence
100% confidence
Finding

Referenced artifact was not completely inspected

Content

Scanner excerpt · SKILL.md (reported line 17)May include surrounding context.

md
| `mcp-server/requirements.txt` | Python 依赖清单 | 声明 MCP Server 运行所需的第三方包 |

Context Leakage

High
Category
Data Exfiltration
Confidence
93% confidence
Finding

The chat method forwards the full messages payload to an HTTP endpoint whenever the LOCAL_HTTP backend is used, and the endpoint is configurable rather than cryptographically pinned or restricted to loopback. In a code-risk scanning skill, those messages may contain proprietary source code, secrets, or vulnerability details, so misconfiguration or malicious reconfiguration can cause sensitive context leakage.

Content

Scanner excerpt · core/llm_client.py (reported line 149)May include surrounding context.

python
stream: bool = False,
        on_token: Optional[callable] = None,
    ) -> str:
        """Send chat request with auto-retry.

        Args:
            stream: Enable streaming for HTTP backends.

Context Leakage

High
Category
Data Exfiltration
Confidence
94% confidence
Finding

The chat_json path also sends user messages and potentially schema/error details back through the same LLM transport, including retry prompts that may echo parsing failures and expected schema structure. In this skill context, that increases the chance of leaking analyzed code, findings, or internal validation metadata to a configurable HTTP service.

Content

Scanner excerpt · core/llm_client.py (reported line 257)May include surrounding context.

python
max_tokens: Optional[int] = None,
        schema: Optional[type] = None,
    ) -> dict:
        """Send chat request, parse JSON with auto-retry and optional schema validation.

        Args:
            schema: Pydantic model class for output validation.

Possible Typosquatting: 'uvicorn' resembles popular package 'gunicorn'

High
Category
Supply Chain
Confidence
70% confidence
Finding

Package name closely resembles a popular package, suggesting possible typosquatting. Attackers publish malicious packages with similar names to trick developers into installing them.

Content

No source excerpt is available for this finding.

Intent-Code Divergence

High
Category
Not specified by scanner
Confidence
98% confidence
Finding

The server claims SSE mode requires API key authentication, but it wraps the app with APIKeyAuthMiddleware that is not defined or imported anywhere in this file. If SSE mode is used, this will either crash at startup (causing denial of service) or indicate that the intended authentication control is missing, meaning operators may believe the endpoint is protected when it is not.

Content

No source excerpt is available for this finding.

Natural-Language Policy Violations

Medium
Category
Not specified by scanner
Confidence
89% confidence
Finding

文件标题和导语明确将该说明文档限定为中文版本(如“README_CN.md”“开发者说明”),但文中未说明这是可选本地化版本,也未提供语言选择或用户 opt-in。根据规则,强制特定语言而无选择机制属于自然语言层面的策略风险。

Content

No source excerpt is available for this finding.

Undeclared Tool Scope

Medium
Category
MCP Least Privilege
Confidence
84% confidence
Finding

The skill exposes broad implied capabilities (environment access, file read/write, network, shell) without declaring any tool scope or permission boundaries. In a code-auditing skill that may receive sensitive source trees, this increases the risk of over-privileged execution, unexpected data exfiltration, or filesystem modification if the backing implementation is compromised or behaves differently than described.

Content

No source excerpt is available for this finding.

Natural-Language Policy Violations

Medium
Category
Not specified by scanner
Confidence
88% confidence
Finding

The file is written entirely in Chinese and repeatedly instructs the agent to present results using Chinese section headings and phrasing, but it does not offer the user a language choice or state that Chinese is optional. This creates a locale/language policy issue because the skill implicitly forces a specific language regardless of user preference.

Content

No source excerpt is available for this finding.

Intent-Code Divergence

Medium
Category
Not specified by scanner
Confidence
96% confidence
Finding

The privacy section says cloud LLM API usage is the default, while the execution section says enable_ai defaults to false. This contradiction is dangerous because users may misunderstand whether their code will be transmitted externally, leading to accidental disclosure of proprietary or sensitive source material.

Content

No source excerpt is available for this finding.

Autonomous Decision Making

Medium
Category
Excessive Agency
Confidence
85% confidence
Finding

Skill enables autonomous high-impact decisions without human-in-the-loop verification. Critical operations (destructive commands, financial transactions, data deletion) should require explicit user confirmation.

Content

Scanner excerpt · agents/deep_verifier.py (reported line 189)May include surrounding context.

python
# Strategy 2: Knowledge base cross-validation (CVE lookup)
        if risk.cwe_id and risk.cwe_id.startswith("CWE-"):
            # Don't auto-confirm: CWE ID from Agent 1 is not cross-validation.
            # Only confirm if CVE data exists (real knowledge-base validation).
            reasons.append(f"CWE tagged: {risk.cwe_id}")

Missing User Warnings

Medium
Category
Not specified by scanner
Confidence
95% confidence
Finding

The code sends the entire source file content and prior risk summaries to an external LLM via self.llm.chat_json, which can expose proprietary code, secrets, or sensitive logic to a third-party service. Even though this appears intended for security analysis, there is no visible consent gate, redaction, or user-facing disclosure in this file, so sensitive data may be transmitted automatically.

Content

No source excerpt is available for this finding.

Missing User Warnings

Medium
Category
Not specified by scanner
Confidence
96% confidence
Finding

The analyzer embeds the entire source file content into the prompt sent to self.llm.chat_json, which can expose proprietary code, secrets, credentials, or regulated data to an external LLM service. In a code-risk scanning skill, this is especially sensitive because users may submit private repositories and may not realize full file contents are being transmitted off-box.

Content

No source excerpt is available for this finding.

Missing User Warnings

Medium
Category
Not specified by scanner
Confidence
95% confidence
Finding

When no static findings exist, the code still sends the full source file to the LLM for semantic scanning, creating the same confidentiality and privacy exposure even in cases where remote analysis may not be expected. This broadens the data-sharing behavior from 'validation of findings' to unconditional code exfiltration for deeper inspection.

Content

No source excerpt is available for this finding.

Intent-Code Divergence

Medium
Category
Not specified by scanner
Confidence
98% confidence
Finding

The module docstring says it parses AST using Tree-sitter, and the class is described as a Tree-sitter static analyzer. However, the actual analysis logic in _analyze_c and _analyze_python just splits file content into lines and applies re.search patterns, with no Tree-sitter import, parser construction, or AST traversal anywhere in the file.

Content

No source excerpt is available for this finding.

Unbounded Output

Medium
Category
Output Handling
Confidence
75% confidence
Finding

Output size or generation rate is not bounded. Unbounded output enables denial-of-service through resource exhaustion, log flooding, or context-window stuffing.

Content

Scanner excerpt · agents/static_analyzer.py (reported line 64)May include surrounding context.

python
"cwe": "CWE-120",
        "severity": Severity.MEDIUM,
        "title": "Unbounded scanf()",
        "desc": 'scanf("%s", ...) has no length limit',
        "fix": 'Use scanf("%99s", buf) to limit length, or use fgets',
    },
    "system": {

Unrestricted Tool Access

Medium
Category
Excessive Agency
Confidence
80% confidence
Finding

Skill grants unrestricted tool access without appropriate constraints. An agent with unfettered tool access can perform arbitrary actions including file modification, network requests, and code execution.

Content

Scanner excerpt · agents/static_analyzer.py (reported line 132)May include surrounding context.

python
"cwe": "CWE-502",
        "severity": Severity.CRITICAL,
        "title": "Deserialization via pickle.loads()",
        "desc": "pickle.loads() deserializing untrusted data can execute arbitrary code",
        "fix": "Use json or msgpack instead of pickle",
    },
    "subprocess.call": {

Unrestricted Tool Access

Medium
Category
Excessive Agency
Confidence
80% confidence
Finding

Skill grants unrestricted tool access without appropriate constraints. An agent with unfettered tool access can perform arbitrary actions including file modification, network requests, and code execution.

Content

Scanner excerpt · agents/static_analyzer.py (reported line 153)May include surrounding context.

python
"cwe": "CWE-502",
        "severity": Severity.CRITICAL,
        "title": "Deserialization via pickle.loads()",
        "desc": "pickle.loads() deserializing untrusted data can execute arbitrary code",
        "fix": "Use json or msgpack instead of pickle",
    },
    "subprocess.call": {

Intent-Code Divergence

Medium
Category
Not specified by scanner
Confidence
96% confidence
Finding

The module docstring claims 'No cloud API calls', but the implementation can POST chat contents to any URL in config.api_url when LOCAL_HTTP is selected. If configuration is changed to a non-local endpoint, sensitive code or audit context could be silently exfiltrated to a remote service under a false assurance of local-only processing.

Content

No source excerpt is available for this finding.

subprocess module call

Medium
Category
Dangerous Code Execution
Confidence
70% confidence
Finding

subprocess module calls execute external commands. Without careful input validation, this enables command injection.

Content

Scanner excerpt · core/llm_client.py (reported line 118)May include surrounding context.

python
gpu_layers = self.config.n_gpu_layers
        try:
            import subprocess
            result = subprocess.run(
                ["rocm-smi", "--showmeminfo", "vram"],
                capture_output=True, text=True, timeout=5,
            )