Back to skill

Security audit

Dual Retrieval

Security checks for vulnerabilities and agentic risk

Overview

The skill appears to be a real dual-retrieval helper, but it can read broad local QMD cache data and expose indexed content without clear scoping or disclosure.

Install only if you trust this skill to read your local M-Flow and QMD memory/index stores. Before use, fix or verify QMD collection scoping, change the hardcoded QMD database path as needed, avoid running the debug/schema scripts on sensitive indexes, and be aware that test runs may write retrieved content into a markdown report.

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)

T05 · Unauthorized Access and Privilege Escalation

Warning
Location
scripts/__init__.py:213
Finding

Configured QMD Collection Scope Is Ignored

Content
View full analysis

Vulnerability Details

File Location: scripts/__init__.py:121-123, 213-218
Vulnerability Type: Authorization scope bypass
Risk Level: Medium

Vulnerable Code

python
self.mflow_memory = mflow_memory
self.qmd_searcher = QMDSearcher()
self.qmd_collections = qmd_collections
self.merge_strategy = merge_strategy
python
qmd_results = self.qmd_searcher.search(
    query=query,
    top_k=top_k,
    collection=None  # Search all collections
)

Technical Analysis

The constructor accepts qmd_collections, which indicates that callers can configure the collections the pipeline is permitted or intended to search. Although this value is retained in self.qmd_collections, it is not used by _search_qmd.

Instead, every search explicitly passes collection=None. In QMDSearcher.search, a null collection causes the collection predicate to be omitted, resulting in a query across every active collection in the database.

This creates an authorization and data-isolation weakness when collection configuration represents a tenant, user, project, or confidentiality boundary. The API gives callers the appearance that retrieval can be scoped, while the actual database operation is unrestricted.

Attack Path

  1. An application creates DualRetrievalPipeline with qmd_collections restricted to one or more authorized collections.
  2. A user submits a query containing terms likely to occur in documents outside the authorized scope.
  3. _search_qmd ignores the configured collection list and passes collection=None.
  4. QMDSearcher.search searches every active collection.
  5. Matching content and metadata from other collections are returned in qmd_results and may be included in merged_results.
  6. The unauthorized content may subsequently be displayed, logged, or written into a generated report.

Impact Assessment

A user able to invoke the retrieval pipeline may obtain docum ...[truncated 415 chars]

Remediation
View remediation

Remediation Suggestions

  • Enforce self.qmd_collections in _search_qmd rather than passing collection=None.
  • If multiple collections are supported, execute a parameterized query for each authorized collection or extend QMDSearcher.search to accept a collection list and generate parameter placeholders safely.
  • Reject searches when a collection scope is required but no authorized collections are configured.
  • Do not silently interpret an empty collection list as permission to search all collections.
  • Apply authorization at the database-query layer so callers cannot bypass it through an alternate pipeline path.
  • Add tests proving that documents from unauthorized collections never appear in direct, merged, logged, or report output.
  • Consider associating collection permissions with an authenticated caller identity rather than accepting scope solely from caller-controlled input.

T09 · Insecure Skill Coding Practices

Warning
Location
scripts/check_qmd_schema.py:7
Finding

Schema Diagnostic Script Exposes Sample Database Records

Content
View full analysis

Vulnerability Details

File Location: scripts/check_qmd_schema.py:7-26
Vulnerability Type: Sensitive information exposure through diagnostic output
Risk Level: Medium

Vulnerable Code

python
# Get all tables
cursor.execute("SELECT name FROM sqlite_master WHERE type='table'")
tables = cursor.fetchall()
print('Tables:', tables)

for t in tables:
    name = t[0]
    cursor.execute(f'PRAGMA table_info({name})')
    cols = cursor.fetchall()
    print(f'\n{name}:')
    for c in cols:
        print(f'  {c}')
    
    # Sample data
    cursor.execute(f'SELECT * FROM {name} LIMIT 2')
    rows = cursor.fetchall()
    print(f'  Sample rows: {len(rows)}')
    for r in rows[:2]:
        print(f'    {str(r)[:200]}')

conn.close()

Technical Analysis

The script is described as a database-schema inspection utility, but it does more than enumerate tables and columns. It selects complete records from every discovered table and prints the first 200 characters of each sampled row.

QMD tables can contain indexed document bodies, file paths, titles, collection metadata, or other locally stored information. Printing arbitrary row samples is not necessary to inspect the schema and can transfer database content into terminal history, continuous-integration logs, agent execution transcripts, or centralized logging systems.

Table names originate from sqlite_master, so this finding is not based on externally supplied SQL injection. The confirmed weakness is excessive disclosure of locally indexed records.

Attack Path

  1. The QMD database contains sensitive indexed documents or metadata.
  2. A user, automation process, or troubleshooting workflow runs check_qmd_schema.py.
  3. The script enumerates all tables in the database.
  4. It executes SELECT * against every table and samples two records.
  5. Up to 200 characters from each sampled row are written to standard output.
  6. The ...[truncated 673 chars]
Remediation
View remediation

Remediation Suggestions

  • Remove all SELECT * sample queries from the schema-checking utility.
  • Restrict normal output to table names, column names, declared types, indexes, and constraints.
  • If sample inspection is indispensable, require an explicit command-line option that clearly warns about sensitive output.
  • Apply field-aware redaction and omit document bodies, paths, secrets, tokens, and personally identifiable information.
  • Disable sample output in CI, production, and agent-driven execution contexts.
  • Send diagnostic output only to a protected destination with appropriate access controls and retention policies.
  • Add tests ensuring the default mode never prints database row values.

T09 · Insecure Skill Coding Practices

Warning
Location
scripts/qmd_debug.py:13
Finding

