Back to skill

Security audit

PDCA+ISO9001质量管理

Security checks for vulnerabilities and agentic risk

Overview

This quality-management skill is mostly coherent, but it includes unsafe local rule evaluation and broad file-writing paths that need review before installation.

Review this skill carefully before installing. Use it only in a contained workspace, avoid importing untrusted project data, do not let untrusted users control rule conditions, project IDs, or report filenames, and treat generated reports and the knowledge base as potentially sensitive business records.

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

T09 · Insecure Skill Coding Practices

Error
Location
scripts/knowledge_manager.py:226
Finding

Arbitrary Python Code Execution Through Persistent Rule Evaluation

Content
View full analysis
str: """ 添加规则到规则库 Args: rule_data: 规则数据,包含name、condition、action、priority、description等字段 Returns: 规则ID """ rule_id = f"rule_{rule_data.get('priority', 'medium')}_{rule_data.get('name', '').replace(' ', '_')}_{datetime.now().strftime('%Y%m%d')}" rule_data['id'] = rule_id rule_data['created_at'] = datetime.now().isoformat() rule_data['enabled'] = True rule_data['trigger_count'] = 0 file_path = os.path.join(self.rule_lib_dir, f"{rule_id}.json") save_json_file(rule_data, file_path) logger.info(f"新规则已添加到规则库: {rule_id} - {rule_data.get('name', '')}") return rule_id ``` ```python def evaluate_rules(self, context: Dict[str, Any]) -> List[Dict[str, Any]]: matched_rules = [] enabled_rules = self.get_enabled_rules() for rule in enabled_rules: try: condition = rule.get('condition', '') if not condition: continue for key, value in context.items(): condition = condition.replace(f"${key}", str(value)) if eval(condition, {"__builtins__": {}}, {}): rule['trigger_count'] += 1 matched_rules.append(rule) file_path = os.path.join( self.rule_lib_dir, f"{rule['id']}.json" ) save_json_file(rule, file_path) except Exception as e: logger.error(f"规则评估失败 {rule['id']}: {e}") continue return matched_rules ``` The automatic knowledge-extraction path can also persist project-supplied conditions as enabled rules: ```python improvement_measures = act_data.get('improvement_measures', []) for measure in improvement_me ...[truncated 2832 chars]
Remediation
View remediation
=", "value": 90 } ``` 3. Implement an explicit operator allowlist such as `==`, `!=`, `>`, `>=`, `<`, `<=`, `in`, `and`, and `or`. 4. Validate field names against a schema and restrict values to primitive JSON types. 5. If textual expressions are required, parse them with `ast.parse(..., mode="eval")` and reject every node except a narrowly defined allowlist. Never compile or evaluate attribute access, calls, comprehensions, lambdas, subscripting of arbitrary objects, or dunder names. 6. Quote and type-check context values instead of performing raw string replacement. 7. Require authorization and review before enabling newly learned rules. 8. Store automatically extracted rules in a disabled or quarantined state until validated. 9. Review and delete existing persisted rule files that contain Python syntax or unexpected condition structures. 10. Add negative tests covering object traversal, function calls, attribute access, malformed substitutions, and expressions that attempt filesystem or command access. ]]>

T09 · Insecure Skill Coding Practices

Error
Location
scripts/report_generator.py:523
Finding

Path Traversal in Report Filename Allows Writes Outside the Report Directory

