Back to skill

Security audit

macOS微信发送器

Security checks for vulnerabilities and agentic risk

Overview

This skill matches its stated WeChat automation purpose, but it can immediately send real messages/files and has verified AppleScript injection risks from crafted inputs.

Install only if you are comfortable with a skill that can control WeChat on your Mac and send real messages or local files immediately. Use only trusted, manually reviewed contact names, message text, and file paths; adding confirmation prompts and argv-based AppleScript input handling would materially reduce risk.

Vulnerability Patterns
  • 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
  • Embedded Malicious CodeShips malicious scripts inside the skill and executes them locally
Findings (3)

T09 · Insecure Skill Coding Practices

Error
Location
wechat_sender.py:47
Finding

AppleScript Injection Through the Contact Name

Content
View full analysis

Vulnerability Details

File Location: wechat_sender.py, lines 47-73
Vulnerability Type: AppleScript injection through an unescaped command-line argument
Risk Level: High

Vulnerable Code

python
def search_contact(contact: str):
    script = f'''
    tell application "System Events"
        tell process "WeChat"
            set frontmost to true
        end tell
    end tell
    delay 0.3
    tell application "System Events"
        tell process "WeChat"
            keystroke "f" using {{command down, shift down}}
        end tell
    end tell
    delay 0.5
    tell application "System Events"
        keystroke "{contact}"
    end tell
    delay 0.8
    tell application "System Events"
        keystroke return
    end tell
    delay 1
    '''
    _run_osascript(script)

Technical Analysis

The contact value originates from the --contact command-line argument and is inserted directly into an AppleScript string literal using an f-string. It is not encoded or escaped for AppleScript syntax.

Although subprocess.run() uses an argument array and therefore avoids shell parsing, the resulting string is executable AppleScript source. A contact value containing a quotation mark, line break, AppleScript statements, and trailing comment syntax can terminate the intended keystroke argument and inject additional commands.

The generated script is passed to osascript, so injected statements execute with the permissions of the user running the skill.

Attack Path

  1. An attacker gains influence over the value supplied to --contact, such as through an agent-generated command, automation workflow, or untrusted external input.
  2. The attacker supplies a contact value crafted to close the AppleScript string literal.
  3. The value appends one or more AppleScript statements and neutralizes the remaining generated syntax.
  4. search_contact() interpolates the v ...[truncated 865 chars]
Remediation
View remediation

Remediation Suggestions

  • Do not interpolate the contact name into AppleScript source.

  • Pass the contact as a positional osascript argument and retrieve it through an on run argv handler:

    python
    script = '''
    on run argv
        set contactName to item 1 of argv
        tell application "System Events"
            tell process "WeChat"
                set frontmost to true
                keystroke "f" using {command down, shift down}
            end tell
            delay 0.5
            keystroke contactName
            delay 0.8
            keystroke return
        end tell
    end run
    '''
    subprocess.run(
        ["osascript", "-e", script, contact],
        check=True,
        capture_output=True,
        text=True,
        timeout=30,
    )
    
  • Apply reasonable length and control-character validation to contact names as defense in depth.

  • Reject values containing unexpected line breaks or non-printable characters when such characters are not legitimate contact-name content.

  • Check and propagate subprocess failures instead of continuing and reporting success.

T09 · Insecure Skill Coding Practices

Error
Location
wechat_sender.py:76
Finding

AppleScript Injection Through a Crafted File Path

Content
View full analysis

Vulnerability Details

File Location: wechat_sender.py, lines 76-95
Vulnerability Type: AppleScript injection through an unescaped filesystem path
Risk Level: High

Vulnerable Code

python
def send_file(file_path: str, contact: str = "老婆"):
    abs_path = os.path.abspath(file_path)
    if not os.path.exists(abs_path):
        print(f"❌ 文件不存在: {abs_path}")
        return False

    print(f"📤 发送文件到 [{contact}]: {abs_path}")

    ensure_wechat_active()
    time.sleep(0.5)

    apple_script = f'''
    tell application "Finder"
        set theFile to POSIX file "{abs_path}" as alias
        select theFile
        activate
    end tell
    delay 0.3
    tell application "System Events"
        keystroke "c" using {{command down}}
    end tell
    '''
    _run_osascript(apple_script)

Technical Analysis

os.path.abspath() canonicalizes the path format but does not escape AppleScript metacharacters. The resulting abs_path is embedded directly between quotation marks in executable AppleScript.

