Course contentsShow
← Security
Lesson 1230 of 3,05225. Application Security - Secure CodingFree lesson

Safe Command Execution Patterns

Learn to safely execute external commands using parameterized APIs, argument arrays, and avoiding shell interpretation.

Safe Command Execution Patterns

What you'll learn: How to execute external commands securely by avoiding shell interpretation and using parameterized APIs that prevent injection attacks.

When your application needs to run external programs (like image processors, system utilities, or scripts), the wrong approach can let attackers inject malicious commands. As we learned, shell injection is a critical risk. The solution is to execute commands without involving a shell interpreter.

The Core Problem

Functions that invoke a shell (like system(), exec() with shell interpretation, or backticks) treat your entire command as a string. If user input mixes into that string, attackers can insert semicolons, pipes, or other shell metacharacters to run arbitrary commands.

Analogy: Asking someone to "deliver this message exactly as written" is safe. But saying "interpret and act on this message however you think best" opens the door to misunderstanding—or malicious creativity.

The Safe Pattern: Parameterized Execution

Use APIs that accept the program path and arguments as separate array elements, not concatenated strings:

  • Instead of: system("convert " + userFile + " output.png") ❌
  • Use: An array-based API where the executable and each argument are distinct items

The safe approach treats the program name and each argument as independent values. The operating system passes them directly to the target program without shell parsing, so metacharacters lose their special meaning.

Key Principles

  1. Argument arrays, not string concatenation — Each parameter is a separate array element
  2. No shell interpretation — Bypass sh, cmd.exe, or similar interpreters
  3. Validate the command itself — Only allow execution of known, approved programs
  4. Validate arguments — Even without a shell, ensure inputs match expected formats

Key Takeaway: Always execute external commands using parameterized APIs that accept argument arrays and avoid shell interpretation—this prevents injected metacharacters from being interpreted as commands.