Content
View full analysis
str: """ 保存报告到文件 Args: content: 报告内容 filename: 文件名(不含扩展名) format: 报告格式 Returns: 保存的文件路径 """ extensions = { 'markdown': '.md', 'html': '.html', 'json': '.json' } ext = extensions.get(format.lower(), '.md') file_path = os.path.join(self.report_dir, f"{filename}{ext}") write_text_file(content, file_path) logger.info(f"报告已保存到: {file_path}") return file_path ``` The called helper creates parent directories and overwrites the selected path: ```python def write_text_file(content: str, file_path: str) -> bool: try: ensure_dir(os.path.dirname(file_path)) with open(file_path, 'w', encoding='utf-8') as f: f.write(content) return True except Exception as e: logger.error(f"写入文本文件失败 {file_path}: {e}") return False ``` ### Technical Analysis The `filename` argument is directly combined with `self.report_dir` without validation or canonical containment checking. A filename containing `../` components can escape the intended `reports` directory. On supported platforms, an absolute path may also cause `os.path.join()` to discard the preceding report directory. The helper opens the resulting path in `w` mode, so an existing file is truncated and replaced. It also creates missing parent directories. Although the method appends one of the configured report extensions, an attacker can still create or overwrite matching Markdown, HTML, or JSON files at arbitrary writable locations. ### Attack Path 1. An attacker reaches a workflow or API that passes a controllable filename to `save_report()`. 2. The attacker supplie ...[truncated 1074 chars]
Remediation
View remediation

T05 · Unauthorized Access and Privilege Escalation

Warning
Location
scripts/pdca_engine.py:100
Finding

Unvalidated Object Identifiers Permit JSON Path Traversal and Unauthorized Data Modification

Content
View full analysis
Optional[Project]: project_path = os.path.join(self.data_dir, f"{project_id}.json") if not os.path.exists(project_path): logger.error(f"项目不存在: {project_id}") return None data = load_json_file(project_path) if not data: return None data['current_phase'] = PDCAPhase(data['current_phase']) data['status'] = ProjectStatus(data['status']) return Project(**data) ``` ```python def _save_project(self, project: Project) -> bool: project_path = os.path.join(self.data_dir, f"{project.id}.json") data = asdict(project) data['current_phase'] = data['current_phase'].value data['status'] = data['status'].value return save_json_file(data, project_path) ``` Knowledge-manager identifiers are handled in the same way: ```python def toggle_rule(self, rule_id: str, enabled: bool) -> bool: file_path = os.path.join(self.rule_lib_dir, f"{rule_id}.json") if not os.path.exists(file_path): logger.warning(f"规则不存在: {rule_id}") return False rule = load_json_file(file_path) if not rule: return False rule['enabled'] = enabled rule['updated_at'] = datetime.now().isoformat() return save_json_file(rule, file_path) ``` ```python def update_pattern_success_rate(self, pattern_id: str, success: bool) -> bool: file_path = os.path.join(self.pattern_lib_dir, f"{pattern_id}.json") if not os.path.exists(file_path): logger.warning(f"模式不存在: {pattern_id}") return False pattern = load_json_file(file_path) if not pattern: return False total = pattern.get('occurrence_cou ...[truncated 2542 chars]
Remediation
View remediation
Path: if not re.fullmatch(pattern, object_id): raise ValueError("Invalid object identifier") base = Path(base_dir).resolve() target = (base / f"{object_id}.json").resolve() if target.parent != base: raise ValueError("Object path escapes storage directory") return target ``` 4. Apply the helper consistently to project, experience, template, rule, and pattern operations. 5. Do not trust `Project.id` when saving a caller-supplied object. Reload the authoritative object by a validated ID or make identifiers immutable. 6. Add authorization checks if these methods are exposed across users or tenants. 7. Use restrictive filesystem permissions so each store can access only its own directory. 8. Add traversal tests for POSIX paths, Windows paths, mixed separators, absolute paths, and symlinks. ]]>

T09 · Insecure Skill Coding Practices

Warning
Location
scripts/report_generator.py:560
Finding

Unescaped Project and Decision Data Produces Active HTML Reports

Content
View full analysis
{report.decision_content[:500]}{'...' if len(report.decision_content) > 500 else ''} ## 三、摘要 {report.summary} """ ``` The Markdown-to-HTML conversion preserves raw HTML and embeds it directly into the document body: ```python def _markdown_to_html(self, markdown_content: str) -> str: html = markdown_content html = re.sub(r'^# (.*?)$', r'

\1

', html, flags=re.MULTILINE) html = re.sub(r'^## (.*?)$', r'

\1

', html, flags=re.MULTILINE) html = re.sub(r'^### (.*?)$', r'

\1

