Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Anti-Cross-Site Scripting (XSS) for Spring Boot Apps Without Spring Security

DZone's Guide to

Anti-Cross-Site Scripting (XSS) for Spring Boot Apps Without Spring Security

Learn how to get the most out of your Spring Boot applications by getting rid of any XSS patterns in your web app's code.

· Security Zone
Free Resource

Discover how to protect your applications from known and unknown vulnerabilities.

XSS (Cross Site Scripting) is one of the most common security issues found in web applications. One of the ways to handle this issue is to strip XSS patterns in the input data. The other approach is encoding the response.

There are different libraries (Jsoup/HTML-Sanitizer) which could be used to remove XSS patterns in the input data, using regex patterns, though, may not be the right idea.

I will be presenting a simple approach to remove XSS patterns in the input using HTML-Sanitizer with Spring Boot- and Spring REST-based applications which produce and consume JSON data. 

Spring Boot, by default, uses Jackson to serialize and deserialize JSON, so I will be writing a simple JSON Deserializer to deserialize JSON to Java objects. As a part of the deserialization process, any  XSS patterns present in the code will be removed.

import static org.jsoup.parser.Parser.unescapeEntities;
...

@JsonComponent (1)
public class DefaultJsonDeserializer 
  extends JsonDeserializer<String> 
implements ContextualDeserializer{
(2)
  public static final PolicyFactory POLICY_FACTORY = 
    new HtmlPolicyBuilder().allowElements("a", "p")
      .allowUrlProtocols("https")
      .allowAttributes("class").onElements("p")
      .toFactory();

    @Override
    public String deserialize(JsonParser parser, DeserializationContext ctxt) 
         throws IOException {
        String value = parser.getValueAsString();
        if (StringUtils.isEmpty(value) ) return value;
        else                             {
            String originalWithUnescaped  = unescapeUntilNoHtmlEntityFound(value);
           return unescapeEntities(POLICY_FACTORY.sanitize(originalWithUnescaped), true);
        }
    }

    @Override
    public JsonDeserializer<?> createContextual(DeserializationContext ctxt, 
                                                BeanProperty property) 
           throws JsonMappingException {
        return this;
    }

    (3)
    private String unescapeUntilNoHtmlEntityFound(final String value){
        String unescaped = unescapeEntities(value, true);
        if ( !unescaped.equals(value) ) return unescapeUntilNoHtmlEntityFound(unescaped);
        else                            return unescaped;
    }
}

Above is the implementation of JSONDeserializer which removes CSS patterns from JSON input.

(1) @JsonComponent is an annotation which allows component scanning for JSON serializers and deserializers in a Spring Boot application.

(2) HTML-Sanitizer provides HtmlPolicyBuilder the ability to build PolicyFactory, allowing you to describe the allowed elements and attributes. You may want to extract this part of the code in a separate class to build PolicyFactory

(3) unescapeUntilNoHtmlEntityFound is called recursively to unescape the input, like: 

"<p>&lt;p&gt;&amp;lt;a href=&amp;quot;#&amp;quot; onclick=&amp;quot;alert(1)&amp;quot;&amp;gt;PLEASE&amp;lt;/a&amp;gt;</p>";

And then remove the XSS patterns.

Below is the snippet I used to register JsonDeserializer:

@Configuration 
public class WebConfiguration extends WebMvcConfigurerAdapter {
    @Override (1)
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(jsonConverter());
    }

    @Bean     (2)
    public HttpMessageConverter<?> jsonConverter() {
        SimpleModule module = new SimpleModule();
        module.addDeserializer(String.class, new DefaultJsonDeserializer());

        ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json().build();
        objectMapper.registerModule(module);

        return new MappingJackson2HttpMessageConverter(objectMapper);
    }
}

(1) extendMessageConverters allows the extension to the list of registered message converters. 

(2) jsonConverter is a used to register DefaultJsonSerializer and is registered as a Spring bean.

DefaultJsonSerializer would deserialize any kind of JSON input to a Java object before removing the XSS patterns from the input.

Similar to a deserializer, you could also create a serializer to serialize a Java object to JSON where you could escape the JSON (ESAPI) before returning it to the client.

Please note: This approach does not use Spring Security.

Find out how Waratek’s award-winning virtualization platform can improve your web application security, development and operations without false positives, code changes or slowing your application.

Topics:
xss ,spring boot ,security ,json

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}