T09 · Insecure Skill Coding Practices
- Location
scripts/config.py:45- Finding
API Key Persisted in Plaintext Without Restrictive File Permissions
- Content
View full analysis
Vulnerability Details
File Location:
scripts/config.py, lines 45-66
Vulnerability Type: Plaintext credential storage with insufficient file-permission controls
Risk Level: MediumVulnerable 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 FalseTechnical Analysis
The function persistently writes the user's API key as plaintext into a relative
.envfile.Path.write_text()does not explicitly establish owner-only permissions. For a newly created file, its permissions depend on the process umask; for an existing file, potentially permissive permissions remain unchanged. The implementation also does not verify the ownership, type, or permissions of an existing.envpath before overwriting it.Consequently, a local user or process able to read the working directory may retrieve the credential. A maliciously prepared working environment could also expose the key through a pre-existing permissive file or redirected path. The code does not reject newline characters in the supplied key, which could additionally permit unintended entries to be injected into the generated
.envfile, although no direct code-execution path was id ...[truncated 1296 chars]- Remediation
View remediation
Remediation Suggestions
- Prefer session-only credential handling or an operating-system credential store rather than writing the key to the project directory.
- If file persistence is necessary, create the credential file atomically with owner-only permissions such as mode
0600. - For an existing
.envfile, verify that it is a regular file owned by the expected user and reject unsafe ownership, symbolic links, or group/world-accessible permissions. - Set restrictive permissions explicitly after creation and fail closed if they cannot be enforced.
- Validate the API key before storage, including rejecting carriage returns and newline characters.
- Store the file at a deterministic, user-private configuration location rather than relative to the current working directory.
- Inform the user that the credential will be persisted and obtain consent; provide a supported method to remove or rotate the stored key.
- Ensure
.envis excluded from version control, backups, diagnostic bundles, and logs.
