Back to skill

Security audit

commercial_invoice_ocr

Security checks for vulnerabilities and agentic risk

Overview

The skill is a disclosed cloud invoice OCR tool, but it needs Review because a configurable, unvalidated API endpoint can redirect sensitive invoices and the Scnet API token away from Scnet.

Install only if you are comfortable sending selected invoice images or PDFs to Scnet's cloud OCR service. Before use, keep `config/.env` private, do not change `SCNET_API_BASE` away from the official Scnet HTTPS endpoint, confirm each document is allowed to leave your environment, and prefer pinned dependencies in an isolated virtual environment.

Vulnerability Patterns
  • Insecure DependenciesIntroduces malicious components through unsafe dependency sources
  • 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)

T09 · Insecure Skill Coding Practices

Error
Location
scripts/main.py:51
Finding

Configurable OCR Endpoint Can Expose API Credentials and Sensitive Invoice Data

Content
View full analysis

Vulnerability Details

File Location: scripts/main.py:51-112
Vulnerability Type: Unvalidated network destination for sensitive data
Risk Level: High

Vulnerable Code

python
config = {}
with open(ENV_FILE, 'r', encoding='utf-8') as f:
    for line in f:
        line = line.strip()
        if not line or line.startswith('#'):
            continue
        if '=' in line:
            key, value = line.split('=', 1)
            key = key.strip()
            value = value.strip().strip('"').strip("'")
            config[key] = value

# 检查必要配置
api_key = config.get('SCNET_API_KEY', '')
if not api_key or api_key == 'your_scnet_api_key_here':
    error_msg = (
        "\n===============================================\n"
        "Scnet API Key 未配置\n"
        "===============================================\n"
        "请按以下步骤配置:\n\n"
        "1. 申请 Scnet API Token:\n"
        "   访问 https://www.scnet.cn 注册并获取密钥\n\n"
        "2. 配置 Token:\n"
        f"   编辑 {ENV_FILE}\n"
        "   设置 SCNET_API_KEY=你的密钥\n"
    )
    sys.exit(error_msg)

config.setdefault('SCNET_API_BASE', 'https://api.scnet.cn/api/llm/v1')
return config

