Back to skill

Security audit

flutter-hive-database

Security checks for vulnerabilities and agentic risk

Overview

This Flutter Hive code generator appears purpose-built rather than malicious, but it needs review because crafted model JSON can make it write or inject unsafe source code beyond the intended scope.

Review before installing or running this skill. Use only model JSON you wrote or fully trust, avoid copied entity definitions from untrusted sources, and inspect generated Dart files before building the app. The publisher should add strict schema validation and path containment checks before this is treated as routine code generation.

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

T05 · Unauthorized Access and Privilege Escalation

Error
Location
scripts/generate.py:410
Finding
Entity Name Path Traversal Allows Writes Outside the Flutter Project<![CDATA[ ## Vulnerability Details **File Location**: `scripts/generate.py:410-419` **Vulnerability Type**: Path traversal and unauthorized filesystem write **Risk Level**: High ### Vulnerable Code ```python def cmd_model(project: str, feature: str, entity: dict): root = _validate_project_root(project) feat = _validate_feature(feature) pkg = _get_package_name(root) name = entity["name"] snake = _snake(name) db_dir = root / "lib" / feat / "database" models_dir = db_dir / "models" repo_file = db_dir / f"{snake}_repository.dart" print(f"\n📦 项目: {pkg} 功能模块: {feature} 实体: {name}\n") # 创建 Model 文件 _write(models_dir / f"{snake}_model.dart", gen_model(entity)) ``` The relevant input validation only verifies that the JSON object contains `name` and `fields`: ```python entity = json.loads(args.entity) if not isinstance(entity, dict) or "name" not in entity or "fields" not in entity: print("[错误] --entity JSON 结构非法,需包含 name 和 fields 字段") sys.exit(1) cmd_model(args.project, args.feature, entity) ``` The transformation applied to the name does not remove path components: ```python def _snake(name): return re.sub(r"(?<!^)(?=[A-Z])", "_", name).lower() ``` ### Technical Analysis Repository mode protects its `--name` argument with `_validate_name()`, but model mode directly takes `entity["name"]` from attacker-controlled JSON and uses it in output paths. No equivalent call to `_validate_name()` occurs. The `_snake()` function only inserts underscores before uppercase letters and converts the value to lowercase. It does not reject `/`, `\`, `..`, absolute path syntax, or control characters. Consequently, the following path construction can retain traversal components: ```python models_dir / f"{snake}_model.dart" ``` `_write()` then creates missing parent directories and writes the generated content: ```python def _write(path: Path, content: str, overwrite=False): path.parent.mkdir(parents=True, exist ...[truncated 2032 chars]
Remediation
<![CDATA[ ## Remediation Suggestions 1. Validate model entity names before using them in source code or paths: ```python name = _validate_name(entity["name"]) ``` 2. Enforce the same strict identifier policy consistently across repository and model modes. Entity names should be valid PascalCase Dart identifiers and must not contain dots, separators, whitespace, quotes, or control characters. 3. Resolve each destination and verify that it remains under the approved directory before creating directories or writing: ```python def _safe_child(base: Path, relative: str) -> Path: base = base.resolve() destination = (base / relative).resolve() try: destination.relative_to(base) except ValueError: raise ValueError(f"Output path escapes destination directory: {destination}") return destination ``` 4. Apply containment checks to both `model_file` and `repo_file`, rather than relying solely on input validation. 5. Avoid calling `mkdir()` until after containment validation succeeds. 6. Add regression tests covering `../`, nested traversal, absolute paths, backslashes, mixed separators, encoded or Unicode separator variants, and valid PascalCase names. ]]>

T09 · Insecure Skill Coding Practices

Error
Location
scripts/generate.py:262
Finding
Unvalidated Entity Schema Enables Generated Dart Source Injection<![CDATA[ ## Vulnerability Details **File Location**: `scripts/generate.py:262-315` and `scripts/generate.py:463-469` **Vulnerability Type**: Code-generation injection **Risk Level**: High ### Vulnerable Code The entity and field values are inserted directly into generated Dart source: ```python def gen_model(entity: dict) -> str: name = entity["name"] fields = entity["fields"] fields_code = "".join( f" final {f['type']}{nullable_suffix(f)} {f['name']};\n" for f in fields ) ctor_params = "\n".join( f" {'this' if f.get('nullable', True) else 'required this'}.{f['name']}," for f in fields ) to_json_lines = ",\n".join( f" '{f['name']}': {to_json_expr(f)}" for f in fields ) from_json_lines = ",\n".join( f" {f['name']}: {from_json_expr(f)}" for f in fields ) copy_with_params = ", ".join( f"{f['type']}{'?' if f.get('nullable', True) else '?'} {f['name']}" for f in fields ) copy_with_body = ",\n ".join( f"{f['name']}: {f['name']} ?? this.{f['name']}" for f in fields ) to_str = ", ".join(f"{f['name']}: ${{{f['name']}}}" for f in fields) eq_body = " && ".join(f"other.{f['name']} == {f['name']}" for f in fields) hash_body = (f"Object.hash({', '.join(f['name'] for f in fields)})" if len(fields) > 1 else f"{fields[0]['name']}.hashCode") return f"""\ /// {name} 数据模型 /// 存储策略:toJson() → Hive Box<Map> → fromJson(),无需 TypeAdapter class {name}Model {{ {fields_code} const {name}Model({{ {ctor_params} }}); Map<String, dynamic> toJson() => {{ {to_json_lines} }}; factory {name}Model.fromJson(Map<dynamic, dynamic> json) => {name}Model( {from_json_lines} ); {name}Model copyWith({{{copy_with_params}}}) => {name}Model( {copy_with_body}, ); @override String toString() => '{name}({to_str})'; @overri ...[truncated 4006 chars]
Remediation
<![CDATA[ ## Remediation Suggestions 1. Introduce strict entity-schema validation before calling any generation function. 2. Validate entity and field names as Dart identifiers. Apply an allowlist such as: ```python DART_IDENTIFIER = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$") ``` Also reject Dart reserved words and require the entity name to satisfy the intended PascalCase convention. 3. Enforce the documented type allowlist: ```python ALLOWED_TYPES = { "int", "double", "String", "bool", "DateTime", "List", "Map", } ``` Do not accept arbitrary type expressions from JSON. 4. Require `fields` to be a non-empty list of dictionaries. For each field, require: - Exactly the approved keys. - A valid identifier in `name`. - A string from `ALLOWED_TYPES` in `type`. - A Boolean value in `nullable`. - No duplicate field names. 5. Reject unknown properties and invalid value types with controlled error messages rather than allowing uncaught exceptions. 6. Treat generated source as structured output. Build declarations exclusively from validated tokens and escape values placed inside Dart string literals. Do not reuse an identifier as a string literal without dedicated escaping. 7. Validate the complete generated source with `dart format` or static analysis before accepting it. This should be defense in depth and must not replace input validation. 8. Generate into a staging directory first, validate all output, and only then move files into the application source tree. 9. Add negative tests for quotes, braces, semicolons, comments, newlines, interpolation markers, reserved words, arbitrary type expressions, empty fields, duplicate fields, malformed field objects, and non-Boolean `nullable` values. ]]>
Vulnerability Patterns
  • MCP Least PrivilegeUnderdeclared Capability, Wildcard Permission, Missing Permission Declaration
  • Prompt InjectionInstruction Override, Hidden Instructions, Exfiltration Commands
  • Data ExfiltrationExternal Transmission, Env Variable Harvesting, File System Enumeration
  • Privilege EscalationExcessive Permissions, Sudo/Root Execution, Credential Access
  • Supply ChainUnpinned Dependencies, External Script Fetching, Obfuscated Code
Findings (2)

Lp3

Medium
Category
MCP Least Privilege
Confidence
90% confidence
Finding
The skill instructs the agent to run a local code-generation script and create or modify project files, but it does not declare any explicit tool scope such as allowed-tools or permissions. This mismatch weakens policy enforcement and can cause the skill to receive broader file read/write capabilities than users or reviewers expect, increasing the risk of unintended filesystem access or silent code modification.

Natural-Language Policy Violations

Medium
Confidence
95% confidence
Finding
The manifest description is written entirely in Chinese and gives no indication that the skill supports other languages or that Chinese is a required locale. Under the policy, forcing a specific language without user opt-in is a natural-language policy violation unless the locale restriction is explicit and justified.

Static analysis

No suspicious patterns detected.