GuardAPI Logo
GuardAPI

Fix Command Injection in Hapi

Command Injection in Hapi.js occurs when untrusted input from 'request.payload', 'request.params', or 'request.query' is passed directly to system shell execution functions. This allows an attacker to break out of the intended command using shell metacharacters like ';', '&&', or '|' to achieve Remote Code Execution (RCE). Stop using 'child_process.exec' with template literals; it's a massive security hole.

The Vulnerable Pattern

const { exec } = require('child_process');

server.route({ method: ‘POST’, path: ‘/v1/system/ping’, handler: (request, h) => { const { target } = request.payload; // VULNERABLE: Input is concatenated into a shell command string exec(ping -c 1 ${target}, (error, stdout, stderr) => { if (error) console.error(error); console.log(stdout); }); return { status: ‘pinged’ }; } });

The Secure Implementation

The vulnerability exists because 'child_process.exec' invokes '/bin/sh' to parse the command string, allowing shell injection. The fix involves two primary steps: 1. Replace 'exec' with 'execFile' or 'spawn'. These functions execute the binary directly and pass arguments as an array, which prevents the shell from interpreting metacharacters. 2. Implement strict input validation using Hapi's 'Joi' integration to ensure the input matches an expected pattern (like a hostname or IP address) before it even reaches the handler.

const { execFile } = require('child_process');
const Joi = require('joi');

server.route({ method: ‘POST’, path: ‘/v1/system/ping’, options: { validate: { payload: Joi.object({ // DEFENSE-IN-DEPTH: Strict input validation target: Joi.string().hostname().required() }) } }, handler: (request, h) => { const { target } = request.payload; // SECURE: execFile does not spawn a shell by default and treats arguments as literal strings execFile(‘/bin/ping’, [‘-c’, ‘1’, target], (error, stdout, stderr) => { if (error) console.error(error); console.log(stdout); }); return { status: ‘pinged’ }; } });

System Alert • ID: 5885
Target: Hapi API
Potential Vulnerability

Your Hapi API might be exposed to Command Injection

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