Fix SQL Injection (Legacy & Modern) in Sinatra
Sinatra's simplicity is a vulnerability magnet if you're handling DB queries like it's 2005. Whether you're using raw SQL with the 'pg' gem or an ORM like ActiveRecord/Sequel, string interpolation in your query logic is an invitation for a total database takeover. Stop concatenating user input into your SQL strings unless you want your entire schema dumped via a simple UNION SELECT.
The Vulnerable Pattern
get '/user/:username' do # FATAL: Direct string interpolation into the query @user = User.find_by_sql("SELECT * FROM users WHERE username = '#{params[:username]}' LIMIT 1") @user.to_json endOr via raw Sequel:
DB[“SELECT * FROM users WHERE username = ’#{params[:username]}’“]
The Secure Implementation
The vulnerability stems from treating untrusted user input as executable SQL code. By using string interpolation ('#{...}'), an attacker can inject control characters like single quotes to break out of the data context and append malicious commands. The fix is Parameterized Queries (Prepared Statements). By using the '?' placeholder or ORM hash syntax, the database driver is instructed to treat the input strictly as a literal value (data), effectively neutralizing any SQL control characters before the query hits the engine.
get '/user/:username' do # Modern approach: Use ActiveRecord's built-in parameterization @user = User.find_by(username: params[:username])Legacy/Manual approach: Use array-based placeholders
@user = User.find_by_sql([‘SELECT * FROM users WHERE username = ? LIMIT 1’, params[:username]])
@user.to_json end
Raw Sequel fix:
DB[‘SELECT * FROM users WHERE username = ?’, params[:username]]
Your Sinatra API
might be exposed to SQL Injection (Legacy & Modern)
74% of Sinatra 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.