Back to skill

Security audit

SQL Database Toolkit

Security checks for vulnerabilities and agentic risk

Overview

This database skill is coherent in purpose but needs Review because it can modify databases and expose credentials without enough safeguards or warnings.

Review this skill carefully before installing. Use read-only or least-privilege database credentials where possible, avoid pasting real passwords into command lines or chats, do not run mutating SQL unless you explicitly intend to change data, and treat exported CSV/SQL files as sensitive untrusted artifacts.

Vulnerability Patterns
  • 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
  • Embedded Malicious CodeShips malicious scripts inside the skill and executes them locally
Findings (2)

T09 · Insecure Skill Coding Practices

Warning
Location
scripts/db_schema.py:65
Finding

Database Credentials Exposed Through Command-Line Arguments and Schema Output

Content
View full analysis

Vulnerability Details

File Location: SKILL.md:15-18; scripts/db_schema.py:65-72
Vulnerability Type: Credential exposure through process arguments and plaintext logging
Risk Level: Medium

Vulnerable code snippets:

SKILL.md:15-18

bash
# PostgreSQL
python3 skills/sql-db-toolkit/scripts/db_query.py --conn "postgresql://user:pass@host:5432/db" --sql "SELECT table_name FROM information_schema.tables"

scripts/db_schema.py:65-72

python
def inspect_generic(conn_str):
    """Generic schema inspection using SQL standard queries."""
    import importlib
    if conn_str.startswith('postgresql://'):
        pg = importlib.import_module('psycopg2')
        conn = pg.connect(conn_str)
        output = [f"Connection: {conn_str}"]
        c = conn.cursor()

Technical Analysis

The documented interface encourages users to provide a database connection URL containing a username and password through the --conn command-line argument. Command-line arguments may be captured by shell history, process-monitoring utilities, job runners, audit systems, Agent transcripts, or CI/CD logs.

The schema inspection implementation compounds this exposure by copying the complete connection string into its output without redacting the password. Any destination that collects standard output can consequently retain reusable database credentials.

Attack Path

  1. A user follows the documented example and invokes a script with a credential-bearing PostgreSQL URL in --conn.
  2. The invocation is retained in shell history or observed through process inspection or execution logging.
  3. When db_schema.py is used, the full URL is also written to standard output.
  4. Another local user, log reader, transcript consumer, or monitoring-system operator obtains the username and password.
  5. The exposed credentials are reused to connect directly to the database.

Impact Assessment

Successful ...[truncated 451 chars]

Remediation
View remediation

Remediation Suggestions

  • Do not recommend credential-bearing connection URLs directly in command-line arguments.
  • Accept secrets through protected environment variables, an interactive password prompt, a permission-restricted configuration file, or a platform secret manager.
  • Parse connection URLs before display and replace passwords with a fixed redaction marker such as ***.
  • Avoid printing connection strings unless explicitly requested by a diagnostic option; even then, print only non-sensitive fields such as database type, host, port, and database name.
  • Update documentation to use placeholders and explain secure secret provisioning.
  • Ensure CI/CD and Agent execution systems mask database secrets in arguments and logs.
  • Rotate any credentials that may already have been recorded in process, transcript, or shell-history logs.

T09 · Insecure Skill Coding Practices

Warning
Location
scripts/db_export.py:38
Finding

Unsafe CSV and SQL Export Generation Enables Downstream Formula or SQL Injection

Content
View full analysis

Vulnerability Details

File Location: scripts/db_export.py:38-63
Vulnerability Type: Improper neutralization of exported spreadsheet formulas, SQL identifiers, and SQL literals
Risk Level: Medium

Vulnerable code snippet:

python
if fmt == 'csv':
    with open(args.output, 'w', newline='') as f:
        w = csv.writer(f)
        w.writerow(cols)
        w.writerows(rows)
elif fmt == 'json':
    data = [dict(zip(cols, r)) for r in rows]
    with open(args.output, 'w') as f:
        json.dump(data, f, indent=2, default=str)
elif fmt == 'sql':
    # Get table name hint from query
    table_hint = 'exported_table'
    with open(args.output, 'w') as f:
        f.write(f"-- Exported {len(rows)} rows\n-- {args.sql}\n\n")
        for row in rows:
            vals = []
            for v in row:
                if v is None:
                    vals.append('NULL')
                elif isinstance(v, (int, float)):
                    vals.append(str(v))
                else:
                    vals.append(repr(str(v)))
            f.write(f"INSERT INTO {table_hint} ({', '.join(cols)}) VALUES ({', '.join(vals)});\n")

Technical Analysis

