Course contentsShow
← Security
Lesson 609 of 3,05213. Web Security - Injection AttacksFree lesson

Command Injection Prevention: Input Validation

Implementing strict allowlists, avoiding shell invocation, and validating all user-supplied parameters.

Command Injection Prevention: Input Validation

You'll learn how to stop command injection attacks by strictly controlling what input your application accepts.

Now that you understand how attackers exploit command injection vulnerabilities, it's time to lock the door. Prevention revolves around three core principles: allowlists, avoiding shell invocation, and parameter validation.

The Three Pillars of Protection

1. Strict Allowlists (Not Blocklists)

Think of this like a VIP guest list at an exclusive event—only explicitly approved items get through. Instead of trying to block dangerous characters (which attackers can bypass), define exactly what is allowed.

For example, if your application expects a filename, only accept alphanumeric characters and specific extensions:

  • ✅ Allow: report_2024.pdf
  • ❌ Reject: report; rm -rf /

2. Avoid Shell Invocation

Whenever possible, use direct API calls instead of spawning a shell. Instead of executing ping [user_input] through a shell, use your language's built-in networking libraries. No shell means no shell metacharacters to exploit.

3. Validate All User-Supplied Parameters

Every input is suspect. Validate:

  • Format: Does it match expected patterns (regex)?
  • Type: Is it the correct data type?
  • Length: Is it within reasonable bounds?
  • Content: Does it contain only allowlisted characters?

The Allowlist Approach

Instead of blacklisting ;, |, &, $(), attackers will find new ways around your filters. An allowlist approach defines: "Only letters A-Z, numbers 0-9, and underscores are permitted." Everything else is rejected—no exceptions.

Key Takeaway: Command injection prevention requires strict allowlisting of valid inputs, avoiding shell invocation when possible, and rigorously validating every user-supplied parameter against expected formats—never trust user input.