subagent-cortex-code icon indicating copy to clipboard operation
subagent-cortex-code copied to clipboard

Security Review: 5 new Critical + 21 prior findings still open (post-hardening)

Open ieatgybs opened this issue 7 months ago • 1 comments

Context

We ran a comprehensive security review of this skill on 2026-04-23 (pre-hardening) and again on 2026-04-30 (post-hardening, commit a455d30). The first review identified 5 Critical, 9 High, 11 Medium, and 12 Low findings. We used multiple parallel security review agents covering execution scripts, security modules, shell wrappers, config/SKILL.md files, and the test suite.

The hardening commits fixed the most impactful items — thank you. The shipped config.yaml default, subprocess management, --bypass removal, shell=True, and broken test imports are all resolved. However, 21 prior findings remain open and 17 new findings were discovered, including 5 new Critical issues concentrated in the security modules and shell wrappers.


Prior Findings: What's Fixed (Thank You!)

# Finding Status
C1 Shipped config.yaml defaults to auto FIXED
C2 Org-policy bypass via --input-format stream-json FIXED
C5 Shell wrappers crash (--output-file argparse) FIXED
C6 No subprocess timeout FIXED
C7 Subprocess orphaned on exception FIXED
C8 stderr deadlock FIXED
C9 discover_cortex indentation bug FIXED
C10 Session file read no size limit FIXED
C11 shell=True in discover_cortex.py FIXED
C12 Shared test imports wrong symbol FIXED
H8 --bypass flag in script copies FIXED

Prior Findings: Still Open

Critical (2 remaining)

# Finding Detail
C3 DEPLOY envelope Shares DESTRUCTIVE_SHELL_TOOLS blocklist with RW, but deploy_envelope_confirmation config flag is never read or
enforced anywhere
C4 Bash blocklist patterns Bash(rm *) pattern likely doesn't match actual Cortex CLI tool invocations; Bash tool itself never blocked
in RO/RESEARCH

High (8 remaining)

# Finding
H1 $OUTPUT_FILE interpolated into python3 -c string in execute_cortex_codex.sh:61 — shell injection
H2 Predictable /tmp/codex-cortex-latest.json — symlink race
H3 Prompt injection regex trivially bypassable (no Unicode normalization)
H4 API_KEY_PATTERN compiled but disabled (commented out) in prompt_sanitizer.py
H5 Overly broad routing keywords (stream, task, stage, pipe) intercept non-Snowflake prompts
H6 CORTEX_SKILL_ORG_POLICY env var lets users redirect org policy to permissive file
H7 Credential path detection uses naive substring matching (.env matches "environment")
H9 Incomplete KNOWN_TOOLS list — unknown tools silently allowed through

Medium (11 remaining)

All 11 medium findings from the prior review remain open (config escalation, cache integrity, audit log integrity, TOCTOU, error output leaks, LLM routing manipulation, security wrapper bypass, RW envelope blocklist, unquoted sed variable, 644 permissions, no prompt-mode audit logging).


New Findings (Post-Hardening)

New Critical (5)

N-C1: envelope="NONE" disables all tool restrictions

  • File: execute_cortex.py:108-124
  • NONE is a valid argparse choice, but when selected, envelope_tools stays [] — zero tools blocked. No allowed_envelopes check in execute_cortex.py (only checked in security_wrapper.py). Direct invocation with --envelope NONE --approval-mode auto = unrestricted execution.
  • Fix: Reject NONE in auto/envelope_only mode, or remove it from argparse choices.

N-C2: Unicode/zero-width bypass of ALL injection detection

  • File: security/prompt_sanitizer.py:33-39
  • No unicodedata.normalize(), no zero-width character stripping. Every injection pattern defeated by: Cyrillic homoglyphs (ignоre with Cyrillic о), zero-width spaces (ignoreall), non-breaking spaces, full-width characters.
  • Fix: Add unicodedata.normalize('NFKD', text) and strip zero-width characters before pattern matching.

N-C3: User config can escalate to auto without org policy

  • File: security/config_manager.py:114-160
  • 3-layer precedence (org > user > defaults) only works when org policy exists. Without it, user config freely overrides defaults. A user can create config.yaml with approval_mode: auto and bypass all approval prompts.
  • Fix: Add an immutable security floor that user config cannot relax without org policy present.

N-C4: Stale insecure /tmp/cortex-capabilities.json in predict_tools.py

  • File: shared/scripts/predict_tools.py:43
  • While discover_cortex.py correctly uses CacheManager, predict_tools.py still reads from world-writable /tmp/. Cache poisoning affects tool predictions, potentially tricking approval prompts into showing fewer tools than will execute.
  • Fix: Use CacheManager consistently across all scripts.

