GuardAPI Logo
GuardAPI

Fix Command Injection in NestJS

Command injection in NestJS occurs when unsanitized user input reaches Node.js sub-process functions like child_process.exec(). Because exec() invokes a shell (/bin/sh or cmd.exe), it interprets shell metacharacters (;, |, &, $), allowing an attacker to escape the intended command and achieve Remote Code Execution (RCE).

The Vulnerable Pattern

import { Controller, Get, Query } from '@nestjs/common';
import { exec } from 'child_process';

@Controller(‘tools’) export class ToolsController { @Get(‘nslookup’) lookup(@Query(‘domain’) domain: string) { // CRITICAL VULNERABILITY: User input is concatenated directly into a shell command // Payload example: ?domain=google.com; cat /etc/passwd exec(nslookup ${domain}, (err, stdout) => { console.log(stdout); }); } }

The Secure Implementation

To remediate command injection, stop using child_process.exec(). Instead, use child_process.spawn() or child_process.execFile(). These functions do not spawn a shell by default; they execute the binary directly. By passing arguments as an array rather than a single string, the OS treats the input as literal data rather than executable shell code. Additionally, always implement strict input validation using a DTO with class-validator or manual regex to ensure the input conforms to expected patterns before it ever touches a system call.

import { Controller, Get, Query, BadRequestException } from '@nestjs/common';
import { spawn } from 'child_process';

@Controller(‘tools’) export class ToolsController { @Get(‘nslookup’) async lookup(@Query(‘domain’) domain: string) { // 1. Strict Input Validation (Allowlist/Regex) if (!/^[a-zA-Z0-9.-]+$/.test(domain)) { throw new BadRequestException(‘Invalid domain format’); }

// 2. Use spawn() with an arguments array to bypass shell parsing
return new Promise((resolve, reject) => {
  const child = spawn('nslookup', [domain]);
  let output = '';
  
  child.stdout.on('data', (data) => output += data.toString());
  child.on('close', () => resolve({ result: output }));
  child.on('error', (err) => reject(err));
});

} }

System Alert • ID: 7455
Target: NestJS API
Potential Vulnerability

Your NestJS API might be exposed to Command Injection

74% of NestJS apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.

RUN FREE SECURITY DIAGNOSTIC
GuardLabs Engine: ONLINE

Free Tier • No Credit Card • Instant Report

Verified by Ghost Labs Security Team

This content is continuously validated by our automated security engine and reviewed by our research team. Ghost Labs analyzes over 500+ vulnerability patterns across 40+ frameworks to provide up-to-date remediation strategies.