ruby.aws-lambda.security.mysql2-sqli.mysql2-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 sanitize statements like so: escaped = client.escape(user_input)

Run Locally

Run in CI

Defintion

rules:
  - id: mysql2-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 sanitize statements like so:
      `escaped = client.escape(user_input)`"
    mode: taint
    metadata:
      references:
        - https://github.com/brianmario/mysql2
      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
        - mysql2
      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: $CLIENT.query($QUERY,...)
              - pattern: $CLIENT.prepare($QUERY,...)
          - pattern-inside: |
              require 'mysql2'
              ...
    pattern-sanitizers:
      - pattern: $CLIENT.escape(...)
    pattern-sources:
      - patterns:
          - pattern: event
          - pattern-inside: |
              def $HANDLER(event, context)
                ...
              end
    severity: WARNING

Examples

mysql2-sqli.rb

require 'json'
require 'mysql2'

def mysql_client
  @mysql_client ||= Mysql2::Client.new(
    host: ENV['RDS_ARN'],
    username: 'rootuser',
    password: 'rootuser00',
    database: 'access_db',
    port: 3306
  )
end

def handler(event:, context:)
  # ok: mysql2-sqli
  mysql_client.query("CREATE TABLE access_table (id varchar(32) NOT NULL, timestamp varchar(32));")

  # ruleid: mysql2-sqli
  results = mysql_client.query("SELECT * FROM users WHERE group='#{event['id']}'")

  escaped = client.escape(event['id'])
  # ok: mysql2-sqli
  results2 = mysql_client.query("SELECT * FROM users WHERE group='#{escaped}'")

  {statusCode: 200, body: JSON.generate(results)}
end