def recognize_with_retry(ocr_type, file_path, config, retry_count=0):
    """
    带重试机制的 OCR 识别函数。
    当遇到 429 (Too Many Requests) 时,自动等待后重试。
    调用 Scnet OCR API 进行识别"""
    api_base = config['SCNET_API_BASE']
    api_key = config['SCNET_API_KEY']
    url = f"{api_base}/ocr/recognize"

    # 检查文件是否存在
    if not os.path.isfile(file_path):
        sys.exit(f"错误: 文件不存在 - {file_path}")

    # 自动检测 MIME 类型
    mime_type, _ = mimetypes.guess_type(file_path)
    if mime_type is None:
        mime_type = 'application/octet-stream'

    headers = {
        'Authorization': f'Bearer {api_key}'
    }

    try:
        with open(file_path, 'rb') as f:
            files = {
                'file': (os.path.basename(file_path), f, mime_t
...[truncated 2572 chars]
Remediation
View remediation

Remediation Suggestions

  1. Remove arbitrary endpoint configuration if it is not operationally required, and use a constant trusted endpoint:
    python
    API_BASE = "https://api.scnet.cn/api/llm/v1"
    
  2. If endpoint configuration must remain available, parse it with urllib.parse.urlsplit and require:
    • The https scheme.
    • An exact allowlisted hostname such as api.scnet.cn.
    • No embedded username or password.
    • An approved port and path prefix.
  3. Reject unexpected destinations before reading the invoice or constructing the authorization header.
  4. Do not attach the Scnet credential to custom or non-Scnet destinations. Use separate credentials for explicitly supported private endpoints.
  5. Establish a restrictive redirect policy and verify the final destination before transmitting sensitive material.
  6. Protect config/.env with owner-only permissions and verify that it is not writable by less-privileged users.
  7. Require explicit user confirmation before uploading sensitive invoices and clearly display the validated destination.
  8. Add automated tests confirming rejection of plaintext URLs, unexpected hosts, userinfo, unapproved ports, and malformed endpoints.

T08 · Insecure Dependencies

Warning
Location
SKILL.md:69
Finding

Unpinned Third-Party Dependency Installation

Content
View full analysis

Vulnerability Details

File Location: SKILL.md:69-74
Vulnerability Type: Unpinned dependency resolved through the ambient package index
Risk Level: Medium

Vulnerable Code

markdown
### 依赖安装

本技能需要 Python 3.6+ 和 requests 库。请运行以下命令:

```bash
   pip install requests
text

### Technical Analysis

The installation instructions retrieve `requests` without a version constraint, lock file, or integrity hash. Package resolution therefore depends on the active pip configuration and package index at installation time.

Although `requests` is a legitimate package, this installation process is not reproducible. A compromised package repository, maliciously configured index, dependency substitution event, or compromised future release could cause unreviewed code to be installed. Python package installation can execute package build logic, and the installed package is later imported by `scripts/main.py`.

### Attack Path

1. A user follows the documented `pip install requests` instruction.
2. The user's pip configuration points to a compromised or attacker-controlled index, or the resolved package release or dependency has been compromised.
3. Pip downloads and installs content that was not reviewed with this Skill.
4. Malicious build logic may execute during installation, or malicious runtime code may execute when `scripts/main.py` imports `requests`.
5. The package runs with the privileges of the user or environment performing the installation or invoking the Skill.

This path is conditional on compromise or manipulation of the dependency source; the audit found no evidence that the current `requests` package itself is malicious.

### Impact Assessment

A compromised dependency could execute code with the permissions of the installing or invoking user. Depending on those permissions, it could access local files and environment data, alter user-owned resources, intercept the invoice and API token handled
...[truncated 296 chars]
Remediation
View remediation

Remediation Suggestions

  1. Create a reviewed requirements or lock file that pins requests and all transitive dependencies to exact versions.
  2. Include cryptographic hashes and install with hash verification, for example:
    bash
    python -m pip install --require-hashes -r requirements.txt
    
  3. Generate and review the lock file using a dependency-management tool that supports deterministic resolution.
  4. Explicitly use the trusted official package index in installation guidance and prohibit untrusted extra indexes.
  5. Install dependencies inside an isolated virtual environment rather than globally or with administrator privileges.
  6. Use automated dependency vulnerability scanning and controlled update reviews to keep pinned packages secure.
  7. Document supported Python versions consistently and test the locked dependency set against each supported version.
Vulnerability Patterns
  • Data ExfiltrationExternal Transmission, Env Variable Harvesting, File System Enumeration
  • Privilege EscalationExcessive Permissions, Sudo/Root Execution, Credential Access
  • Excessive AgencyUnrestricted Tool Access, Autonomous Decision Making, Scope Creep
  • Trigger AbuseOverly Broad Trigger, Shadow Command Trigger, Keyword Baiting Trigger
  • MCP Least PrivilegeUnderdeclared Capability, Wildcard Permission, Missing Permission Declaration
Findings (22)

Credential Access

High
Category
Privilege Escalation
Confidence
60% confidence
Finding

Code accesses credential files (SSH keys, AWS credentials, etc.). This could indicate credential theft attempts.

Content

Scanner excerpt · scripts/main.py (reported line 20)May include surrounding context.

python
# 获取技能根目录(脚本所在目录的上一级)
SKILL_ROOT = Path(__file__).parent.parent.absolute()
ENV_FILE = SKILL_ROOT / "config" / ".env"

# --- 新增:重试配置 ---
MAX_RETRIES = 3            # 最大重试次数

Credential Access

High
Category
Privilege Escalation
Confidence
60% confidence
Finding

Code accesses credential files (SSH keys, AWS credentials, etc.). This could indicate credential theft attempts.

Content

Scanner excerpt · SKILL.md (reported line 66)May include surrounding context.

md
# --------------------

def load_config():
    """从 .env 文件加载配置,若文件不存在则抛出友好错误"""
    if not ENV_FILE.exists():
        error_msg = (
            "\n===============================================\n"

Credential Access

High
Category
Privilege Escalation
Confidence
60% confidence
Finding

Code accesses credential files (SSH keys, AWS credentials, etc.). This could indicate credential theft attempts.

Content

Scanner excerpt · SKILL.md (reported line 128)May include surrounding context.

md
# --------------------

def load_config():
    """从 .env 文件加载配置,若文件不存在则抛出友好错误"""
    if not ENV_FILE.exists():
        error_msg = (
            "\n===============================================\n"

Credential Access

High
Category
Privilege Escalation
Confidence
60% confidence
Finding

Code accesses credential files (SSH keys, AWS credentials, etc.). This could indicate credential theft attempts.

Content

Scanner excerpt · scripts/main.py (reported line 29)May include surrounding context.

python
# --------------------

def load_config():
    """从 .env 文件加载配置,若文件不存在则抛出友好错误"""
    if not ENV_FILE.exists():
        error_msg = (
            "\n===============================================\n"

Vague Triggers

Medium
Category
Not specified by scanner
Confidence
92% confidence
Finding

The README is effectively a generic GitLab template and does not define what conditions should trigger or invoke this skill. For a skill that uploads local invoice images/PDFs to a third-party OCR cloud service, ambiguous invocation scope can cause accidental use on unintended files or in unintended workflows, increasing the risk of unauthorized data transfer.

Content

No source excerpt is available for this finding.

Missing User Warnings

Medium
Category
Not specified by scanner
Confidence
97% confidence
Finding

The README omits any user-facing disclosure that the skill uploads local commercial invoice images/PDFs to Scnet's cloud for OCR processing. Because invoices commonly contain sensitive commercial, financial, and counterpart data, lack of notice and handling warnings can lead users to expose confidential documents without informed consent or understanding of retention, sharing, or compliance implications.

Content

No source excerpt is available for this finding.

Autonomous Decision Making

Medium
Category
Excessive Agency
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.

Content

Scanner excerpt · README.md (reported line 38)May include surrounding context.

md
* [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/)
* [Analyze your code for known vulnerabilities with Static Application Security Testing (SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
* [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
* [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
* [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)

Undeclared Tool Scope

Medium
Category
MCP Least Privilege
Confidence
95% confidence
Finding

The skill documentation clearly indicates it will read local files, invoke Python from the shell, and send data over the network, but it does not declare any explicit tool scope such as permissions or allowed-tools. This creates an authorization gap where an agent may invoke broader capabilities than users expect, especially because the skill processes sensitive local invoice files and transmits them to a third-party service.

Content

No source excerpt is available for this finding.

Natural-Language Policy Violations

Medium
Category
Not specified by scanner
Confidence
87% confidence
Finding

The file presents the entire skill description and operating instructions only in Chinese, with no indication that the user can choose another language or that the locale restriction is required for a region-specific compliance reason. Under the stated policy, forcing a specific language without user opt-in is a natural-language policy concern.

Content

No source excerpt is available for this finding.

External Transmission

Medium
Category
Data Exfiltration
Confidence
97% confidence
Finding

The skill is explicitly configured to upload local invoice files to an external endpoint at api.scnet.cn. Since invoices commonly contain sensitive commercial and financial data, external transmission materially increases confidentiality and compliance risk, especially if users do not fully understand that their local documents leave the environment.

Content

Scanner excerpt · SKILL.md (reported line 58)May include surrounding context.

SCNET_API_KEY=your_scnet_api_key_here

API 基础地址(一般无需修改)

SCNET_API_BASE=https://api.scnet.cn/api/llm/v1

text
2. 添加:`SCNET_API_KEY=你的密钥`
3. 设置文件权限为 600(仅所有者可读写)

Intent-Code Divergence

Medium
Category
Not specified by scanner
Confidence
95% confidence
Finding

SKILL.md 整体将该技能描述为“商业发票识别 OCR”,但参数说明中却写明 ocrType 必须为 BILL_OF_LADING(提单)。这不是简单的文档缺漏,而是对技能核心识别对象的主动性矛盾描述,会误导调用方对实际用途和支持能力的理解。

Content

No source excerpt is available for this finding.

Intent-Code Divergence

Medium
Category
Not specified by scanner
Confidence
91% confidence
Finding

参数表中声明 ocrType 必须为 BILL_OF_LADING,但命令行示例实际传入的是 COMMERCIAL_INVOICE。两处文档对同一输入参数给出了互相冲突的值,直接影响调用者对技能真实意图和支持范围的判断。

Content

No source excerpt is available for this finding.

Vague Triggers

Medium
Category
Not specified by scanner
Confidence
94% confidence
Finding

The activation guidance says the AI may auto-trigger the skill from broad descriptive keywords, but it does not impose explicit constraints such as requiring user confirmation before reading a local file or uploading it to a third party. Because the skill handles sensitive invoice documents, vague triggering raises the risk of unintended collection and external transmission of commercial data.

Content

No source excerpt is available for this finding.

External Transmission

Medium
Category
Data Exfiltration
Confidence
96% confidence
Finding

The configuration table reiterates use of a third-party API base for processing, confirming that sensitive invoice content is sent off-host. In the context of trade documents containing contract numbers, credit terms, and pricing data, this external transfer is security-relevant and can expose confidential business information if mishandled.

Content

Scanner excerpt · SKILL.md (reported line 110)May include surrounding context.

md
| 变量名 | 默认值 | 说明 |
|--------|--------|------|
| SCNET_API_KEY | 必需 | Scnet API 密钥 |
| SCNET_API_BASE | https://api.scnet.cn/api/llm/v1 | API 基础地址(一般无需修改) |

### 输出

External Transmission

Medium
Category
Data Exfiltration
Confidence
95% confidence
Finding

The skill explicitly sends locally supplied invoice images/PDFs to a third-party cloud endpoint, which creates a real data-exfiltration/privacy risk because commercial invoices commonly contain sensitive business and financial information. Although the document warns about this behavior, the risk remains material if users are not given clear consent controls, data-handling disclosures, and minimization safeguards before upload.

Content

Scanner excerpt · references/api-docs.md (reported line 6)May include surrounding context.

md
> **⚠️ 隐私与安全提示**:调用本接口会将本地文件内容上传至第三方 Scnet 云端服务(`api.scnet.cn`)。商业发票通常包含公司名称、地址、发票金额、信用证号、合同号、贸易条款等敏感商业信息。请确保用户已知情并同意文件外传后再调用。

## 接口地址
`POST https://api.scnet.cn/api/llm/v1/ocr/recognize`

## 请求头
- `Content-Type: multipart/form-data`

Natural-Language Policy Violations

Medium
Category
Not specified by scanner
Confidence
94% confidence
Finding

The module docstring and user-facing usage/messages are written entirely in Chinese, and the script states it outputs OCR JSON for a specific invoice workflow without any indication that users may choose another language. Under the policy, forcing a specific language without opt-in is a natural-language policy violation unless the locale restriction is clearly documented and justified.

Content

No source excerpt is available for this finding.

Sudo/Root Execution

Medium
Category
Privilege Escalation
Confidence
80% confidence
Finding

Commands invoke sudo or root privileges. Verify this elevated access is necessary and justified.

Content

Scanner excerpt · scripts/main.py (reported line 45)May include surrounding context.

python
"   b) 配置文件:\n"
            f"      mkdir -p {SKILL_ROOT}/config\n"
            f"      echo 'SCNET_API_KEY=你的密钥' > {ENV_FILE}\n"
            f"      chmod 600 {ENV_FILE}\n"
            "\n配置完成后重新运行。"
        )
        sys.exit(error_msg)

Sudo/Root Execution

Medium
Category
Privilege Escalation
Confidence
80% confidence
Finding

Commands invoke sudo or root privileges. Verify this elevated access is necessary and justified.

Content

Scanner excerpt · scripts/main.py (reported line 152)May include surrounding context.

python
"   b) 配置文件:\n"
            f"      mkdir -p {SKILL_ROOT}/config\n"
            f"      echo 'SCNET_API_KEY=你的密钥' > {ENV_FILE}\n"
            f"      chmod 600 {ENV_FILE}\n"
            "\n配置完成后重新运行。"
        )
        sys.exit(error_msg)

