1

I want to prevent xss attacks in my spring application.

I added

 <context-param>
        <param-name>defaultHtmlEscape</param-name>
        <param-value>true</param-value>
  </context-param>

into my web.xml (I found this soulution here)

but on my page I save content with name <script>alert(1);</script> and this scripts executes after page refresh.

client side code:

$.ajax({
       type: 'POST',
       url: 'setContentName',
       dataType: 'json',
       data: {contentId: id, name: params.value}
});

What do I wrong?

P.S.

I load content using javascript after refresh

Community
  • 1
  • 1
gstackoverflow
  • 36,709
  • 117
  • 359
  • 710

2 Answers2

3

Mine is a somewhat controversial opinion, but I think you should validate and reject inbound XSS. You should escape it on output too, but it shouldn't be in your database in the first place, as dbs are long-lasting and often cross-application.

See https://www.owasp.org/index.php/OWASP_JSON_Sanitizer

Use Hibernate Validator (you don't need to use Hibernate ORM) with JSoup to avoid XSS in your db:

Foo.java:

@Entity
class Foo {

  @SafeHtml(whitelistType = SafeHtml.WhiteListType.NONE)
  private String name;

  ...
}

FooController.java:

@Controller
public class FooController {

  @RequestMapping(method=POST)
  String submit(@Validated Foo foo) {
     ...
  }

}

pom.xml:

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-validator</artifactId>
        <version>5.1.2.Final</version>
    </dependency>

    <dependency>
        <groupId>org.jsoup</groupId>
        <artifactId>jsoup</artifactId>
        <version>1.8.1</version>
    </dependency>

See Adding additonal Security to Website for more anti-XSS measures

Neil McGuigan
  • 46,580
  • 12
  • 123
  • 152
-1

I use JSTL for the purpose. Include c prefix in the jsp page,

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

For the value you want to show

<c:out value=${someVar} escapeXml="true" />

Setting the attribute excapeXml="true" is optional in this scenario because its default value is true

Oracle Documentation

Dino Tw
  • 3,167
  • 4
  • 34
  • 48
  • This doesn't prevent XSS attack content winding up in your DB, which op's attempt does at least attempt to accomplish. As such I feel this is an incomplete and potentially misleading/dangerous answer. – Madbreaks Oct 18 '17 at 18:07