T09 · Insecure Skill Coding Practices
Warning
- Location
- scripts/config.py:46
- Finding
- API Key Persisted in Plaintext Without File Permission Hardening<![CDATA[ ## Vulnerability Details **File Location**: `scripts/config.py:46-65` **Vulnerability Type**: Plaintext sensitive-data storage **Risk Level**: Medium ### Vulnerable Code ```python def save_api_key_to_env(api_key: str) -> bool: """将API key保存到.env文件""" try: env_path = Path(".env") lines = [] if env_path.exists(): lines = env_path.read_text(encoding="utf-8").splitlines() found = False new_lines = [] for line in lines: if line.startswith("XBY_APIKEY="): new_lines.append(f"XBY_APIKEY={api_key}") found = True else: new_lines.append(line) if not found: new_lines.append(f"XBY_APIKEY={api_key}") env_path.write_text("\n".join(new_lines) + "\n", encoding="utf-8") os.environ["XBY_APIKEY"] = api_key return True except Exception as e: print(f"保存API key失败: {e}") return False ``` ### Technical Analysis The function stores the user-provided API key as plaintext in a `.env` file located in the process's current working directory. The file is created using `Path.write_text()` without explicitly enforcing restrictive filesystem permissions, validating file ownership, checking whether the target is a symbolic link, or confirming that the working directory is private. The resulting permissions depend on the process umask and the state of any pre-existing `.env` file. In a shared or incorrectly configured environment, other local accounts or processes may be able to read the credential. Because the file is placed in the working directory, it may also be included inadvertently in source-control commits, archives, backups, or diagnostic bundles. The code additionally places the key in the process environment. Child processes created afterward may inherit it, increasing the credential's exposure scope. ### Attack Path 1. A user provides an Xiaobenyang API key as requi ...[truncated 1149 chars]
- Remediation
- <![CDATA[ ## Remediation Suggestions 1. Prefer session-only credential handling or an operating-system credential manager instead of plaintext persistence. 2. Obtain explicit user consent before persisting an API key. 3. If file storage is unavoidable, create the file atomically with mode `0600` and verify the final permissions. 4. Validate that `.env` is a regular file owned by the expected user; reject symbolic links and unexpected owners. 5. Resolve storage against a private, explicitly configured directory rather than the ambient working directory. 6. Add `.env` to `.gitignore` and exclude it from archives, logs, backups, and diagnostic output. 7. Avoid exporting the key into the process environment unless required, and prevent unnecessary inheritance by child processes. 8. Document credential rotation and revocation procedures in case the file is exposed. ]]>
