2

I'm currently developing a service where customers can enter free text in the web interface. To avoid XSS or similar attacks, the text should be escaped in the backend. Does Scala or Slick offer a possibility similar to PHP to escape strings?

So far I checked StackOverflow and the Scala Essential Book for a working solution, so far with no luck. Is there a native solution provided by Scala or Slick comparable to PHP's mysql-escape-string?

Krzysztof Atłasik
  • 21,985
  • 6
  • 54
  • 76
Friso
  • 127
  • 1
  • 10

1 Answers1

3

Function mysqli-escape-string from PHP doesn't help you with doing any sanitization against XSS. It was intended to attempt to escape strings, that could cause SQL Injection. It is now deprecated and shouldn't be used anymore. The preferred way in PHP to prevent your code against SQL Injection is to use Prepared Statement with bind variables.

That said, neither Slick nor Scala have built-in functions doing string sanitization against XSS.

Slick has a nice feature, that changes all strings you are inserting using interpolation to bind variables, which prevents SQL Injection, but it has nothing to do with preventing XSS (it is something similar to Prepared Statements but with less boilerplate).

To prevent XSS you should use some library, which allows sanitization of strings, that might potentially contain XSS. There's Java project java-html-sanitizer from OWASP, that does that. You could use it like:

object HtmlSanitizer {

    //First define your policy for allowed elements
    private lazy val policy = new HtmlPolicyBuilder()
       .allowElements("p")
       .allowElements("a")
       .allowUrlProtocols("https")
       .allowAttributes("href").onElements("a")
       .requireRelNofollowOnLinks()
       .toFactory()

    def sanitize(unsafeHTML: String) = policy.sanitize(unsafeHTML)
 }

and then:

HtmlSanitizer.sanitize("<p><svg/onload=alert('XSS')</p>") // "<p></p>"
Krzysztof Atłasik
  • 21,985
  • 6
  • 54
  • 76