Spring Boot escape characters at Request Body for XSS protection

spring cross site scripting (xss issues solution)
spring boot encrypt request
xss injection vulnerability spring boot
strict transport security header spring boot
how to set content security policy header in spring boot
xss filter java
java xss filter library
spring boot tricks

I'm trying to secure my spring boot application using a XSSFilter like this:

public class XSSFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException { }

    @Override
    public void destroy() { }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        chain.doFilter(new XSSRequestWrapper((HttpServletRequest) request), response);
    }

}

And the wrapper:

public class XSSRequestWrapper extends HttpServletRequestWrapper {

    public XSSRequestWrapper(HttpServletRequest servletRequest) {
        super(servletRequest);
    }

    @Override
    public String[] getParameterValues(String parameter) {
        String[] values = super.getParameterValues(parameter);

        if (values == null) {
            return null;
        }

        int count = values.length;
        String[] encodedValues = new String[count];
        for (int i = 0; i < count; i++) {
            encodedValues[i] = replaceXSSCharacters((values[i]));
        }

        return encodedValues;
    }

    private String replaceXSSCharacters(String value) {
        if (value == null) {
            return null;
        }

        return value
                .replace("&","&#38;")
                .replace("<", "&#60;")
                .replace(">","&#62;")
                .replace("\"","&#34;")
                .replace("'","&#39;");
    }

    @Override
    public String getParameter(String parameter) {
        return replaceXSSCharacters(super.getParameter(parameter));
    }

    @Override
    public String getHeader(String name) {
        return replaceXSSCharacters(super.getHeader(name));
    }

}

The problem is, that only secures the Request parameters and Headers, not the Request body, and sometimes my Controller receive data using @RequestBody.

So, if i submit to my controller a json like this:

{"name":"<script>alert('hello!')</script>"}

The html chars at the name property doesn't get escaped like i need. How can i escape the RequestBody?

EDIT: This is different from the "duplicated" question. My question is very Specific. How to escape characters on Request Body.

I resolved with a custom class:

@Configuration
public class AntiXSSConfig  {

