Identify the critical security vulnerability in this Node.js code snippet that uses an environment variable.

Node.js interview question for Advanced practice.

Answer

The code is vulnerable to Command Injection because it directly concatenates an unsanitized environment variable into a shell command string.

Explanation

The primary vulnerability is Command Injection. The exec function spawns a shell and executes the command within it. Since the logFilePath variable is directly embedded in the command string, an attacker who can control this environment variable could inject arbitrary shell commands. For example, setting LOGFILEPATH to malicious.log; rm -rf / could execute a destructive command after the tail command completes. The fix is to avoid exec with un-sanitized input. Instead, use execFile, which does not spawn a shell and treats arguments as data, not executable commands.

Related Questions