diff --git a/lib/rex/text.rb b/lib/rex/text.rb index 6419c1d19e..912b08990b 100644 --- a/lib/rex/text.rb +++ b/lib/rex/text.rb @@ -292,6 +292,22 @@ module Text end end + # Encode a string in a manor useful for HTTP URIs and URI Parameters. + # + # a = "javascript".gsub(/./) {|i| "(" + [ Rex::Text.html_encode(i, 'hex'), Rex::Text.html_encode(i, 'int'), Rex::Text.html_encode(i, 'int-wide')].join('|') +')[\s\x00]*' } + def self.html_encode(str, mode = 'hex') + case mode + when 'hex' + return str.gsub(/./) { |s| Rex::Text.to_hex(s, '&#x') } + when 'int' + return str.unpack('C*').collect{ |i| "&#" + i.to_s }.join('') + when 'int-wide' + return str.unpack('C*').collect{ |i| "&#" + ("0" * (7 - i.to_s.length)) + i.to_s }.join('') + else + raise TypeError, 'invalid mode' + end + end + # # Converts a hex string to a raw string # diff --git a/lib/rex/text.rb.ut.rb b/lib/rex/text.rb.ut.rb index b8a594a0dd..aadc4def78 100644 --- a/lib/rex/text.rb.ut.rb +++ b/lib/rex/text.rb.ut.rb @@ -21,6 +21,17 @@ class Rex::Text::UnitTest < Test::Unit::TestCase } end + def test_html_encode + assert_equal('A', Rex::Text.html_encode('A'), 'html_encode default') + assert_equal('A', Rex::Text.html_encode('A','hex'), 'html_encode hex') + assert_equal('A', Rex::Text.html_encode('A','int'), 'html_encode int') + assert_equal('A', Rex::Text.html_encode('A','int-wide'), 'html_encode int-wide') + + assert_raises(TypeError) { + Rex::Text.html_encode('a', 'umpa lumpa') + } + end + def test_rand_text srand(0) assert_equal("\254/u\300C\373\303g\t\323", Rex::Text.rand_text(10), 'rand text 1')