', html, flags=re.MULTILINE) html = re.sub(r'\*\*(.*?)\*\*', r'\1', html) html = re.sub(r'\*(.*?)\*', r'\1', html) html = re.sub(r'^- (.*?)$', r'
  • \1
  • ', html, fl ...[truncated 2643 chars]
    Remediation
    View remediation
    Vulnerability Patterns
    • Excessive AgencyUnrestricted Tool Access, Autonomous Decision Making, Scope Creep
    • System Prompt LeakageDirect Leakage, Indirect Extraction, Tool-Based Exfiltration
    • Behavioral ASTexec() Call, eval() Call, Dynamic Import
    • MCP Least PrivilegeUnderdeclared Capability, Wildcard Permission, Missing Permission Declaration
    • Prompt InjectionInstruction Override, Hidden Instructions, Exfiltration Commands
    Findings (25)

    Direct Prompt Extraction

    High
    Category
    System Prompt Leakage
    Confidence
    85% confidence
    Finding

    Skill contains instructions that could directly expose system prompts, internal rules, or hidden instructions to users or external parties.

    Content

    Scanner excerpt · scripts/knowledge_manager.py (reported line 245)May include surrounding context.

    python
    file_path = os.path.join(self.rule_lib_dir, f"{rule_id}.json")
            save_json_file(rule_data, file_path)
            logger.info(f"新规则已添加到规则库: {rule_id} - {rule_data.get('name', '')}")
            return rule_id
        def get_enabled_rules(self) -> List[Dict[str, Any]]:
            """
            获取所有启用的规则
    

    Direct Prompt Extraction

    High
    Category
    System Prompt Leakage
    Confidence
    85% confidence
    Finding

    Skill contains instructions that could directly expose system prompts, internal rules, or hidden instructions to users or external parties.

    Content

    Scanner excerpt · scripts/knowledge_manager.py (reported line 263)May include surrounding context.

    python
    # 按优先级排序
            priority_order = {'critical': 0, 'high': 1, 'medium': 2, 'low': 3}
            rules.sort(key=lambda x: priority_order.get(x.get('priority', 'medium'), 99))
            return rules
        def evaluate_rules(self, context: Dict[str, Any]) -> List[Dict[str, Any]]:
            """
            评估规则,返回匹配的规则
    

    Context-Inappropriate Capability

    High
    Category
    Not specified by scanner
    Confidence
    99% confidence
    Finding

    This method implements dynamic rule execution by loading stored conditions and evaluating them as Python expressions. In this skill context, rules can be auto-generated from project data and persisted to disk, so untrusted or manipulated data may later be executed during rule evaluation, creating a dangerous injection path inconsistent with ordinary quality-management logic.

    Content

    No source excerpt is available for this finding.

    eval() call detected

    High
    Category
    Dangerous Code Execution
    Confidence
    98% confidence
    Finding

    The code evaluates rule conditions loaded from the rule library after performing naive string substitution with values from context. Even with builtins removed, using eval on dynamically supplied expressions is unsafe because an attacker who can add or influence rule content can execute unintended Python expressions or abuse object traversal, turning a knowledge-management feature into code-like execution.

    Content

    Scanner excerpt · scripts/knowledge_manager.py (reported line 284)May include surrounding context.

    python
    for key, value in context.items():
                        condition = condition.replace(f"${key}", str(value))
                    # 执行条件判断(简化实现)
                    if eval(condition, {"__builtins__": {}}, {}):
                        rule['trigger_count'] += 1
                        matched_rules.append(rule)
                        # 更新触发次数
    

    Missing User Warnings

    Medium
    Category
    Not specified by scanner
    Confidence
    92% confidence
    Finding

    The README promotes automatic learning and knowledge retention of project experience and lessons learned, but provides no warning that business, personal, or sensitive operational data may be ingested, stored, or reused. In a quality-management skill that operates across the full project lifecycle, this increases the risk of unintended persistence, over-collection, and disclosure of sensitive internal information.

    Content

    No source excerpt is available for this finding.

    Missing User Warnings

    Medium
    Category
    Not specified by scanner
    Confidence
    90% confidence
    Finding

    The README shows how to generate and save reports to disk without warning that those reports may contain sensitive project, compliance, or decision-making content. This can lead users to persist confidential data in insecure locations, increasing the chance of unauthorized access, leakage through backups or file sharing, and noncompliance with internal data-handling requirements.

    Content

    No source excerpt is available for this finding.

    Undeclared Tool Scope

    Medium
    Category
    MCP Least Privilege
    Confidence
    92% confidence
    Finding

    The skill advertises operational commands that read context files and generate reports/knowledge-base artifacts, but it declares no explicit tool scope or permissions boundaries. That creates an authorization gap: a host agent may permit filesystem read/write behavior implicitly, allowing broader file access or persistence than users expect.

    Content

    No source excerpt is available for this finding.

    Natural-Language Policy Violations

    Medium
    Category
    Not specified by scanner
    Confidence
    91% confidence
    Finding

    The description field is written entirely in Chinese ("PDCA+ISO9001质量管理决策系统技能"), which signals a language-specific skill presentation. In this config there is no accompanying opt-in, alternate locale option, or justification that the skill is intended only for a Chinese-speaking or region-specific context.

    Content

    No source excerpt is available for this finding.

    Missing User Warnings

    Medium
    Category
    Not specified by scanner
    Confidence
    93% confidence
    Finding

    The document states that files may be automatically updated, records permanently stored, and project knowledge automatically extracted, but it does not clearly disclose that user data may be modified or persisted. In this skill context, those are state-changing operations on potentially sensitive quality records, so lack of transparency can lead to unintended data retention, integrity issues, and unauthorized propagation of internal information.

    Content

    No source excerpt is available for this finding.

    Missing User Warnings

    Medium
    Category
    Not specified by scanner
    Confidence
    90% confidence
    Finding

    The document encourages direct deployment and direct import of existing quality-system files into a knowledge base without warning that those materials may contain sensitive business, operational, supplier, audit, or compliance data. In a quality-management skill, this omission is meaningful because users may reasonably assume the import path is safe by default and expose confidential records to storage, analysis, or downstream reuse.

    Content

    No source excerpt is available for this finding.

    Natural-Language Policy Violations

    Medium
    Category
    Not specified by scanner
    Confidence
    94% confidence
    Finding

    This Python file is a code file, so SQP-3 applies. The module docstring and all user-facing report strings are written exclusively in Chinese, and the generated report content later in the file also hardcodes Chinese output, indicating a fixed locale rather than offering user choice.

    Content

    No source excerpt is available for this finding.

    Natural-Language Policy Violations

    Medium
    Category
    Not specified by scanner
    Confidence
    92% confidence
    Finding

    This Python file is a code file, so SQP-3 applies. The module docstring and all user-facing report content are hard-coded in Chinese, including summaries and generated markdown, which indicates a fixed language/locale behavior without any opt-in or alternative language path.

    Content

    No source excerpt is available for this finding.

    Missing User Warnings

    Medium
    Category
    Not specified by scanner
    Confidence
    87% confidence
    Finding

    This code performs irreversible file deletion via os.remove during cleanup of old data. Although the function has an internal docstring and logging, there is no user-facing confirmation or disclosure that invoking cleanup will permanently remove files from the knowledge base.

    Content

    No source excerpt is available for this finding.

    Missing User Warnings

    Medium
    Category
    Not specified by scanner
    Confidence
    92% confidence
    Finding

    This code persists newly created project data to disk via _save_project(project), which results in file creation under the skill's data directory. Although there is internal logging after the save, there is no confirmation prompt or explicit docstring/comment warning that user-provided project content will be stored on the local filesystem.

    Content

    No source excerpt is available for this finding.

    Missing User Warnings

    Medium
    Category
    Not specified by scanner
    Confidence
    94% confidence
    Finding

    When auto_archive_on_complete is enabled, the code automatically archives project information, lessons learned, and improvement measures into the knowledge base. This is a secondary persistence action affecting user/project data, but the code around completion does not provide a clear warning or confirmation that archival will occur.

    Content

    No source excerpt is available for this finding.

    Natural-Language Policy Violations

    Medium
    Category
    Not specified by scanner
    Confidence
    92% confidence
    Finding

    This code file contains natural-language documentation entirely in Chinese, and later user-facing messages and notifications are also emitted in Chinese. Under the policy rule, forcing a specific language without user opt-in is a locale/language policy violation unless the constraint is explicitly documented and justified, which is not present here.

    Content

    No source excerpt is available for this finding.

    Natural-Language Policy Violations

    Medium
    Category
    Not specified by scanner
    Confidence
    89% confidence
    Finding

    Several runtime messages such as error logs and notification content are hard-coded in Chinese, and the notification path prints localized text directly to users. Because no alternative locale or user choice is offered, this creates a language policy issue for a general-purpose utility module.

    Content

    No source excerpt is available for this finding.

    Missing User Warnings

    Low
    Category
    Not specified by scanner
    Confidence
    86% confidence
    Finding

    The documentation describes automatic archival to a knowledge base and report generation to files, but provides no warning about persistence, retention, or possible inclusion of sensitive project data. This can lead to inadvertent storage of confidential information and surprise filesystem side effects, especially in enterprise decision-making contexts where reports and lessons learned may contain sensitive material.

    Content

    No source excerpt is available for this finding.

    Natural-Language Policy Violations

    Low
    Category
    Not specified by scanner
    Confidence
    81% confidence
    Finding

    The file presents the skill name and description entirely in Chinese, which indicates a fixed language/locale orientation in natural-language content. There is no accompanying user choice, opt-in, or justification that this skill is specifically intended only for a Chinese-speaking or region-specific context.

    Content

    No source excerpt is available for this finding.

    Natural-Language Policy Violations

    Low
    Category
    Not specified by scanner
    Confidence
    75% confidence
    Finding

    SQP-3适用于所有文件类型。该文档从标题到功能说明均默认以中文进行交互与输出,没有说明语言可配置、可切换,或该限制是否仅适用于特定中文场景。若组织要求不得强制特定语言而未提供用户选择,这可能构成语言/locale策略问题。

    Content

    No source excerpt is available for this finding.

    Natural-Language Policy Violations

    Low
    Category
    Not specified by scanner
    Confidence
    92% confidence
    Finding

    This Python file contains user-/maintainer-facing natural-language comments in Chinese alongside English, such as the description on L02 and export note on L05. Because the file does not state that the skill is Chinese-specific or offer language/locale choice, it may violate the policy against forcing a specific language without user opt-in.

    Content

    No source excerpt is available for this finding.

    Natural-Language Policy Violations

    Low
    Category
    Not specified by scanner
    Confidence
    78% confidence
    Finding

    Module and class documentation, along with user-visible log messages, are exclusively in Chinese. Under the policy, forcing a specific language without offering a user choice or documenting the locale constraint can be 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
    97% confidence
    Finding

    Natural-language strings in the module docstring and throughout the code are written in Chinese, and there is no indication that users can opt into another language or that the skill is intentionally limited to a Chinese-language context. This can violate language/locale policy when a skill implicitly forces a specific language without user choice.

    Content

    No source excerpt is available for this finding.

    Natural-Language Policy Violations

    Low
    Category
    Not specified by scanner
    Confidence
    97% confidence
    Finding

    The generated HTML template sets lang="zh-CN", which forces a specific language/locale in output. The file does not provide any user opt-in, language selection mechanism, or justification that the skill is intended only for a Chinese locale.

    Content

    No source excerpt is available for this finding.

    Dynamic attribute access via getattr()

    Low
    Category
    Dangerous Code Execution
    Confidence
    50% confidence
    Finding

    Dynamic getattr() with a non-literal attribute name can access arbitrary object attributes, potentially bypassing access controls.

    Content

    Scanner excerpt · scripts/utils.py (reported line 242)May include surrounding context.

    python
    if not level_enabled:
            return True
        # 记录日志
        log_method = getattr(logger, level, logger.info)
        log_method(f"通知 [{level}]: {message}")
        # TODO: 实现实际的通知发送(飞书、微信等)
        for channel in channels:
    

    Static analysis

    Detected: suspicious.dynamic_code_execution

    Dynamic code execution detected.

    Critical
    Code
    suspicious.dynamic_code_execution
    Location
    scripts/knowledge_manager.py:284