Fix Command Injection in Grape
Command injection in Grape APIs occurs when unsanitized parameters are passed directly to shell interpreters. In Ruby, using backticks, %x, or string-based system calls allows an attacker to append malicious payloads via shell metacharacters like semicolon, pipe, or backticks. To mitigate this, you must avoid the shell entirely by using array-based execution or strict allow-listing.
The Vulnerable Pattern
class VulnerableAPI < Grape::API
format :json
params do
requires :image_id, type: String
end
get :metadata do
# DANGER: String interpolation into backticks invokes /bin/sh
# Payload example: image_id = '1; rm -rf /'
metadata = `identify #{params[:image_id]}`
{ data: metadata }
end
end
The Secure Implementation
The vulnerability stems from the Ruby backtick method (` `) which executes the string in a subshell. By passing an array to 'Open3.capture3' (or 'system' with multiple arguments), the OS executes the binary directly without spawning a shell. This ensures that the user-provided 'image_id' is treated strictly as a literal argument rather than a command sequence. Always validate input types and use POSIX-compliant argument passing to neutralize shell metacharacters.
require 'open3'
class SecureAPI < Grape::API format :json params do requires :image_id, type: String end get :metadata do # SECURE: Pass arguments as an array to bypass shell parsing begin stdout, stderr, status = Open3.capture3(‘identify’, params[:image_id]) if status.success? { data: stdout } else error!({ error: ‘Process failed’, details: stderr }, 400) end rescue Errno::ENOENT error!({ error: ‘Executable not found’ }, 500) end end end
Your Grape API
might be exposed to Command Injection
74% of Grape apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.
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.