CSV values are written verbatim. Quoting performed by csv.writer preserves CSV structure but does not prevent spreadsheet applications from interpreting cells beginning with formula-significant characters such as =, +, -, or @ as formulas. Therefore, attacker-controlled database content can remain active when the export is opened in spreadsheet software.

SQL export generation is also unsafe. Column names obtained from cursor.description are inserted directly into the statement without SQL identifier quoting. String values are serialized with Python repr(), which is not an SQL literal-escaping mechanism and does not provide consistent protection across SQL dialects. The generated file is therefore not guaranteed to preserve data s ...[truncated 2219 chars]

Remediation
View remediation

Remediation Suggestions

  • Offer an explicit spreadsheet-safe CSV mode that prefixes cells beginning with =, +, -, or @ with a neutralizing character accepted by the target spreadsheet workflow.
  • Clearly distinguish raw CSV intended for machine processing from spreadsheet-safe CSV.
  • Generate SQL using a database-aware serialization library rather than Python repr().
  • Quote every identifier using the target database dialect and validate aliases against an expected identifier policy.
  • Escape string literals according to the selected destination SQL dialect, or avoid textual SQL generation by importing through parameterized statements.
  • Do not insert raw query text into executable SQL artifacts. If provenance is needed, encode it safely in metadata or prefix every physical line with the SQL comment marker.
  • Require an explicit destination dialect for SQL exports and add tests covering quotes, backslashes, newlines, comment markers, Unicode, binary values, and adversarial column aliases.
  • Warn users that generated export files contain untrusted database content and should be reviewed before being opened in spreadsheet software or executed.
Vulnerability Patterns
  • Data ExfiltrationExternal Transmission, Env Variable Harvesting, File System Enumeration
  • MCP Tool PoisoningHidden Instructions, Unicode Deception, Parameter Description Injection
  • Prompt InjectionInstruction Override, Hidden Instructions, Exfiltration Commands
  • Privilege EscalationExcessive Permissions, Sudo/Root Execution, Credential Access
  • Supply ChainUnpinned Dependencies, External Script Fetching, Obfuscated Code
Findings (6)

Missing User Warnings

Medium
Category
Not specified by scanner
Confidence
92% confidence
Finding

The skill explicitly advertises destructive capabilities such as INSERT/UPDATE/DELETE, backups, restores, and migrations, but provides no warning about irreversible changes, privilege scope, or the need to confirm before running write operations. In an agent setting, that omission increases the chance of accidental data loss or unauthorized modification because users may treat the tool as routine querying rather than a high-impact database administration capability.

Content

No source excerpt is available for this finding.

Missing User Warnings

Medium
Category
Not specified by scanner
Confidence
94% confidence
Finding

The examples include raw credentials directly inside connection strings, which normalizes exposing secrets in commands, documentation, shell history, logs, and screenshots. In conversational or agent-driven environments, this pattern can lead to credential leakage and reuse of insecure handling practices across real production databases.

Content

No source excerpt is available for this finding.

Missing User Warnings

Medium
Category
Not specified by scanner
Confidence
91% confidence
Finding

This code performs file writes of database query results to a user-specified path in CSV, JSON, or SQL formats. Although the script's purpose is export, there is no explicit warning in the code about potentially sensitive data being written to disk, beyond a final success message after the write completes.

Content

No source excerpt is available for this finding.

Intent-Code Divergence

Medium
Category
Not specified by scanner
Confidence
94% confidence
Finding

The script is presented as a query executor/formatter, but it also executes arbitrary non-SELECT SQL and commits changes automatically. In an agent skill context, this mismatch increases the risk that upstream components or users treat it as read-only and accidentally allow UPDATE, DELETE, DROP, or other state-changing statements against a live database.

Content

No source excerpt is available for this finding.

Missing User Warnings

Medium
Category
Not specified by scanner
Confidence
96% confidence
Finding

The code executes any SQL provided via --sql and automatically commits all non-read queries without warning, confirmation, or policy checks. In an agent setting, this enables accidental or adversarial destructive actions like DELETE, DROP, ALTER, or mass UPDATE against connected databases, especially if the tool is exposed to untrusted prompts or loosely constrained automation.

Content

No source excerpt is available for this finding.

Missing User Warnings

Medium
Category
Not specified by scanner
Confidence
96% confidence
Finding

The PostgreSQL inspection path includes the full connection string in output via output = [f"Connection: {conn_str}"]. If the URI contains embedded credentials, printing it to stdout can expose usernames, passwords, or tokens in terminals, logs, CI output, or agent transcripts. In this schema-inspection context, users are likely to pass real database URIs, which makes accidental secret disclosure more plausible.

Content

No source excerpt is available for this finding.

Static analysis

No suspicious patterns detected.