SQL Injection High

User input is fed into an SQL command. This allows a user to execute an SQL command injection and run custom actions, which could leak sensitive data or delete data in the database. Ensure the user does not have direct influence on the command.

Detector ID
ruby/sql-injection@v1.0
Category
Common Weakness Enumeration (CWE) external icon
Tags
-

Noncompliant example

1require 'pg'
2
3def sql_injection_noncompliant(event:, context:)
4  conn = PG::Connection.open(:dbname => 'test')
5
6  # Noncompliant: User-controlled parameter is used in SQL Statement.
7  res2 = conn.exec_params('SELECT * FROM foobar WHERE id = %{id}' % {id: event['id']})
8  
9end

Compliant example

1require 'pg'
2
3def sql_injection_compliant(event:, context:)
4  conn = PG::Connection.open(:dbname => 'test')
5
6  # Compliant: Parameterized SQL Statement.
7  res = conn.exec_params('SELECT $1 AS a, $2 AS b, $3 AS c', [event['id'], 2, nil])
8  
9end