Back to skill

Security audit

Sfaeflow Solana Skill

Security checks for vulnerabilities and agentic risk

Overview

This payment skill is mostly coherent with its stated Solana purpose, but its scripts handle payment and wallet inputs in unsafe ways that could allow local code execution or unintended transfers.

Install only after the publisher replaces inline node -e/ts-node -e code with checked-in scripts that parse arguments safely, pins dependencies with a lockfile, validates recipient and amount before loading the keypair, protects the keypair with restrictive permissions or a safer signer, and adds clear operator controls such as dry-run, confirmation, and spending-policy guidance.

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 (3)

T09 · Insecure Skill Coding Practices

Error
Location
scripts/save_config.sh:27
Finding
JavaScript Code Injection Through the Wallet Owner Argument<![CDATA[ ## Vulnerability Details **File Location**: `scripts/save_config.sh`, lines 27-34 **Vulnerability Type**: Untrusted input embedded in executable JavaScript **Risk Level**: High ### Vulnerable Code ```bash # Update config with wallet owner using a portable approach TMP_FILE=$(mktemp) node -e " const fs = require('fs'); const cfg = JSON.parse(fs.readFileSync('$CONFIG_DIR/config.json', 'utf8')); cfg.walletOwner = '$WALLET_OWNER'; fs.writeFileSync('$CONFIG_DIR/config.json', JSON.stringify(cfg, null, 2)); " ``` ### Technical Analysis The value supplied through `--wallet-owner` is directly interpolated into JavaScript source passed to `node -e`: ```javascript cfg.walletOwner = '$WALLET_OWNER'; ``` No escaping or syntactic validation occurs before interpolation. An attacker-controlled value containing a single quote followed by JavaScript statements can terminate the intended string literal and inject arbitrary JavaScript. Any public-key validation performed after interpolation would be insufficient because the injected source is parsed and executed by Node.js first. In this script, the value is not validated as a Solana public key at all. The script also creates a temporary file with `mktemp` but never uses or removes it. This is not the primary vulnerability, but the unnecessary operation should be removed. ### Attack Path 1. An attacker influences the value passed to `save_config.sh --wallet-owner`. 2. The crafted value closes the JavaScript string assigned to `cfg.walletOwner`. 3. The value appends arbitrary JavaScript and neutralizes the remaining expected syntax. 4. Bash expands the argument into the source passed to `node -e`. 5. Node.js parses and executes the injected statements with the privileges of the user running the skill. 6. The injected code can read or modify files available to that user, including `.safeflow/agent-keypair.json` and `.safeflow/config.json`. ### Impact Assessment Successful exploitation provides arbitrar ...[truncated 588 chars]
Remediation
<![CDATA[ ## Remediation Suggestions Move the JavaScript implementation into a checked-in `.js` file and pass the wallet owner as a normal process argument: ```bash node scripts/save_config.js --wallet-owner "$WALLET_OWNER" ``` Read the value from `process.argv` rather than constructing JavaScript source code from it. Validate it before updating the configuration: ```javascript const { PublicKey } = require('@solana/web3.js'); const walletOwner = getArgument('--wallet-owner'); const validatedOwner = new PublicKey(walletOwner).toBase58(); cfg.walletOwner = validatedOwner; ``` Additional hardening should include: - Never interpolate user input into `node -e`, `eval`, or similar executable source strings. - Write the updated configuration to a securely created temporary file and atomically rename it, or remove the unused `mktemp` call. - Set restrictive permissions on `.safeflow`, the keypair, and configuration files. - Reject missing, malformed, or unexpectedly long argument values. ]]>

T09 · Insecure Skill Coding Practices

Error
Location
scripts/execute_payment.sh:34
Finding
Arbitrary JavaScript Execution Through Payment Arguments<![CDATA[ ## Vulnerability Details **File Location**: `scripts/execute_payment.sh`, lines 34-83 **Vulnerability Type**: Untrusted payment parameters embedded in executable TypeScript/JavaScript **Risk Level**: High ### Vulnerable Code ```bash npx ts-node -e " const fs = require('fs'); const { Connection, Keypair, PublicKey, LAMPORTS_PER_SOL } = require('@solana/web3.js'); const { BN } = require('@coral-xyz/anchor'); (async () => { const config = JSON.parse(fs.readFileSync('$CONFIG_DIR/config.json', 'utf8')); const idl = JSON.parse(fs.readFileSync('target/idl/safeflow_solana.json', 'utf8')); const keypairData = JSON.parse(fs.readFileSync(config.keypairPath, 'utf8')); const keypair = Keypair.fromSecretKey(Uint8Array.from(keypairData)); const walletOwner = new PublicKey('${WALLET_OWNER_OVERRIDE}' || config.walletOwner); const clusterUrl = config.cluster === 'devnet' ? 'https://api.devnet.solana.com' : config.cluster === 'mainnet' ? 'https://api.mainnet-beta.solana.com' : 'http://localhost:8899'; const { SafeFlowAgent } = require('./sdk/src/agent'); const agent = new SafeFlowAgent({ connection: new Connection(clusterUrl, 'confirmed'), programId: new PublicKey(config.programId), keypair, idl, }); if (${QUERY_MODE}) { const session = await agent.getSessionInfo(walletOwner); const vault = await agent.getVaultBalance(walletOwner); console.log('Session Status:'); console.log(' Active :', session.isActive); console.log(' Remaining :', session.remainingBudget.toString(), 'lamports'); console.log(' Total Spent :', session.totalSpent.toString(), 'lamports'); console.log(' Max Total :', session.maxSpendTotal.toString(), 'lamports'); console.log(' Rate Limit :', session.maxSpendPerSecond.toString(), 'lamports/s'); console.log(' Expires At :', new Date(session.expiresAt.toNumber() * 1000).toISOString()); console.log(' Vault Balance :', vault / LA ...[truncated 2889 chars]
Remediation
<![CDATA[ ## Remediation Suggestions Replace the inline `ts-node -e` program with a checked-in TypeScript or compiled JavaScript file. Pass all values as ordinary command-line arguments or through a structured input channel: ```bash node scripts/execute_payment.js \ --recipient "$RECIPIENT" \ --amount "$AMOUNT" \ --evidence-id "$EVIDENCE_ID" \ --wallet-owner "$WALLET_OWNER_OVERRIDE" ``` Inside the implementation: 1. Parse values from `process.argv`. 2. Validate the wallet owner and recipient by constructing `PublicKey` objects. 3. Require the amount to match a strict unsigned-integer format, such as `^[0-9]+$`. 4. Apply an appropriate maximum amount and reject zero or negative values. 5. Enforce an evidence-ID length and character policy. 6. Load the private key only after all untrusted arguments have passed validation. 7. Avoid `eval`, `node -e`, `ts-node -e`, and all other forms of dynamically constructed source code. 8. Confirm the normalized recipient and amount to the caller before signing when the workflow permits. 9. Restrict keypair file permissions to the owning user. ]]>

T08 · Insecure Dependencies

Warning
Location
scripts/execute_payment.sh:34
Finding
Unpinned Runtime Package Execution Through npx<![CDATA[ ## Vulnerability Details **File Location**: `scripts/execute_payment.sh`, line 34 **Vulnerability Type**: Unsafe and unpinned dependency execution **Risk Level**: Medium ### Vulnerable Code ```bash npx ts-node -e " ``` ### Technical Analysis The project contains no reviewed package manifest or lockfile establishing a fixed `ts-node` version. Invoking `npx ts-node` can resolve a locally available binary, but when the package is absent, `npx` may offer to retrieve or retrieve package content from the configured package registry. This makes payment execution dependent on mutable external supply-chain state. Any package selected by the resolver runs with the privileges of the current user. In this workflow, it executes code that reads the Solana private key and performs payment operations. This finding concerns unsafe dependency resolution rather than evidence that the current `ts-node` package is malicious. ### Attack Path 1. The skill is run in an environment where `ts-node` is not installed locally and pinned. 2. `npx` attempts to resolve the command through its configured package sources. 3. Package content not represented by a committed and reviewed lockfile is downloaded or selected. 4. Package installation hooks or executable code run with the invoking user's privileges. 5. Malicious or compromised dependency code can read `.safeflow/agent-keypair.json`, modify execution, intercept transaction parameters, or exfiltrate local data. Registry compromise, resolver misconfiguration, dependency substitution, or future package compromise could enable this path. ### Impact Assessment A compromised dependency would execute as the user running the skill and would have access to: - The agent's private key and configuration. - Payment recipients, amounts, and evidence identifiers. - Local files readable by the current user. - Network access available to the process. - The ability to alter or suppress transaction execution. The scope is especially ...[truncated 80 chars]
Remediation
<![CDATA[ ## Remediation Suggestions Establish a reproducible dependency chain: 1. Add a package manifest declaring exact or tightly constrained dependency versions. 2. Commit a lockfile generated by the selected package manager. 3. Install dependencies in a controlled build or deployment phase using lockfile enforcement, such as `npm ci`. 4. Invoke only the installed local binary: ```bash npx --no-install ts-node scripts/execute_payment.ts ``` Alternatively, compile the TypeScript during a trusted build and execute the generated JavaScript directly with Node.js. Additional controls should include: - Verify package integrity through the lockfile. - Disable unnecessary lifecycle scripts during installation where feasible. - Use an approved registry and dependency allowlist. - Run dependency auditing and review updates before deployment. - Avoid runtime package downloads in any process that can access private keys. ]]>
Vulnerability Patterns
  • Data ExfiltrationExternal Transmission, Env Variable Harvesting, File System Enumeration
  • Prompt InjectionInstruction Override, Hidden Instructions, Exfiltration Commands
  • Privilege EscalationExcessive Permissions, Sudo/Root Execution, Credential Access
  • Supply ChainUnpinned Dependencies, External Script Fetching, Obfuscated Code
  • Excessive AgencyUnrestricted Tool Access, Autonomous Decision Making, Scope Creep
Findings (3)

Missing User Warnings

Medium
Confidence
95% confidence
Finding
The skill explicitly states that the agent generates and stores a Solana keypair locally in `.safeflow/agent-keypair.json`, but it provides no guidance on secure storage, filesystem permissions, encryption, rotation, or avoiding accidental exposure through logs, backups, or source control. Because this key authorizes spending within the session cap, compromise of the local private key could let an attacker execute unauthorized payments up to the configured limits.

Rp1

Medium
Category
MCP Rug Pull
Confidence
93% confidence
Finding
Using `npx ts-node` without pinning an exact version allows the script to resolve and execute whatever package version is available from the local environment or registry at runtime. In a payment-execution skill, this creates a supply-chain execution risk: a malicious or compromised `ts-node` package could run arbitrary code, exfiltrate the Solana keypair loaded from `config.keypairPath`, or alter payment behavior before the transfer is submitted.

Missing User Warnings

Medium
Confidence
95% confidence
Finding
The script performs a real on-chain payment immediately after parsing CLI arguments, with no interactive confirmation, preview, or secondary approval step. In the context of an autonomous payment skill that holds a usable keypair and session budget, operator error, prompt/agent misuse, or parameter tampering could cause irreversible transfers to an unintended recipient.

Static analysis

No suspicious patterns detected.