1

I am in a rails app building a string of html to send to a third party email service such as the below:

table_html = ""
  @tickets.each do |ticket|
    table_html << "<tr>"
    table_html << "<td> #{ticket.number} </td>"
    table_html << "<td>#{ticket.section_name} - #{ticket.row_name} </td>" 
    table_html << "</tr>"           
  end 

I was told by a colleague to always escape html entities when constructing html like this because of the risk of an injection attack. I understand the basics of an injection attack, but could someone explain how escaping lowers that risk, and what I should use to escape? Was looking into using haml. Thanks!

BC00
  • 1,589
  • 3
  • 29
  • 47
  • Rails escapes by default. Where are you using this code? Probably you don't have to do anything. – Mischa May 13 '14 at 02:55
  • 1
    Its not in a view, its in a ruby class in the lib directory – BC00 May 13 '14 at 02:57
  • 2
    Hm, then it's probably not escaped. What escaping does (among other things) is change `<` to `<`. This results in e.g. `` being shown literally, instead of having a JavaScript alert popping up on your page. I advice you to convert your code to a view or [using the functionality that Rails provides for escaping](http://api.rubyonrails.org/classes/ERB/Util.html#method-c-html_escape) in your class. – Mischa May 13 '14 at 03:06
  • Why is is in lib? Can't you integrate mailer service using ActionMailer or similar? – Mike Szyndel May 13 '14 at 23:35
  • This may be of some interest, possibly already answered on SO: http://stackoverflow.com/a/5210999/1662973 – Anthony Horne May 14 '14 at 00:27

0 Answers0