Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GWT Safe HTML Framework: When to use, and why?

Tags:

java

html

xss

gwt

In reading JavaDocs and various GWT articles, I've occassionally run into the following Safe* classes:

  • SafeHtml
  • SafeHtmlBuilder

It looks like SafeHtml is somehow used when creating a new Widget or Composite, and helps ensure that the Widget/Composite doesn't execute any scripts on the client-side. Is this the case, or am I way off-base? Can someone provide a code example of SafeHtml being used properly in action?

If so, then what's the point of SafeHtmlBuilder? Do you use it inside of a Widget to somehow "build up" safe HTML?

like image 228
Bantha Fodder Avatar asked Oct 23 '12 09:10

Bantha Fodder


People also ask

What is safe HTML?

A SafeHtml is a string-like object that carries the security type contract that its value as a string will not cause untrusted script execution when evaluated as HTML in a browser.

What is SafeHtml in GWT?

It is used essentially like a StringBuilder ; unlike a StringBuilder , it automatically HTML-escapes appended input where necessary. In addition, it supports methods that allow strings with HTML markup to be appended without escaping: One can append other SafeHtml objects, and one can append constant strings.

What is SafeHtml in Java?

An object that implements this interface encapsulates HTML that is guaranteed to be safe to use (with respect to potential Cross-Site-Scripting vulnerabilities) in an HTML context. Note on usage: SafeHtml should be used to ensure user input is not executed in the browser.


1 Answers

The simplest way to view SafeHtml is as a String where any HTML markup has been appropriately escaped. This protects against Cross-Site Scripting (XSS) attacks as it ensures, for example, if someone enters their name in a form as <SCRIPT>alert('Fail')</SCRIPT> this is the text that gets displayed when your page is rendered rather than the JavaScript being run.

So instead of having something like:

String name = getValueOfName();
HTML widget = new HTML(name);

You should use:

String name = getValueOfName();
HTML widget = new HTML(SafeHtmlUtils.fromString(name));

SafeHtmlBuilder is like a StringBuilder except that it automatically escapes HTML markup in the Strings you add. So to extend the above example:

String name = getValueOfName();
SafeHtmlBuilder shb = new SafeHtmlBuilder();
shb.appendEscaped("Name: ").appendEscaped(name);
HTML widget = new HTML(shb.toSafeHtml());

The is a good guide to SafeHtml in the GWT documentation that is worth a read.

like image 75
Dave Webb Avatar answered Sep 29 '22 10:09

Dave Webb