    @Autowired()
    public void configeJackson(ObjectMapper mapper) {
        mapper.getFactory().setCharacterEscapes(new HTMLCharacterEscapes());
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

    public static class HTMLCharacterEscapes extends JsonpCharacterEscapes {

        @Override
        public int[] getEscapeCodesForAscii() {
            int[] asciiEscapes = CharacterEscapes.standardAsciiEscapesForJSON();
            // and force escaping of a few others:
            asciiEscapes['<'] = CharacterEscapes.ESCAPE_CUSTOM;
            asciiEscapes['>'] = CharacterEscapes.ESCAPE_CUSTOM;
            asciiEscapes['&'] = CharacterEscapes.ESCAPE_CUSTOM;
            asciiEscapes['"'] = CharacterEscapes.ESCAPE_CUSTOM;
            asciiEscapes['\''] = CharacterEscapes.ESCAPE_CUSTOM;
            return asciiEscapes;
        }

        @Override
        public SerializableString getEscapeSequence(int ch) {
            switch (ch) {
                case '&' : return new SerializedString("&#38;");
                case '<' : return new SerializedString("&#60;");
                case '>' : return new SerializedString("&#62;");
                case '\"' : return new SerializedString("&#34;");
                case '\'' : return new SerializedString("&#39;");
                default : return super.getEscapeSequence(ch);
            }
        }
    }
}

It covers all the cases.

Anti-Cross-Site Scripting (XSS) for Spring Boot Apps Without Spring , I resolved with a custom class: @Configuration public class AntiXSSConfig { @​Autowired() public void configeJackson(ObjectMapper mapper) { mapper. X-XSS-Protection Header¶ The X-XSS-Protection header has been deprecated by modern browsers and its use can introduce additional security issues on the client side. As such, it is recommended to set the header as X-XSS-Protection: 0 in order to disable the XSS Auditor, and not allow it to take the default behavior of the browser handling the

  1. Have a local String field in XSSRequestWrapper which holds the cleaned-up body (probably not suitable for large bodies).
  2. Populate this field in the constructor by reading request.getInputStream() and cleaning up the body the same way as parameters.
  3. Override getInputStream and getReader methods of HttpServletRequestWrapper, and construct an InputStream (string -> byte array -> ByteArrayInputStream) and Reader (StringReader) from the String field and return them respectively. Maybe cache the constructed InputStream and Reader objects for better performance for when the methods are called repeatedly.

You may also be interested in cleaning up JSON when it is being deserialized into Java object.

JSP spring boot / cloud uses filter to prevent XSS, I'm trying to secure my spring boot application using a XSSFilter like this: public class XSSFilter implements Filter { #Override public void init(FilterConfig  Don't use RegEx to prevent XSS attacks! Why? Regex is not a tool that can be used to correctly parse HTML. There are much better ways to prevent XSS attacks. An example, using your code, modified to use Spring HtmlUtils.

To remove XSS characters you just override AbstractJackson2HttpMessageConverter - this converter has responsibility to read request.inputStream to RequestBody object

@Component
public class XSSRequestBodyConverter extends AbstractJackson2HttpMessageConverter {
    public XSSRequestBodyConverter(ObjectMapper objectMapper) {
        super(objectMapper, MediaType.APPLICATION_JSON, new MediaType("application", "*+json"));
    }

@Override
public Object read(Type type, Class<?> contextClass, HttpInputMessage inputMessage)
        throws IOException, HttpMessageNotReadableException {

    Object requestBody = super.read(type, contextClass, inputMessage);
    //Remove xss from requestBody here
    String requestInStr = objectMapper.writeValueAsString(requestBody);
    return objectMapper.readValue(replaceXSSCharacters(requestInStr), Object.class);
}


}

Preventing XSS attacks in a Spring MVC application controller , XSS (Cross Site Scripting) is one of the most common security issues found in remove XSS patterns in the input using HTML-Sanitizer with Spring Boot- you could escape the JSON (ESAPI) before returning it to the client. Simply put, the @RequestBody annotation maps the HttpRequest body to a transfer or domain object, enabling automatic deserialization of the inbound HttpRequest body onto a Java object. First, let's have a look at a Spring controller method:

Securing Spring Boot Web Applications, Based on filter interception, special characters are replaced by HTML transitional Request Header; Request Body; Request parameter. III. One option would be to encode the characters it in the output, but HTML-encoding characters in a JSON API seems a bit strange to me. A third option would be to just remove the string from the output and instead say something like "The provided value was not valid", but that would reduce usability a bit.

To avoid XSS security threat in spring application, import org.springframework.web.util.HtmlUtils; public class HtmlUtils { /** * Verify if a string contains any HTML characters by comparing its * HTML-escaped  In Spring Boot @ResponseBody tutorial, we are going to use the Spring @ResponseBody annotation in a controller to write data to the body of the response object. Tweet Spring is a popular Java application framework and Spring Boot is an evolution of Spring which helps create stand-alone, production-grade Spring based applications easily.

22. Web MVC framework - Project Metadata API Guide, This article applies to sites created with the Spring Boot framework. We will Input Validation; Form Field Input Validation; Output Encoding to Prevent Reflected XSS Attacks SQL Injection is a common and easy to understand attack. ]+$", message="Name must not include special characters. Previous Post Next Post  In the following exercise we will be modifying the spring-security-samples-boot-insecure application. Before we make any changes, it is best to verify that the sample works properly. Perform the following steps to ensure that spring-security-samples-boot-insecure works.

Comments
  • I think you can escape the chars in received text in Jakson object mapper before converting it into an object. E.g. stackoverflow.com/questions/26776311/…
  • Possible duplicate of How to escape Special Characters in JSON
  • But how can i set these serializing options in SpringBoot?