External Transmission

Medium
Category
Data Exfiltration
Confidence
96% confidence
Finding

The skill uploads user-provided local images/PDFs containing commercial invoice data to an external cloud OCR endpoint at api.scnet.cn. Because invoices commonly contain sensitive business and personal data, this creates a real data exfiltration/privacy risk if users are not clearly informed, if consent is not explicit, or if the remote service is untrusted or misconfigured.

Content

Scanner excerpt · scripts/main.py (reported line 78)May include surrounding context.

python
)
        sys.exit(error_msg)

    config.setdefault('SCNET_API_BASE', 'https://api.scnet.cn/api/llm/v1')
    return config

def recognize_with_retry(ocr_type, file_path, config, retry_count=0):

Natural-Language Policy Violations

Low
Category
Not specified by scanner
Confidence
89% confidence
Finding

This markdown file uses Chinese for its visible headings and entries, which can impose a specific language on users without any opt-in or explanation. The policy allows locale constraints when they are explicitly justified, but no such justification appears here.

Content

No source excerpt is available for this finding.

Intent-Code Divergence

Low
Category
Not specified by scanner
Confidence
96% confidence
Finding

L61 声称识别结果位于 data[0].result[0].elements,但前面的响应示例实际结构是 data.result[0].elements,且 L63 又称结果位于 data[0].result[0].stamps。这些文档说明相互冲突,会误导实现者对实际返回结构和结果位置的理解。

Content

No source excerpt is available for this finding.

Missing User Warnings

Low
Category
Not specified by scanner
Confidence
81% confidence
Finding

This manifest states that local images/PDFs are uploaded to the Scnet cloud, but it does not explicitly warn users in the description that the skill depends on an API key credential. Because this is a manifest file describing behavior that transmits user documents to an external service, users would benefit from a clear disclosure that credentialed third-party processing is involved.

Content

No source excerpt is available for this finding.