macOS filenames can contain characters that are significant inside generated source, including quotation marks, backslashes, and line breaks. The existence check does not make the path trustworthy because an attacker can first create, or identify, a real file whose name contains the required characters. A crafted existing path can therefore terminate the intended AppleScript literal and insert additional statements.

Using an argument array for the osascript process only prevents shell injection. It does not protect dynamically generated AppleScript from source-code injection.

Attack Path

  1. An attacker creates or causes the creation of a file with a maliciously crafted name in a directory accessible to the invoking user.
  2. The attacker causes the skill to process that path through --file.
  3. os.path.exists() succeeds because the crafted file is real.
  4. `abs_path ...[truncated 898 chars]
Remediation
View remediation

Remediation Suggestions

  • Pass the path as data through argv instead of embedding it into AppleScript source:

    python
    script = '''
    on run argv
        set suppliedPath to item 1 of argv
        tell application "Finder"
            set theFile to POSIX file suppliedPath as alias
            select theFile
            activate
        end tell
        delay 0.3
        tell application "System Events"
            keystroke "c" using {command down}
        end tell
    end run
    '''
    subprocess.run(
        ["osascript", "-e", script, abs_path],
        check=True,
        capture_output=True,
        text=True,
        timeout=30,
    )
    
  • Verify that the target is a regular file with os.path.isfile() where appropriate.

  • If the workflow has an expected output directory, resolve the path and enforce that it remains inside that approved directory.

  • Avoid relying on manual escaping routines for executable-language literals.

  • Use check=True, inspect errors, and stop the send workflow if selecting or copying the file fails.

T09 · Insecure Skill Coding Practices

Error
Location
wechat_sender.py:121
Finding

Incomplete AppleScript Escaping Allows Message Injection

Content
View full analysis

Vulnerability Details

File Location: wechat_sender.py, lines 121-137
Vulnerability Type: AppleScript injection caused by incomplete string escaping
Risk Level: High

Vulnerable Code

python
def send_message(message: str, contact: str = "老婆"):
    ensure_wechat_active()
    time.sleep(0.5)
    search_contact(contact)
    time.sleep(0.5)

    escaped_msg = message.replace('"', '\\"')
    script = f'''
    tell application "System Events"
        tell process "WeChat"
            set frontmost to true
        end tell
    end tell
    delay 0.3
    tell application "System Events"
        keystroke "{escaped_msg}"
    end tell
    delay 0.3
    tell application "System Events"
        keystroke return
    end tell
    '''
    _run_osascript(script)

Technical Analysis

The code attempts to make the message safe by replacing quotation marks with \". This is not a complete AppleScript encoding mechanism. In particular, attacker-controlled backslashes can alter the interpretation of inserted escape sequences, and line breaks or other control characters can affect the generated source.

Escaping only one character is unsafe when constructing source code for another language. A crafted combination of backslashes and quotation marks can cause a quotation mark to terminate the intended AppleScript string instead of remaining part of the message. Additional AppleScript statements can then be appended.

Because the entire generated string is executed by osascript, successful injection provides code execution through AppleScript rather than merely changing the text sent to WeChat.

Attack Path

  1. An attacker controls or influences the value passed through --message.
  2. The attacker supplies a crafted sequence containing backslashes, quotation marks, and AppleScript syntax.
  3. The quote replacement runs, but the attacker-controlled backslashes change how the resu ...[truncated 865 chars]
Remediation
View remediation

Remediation Suggestions

  • Remove manual quote replacement and pass the complete message through osascript positional arguments:

    python
    script = '''
    on run argv
        set messageText to item 1 of argv
        tell application "System Events"
            tell process "WeChat"
                set frontmost to true
            end tell
            delay 0.3
            keystroke messageText
            delay 0.3
            keystroke return
        end tell
    end run
    '''
    subprocess.run(
        ["osascript", "-e", script, message],
        check=True,
        capture_output=True,
        text=True,
        timeout=30,
    )
    
  • Treat command-line messages as untrusted data, especially when they originate from agent output, webhooks, files, or other users.

  • Optionally enforce a maximum message length and reject unsupported control characters.

  • Check the osascript return code and report success only after every required automation step succeeds.

  • Consider using the clipboard for Unicode text input, while preserving and restoring the user's previous clipboard contents and ensuring clipboard data is handled securely.

Vulnerability Patterns
  • Data ExfiltrationExternal Transmission, Env Variable Harvesting, File System Enumeration
  • Behavioral ASTexec() Call, eval() Call, Dynamic Import
  • MCP Least PrivilegeUnderdeclared Capability, Wildcard Permission, Missing Permission Declaration
  • MCP Tool PoisoningHidden Instructions, Unicode Deception, Parameter Description Injection
  • Prompt InjectionInstruction Override, Hidden Instructions, Exfiltration Commands
Findings (9)

Tp2

High
Category
MCP Tool Poisoning
Confidence
85% confidence
Finding

Mixing characters from multiple Unicode scripts in a single identifier is a common technique to create visually ambiguous tool names.

Content

No source excerpt is available for this finding.

Undeclared Tool Scope

Medium
Category
MCP Least Privilege
Confidence
95% confidence
Finding

The skill explicitly relies on shell-capable operations (brew install, open -a WeChat, and invoking a Python script) but does not declare any permissions or allowed-tools scope. This creates an authorization and review gap: an agent or user may invoke shell actions without an explicit, least-privilege declaration, increasing the chance of unintended execution or misuse.

Content

No source excerpt is available for this finding.

Missing User Warnings

Medium
Category
Not specified by scanner
Confidence
97% confidence
Finding

This skill automates sending messages and files to real WeChat contacts and groups, yet the documentation does not prominently warn users that execution will cause external, real-world communication. Because it targets actual recipients and can send arbitrary files/messages through GUI automation, missing consent and safety warnings materially increase the risk of accidental data leakage, misdelivery, or unauthorized outbound messaging.

Content

No source excerpt is available for this finding.

subprocess module call

Medium
Category
Dangerous Code Execution
Confidence
95% confidence
Finding

The script builds AppleScript from untrusted user input and passes it directly to osascript. In both search_contact and send_message, attacker-controlled text is interpolated into AppleScript string literals with insufficient escaping, so crafted input can break out of the string and inject arbitrary AppleScript commands, leading to arbitrary UI automation or system actions under the user's macOS permissions.

Content

Scanner excerpt · wechat_sender.py (reported line 24)May include surrounding context.

python
def _run_osascript(script: str) -> tuple[int, str]:
    """执行 AppleScript, 返回 (returncode, output)"""
    p = subprocess.run(["osascript", "-e", script],
                       capture_output=True, text=True, timeout=30)
    return p.returncode, p.stdout.strip()

subprocess module call

Medium
Category
Dangerous Code Execution
Confidence
70% confidence
Finding

subprocess module calls execute external commands. Without careful input validation, this enables command injection.

Content

Scanner excerpt · wechat_sender.py (reported line 31)May include surrounding context.

python
def _cliclick(coord: str):
    """执行 cliclick 点击"""
    subprocess.run(["cliclick", coord], capture_output=True, timeout=10)


def ensure_wechat_active() -> bool:

subprocess module call

Medium
Category
Dangerous Code Execution
Confidence
70% confidence
Finding

subprocess module calls execute external commands. Without careful input validation, this enables command injection.

Content

Scanner excerpt · wechat_sender.py (reported line 44)May include surrounding context.

python
''')
    if rc != 0:
        # 尝试打开微信
        subprocess.run(["open", "-a", "WeChat"], capture_output=True, timeout=30)
        time.sleep(3)
        return True
    return True

Missing User Warnings

Medium
Category
Not specified by scanner
Confidence
89% confidence
Finding

The file-send path automates clipboard copy, window focus, paste, and send with no confirmation or verification that the correct chat is active. Because this skill is specifically designed to transmit arbitrary local files through WeChat, a focus mistake, contact mismatch, or maliciously supplied invocation can leak sensitive files immediately and irreversibly to the wrong recipient.

Content

No source excerpt is available for this finding.

Missing User Warnings

Medium
Category
Not specified by scanner
Confidence
84% confidence
Finding

The tool sends messages immediately with no confirmation, recipient verification, or safety interlock, which increases the chance of unintended delivery to the wrong contact. In a UI-automation context like this one, focus changes or search mismatches can cause silent misdelivery of potentially sensitive content.

Content

No source excerpt is available for this finding.

Intent-Code Divergence

Low
Category
Not specified by scanner
Confidence
97% confidence
Finding

The CLI help text says "发送到群聊" for the --group flag, implying documented behavior difference for group chats. However, args.group is parsed and then ignored entirely; no branch or logic changes behavior based on that flag, so the documentation actively overstates what the code does.

Content

No source excerpt is available for this finding.