Cross-site scripting High

User-controllable input must be sanitized before it's included in output used to dynamically generate a web page. Unsanitized user input can introduce cross-side scripting (XSS) vulnerabilities that can lead to inadvertedly running malicious code in a trusted context.

Detector ID
java/cross-site-scripting@v1.0
Category
Common Weakness Enumeration (CWE) external icon

Noncompliant example

1public ModelAndView inputSanitizationNonCompliant(@RequestParam String favoriteColor) {
2    ModelAndView modelAndView = new ModelAndView();
3    modelAndView.setViewName("jsp/example.jsp");
4    // Noncompliant: user-supplied parameter might contain malicious content.
5    modelAndView.addObject("preferredColor", favoriteColor);
6    return modelAndView;
7}

Compliant example

1public ModelAndView inputSanitizationCompliant(@RequestParam String favoriteColor) {
2    ModelAndView modelAndView = new ModelAndView();
3    modelAndView.setViewName("jsp/example.jsp");
4    // Compliant: user-supplied parameter must be in allow-list.
5    if (favoriteColor.matches("[a-z]+")) {
6        modelAndView.addObject("preferredColor", favoriteColor);
7    } else {
8        throw new IllegalArgumentException("Invalid color!");
9    }
10    return modelAndView;
11}