Sanitizing UTF8 in ruby
Rails 2.3.4 was released largely to address an XSS exploit where user input with specialy crafted UTF8 could bypass the normal sanitize hepers.
The problem is that string like
Would be interpreted by ruby as
However, a web browser might perform additional cleanup to interpret it as a script tag. Further, though less serious, problems with this are that it can sometimes cause HPricot to segfault, and libxml-ruby will raise an exception.
The solution was to sanitize the invalid UTF8 code before displaying it to the browser. If you need to use this outside of the SanitizeHelper methods, ActiveSupport::Multibyte::clean() and ActiveSupport::Multibyte::verify() have been created. commit
If you need something similar but aren’t running rails or can’t upgrade to 2.3.4, here’s a solution. You can split up a string by its utf characters by splitting against an empty regex string.
and then matching against a regex (borrowed from Instiki) of valid UTF8 characters
After that you can safely sanitize your HTML and expect web browsers to interpret it the same way.