GuardAPI Logo
GuardAPI
GuardAPI Logo GuardAPI

Fix Command Injection in AdonisJS

Command Injection in AdonisJS is a critical flaw where unsanitized user input reaches system execution functions. When developers use child_process.exec to run shell commands, they provide an entry point for attackers to escape the intended command context using shell metacharacters (e.g., ;, &&, |). This results in full Remote Code Execution (RCE) under the privileges of the Node.js process.

The Vulnerable Pattern

import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext';
import { exec } from 'child_process';

export default class BackupController { public async download({ request }: HttpContextContract) { const { filename } = request.all(); // VULNERABLE: Input is concatenated directly into a shell string exec(tar -czf ./backups/${filename}.tar.gz ./data, (err, stdout) => { if (err) return; console.log(‘Backup created’); }); } }

The Secure Implementation

The fix involves two layers of defense. First, replace 'child_process.exec' with 'child_process.spawn'. Unlike exec, spawn does not create a new shell process by default; it executes the binary directly, passing parameters as a discrete array which prevents shell metacharacter interpretation. Second, implement strict input validation using a whitelist Regex to ensure the input contains only expected characters, effectively neutralizing any attempt to inject malicious payloads even if the execution method were compromised.

import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext';
import { spawn } from 'child_process';

export default class BackupController { public async download({ request, response }: HttpContextContract) { const { filename } = request.all();

// 1. Strict Input Validation (Whitelisting)
if (!/^[a-zA-Z0-9_-]+$/.test(filename)) {
  return response.status(400).send('Invalid filename characters');
}

// 2. Use spawn() with an arguments array instead of exec()
// This avoids spawning a shell and treats arguments as literal data
const child = spawn('tar', ['-czf', `./backups/${filename}.tar.gz`, './data']);

child.on('exit', (code) => {
  console.log(`Process exited with code ${code}`);
});

} }

System Alert • ID: 9865
Target: AdonisJS API
Potential Vulnerability

Your AdonisJS API might be exposed to Command Injection

74% of AdonisJS 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.