QMD Debug Script Prints Full-Text Index Records and Document Metadata

Content
View full analysis

Vulnerability Details

File Location: scripts/qmd_debug.py:13-18, 21-35
Vulnerability Type: Sensitive information exposure through debug output
Risk Level: Medium

Vulnerable Code

python
# Try a simple FTS query
print("\nTrying FTS query:")
try:
    cursor.execute("SELECT * FROM documents_fts LIMIT 2")
    rows = cursor.fetchall()
    print(f"FTS rows: {len(rows)}")
    for r in rows:
        print(f"  {dict(r)}")
except Exception as e:
    print(f"FTS error: {e}")

# Try LIKE query
print("\nTrying LIKE query:")
cursor.execute("""
    SELECT d.path, d.title, c.doc
    FROM documents d
    LEFT JOIN content c ON d.hash = c.hash
    WHERE d.title LIKE '%python%' OR c.doc LIKE '%python%'
    LIMIT 3
""")
rows = cursor.fetchall()
print(f"LIKE rows: {len(rows)}")
for r in rows:
    print(f"  path: {r['path']}, title: {r['title']}")

Technical Analysis

The debug utility retrieves complete rows from the documents_fts table and converts each row to a dictionary before printing it. Depending on the FTS schema, these rows may contain indexed text or document metadata without any truncation or redaction.

The subsequent query also retrieves document bodies through c.doc, although the current print statement exposes only the corresponding paths and titles. Those paths and titles can themselves reveal usernames, project structures, document subjects, or confidential resource names.

Debugging output is commonly collected by terminals, automated test infrastructure, support bundles, or centralized log systems. Consequently, the script can move locally indexed information into a less protected logging context.

Attack Path

  1. Sensitive documents have been indexed in the configured QMD database.
  2. A user or automated process runs qmd_debug.py for troubleshooting.
  3. The script retrieves two complete records from documents_fts.
  4. Each record is printed as a ...[truncated 704 chars]
Remediation
View remediation

Remediation Suggestions

  • Do not print complete FTS rows or convert them to printable dictionaries.
  • Replace record output with non-sensitive diagnostics such as row counts, column names, and query execution status.
  • Avoid retrieving c.doc when only path and title diagnostics are needed.
  • Redact or hash file paths and titles if they must appear in diagnostic output.
  • Require an explicit opt-in flag for any data-bearing debug mode and display a sensitive-data warning.
  • Ensure production and CI workflows cannot invoke verbose data inspection accidentally.
  • Protect, minimize, and expire any logs generated during authorized troubleshooting.
Vulnerability Patterns
  • Data ExfiltrationExternal Transmission, Env Variable Harvesting, File System Enumeration
  • Privilege EscalationExcessive Permissions, Sudo/Root Execution, Credential Access
  • MCP Tool PoisoningHidden Instructions, Unicode Deception, Parameter Description Injection
  • Prompt InjectionInstruction Override, Hidden Instructions, Exfiltration Commands
  • Supply ChainUnpinned Dependencies, External Script Fetching, Obfuscated Code
Findings (7)

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 · scripts/__init__.py (reported line 14)May include surrounding context.

python
from dataclasses import dataclass
from datetime import datetime

# 设置 M-Flow 环境变量(从 .env 加载)
def _setup_mflow_env():
    mflow_dir = Path(__file__).parent.parent.parent / "m_flow"
    env_path = mflow_dir / ".env"

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 · scripts/__init__.py (reported line 17)May include surrounding context.

python
# 设置 M-Flow 环境变量(从 .env 加载)
def _setup_mflow_env():
    mflow_dir = Path(__file__).parent.parent.parent / "m_flow"
    env_path = mflow_dir / ".env"
    if env_path.exists():
        try:
            from dotenv import load_dotenv

Natural-Language Policy Violations

Medium
Category
Not specified by scanner
Confidence
96% confidence
Finding

This markdown file presents the skill's descriptive and operational content only in Chinese, and there is no indication that users may select another language or that the Chinese-only requirement is intentional and justified. Under the policy, forcing a specific language without user opt-in is a natural-language policy violation.

Content

No source excerpt is available for this finding.

Missing User Warnings

Medium
Category
Not specified by scanner
Confidence
85% confidence
Finding

The code creates a directory and writes a markdown report to a fixed path under the repository, which is a file write operation affecting the user's workspace. While there is a post-action info print, there is no prior warning, confirmation, or explanatory comment/docstring disclosing that running the test will persist output to disk.

Content

No source excerpt is available for this finding.

Missing User Warnings

Medium
Category
Not specified by scanner
Confidence
95% confidence
Finding

The script enumerates tables from a user cache database and prints full sample rows directly to stdout, which can expose sensitive cached content, identifiers, paths, or metadata in logs, terminals, and CI outputs. Because the database path targets an Administrator profile cache, the context increases the chance that privileged or sensitive local data is disclosed unintentionally.

Content

No source excerpt is available for this finding.

Natural-Language Policy Violations

Low
Category
Not specified by scanner
Confidence
91% confidence
Finding

The module-level documentation and many user-visible strings/comments present the skill behavior and interface in Chinese, with no indication that the user can choose another language or locale. This can violate language/locale policy when a skill implicitly forces a specific language without opt-in or justification.

Content

No source excerpt is available for this finding.

Intent-Code Divergence

Low
Category
Not specified by scanner
Confidence
96% confidence
Finding

Lines L246-L258 describe the "mflow_first" strategy as giving M-Flow priority while alternately inserting QMD results, but the implementation is effectively identical to the later "interleave" branch and does not provide distinct priority behavior beyond starting with M-Flow. This is an intent/documentation mismatch within the code comments rather than a mere omission.

Content

No source excerpt is available for this finding.