Module: Ronin::Support::Encoding::SQL

Defined in:
lib/ronin/support/encoding/sql.rb

Overview

Contains methods for encoding/decoding escaping/unescaping SQL data.

Core-Ext Methods

Since:

  • 1.0.0

Constant Summary collapse

QUOTE_STYLES =

The quote styles and their quote characters.

Since:

  • 1.0.0

{
  single: "'",
  double: '"',
  tick:   '`'
}

Class Method Summary collapse

Class Method Details

.decode(data) ⇒ String

Returns the SQL decoded form of the String.

Parameters:

  • data (String)

    The SQL string to decode.

Returns:

  • (String)

    The decoded String.

Since:

  • 1.0.0



118
119
120
121
122
123
124
125
126
127
128
129
130
# File 'lib/ronin/support/encoding/sql.rb', line 118

def self.decode(data)
  if (data =~ /^[0-9a-fA-F]{2,}$/ && data.length.even?)
    raw = String.new

    data.scan(/../) do |hex_char|
      raw << hex_char.to_i(16)
    end

    return raw
  else
    unescape(data)
  end
end

.encode(data) ⇒ String

Returns the SQL hex-string encoded form of the String.

Parameters:

Returns:

Since:

  • 1.0.0



97
98
99
100
101
102
103
104
105
106
107
# File 'lib/ronin/support/encoding/sql.rb', line 97

def self.encode(data)
  return '' if data.empty?

  hex_string = String.new('0x')

  data.each_byte do |b|
    hex_string << ('%.2x' % b)
  end

  return hex_string
end

.escape(data, quotes: :single) ⇒ String

Escapes a String for SQL.

Parameters:

  • data (String)

    The String to SQL escape.

  • quotes (:single, :double, :tick) (defaults to: :single)

    Specifies whether to create a single or double quoted string.

Returns:

  • (String)

    The SQL escaped string.

Raises:

  • (ArgumentError)

    The quotes argument was neither :single, :double nor :tick.

Since:

  • 1.0.0



57
58
59
60
61
62
63
64
65
# File 'lib/ronin/support/encoding/sql.rb', line 57

def self.escape(data, quotes: :single)
  char = QUOTE_STYLES.fetch(quotes) do
           raise(ArgumentError,"invalid quoting style #{quotes.inspect}")
         end

  escaped = data.gsub(char,char * 2)

  return "#{char}#{escaped}#{char}"
end

.unescape(data) ⇒ String

Unescapes a SQL String.

Parameters:

  • data (String)

    The SQL string to unescape.

Returns:

  • (String)

    The unescaped SQL string value.

Raises:

  • (ArgumentError)

    The String was not quoted with single, double or tick-mark quotes.

Since:

  • 1.0.0



79
80
81
82
83
84
85
86
87
88
# File 'lib/ronin/support/encoding/sql.rb', line 79

def self.unescape(data)
  char = if    (data[0] == "'" && data[-1] == "'") then "'"
         elsif (data[0] == '"' && data[-1] == '"') then '"'
         elsif (data[0] == '`' && data[-1] == '`') then '`'
         else
           raise(ArgumentError,"#{data.inspect} is not properly quoted")
         end

  return data[1..-2].gsub(char * 2,char)
end