ruby.aws-lambda.security.pg-sqli.pg-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: conn.exec_params('SELECT $1 AS a, $2 AS b, $3 AS c', [1, 2, nil])

Run Locally

Run in CI

Defintion

rules:
  - id: pg-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:
      `conn.exec_params('SELECT $1 AS a, $2 AS b, $3 AS c', [1, 2, nil])`"
    mode: taint
    metadata:
      references:
        - https://www.rubydoc.info/gems/pg/PG/Connection
      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
        - postgres
        - pg
      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: $CONN.exec($QUERY,...)
              - pattern: $CONN.exec_params($QUERY,...)
              - pattern: $CONN.exec_prepared($QUERY,...)
              - pattern: $CONN.async_exec($QUERY,...)
              - pattern: $CONN.async_exec_params($QUERY,...)
              - pattern: $CONN.async_exec_prepared($QUERY,...)
          - pattern-inside: |
              require 'pg'
              ...
    pattern-sources:
      - patterns:
          - pattern: event
          - pattern-inside: |
              def $HANDLER(event, context)
                ...
              end
    severity: WARNING

Examples

pg-sqli.rb

require 'pg'

def show(event:, context:)
  conn = PG::Connection.open(:dbname => 'test')

  # ok: pg-sqli
  res = conn.exec_params('SELECT $1 AS a, $2 AS b, $3 AS c', [event['id'], 2, nil])

  # ruleid: pg-sqli
  res2 = conn.exec_params('SELECT * FROM foobar WHERE id = %{id}' % {id: event['id']})

  {
    body: res2
  }
end