GuardAPI Logo
GuardAPI

Fix Command Injection in Hanami

Command injection is a critical vulnerability that occurs when a Hanami application passes unvalidated user input directly to a system shell. In Ruby-based frameworks like Hanami, this typically happens via backticks, %x, system(), or exec(). An attacker can use shell metacharacters like ; or | to execute arbitrary code with the privileges of the web server process.

The Vulnerable Pattern

module Web::Actions::Reports
  class Show < Web::Action
    def handle(req, res)
      # VULNERABLE: User input from params is interpolated directly into a shell command
      report_id = req.params[:id]
      res.body = `cat ./reports/report_#{report_id}.txt` 
    end
  end
end

The Secure Implementation

The vulnerability exists because Ruby's backticks invoke a subshell to parse the string, allowing characters like '; rm -rf /' to be executed. The fix involves using the Open3 module or system() with multiple arguments. When arguments are passed as a list, Ruby executes the binary directly (execve) without spawning a shell, which prevents the interpretation of shell metacharacters. Additionally, always validate input types and patterns using Hanami::Validations to ensure the input matches expected formats (e.g., integers only).

require 'open3'

module Web::Actions::Reports class Show < Web::Action def handle(req, res) report_id = req.params[:id]

  # SECURE: Use Open3.capture3 with separate arguments to bypass the shell
  # This ensures the input is treated as a literal argument, not a command
  stdout, stderr, status = Open3.capture3("cat", "./reports/report_#{report_id}.txt")

  if status.success?
    res.body = stdout
  else
    res.status = 404
    res.body = "Report not found"
  end
end

end end

System Alert • ID: 7402
Target: Hanami API
Potential Vulnerability

Your Hanami API might be exposed to Command Injection

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