Back to skill

Security audit

智能旅游记录

Security checks for vulnerabilities and agentic risk

Overview

This travel-journal skill is mostly on-purpose, but it needs review because its scripts can copy or overwrite overly broad local file paths and can produce unsafe HTML exports.

Install only if you are comfortable with a local travel journal tool that can read uploaded file paths, write exports, and persist private location/media metadata. Keep it in a constrained workspace, avoid passing arbitrary local paths, review exports before sharing, and require confirmation before delete or trip-ending actions.

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 (3)

T09 · Insecure Skill Coding Practices

Error
Location
scripts/export_generator.py:73
Finding

Stored HTML and Script Injection in Exported Travelogues

Content
View full analysis

Vulnerability Details

File Location: scripts/export_generator.py:73-100, scripts/export_generator.py:150-169, and assets/templates/travelogue.html:268-271
Vulnerability Type: Stored HTML injection / stored cross-site scripting
Risk Level: High

Vulnerable Code

scripts/export_generator.py:73-100:

python
def generate_markdown(trip: Dict, moments: List[Dict]) -> str:
    """生成 Markdown 格式的游记"""
    # 游记标题
    title = trip.get('title', '我的旅行')
    
    md_lines = [f"# 【{title}】", ""]
    
    # 旅行开始信息
    start_time = format_date(trip['startTime'])
    start_loc = trip.get('startLocation', '')
    
    # 按日期分组
    date_groups = group_moments_by_date(moments)
    dates = sorted(date_groups.keys())
    
    # 为每一天生成内容
    for i, date in enumerate(dates, 1):
        day_moments = date_groups[date]
        
        # 提取这一天的主要地点
        locations = [m.get('location') for m in day_moments if m.get('location')]
        main_location = locations[0] if locations else "未知地点"
        
        md_lines.append(f"## Day {i} · {main_location}")
        md_lines.append(f"> {date}")
        md_lines.append("")
        
        # 按时间顺序记录每个素材
        for m in day_moments:
            time_str = format_date(m['timestamp'])
            
            if m['type'] == 'text':
                md_lines.append(m['content'])
                md_lines.append("")
            
            elif m['type'] == 'image':
                md_lines.append(f"![{m.get('content', '旅行照片')}]({m.get('rawUrl', '')})")

scripts/export_generator.py:150-169:

python
def generate_html_from_markdown(md_content: str, trip: Dict) -> str:
    """从 Markdown 生成 HTML"""
    # 使用 markdown 库转换
    html_content = markdown.markdown(
        md_content,
        extensions=['extra', 'codehilite', 'tables']
    )
    
    # 使用模板
    template_path = os.path.join(TEMPLATES_DIR, 'trav
...[truncated 3122 chars]
Remediation
View remediation

Remediation Suggestions

  1. Sanitize converted HTML with a strict allowlist before passing it to the template. Permit only required formatting elements and safe attributes.

  2. Remove executable elements and attributes, including script-capable tags, inline event handlers, dangerous URL schemes, embedded frames, and active SVG content.

  3. Enable Jinja autoescaping:

    python
    from jinja2 import Environment, FileSystemLoader, select_autoescape
    
    env = Environment(
        loader=FileSystemLoader(TEMPLATES_DIR),
        autoescape=select_autoescape(['html', 'xml'])
    )
    
  4. Use |safe only after the HTML has passed through a trusted sanitizer. Do not treat arbitrary Markdown conversion output as inherently safe.

  5. Escape or normalize user-controlled title, location, description, and caption values before composing Markdown.

  6. Validate image and media destinations against an approved local upload directory and reject unexpected URL schemes.

  7. Add regression tests covering raw HTML, event-handler attributes, malformed Markdown links, active SVG, and script-capable URL schemes.

  8. Where possible, apply a restrictive Content Security Policy to hosted exports, disabling inline scripts and limiting resource origins.

T09 · Insecure Skill Coding Practices

Warning
Location
scripts/moment_manager.py:113
Finding

Unrestricted Local File Copy Through the Raw Upload Path

Content
View full analysis

Vulnerability Details

File Location: scripts/moment_manager.py:113-119 and scripts/moment_manager.py:290
Vulnerability Type: Arbitrary readable-file copy / path validation failure
Risk Level: Medium

Vulnerable Code

scripts/moment_manager.py:113-119:

python
# 处理文件上传
stored_path = None
if raw_path and os.path.exists(raw_path):
    # 生成存储文件名
    ext = os.path.splitext(raw_path)[1]
    stored_filename = f"{moment_id}{ext}"
    stored_path = os.path.join(UPLOADS_DIR, stored_filename)
    shutil.copy2(raw_path, stored_path)

scripts/moment_manager.py:290:

python
parser.add_argument('--raw-path', help='原始文件路径')

Technical Analysis

The --raw-path argument is accepted as an unrestricted filesystem path. The implementation verifies only that the path exists and then copies it into the uploads directory.

It does not verify that the source is inside the documented temporary upload directory, that it is a regular file, that it is not a symbolic link, or that its actual content matches an approved media format. There are also no enforced file-size limits.

Consequently, any local file readable by the account running the Skill can be copied into travelogue_data/uploads. The generated destination extension is inherited from the source path without validating the file signature. This can expose sensitive files through later export, backup, synchronization, or file-delivery workflows.

Attack Path

  1. An attacker supplies or causes the agent to supply an absolute path or traversal path as --raw-path.
  2. The selected path points to a sensitive file readable by the Skill process.
  3. os.path.exists() succeeds because no approved-root policy is enforced.
  4. shutil.copy2() copies the file into travelogue_data/uploads under a UUID-based name.
  5. The stored path is recorded in moments.json.
  6. The copied file may subsequently be exposed through travelogue expo ...[truncated 727 chars]
Remediation
View remediation

Remediation Suggestions

  1. Restrict source files to a dedicated staging directory controlled by the application.

  2. Resolve both the source and approved root to canonical paths and verify containment before copying:

    python
    from pathlib import Path
    
    staging_root = Path("./travelogue_data/uploads/staging").resolve()
    source = Path(raw_path).resolve(strict=True)
    
    if not source.is_relative_to(staging_root):
        raise ValueError("Source path is outside the approved upload directory")
    
  3. Reject symbolic links and require source.is_file() for a regular file.

  4. Validate media by file signature or trusted decoding rather than filename extension alone.

  5. Enforce the documented file types and server-side size limits.

  6. Generate the destination extension from the verified media type rather than the untrusted source name.

  7. Open and copy files using race-resistant techniques where the platform supports them, reducing time-of-check/time-of-use and symlink-swap risks.

  8. Ensure upload storage is not automatically published or synchronized without an explicit authorization decision.

T09 · Insecure Skill Coding Practices

Warning
Location
scripts/export_generator.py:245
Finding

Arbitrary File Overwrite Through the Export Output Path

Content
View full analysis

Vulnerability Details

File Location: scripts/export_generator.py:245-269, scripts/export_generator.py:359-389
Vulnerability Type: Arbitrary writable-file overwrite / unrestricted output path
Risk Level: Medium

Vulnerable Code

scripts/export_generator.py:245-269:

python
if output_format == 'markdown':
    # 直接保存 Markdown
    os.makedirs(os.path.dirname(output_path) if os.path.dirname(output_path) else '.', exist_ok=True)
    with open(output_path, 'w', encoding='utf-8') as f:
        f.write(md_content)
    
    return {
        "success": True,
        "file_path": os.path.abspath(output_path),
        "message": f"已生成 Markdown 文件:{output_path}"
    }

elif output_format == 'html':
    # 生成 HTML
    html_content = generate_html_from_markdown(md_content, trip)
    os.makedirs(os.path.dirname(output_path) if os.path.dirname(output_path) else '.', exist_ok=True)
    with open(output_path, 'w', encoding='utf-8') as f:
        f.write(html_content)
    
    return {
        "success": True,
        "file_path": os.path.abspath(output_path),
        "message": f"已生成 HTML 文件:{output_path}"
    }

scripts/export_generator.py:359-389:

python
parser = argparse.ArgumentParser(description='游记导出工具')
parser.add_argument('--action', required=True, 
                   choices=['export', 'preview'],
                   help='操作类型')
parser.add_argument('--trip-id', required=True, help='旅行ID')
parser.add_argument('--format', choices=['markdown', 'html', 'pdf'],
                   default='markdown', help='导出格式')
parser.add_argument('--output', default='./travelogue', help='输出文件路径')

args = parser.parse_args()

result = None

if args.action == 'export':
    # 确定文件扩展名
    ext_map = {
        'markdown': '.md',
        'html': '.html',
        'pdf': '.pdf'
    }
    output_path = args.output
    if not output_path.endswith(ext_map.get(
...[truncated 2259 chars]
Remediation
View remediation

Remediation Suggestions

  1. Restrict all exports to a dedicated output directory.
  2. Resolve the requested path and approved export root canonically, then verify that the destination remains beneath the approved root.
  3. Treat absolute paths and traversal outside the root as invalid.
  4. Reject symbolic-link destinations and check parent-directory components for symlinks.
  5. Avoid silently overwriting existing files. Use exclusive creation mode or require an explicit, authorized overwrite option.
  6. Generate safe filenames server-side from a constrained identifier rather than accepting arbitrary filesystem paths.
  7. Apply the same path policy to Markdown, HTML, PDF, and PDF fallback output.
  8. Run the exporter under a minimally privileged account with access only to travelogue data and the designated export directory.
  9. Add tests for absolute paths, parent traversal, nested symlinks, pre-existing files, and destinations outside the export root.
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
  • Trigger AbuseOverly Broad Trigger, Shadow Command Trigger, Keyword Baiting Trigger
  • MCP Least PrivilegeUnderdeclared Capability, Wildcard Permission, Missing Permission Declaration
Findings (22)

Tp4

High
Category
MCP Tool Poisoning
Confidence
94% confidence
Finding

声明描述的是一个较完整的旅行游记生成器,而本代码块只是其中的素材管理子模块。它支持添加文字/图片/音频/视频素材、复制上传文件到本地 uploads 目录、按 tripId/type/location 查询、统计、删除、更新,以及按日期分组;并依赖 trips.json 判断当前旅行是否进行中。但代码没有生成游记、没有文学叙事生成、没有预览完整游记、没有导出文件,也没有创建或结束旅行记录的逻辑。因此其主要行为与声明的核心能力不一致。虽然“记录旅行/补充素材”部分与声明部分吻合,但若整体技能描述用于表示此代码块全部能力,则属于明显描述-行为不匹配。

Content

No source excerpt is available for this finding.

Tp4

High
Category
MCP Tool Poisoning
Confidence
95% confidence
Finding

描述将该技能定位为“游记生成器”,核心能力应是素材记录、内容组织、叙事生成和导出。该代码块仅覆盖旅行条目的生命周期管理和简单元数据维护,没有任何生成游记文本、整理时间线、处理多媒体素材、预览内容或导出文件的逻辑。虽然“开始旅行”“结束旅行”两个触发与 create/end 行为部分一致,但“记录旅行”“生成游记”“导出游记”等关键触发对应能力在代码中缺失。另有删除旅行记录这一实际能力未在声明中体现。整体上,声明的主要用途与代码实际行为存在实质性不一致。

Content

No source excerpt is available for this finding.

Undeclared Tool Scope

Medium
Category
MCP Least Privilege
Confidence
95% confidence
Finding

The skill explicitly instructs the agent to read and write local files (for uploads, storage, and exports) but does not declare any tool scope such as permissions or allowed-tools. This creates a least-privilege gap: an orchestrator may grant broader file capabilities than intended, and users cannot clearly audit what filesystem access the skill requires.

Content

No source excerpt is available for this finding.

Vague Triggers

Medium
Category
Not specified by scanner
Confidence
95% confidence
Finding

The trigger keywords are broad enough to match ordinary conversation, which can cause unintended activation of a skill that writes files and changes trip state. In this context, accidental invocation is more dangerous because the skill persists local data, may attach user content to the wrong trip, and may perform stateful actions without the user intending to use the skill.

Content

No source excerpt is available for this finding.

Vague Triggers

Medium
Category
Not specified by scanner
Confidence
94% confidence
Finding

Using ambiguous end-of-trip examples like '回家了' or '旅行结束了' risks closing the active trip based on commonplace statements. Because the skill enforces lifecycle rules that stop further recording after ending a trip, a false activation can cause denial of expected functionality, misclassification of later materials, and integrity loss in the user's travel record.

Content

No source excerpt is available for this finding.

Context-Inappropriate Capability

Medium
Category
Not specified by scanner
Confidence
97% confidence
Finding

The template renders content with |safe, which disables escaping and treats potentially user- or model-generated travelogue text as trusted HTML. In this skill, travel records and generated narrative may include untrusted material, so an attacker could inject arbitrary HTML or JavaScript into exported or previewed pages, leading to XSS, credential theft, session abuse, or malicious file content.

Content

No source excerpt is available for this finding.

Missing User Warnings

Medium
Category
Not specified by scanner
Confidence
93% confidence
Finding

The document specifies a destructive '删除旅行' operation that removes the trip record, cascades deletion of associated moments, and deletes uploaded files, but it provides no requirement for explicit user confirmation, undo capability, or safeguards against accidental invocation. In a skill that can be auto-triggered from natural-language travel actions, this increases the risk of unintended irreversible data loss from ambiguity, prompt confusion, or agent misclassification.

Content

No source excerpt is available for this finding.

Missing User Warnings

Medium
Category
Not specified by scanner
Confidence
90% confidence
Finding

The export spec encourages embedding EXIF-derived place/time details and identifying metadata such as author and trip identifiers without any privacy warning or minimization guidance. In a travel-journal context, exported files are likely to be shared, so this can unintentionally disclose sensitive location history, identity, or correlatable trip metadata.

Content

No source excerpt is available for this finding.

Context-Inappropriate Capability

Medium
Category
Not specified by scanner
Confidence
90% confidence
Finding

The template example explicitly renders {{ content|safe }}, which disables HTML escaping for generated body content. In a travelogue skill, that content can plausibly incorporate user-supplied notes, captions, transcriptions, or imported media descriptions, so unsafe rendering can produce stored/exported XSS in HTML outputs or unsafe active content in downstream viewers.

Content

No source excerpt is available for this finding.

Missing User Warnings

Medium
Category
Not specified by scanner
Confidence
89% confidence
Finding

Allowing custom Jinja2 templates together with raw HTML insertion expands the trust boundary and creates a path for unsafe rendering or template misuse. In this skill, users can export HTML/PDF artifacts that may later be opened in browsers or processed by template/rendering tools, increasing the chance of script injection, content tampering, or unsafe local resource inclusion.

Content

No source excerpt is available for this finding.

Natural-Language Policy Violations

Medium
Category
Not specified by scanner
Confidence
89% confidence
Finding

This markdown file is written as a style guide that assumes Chinese output, and L013 explicitly marks the default style within that Chinese-language framework. Under the policy rule for natural-language violations, forcing a specific language without user opt-in is a reportable issue unless the skill offers a language choice or clearly justifies the locale constraint.

Content

No source excerpt is available for this finding.

Natural-Language Policy Violations

Medium
Category
Not specified by scanner
Confidence
93% confidence
Finding

This file consistently presents its interface and generated content in Chinese, including the top-level description and later output formatting, but does not provide any opt-in or language selection mechanism. Under the language/locale policy, forcing a specific language without user choice is a natural-language policy violation unless clearly justified as region-specific.

Content

No source excerpt is available for this finding.

Natural-Language Policy Violations

Medium
Category
Not specified by scanner
Confidence
93% confidence
Finding

The module docstring and user-facing descriptions are written only in Chinese, which imposes a specific language on users without any opt-in or documented locale constraint. Under the policy, language restrictions are only acceptable when the skill offers choice or clearly justifies a region-specific limitation.

Content

No source excerpt is available for this finding.

Description-Behavior Mismatch

Medium
Category
Not specified by scanner
Confidence
93% confidence
Finding

The script exposes destructive delete functionality for trips and also removes related material records from moments.json, while the skill description and triggers emphasize recording/generating/exporting travelogues rather than deletion. This mismatch increases the risk of unintended or unauthorized destructive actions because users or orchestrators may invoke behavior that is not clearly disclosed in the skill’s apparent scope.

Content

No source excerpt is available for this finding.

Missing User Warnings

Medium
Category
Not specified by scanner
Confidence
94% confidence
Finding

Deletion is performed immediately with no confirmation step, soft-delete, or explicit warning that related records will also be removed. In an agent-driven context, this creates a real risk of accidental or prompt-induced data loss, especially because destructive actions can be triggered programmatically and are irreversible in the current design.

Content

No source excerpt is available for this finding.

Description-Behavior Mismatch

Low
Category
Not specified by scanner
Confidence
77% confidence
Finding

The manifest describes this skill as a travelogue recorder/generator/exporter with lifecycle management, but the resource index says moment_manager.py is used for adding/querying/deleting materials. Deleting stored travel moments is not mentioned in the manifest description or trigger set, so the documented capability exceeds the stated behavior.

Content

No source excerpt is available for this finding.

Natural-Language Policy Violations

Low
Category
Not specified by scanner
Confidence
93% confidence
Finding

The HTML root sets lang="zh-CN", which imposes a specific language/locale in the rendered output. Under the policy criteria, forcing a locale without offering user choice or documenting a region-specific reason is a natural-language policy violation.

Content

No source excerpt is available for this finding.

Natural-Language Policy Violations

Low
Category
Not specified by scanner
Confidence
72% confidence
Finding

The entire skill documentation defines data fields, examples, style defaults, errors, and generated content conventions exclusively in Chinese, including a default style preference of '文艺'. There is no indication that language is user-selectable or that the Chinese-only behavior is a justified region-specific requirement.

Content

No source excerpt is available for this finding.

Natural-Language Policy Violations

Low
Category
Not specified by scanner
Confidence
91% confidence
Finding

The HTML examples specify lang="zh-CN", and the same locale appears again in the template example, which implies a fixed language/locale choice. Under the policy, forcing a specific locale without opt-in can be a natural-language policy violation unless clearly documented as region-specific or user-selectable.

Content

No source excerpt is available for this finding.

Natural-Language Policy Violations

Low
Category
Not specified by scanner
Confidence
91% confidence
Finding

The reusable HTML template sets lang="zh-CN", which bakes a specific locale into generated output. The file does not state that users can choose another locale or that the skill is explicitly restricted to Chinese-language exports.

Content

No source excerpt is available for this finding.

Intent-Code Divergence

Low
Category
Not specified by scanner
Confidence
84% confidence
Finding

The top-level documentation frames the script as operating on travel records only, yet delete_trip also removes associated entries from a separate moments.json store. That is broader behavior than the documentation states, affecting additional persisted user content.

Content

No source excerpt is available for this finding.

Natural-Language Policy Violations

Low
Category
Not specified by scanner
Confidence
91% confidence
Finding

User-facing descriptions, help text, and returned messages are written entirely in Chinese, which forces a specific language experience without any opt-in or alternative. The file does not document that the tool is intentionally region- or language-specific, so this is a natural-language policy concern.

Content

No source excerpt is available for this finding.