I am using Clojure/Ring/Compojure-0.4/Enlive stack to build a web application.
Are there functions in this stack that would either strip HTML or HTML-encode (i.e. <a>
to <a>
) user-supplied strings in order to prevent XSS attacks?
User input is a string. Escaping is done when you want to insert some characters into some HTML / SQL / Whatever code which insists on interpreting some characters into special functionalities.
Summary. xss-sanitize allows you to accept html from untrusted sources by first filtering it through a white list. The white list filtering is fairly comprehensive, including support for css in style attributes, but there are limitations enumerated below.
To sanitize a string input which you want to store to the database (for example a customer name) you need either to escape it or plainly remove any quotes (', ") from it. This effectively prevents classical SQL injection which can happen if you are assembling an SQL query from strings passed by the user.
hiccup.util/escape-html
in hiccup does it. That function used to be in Compojure itself (since all of the functionality in hiccup used to be part of Compojure). It's a simple enough function that you could easily write it yourself though.
(defn escape-html
"Change special characters into HTML character entities."
[text]
(.. #^String (as-str text)
(replace "&" "&")
(replace "<" "<")
(replace ">" ">")
(replace "\"" """)))
There's also clojure.contrib.string/escape
, which takes a map of char -> string escape sequences and a string and escapes it for you.
user> (clojure.contrib.string/escape {\< "<" \> ">"} "<div>foo</div>")
"<div>foo</div>"
This strikes me as not as useful as it could be, because you might want to escape multi-character sequences and this won't let you. But it might work for your HTML-escaping needs.
And then there are many Java libraries for this, of course. You could use StringEscapeUtils from Apache Commons:
(org.apache.commons.lang.StringEscapeUtils/escapeHtml4 some-string)
This strikes me as a bit heavyweight for this purpose though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With