require 'brakeman/checks/base_check'

#Checks for select() helper vulnerability in some versions of Rails 3
#http://groups.google.com/group/rubyonrails-security/browse_thread/thread/9da0c515a6c4664
class Brakeman::CheckSelectVulnerability < Brakeman::BaseCheck
  Brakeman::Checks.add self

  @description = "Looks for unsafe uses of select() helper"

  def run_check

    if lts_version? "2.3.18.7"
      return
    elsif version_between? "3.0.0", "3.0.11"
      suggested_version = "3.0.12"
    elsif version_between? "3.1.0", "3.1.3"
      suggested_version = "3.1.4"
    elsif version_between? "3.2.0", "3.2.1"
      suggested_version = "3.2.2"
    elsif version_between? "2.0.0", "2.3.14"
      suggested_version = "3 or use options_for_select"
    else
      return
    end

    @message = "Upgrade to Rails #{suggested_version}, #{tracker.config[:rails_version]} select() helper is vulnerable"

    calls = tracker.find_call(:target => nil, :method => :select).select do |result|
      result[:location][:type] == :template
    end

    calls.each do |result|
      process_result result
    end
  end

  def process_result result
    return if duplicate? result

    third_arg = result[:call].third_arg

    #Check for user input in options parameter
    if sexp? third_arg and include_user_input? third_arg
      add_result result

      if node_type? third_arg, :string_interp, :dstr
        confidence = CONFIDENCE[:med]
      else
        confidence = CONFIDENCE[:low]
      end

      warn :template => result[:location][:template],
          :warning_type => "Cross Site Scripting",
          :warning_code => :select_options_vuln,
          :result => result,
          :message => @message,
          :confidence => confidence
    end
  end
end