N-C5: Cursor SKILL.md hardcodes --approval-mode "auto"

  • File: integrations/cursor/SKILL.md:49
  • All Cursor examples pass --approval-mode "auto", contradicting the stated prompt default. Cursor users get auto-approval by design.
  • Fix: Remove --approval-mode "auto" from Cursor SKILL.md examples.

New High (6)

# Finding File Detail
N-H1 World-readable /tmp/cortex-capabilities.json predict_tools.py:43 Any user can read (leaks capabilities) or write (poisons
predictions)
N-H2 Async nohup process orphaned execute_cortex_async.sh:51-52 PID not persisted; no watchdog; background process lives indefinitely
N-H3 Audit log trivially tamperable audit_logger.py:86-94 Plain JSON lines; no HMAC/hash chain; user can modify own audit trail
N-H4 Cache fingerprint self-signed cache_manager.py:51-73 SHA-256 stored alongside data; attacker recomputes hash after modification
N-H5 SKILL.md files reference /tmp/ for cache SKILL.md:66 LLM may follow literally, bypassing secure CacheManager
N-H6 Install scripts set permissive permissions install.sh:38 chmod +x on .py files; chmod 644 on config; world-readable on
shared systems

New Medium (6)

# Finding File Detail
N-M1 --output-file path traversal execute_cortex.py:339-341 No path validation; mkdir(parents=True) creates arbitrary directories
N-M2 5-second timeout default in security wrapper security_wrapper.py:227 execution_timeout_seconds not in DEFAULT_CONFIG; falls
back to 5s
N-M3 Dry-run mode leaks unsanitized prompt security_wrapper.py:128-149 Returns original PII alongside sanitized version
N-M4 __CODING_AGENT__ placeholder in audit path config_manager.py:22 If sed replacement fails, audit logs go to nonexistent
directory
N-M5 Codex config documents sandbox escape integrations/codex/cortexcode-tool-codex.yaml:3-4 Comment describes using ~/.cache/ to
escape Codex sandbox
N-M6 --bypass flag still documented in SKILL.md SKILL.md:295 "Avoids using --bypass" teaches LLMs the flag exists

Test Suite Gaps

Issue Severity
2 stub tests (test_envelope_ro_restrictions, test_envelope_rw_permissions) contain only pass Critical
No test verifies sanitized prompt reaches subprocess.Popen (mock hides handoff) Critical
3 material drifts between scripts/security_wrapper.py and shared/scripts/security_wrapper.py Critical
Zero adversarial sanitizer bypass tests (Unicode, zero-width, encoding) Critical
No property-based testing (hypothesis) for prompt sanitizer High

Suggested Priority Order

# Fix Effort Impact
1 Remove --approval-mode "auto" from Cursor SKILL.md 5 min Closes Cursor auto-approval gap
2 Add Unicode normalization + zero-width stripping to prompt sanitizer 30 min Makes injection detection functional
3 Replace /tmp/cortex-capabilities.json with CacheManager in predict_tools.py 15 min Closes cache poisoning in tool predictions
4 Block NONE envelope in execute_cortex.py 10 min Prevents unrestricted execution
5 Fix $OUTPUT_FILE injection in execute_cortex_codex.sh (use sys.argv) 5 min Closes shell injection
6 Replace predictable /tmp/codex-cortex-latest.json with mktemp 5 min Closes symlink race
7 Add security floor to config_manager.py 30 min Prevents config-based bypass
8 Set 0600/0700 permissions in install scripts 10 min Shared system protection
9 Update SKILL.md to reference ~/.cache/cortex-skill/ 10 min Prevents LLM from using insecure path
10 Fix stub tests + add adversarial sanitizer tests 1 hr Closes critical test gaps

Overall Verdict

Improved from CRITICAL to HIGH risk. Not yet suitable for general enterprise deployment.

The team fixed the most impactful items (config defaults, subprocess management, bypass removal). But 21 prior findings remain open, and the security modules added to address the prior review contain their own vulnerabilities. The prompt sanitizer is trivially bypassable, the Cursor integration ships with auto-approval, and shell wrapper scripts were barely touched.

We're happy to re-review after fixes are applied. Full detailed report available upon request.

ieatgybs avatar May 01 '26 16:05 ieatgybs

Thanks for the detailed security review. PR #14 addresses the issue #13 findings across both supported routes:

  • Claude/Cursor skill route
  • Codex/terminal cortexcode-tool CLI route

