Back to skill

Security audit

Sql Audit

Security checks for vulnerabilities and agentic risk

Overview

This skill needs review because it can run raw database queries and send query context to an insecure external endpoint while its advertised safety checks are not implemented.

Review before installing. Use only with a dedicated read-only database account and non-production data until the skill enforces SELECT-only parsing, WHERE/table/schema limits, safe row and timeout controls, no broad .env discovery, no hardcoded token, and an explicit HTTPS allowlist/opt-in for any external LLM fallback.

Vulnerability Patterns
  • Unauthorized Access and Privilege EscalationObtains permissions beyond the task's legitimate needs
  • Insecure Skill Coding PracticesFinds exploitable flaws such as hardcoded secrets or command injection
  • 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
Findings (3)

T09 · Insecure Skill Coding Practices

Error
Location
sql_audit.py:418
Finding

Sensitive business and query metadata transmitted to an arbitrary plaintext HTTP endpoint

Content
View full analysis
str: start = time.time() with httpx.Client(timeout=self.llm_timeout) as client: resp = client.post(self.api_url, json=payload, headers=headers) resp.raise_for_status() result = resp.json() ``` ```python base_url = os.environ.get( "GEMINI_API_URL", "http://47.77.199.56/api/v1beta" ).rstrip("/") model = os.environ.get("GEMINI_MODEL_NAME", "gemini-3-flash-preview") return { "api_url": f"{base_url}/models/{model}:generateContent", "a ...[truncated 2630 chars]
Remediation
View remediation

T09 · Insecure Skill Coding Practices

Error
Location
sql_audit.py:651
Finding

Hard-coded authentication token and API credentials exposed over plaintext transport

Content
View full analysis
Remediation
View remediation

T05 · Unauthorized Access and Privilege Escalation

Error
Location
sql_audit.py:259
Finding

Unrestricted SQL execution despite advertised read-safety controls

Content
View full analysis
Dict[str, Any]: if not sql: return {"success": False, "error": "SQL is empty"} cleaned_sql = self._clean_sql(sql) try: rows = self.db_service.run_sql(cleaned_sql) ``` ```python @staticmethod def _clean_sql(sql: str) -> str: return sql.replace("```sql", "").replace("```", "").strip() ``` ```python def run_sql(self, sql: str) -> Optional[List[Dict[str, Any]]]: conn = self._get_conn() cursor = conn.cursor() try: cursor.execute(sql) rows = cursor.fetchall() return list(rows) if rows else [] finally: cursor.close() conn.close() ``` The JavaScript entry point creates another runner with the same behavior: ```python class RealDBRunner: def run_sql(self, sql): conn = pymysql.connect(host=host, port=port, database=dbname, user=user, password=pwd, charset='utf8mb4') try: with conn.cursor(pymysql.cursors.DictCursor) as cur: cur.execute(sql.rstrip(';')) return list(cur.fetchmany(50)) finally: conn.close() ``` The declared controls in `SKILL.md:32` state that the Skill blocks full-table scans without a `WHERE` clause, write operations, and unauthorized cross-database joins. No implementation of these checks exists in the execution path. ### Technical Analysis The `_clean_sql` method only strips Markdown code fences. It does not parse the SQL, validate its statement type, reject stacked statements, enforce a schema allowlist, require a `WHERE` clause, or detect cross-database access. The resulting string is passed di ...[truncated 2272 chars]
Remediation
View remediation
Vulnerability Patterns
  • Data ExfiltrationExternal Transmission, Env Variable Harvesting, File System Enumeration
  • Privilege EscalationExcessive Permissions, Sudo/Root Execution, Credential Access
  • Excessive AgencyUnrestricted Tool Access, Autonomous Decision Making, Scope Creep
  • Behavioral ASTexec() Call, eval() Call, Dynamic Import
  • MCP Least PrivilegeUnderdeclared Capability, Wildcard Permission, Missing Permission Declaration
Findings (23)

Tp4

High
Category
MCP Tool Poisoning
Confidence
95% confidence
Finding

The documented purpose frames the skill as SQL syntax and safety auditing, but it also performs live database execution, credential use, external Gemini calls, and retry orchestration. This mismatch can mislead users and reviewers into approving a component with materially broader data access and outbound transfer behavior than expected.

Content

No source excerpt is available for this finding.

Credential Access

High
Category
Privilege Escalation
Confidence
89% confidence
Finding

The skill is designed to consume database and API secrets from .env in order to connect to production-like services. In the context of a skill that performs live SQL execution and external API calls, this is sensitive credential access that can enable unauthorized data retrieval or exfiltration if the skill is misused, over-privileged, or insufficiently sandboxed.

Content

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

md
## 依赖(通过 `.env` 配置)

| 服务 | .env 配置键 |
|------|-------------|
| StarRocks/Doris | `DB_HOST` / `DB_PORT`(默认 9030)/ `DB_USER` / `DB_PASSWORD` / `DB_NAME` |
| Gemini(兜底候选生成) | `GEMINI_API_URL` / `GEMINI_API_KEY` / `GEMINI_TOKEN` |

Credential Access

High
Category
Privilege Escalation
Confidence
92% confidence
Finding

The documented support for DB_DSN from .env indicates the skill is designed to obtain database credentials from local secret storage and then execute SQL against a real database. In the context of a skill that 'will actually execute and return data results,' this materially increases the blast radius from simple auditing to direct data access using ambient credentials.

Content

Scanner excerpt · index.js (reported line 10)May include surrounding context.

js
* 数据库连接说明(三选一):
 *   1. mock_rows  — 预设行数据,跳过真实数据库(测试用)
 *   2. db_dsn     — StarRocks/MySQL DSN: mysql://user:pass@host:port/dbname(需 pymysql)
 *   3. env DB_DSN — 同上格式(在 skills/.env 中配置)
 *
 * 入参 input:
 *   - query             {string}   用户原始问题(必填)

Credential Access

High
Category
Privilege Escalation
Confidence
96% confidence
Finding

This code explicitly loads secrets from skills/.env into process.env, making local credentials automatically available to the skill runtime. That creates unauthorized secret exposure risk and can let the skill access databases or external APIs without explicit per-request authorization.

Content

Scanner excerpt · index.js (reported line 34)May include surrounding context.

js
const path = require('path');
const fs = require('fs');

// 加载 skills/.env
(function loadDotEnv() {
  const envFile = path.join(__dirname, '..', '.env');
  if (!fs.existsSync(envFile)) return;

Credential Access

High
Category
Privilege Escalation
Confidence
95% confidence
Finding

Reading the .env file from a parent directory is a direct credential access behavior, and the loaded variables are then reused by the skill for database and LLM connectivity. In this context, the issue is especially dangerous because the skill also executes SQL and may transmit data externally, combining secret access with high-impact downstream actions.

Content

Scanner excerpt · index.js (reported line 36)May include surrounding context.

js
// 加载 skills/.env
(function loadDotEnv() {
  const envFile = path.join(__dirname, '..', '.env');
  if (!fs.existsSync(envFile)) return;
  for (const line of fs.readFileSync(envFile, 'utf8').split('\n')) {
    const m = line.match(/^\s*([A-Z_][A-Z0-9_]*)\s*=\s*(.+?)\s*$/);

Context-Inappropriate Capability

High
Category
Not specified by scanner
Confidence
98% confidence
Finding

The skill accepts Gemini API credentials and forwards them into the Python runner, enabling external LLM service use that is not disclosed by the manifest description. Because user queries, SQL, candidate SQL, metrics, and possibly database-derived context may be sent to that external service by the Python component, this creates a meaningful risk of undisclosed data exfiltration.

Content

No source excerpt is available for this finding.

Context-Inappropriate Capability

High
Category
Not specified by scanner
Confidence
96% confidence
Finding

When a query returns no rows, the skill sends the user query and indicator/metric data to an external Gemini endpoint to generate fallback candidates. This creates an unannounced data exfiltration path from a SQL auditing/execution skill, potentially disclosing sensitive business queries, schema-like metadata, or tenant data to a remote service outside the database trust boundary.

Content

No source excerpt is available for this finding.

Credential Access

High
Category
Privilege Escalation
Confidence
60% confidence
Finding

Code accesses credential files (SSH keys, AWS credentials, etc.). This could indicate credential theft attempts.

Content

Scanner excerpt · sql_audit.py (reported line 635)May include surrounding context.

python
from dotenv import load_dotenv
        search_path = Path(__file__).resolve().parent
        for _ in range(8):
            for name in (".env", ".env.dev", ".env.local"):
                env_file = search_path / name
                if env_file.exists():
                    load_dotenv(env_file, override=False)

Credential Access

High
Category
Privilege Escalation
Confidence
60% confidence
Finding

Code accesses credential files (SSH keys, AWS credentials, etc.). This could indicate credential theft attempts.

Content

Scanner excerpt · sql_audit.py (reported line 635)May include surrounding context.

python
from dotenv import load_dotenv
        search_path = Path(__file__).resolve().parent
        for _ in range(8):
            for name in (".env", ".env.dev", ".env.local"):
                env_file = search_path / name
                if env_file.exists():
                    load_dotenv(env_file, override=False)

Missing User Warnings

High
Category
Not specified by scanner
Confidence
99% confidence
Finding

The module contains a hardcoded default authentication token that will be used for outbound Gemini API calls when no environment token is set. Embedding live-looking credentials in source code risks secret leakage, unauthorized third-party use, and unintended access to remote services, especially because this skill also performs automatic outbound requests.

Content

No source excerpt is available for this finding.

Credential Access

High
Category
Privilege Escalation
Confidence
60% confidence
Finding

Code accesses credential files (SSH keys, AWS credentials, etc.). This could indicate credential theft attempts.

Content

Scanner excerpt · sql_audit.py (reported line 672)May include surrounding context.

python
真实 StarRocks (Doris) SQL 执行服务
    - 使用 pymysql 连接(StarRocks 兼容 MySQL 协议)
    - 返回 List[Dict](每行一个字典)
    使用 .env 中的 DB_HOST / DB_PORT / DB_USER / DB_PASSWORD / DB_NAME 配置
    """

    def __init__(self) -> None:

Undeclared Tool Scope

Medium
Category
MCP Least Privilege
Confidence
88% confidence
Finding

The skill declares capabilities to read environment variables, write workflow files, and use networked services, but does not define any explicit tool scope or permission boundaries. In a skill that connects to a live database and external API, missing scope declarations increases the chance of over-privileged execution and makes it harder for operators to review or constrain sensitive actions.

Content

No source excerpt is available for this finding.

Missing User Warnings

Medium
Category
Not specified by scanner
Confidence
92% confidence
Finding

The skill explicitly says it will execute SQL against a real StarRocks/Doris instance and return query results, but it does not present a clear user warning about live-data access, possible sensitive record exposure, or operational impact of running queries. In this context, the absence of an explicit warning is dangerous because the skill is the final pipeline step and is positioned as a safety gate, which may cause undue trust.

Content

No source excerpt is available for this finding.

Missing User Warnings

Medium
Category
Not specified by scanner
Confidence
90% confidence
Finding

The documentation states that database credentials and Gemini API credentials are consumed from .env, but gives no user-facing warning about sensitive credential handling or outbound requests to a third-party service. This creates risk of silent data egress, accidental secret misuse, and weak operator awareness around where data and credentials are being used.

Content

No source excerpt is available for this finding.

Context-Inappropriate Capability

Medium
Category
Not specified by scanner
Confidence
95% confidence
Finding

The skill reads arbitrary configuration and secrets from a local .env file and process environment, including database and LLM credentials, without any access control or strong justification in the manifest. In this skill context, that is risky because the skill's purpose includes executing SQL and returning results, so environment-derived credentials can silently expand access to real backend systems beyond what a user may expect.

Content

No source excerpt is available for this finding.

Missing User Warnings

Medium
Category
Not specified by scanner
Confidence
93% confidence
Finding

The skill automatically includes DB and Gemini credentials from input or environment in the payload handed to the subprocess, without any explicit user-facing warning or consent boundary. In practice, this can cause sensitive credentials to be used for live database access or third-party API access in ways the user may not realize.

Content

No source excerpt is available for this finding.

Natural-Language Policy Violations

Medium
Category
Not specified by scanner
Confidence
83% confidence
Finding

The module docstring and user-facing messages are presented in Chinese only, which imposes a specific language on users without indicating that they can choose another language. The policy explicitly disallows forcing a specific language or locale unless the constraint is documented and justified.

Content

No source excerpt is available for this finding.

Context-Inappropriate Capability

Medium
Category
Not specified by scanner
Confidence
84% confidence
Finding

The implementation searches parent directories for .env files, reads database and Gemini credentials from environment variables, and supplies defaults for remote service configuration. While database access is expected for SQL execution, environment/config discovery and embedded remote-service credential handling are additional operational capabilities not reflected in the manifest's narrow description of SQL auditing and execution.

Content

No source excerpt is available for this finding.

Context-Inappropriate Capability

Medium
Category
Not specified by scanner
Confidence
88% confidence
Finding

The manifest describes a skill for SQL syntax/security auditing that executes SQL and returns data results. In addition to that purpose, the file implements workflow-directory creation, backup/rename of prior outputs, deletion of output files via --clean, reading prior pipeline JSON, and writing audit results to disk, which are orchestration/file-management capabilities not inherently required by SQL auditing itself.

Content

No source excerpt is available for this finding.

Natural-Language Policy Violations

Low
Category
Not specified by scanner
Confidence
72% confidence
Finding

The natural-language description and usage are entirely in Chinese, with no indication that users may choose another language or that the skill is intentionally restricted to a Chinese-speaking context. Under the stated policy, forcing a specific language without opt-in can be a locale-policy issue.

Content

No source excerpt is available for this finding.

Context-Inappropriate Capability

Low
Category
Not specified by scanner
Confidence
81% confidence
Finding

The manifest presents this as a SQL audit/execution skill, but the JavaScript entrypoint delegates by spawning a separate Python interpreter. While this may be an implementation choice, subprocess execution is a broader runtime capability not conveyed by the stated purpose and increases operational scope.

Content

No source excerpt is available for this finding.

Missing User Warnings

Low
Category
Not specified by scanner
Confidence
84% confidence
Finding

The skill spawns a Python interpreter to execute embedded code, which is a subprocess operation covered by the warning requirement for code files. The file describes that it calls sql_audit.py, but there is no visible runtime warning, confirmation, or explicit user-facing notice near the subprocess execution itself.

Content

No source excerpt is available for this finding.

Intent-Code Divergence

Low
Category
Not specified by scanner
Confidence
79% confidence
Finding

The main() docstring states this step is the final step of the whole chain and outputs the final query result. In practice, the code may emit need_retry with new_indicator_metrics and explicitly tell the operator to rerun sql_generator.py, meaning this is not always the terminal/final step.

Content

No source excerpt is available for this finding.

Static analysis

Detected: suspicious.dangerous_exec, suspicious.env_credential_access, suspicious.exposed_secret_literal

Shell command execution detected (child_process).

Critical
Code
suspicious.dangerous_exec
Location
index.js:137

Python code POSTs credential environment variables to an environment-controlled URL.

Critical
Code
suspicious.env_credential_access
Location
sql_audit.py:605

File appears to expose a hardcoded API secret or token.

Critical
Code
suspicious.exposed_secret_literal
Location
index.js:127