Back to skill

Security audit

Kalshi Paper Trading

Security checks for vulnerabilities and agentic risk

Overview

The skill is a coherent Kalshi paper-trading ledger, but its live-market command can be pointed at arbitrary URLs, which is broader network access than the stated purpose needs.

Install only if you are comfortable with a local persistent paper-trading database and live market lookups. Keep KALSHI_BASE_URL and --kalshi-base-url pointed at the official Kalshi API unless deliberately testing, and avoid letting untrusted prompts or copied commands choose that URL.

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

T09 · Insecure Skill Coding Practices

Warning
Location
scripts/kalshi_paper.ts:217
Finding

Unrestricted Market API Base URL Enables Blind Server-Side Request Forgery

Content
View full analysis

Vulnerability Details

File Location: scripts/kalshi_paper.ts, lines 217-245
Vulnerability Type: Blind Server-Side Request Forgery (SSRF)
Risk Level: Medium

Vulnerable Code

ts
function getKalshiBaseUrl(args: CliMap): string {
  const raw =
    (args["kalshi-base-url"] as string | undefined) ??
    process.env.KALSHI_BASE_URL ??
    "https://api.elections.kalshi.com/trade-api/v2";
  return raw.replace(/\/+$/, "");
}

async function fetchJson(url: string): Promise<unknown> {
  const res = await fetch(url, {
    method: "GET",
    headers: {
      accept: "application/json",
      "user-agent": "openclaw-skills-kalshi-paper-trading/1.0",
    },
  });
  const text = await res.text();
  let json: unknown;
  try {
    json = JSON.parse(text);
  } catch {
    json = { raw: text };
  }

  if (!res.ok) {
    throw new Error(`HTTP ${res.status} for ${url}: ${typeof json === "object" ? JSON.stringify(json) : String(json)}`);
  }
  return json;
}

The resulting URL is used by fetchKalshiMarket:

ts
const baseUrl = getKalshiBaseUrl(args);
const url = `${baseUrl}/markets/${encodeURIComponent(marketTicker)}`;
const response = await fetchJson(url) as { market?: KalshiMarketPayload };

Technical Analysis

The sync-market and buy-from-market commands accept a network destination from either the --kalshi-base-url command-line option or the KALSHI_BASE_URL environment variable. The value is used without validating its scheme, hostname, port, resolved IP address, or redirect destination.

Node.js fetch follows HTTP redirects by default. Therefore, restricting the final path to /markets/&lt;ticker&gt; does not prevent exploitation: an attacker-controlled initial server can redirect the request to a loopback, private-network, link-local, or cloud metadata address.

Response-shape validation occurs only after the request and any redirects have completed. An invalid market response may stop database processing, but it does not pre ...[truncated 2071 chars]

Remediation
View remediation

Remediation Suggestions

  1. Allowlist the production endpoint

    • Permit only the official Kalshi HTTPS hostname during normal operation.
    • Compare parsed hostnames exactly rather than using suffix or substring checks.
  2. Validate the URL structurally

    • Parse the value with the URL class.
    • Require https:.
    • Reject embedded credentials.
    • Reject fragments and unexpected ports.
    • Normalize the approved API path rather than accepting arbitrary base paths.
  3. Control redirects

    • Set redirect: "manual" and reject redirects, or validate every redirect destination using the same policy before following it.
    • Do not rely only on validating the initial URL.
  4. Block internal destinations

    • Resolve the hostname and reject loopback, private, link-local, multicast, unspecified, and reserved IPv4 and IPv6 ranges.
    • Revalidate the connected destination to mitigate DNS rebinding and time-of-check/time-of-use issues.
    • Explicitly block cloud metadata addresses.
  5. Separate test configuration

    • Permit arbitrary local endpoints only behind an explicit test-mode switch.
    • Ensure production Agent invocations cannot enable test mode through untrusted input.
  6. Limit request resource consumption

    • Add an AbortSignal timeout.
    • Enforce a maximum response size before parsing or storing the body.
    • Avoid including complete remote response bodies in error messages.
  7. Add regression tests

    • Verify rejection of HTTP URLs, embedded credentials, loopback addresses, private addresses, link-local addresses, unexpected ports, and redirect chains to prohibited destinations.
Vulnerability Patterns
  • Data ExfiltrationExternal Transmission, Env Variable Harvesting, File System Enumeration
  • MCP Least PrivilegeUnderdeclared Capability, Wildcard Permission, Missing Permission Declaration
  • Prompt InjectionInstruction Override, Hidden Instructions, Exfiltration Commands
  • Privilege EscalationExcessive Permissions, Sudo/Root Execution, Credential Access
  • Supply ChainUnpinned Dependencies, External Script Fetching, Obfuscated Code
Findings (3)

Undeclared Tool Scope

Medium
Category
MCP Least Privilege
Confidence
89% confidence
Finding

The skill exposes commands that invoke Node-based scripts which can reasonably access environment variables and make network requests, but the manifest does not declare any tool scope restrictions such as permissions or allowed-tools. This creates an unnecessary trust gap: an agent or reviewer cannot tell from the manifest what capabilities are intended, and a modified or unexpected script could use undeclared network or env access to exfiltrate data or perform unintended external actions.

Content

No source excerpt is available for this finding.

External Transmission

Medium
Category
Data Exfiltration
Confidence
50% confidence
Finding

Data is being sent to an external URL. This could be legitimate telemetry or data exfiltration. Manual review is recommended.

Content

Scanner excerpt · scripts/kalshi_paper.ts (reported line 221)May include surrounding context.

ts
const raw =
    (args["kalshi-base-url"] as string | undefined) ??
    process.env.KALSHI_BASE_URL ??
    "https://api.elections.kalshi.com/trade-api/v2";
  return raw.replace(/\/+$/, "");
}

Missing User Warnings

Low
Category
Not specified by scanner
Confidence
78% confidence
Finding

This markdown file documents mark as writing current market state and reconcile as settling finalized positions, which are data-modifying operations. The section explains what the commands do, but it does not include any warning about their effects on stored ledger state, potential overwrites, or the need to verify inputs before running them.

Content

No source excerpt is available for this finding.

Static analysis

Detected: suspicious.dangerous_exec, suspicious.env_credential_access

Shell command execution detected (child_process).

Critical
Code
suspicious.dangerous_exec
Location
tests/kalshi_paper.test.mjs:21

Environment variable access combined with network send.

Critical
Code
suspicious.env_credential_access
Location
scripts/kalshi_paper.ts:220