Resolution Summary

Finding Status Fix
Cursor auto-approval gap Fixed Removed forced --approval-mode "auto" behavior. Direct execute wrappers now
default to approval_mode: prompt.
Unicode / zero-width sanitizer bypass Fixed Added Unicode normalization, zero-width stripping, homoglyph handling,
and adversarial sanitizer tests.
/tmp/cortex-capabilities.json cache poisoning Fixed Replaced insecure predictable temp cache usage with
CacheManager and secure cache handling.
NONE envelope unrestricted execution Fixed NONE is now rejected before Cortex execution in both skill wrappers
and cortexcode-tool.
$OUTPUT_FILE injection Fixed Shell/Python wrapper now passes output path safely via sys.argv instead of
interpolating shell variables into Python source.
/tmp/codex-cortex-latest.json symlink race Fixed Replaced predictable latest-output temp path with mktemp /
unpredictable temp-file handling.
Config escalation Fixed User config can no longer lower approval_mode from prompt to auto or expand allowed
envelopes unless org policy explicitly authorizes that field/value.
Cache integrity Fixed Cache writes now use secure cache management and integrity checks instead of unauthenticated
predictable temp files.
Audit log integrity Fixed Added audit hash-chain behavior and prompt-mode audit logging for awaiting-approval
events.
TOCTOU / predictable temp file risk Fixed Removed predictable temp paths in Codex wrapper flow and replaced with
safer temp-file creation.
Error output leaks Fixed Error output now redacts sensitive tokens/API-key style values before surfacing/logging.
LLM routing manipulation Fixed Routing logic now context-gates broad Snowflake terms and fail-closes unknown tool
inversion paths.
Security wrapper bypass Fixed security_wrapper.py and cortexcode-tool now gate requested envelopes against
security.allowed_envelopes before routing, approval, or Cortex execution.
RW envelope blocklist Fixed RW retains explicit destructive shell blocklist coverage.
DEPLOY restrictions Fixed DEPLOY requires explicit confirmation and keeps destructive shell restrictions.
Unquoted sed / shell injection risk Fixed Install/wrapper code avoids unsafe shell interpolation; Python
replacement is used where needed.
0644 / shared-system permissions Fixed Install scripts now set private permissions: directories 0700, sensitive
configs/files 0600, launchers/scripts executable-private.
Prompt-mode audit logging Fixed Prompt-mode awaiting-approval events are audited.
Stub tests Fixed Stub/pass-only tests were replaced or supplemented with real assertions and adversarial
regression tests.
Insecure cache path docs Fixed SKILL/docs now reference secure cache locations such as ~/.cache/cortex-skill/.

Additional Fixes From Follow-Up Verification

During manual Codex/Claude verification we found and fixed additional edge cases:

  • cortexcode-tool --envelope NONE originally parsed NONE but ignored the CLI envelope and used the config default. Fixed so CLI envelope overrides are honored and NONE is blocked before Cortex execution.
  • cortexcode-tool originally did not enforce security.allowed_envelopes. Fixed so disallowed envelopes are blocked before routing, approval, or Cortex execution.
  • An unrelated org policy file originally skipped the security floor. Fixed so org policy must explicitly authorize approval-mode relaxation or envelope expansion.
  • Local Codex launcher was corrected to import cortexcode_tool.main as a package module instead of executing main.py directly.

Verification Performed

Validated both local installs and repo source:

  • Claude skill: ~/.claude/skills/cortex-code
  • Codex CLI: ~/.local/bin/cortexcode-tool
  • Codex package: ~/.local/lib/cortexcode-tool
  • Repo source under PR #14

Test results:

  • Targeted CLI/security/config tests: 65 passed
  • Full test suite: 308 passed
  • Local cortexcode-tool --validate-config:
    • Approval mode: prompt
    • Default envelope: RW
  • Active scan confirmed:
    • no active approval_mode defaulting to auto
    • no active executable --input-format command construction
  • Local permission checks confirmed:
    • ~/.local/bin/cortexcode-tool → 0700
    • ~/.local/lib/cortexcode-tool → 0700
    • ~/.claude/skills/cortex-code → 0700
  • Local envelope smoke confirmed:
    • disallowed DEPLOY with allowed_envelopes: [RO] exits before routing/execution
    • NONE envelope exits before Cortex execution
    • no Cortex session starts for blocked envelopes

PR #14 is currently clean and contains the complete fix set for issue #13.

sfc-gh-tjia avatar May 05 '26 02:05 sfc-gh-tjia