ruby.lang.security.bad-deserialization-env.bad-deserialization-env

profile photo of semgrepsemgrep
Author
unknown
Download Count*

Checks for unsafe deserialization. Objects in Ruby can be serialized into strings, then later loaded from strings. However, uses of load and object_load can cause remote code execution. Loading user input with MARSHAL or CSV can potentially be dangerous. Use JSON in a secure fashion instead.

Run Locally

Run in CI

Defintion

rules:
  - id: bad-deserialization-env
    mode: taint
    pattern-sources:
      - pattern-either:
          - pattern: request.env
    pattern-sinks:
      - pattern-either:
          - pattern: |
              CSV.load(...)
          - pattern: |
              Marshal.load(...)
          - pattern: |
              Marshal.restore(...)
          - pattern: |
              Oj.object_load(...)
          - pattern: |
              Oj.load($X)
    message: Checks for unsafe deserialization. Objects in Ruby can be serialized
      into strings, then later loaded from strings. However, uses of load and
      object_load can cause remote code execution. Loading user input with
      MARSHAL or CSV can potentially be dangerous. Use JSON in a secure fashion
      instead.
    metadata:
      references:
        - https://groups.google.com/g/rubyonrails-security/c/61bkgvnSGTQ/m/nehwjA8tQ8EJ
        - https://github.com/presidentbeef/brakeman/blob/main/lib/brakeman/checks/check_deserialize.rb
      category: security
      cwe:
        - "CWE-502: Deserialization of Untrusted Data"
      owasp:
        - A08:2017 - Insecure Deserialization
        - A08:2021 - Software and Data Integrity Failures
      technology:
        - ruby
      cwe2022-top25: true
      cwe2021-top25: true
      subcategory:
        - vuln
      likelihood: LOW
      impact: HIGH
      confidence: LOW
      license: Commons Clause License Condition v1.0[LGPL-2.1-only]
      vulnerability_class:
        - "Insecure Deserialization "
    languages:
      - ruby
    severity: ERROR

Examples

bad-deserialization-env.rb

 def bad_deserialization
   data = request.env[:name]
   # ruleid: bad-deserialization-env
   obj = Marshal.load(data)

   o = Klass.new(request.env[:name])
   data = CSV.dump(o)
   # ruleid: bad-deserialization-env
   obj = CSV.load(data)

   o = Klass.new("hello\n")
   data = request.env[:name]
   # ruleid: bad-deserialization-env
   obj = Oj.object_load(data)
   # ruleid: bad-deserialization-env
   obj = Oj.load(data)
   # ok: bad-deserialization-env
   obj = Oj.load(data,options=some_safe_options)
 end

 def ok_deserialization
    o = Klass.new("hello\n")
    data = CSV.dump(o)
    # ok: bad-deserialization-env
    obj = CSV.load(data)
    
    data = get_safe_data()
    # ok: bad-deserialization-env
    obj = Marshal.load(data)
 end