logo

Database

Ruby Sql Injection User Input

Description

SQL injection vulnerability in Ruby applications where unvalidated user input flows into database queries. This allows attackers to manipulate the query structure and potentially access, modify or delete sensitive data by injecting malicious SQL commands.

Weakness:

297 - SQL injection - Code

Category: Unexpected Injection

Detection Strategy

    Checks if relevant database libraries are imported (sinatra, active_record, pg, sqlite3)

    Identifies database query execution methods that are known to be vulnerable to SQL injection

    Examines if the first argument passed to these query methods contains user-controlled input

    Verifies that no proper SQL sanitization or parameterization is applied to the user input

    Reports a vulnerability when user input reaches a database query without adequate protection

Vulnerable code example

require 'sinatra'
require 'active_record'

get '/users/search' do
    # User input directly interpolated into SQL query - SQL injection vulnerability
    name = params['name']
    User.where("name = '#{name}'").to_json  # Vulnerable: No sanitization of user input
end

✅ Secure code example

require 'sinatra'
require 'active_record'

get '/users/search' do
  # Secure: Using hash syntax prevents SQL injection by automatic parameterization
  User.where(name: params['name']).to_json
end