ruby.aws-lambda.security.activerecord-sqli.activerecord-sqli

profile photo of semgrepsemgrep
Author
unknown
Download Count*

Detected SQL statement that is tainted by event object. This could lead to SQL injection if the variable is user-controlled and not properly sanitized. In order to prevent SQL injection, use parameterized queries or prepared statements instead. You can use parameterized statements like so: Example.find_by_sql ["SELECT title FROM posts WHERE author = ? AND created > ?", author_id, start_date]

Run Locally

Run in CI

Defintion

rules:
  - id: activerecord-sqli
    languages:
      - ruby
    message: 'Detected SQL statement that is tainted by `event` object. This could
      lead to SQL injection if the variable is user-controlled and not properly
      sanitized. In order to prevent SQL injection, use parameterized queries or
      prepared statements instead. You can use parameterized statements like so:
      `Example.find_by_sql ["SELECT title FROM posts WHERE author = ? AND
      created > ?", author_id, start_date]`'
    mode: taint
    metadata:
      references:
        - https://guides.rubyonrails.org/active_record_querying.html#finding-by-sql
      category: security
      owasp:
        - A01:2017 - Injection
        - A03:2021 - Injection
      cwe:
        - "CWE-89: Improper Neutralization of Special Elements used in an SQL
          Command ('SQL Injection')"
      technology:
        - aws-lambda
        - active-record
      cwe2022-top25: true
      cwe2021-top25: true
      subcategory:
        - vuln
      likelihood: MEDIUM
      impact: HIGH
      confidence: MEDIUM
      license: Commons Clause License Condition v1.0[LGPL-2.1-only]
      vulnerability_class:
        - SQL Injection
    pattern-sinks:
      - patterns:
          - pattern: $QUERY
          - pattern-either:
              - pattern: ActiveRecord::Base.connection.execute($QUERY,...)
              - pattern: $MODEL.find_by_sql($QUERY,...)
              - pattern: $MODEL.select_all($QUERY,...)
          - pattern-inside: |
              require 'active_record'
              ...
    pattern-sources:
      - patterns:
          - pattern: event
          - pattern-inside: |
              def $HANDLER(event, context)
                ...
              end
    severity: WARNING

Examples

activerecord-sqli.rb

require 'active_record'
require 'models/restaurant'

def show(event:, context:)
  ActiveRecord::Base.establish_connection(
    adapter: 'mysql2',
    host: ENV['RDS_HOST'],
    username: ENV['RDS_USERNAME'],
    password: ENV['RDS_PASSWORD'],
    database: ENV['RDS_DATABASE']
  )

  query = "SELECT * FROM customers INNER JOIN orders ON customers.id = %{id}" % {id: event["id"]}
  # ruleid: activerecord-sqli
  result = Platform.find_by_sql(query)

  # ok: activerecord-sqli
  result2 = Smth.find_by_sql("SELECT * FROM customers INNER JOIN orders ON customers.id = %{id}", {id: event["id"]})
  
  {
    body: [result, resul2]
  }
end